0e32ba431eae8dde8e9c700069e709f80d34b365
[mdsal.git] / binding / mdsal-binding-generator-util / src / test / java / org / opendaylight / yangtools / binding / generator / util / BindingGeneratorUtilTest.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.binding.generator.util;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertFalse;
12 import static org.junit.Assert.assertNotEquals;
13 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertNull;
15 import static org.junit.Assert.assertTrue;
16 import static org.junit.Assert.fail;
17 import static org.mockito.Mockito.doReturn;
18 import static org.mockito.Mockito.mock;
19 import com.google.common.base.Optional;
20 import com.google.common.collect.ImmutableList;
21 import java.io.File;
22 import java.io.IOException;
23 import java.io.Serializable;
24 import java.net.URISyntaxException;
25 import java.util.ArrayList;
26 import java.util.List;
27 import java.util.Set;
28 import org.junit.Rule;
29 import org.junit.Test;
30 import org.junit.rules.ExpectedException;
31 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
32 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
33 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
34 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
35 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
36 import org.opendaylight.yangtools.yang.binding.BindingMapping;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.Module;
40 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
41 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
42 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
44 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
45 import org.opendaylight.yangtools.yang.model.util.BaseConstraints;
46 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
47 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
48 import org.opendaylight.yangtools.yang.model.util.type.DerivedTypes;
49 import org.opendaylight.yangtools.yang.model.util.type.RestrictedTypes;
50 import org.opendaylight.yangtools.yang.model.util.type.StringTypeBuilder;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
52 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
53
54 public class BindingGeneratorUtilTest {
55     private static final SchemaPath ROOT_PATH = SchemaPath.create(true, QName.create("/root"));
56
57     @Rule
58     public ExpectedException expectedEx = ExpectedException.none();
59
60     private static List<File> loadTestResources(final String testFile) {
61         final List<File> testModels = new ArrayList<File>();
62         File listModelFile;
63         try {
64             listModelFile = new File(BindingGeneratorUtilTest.class.getResource(testFile).toURI());
65         } catch (URISyntaxException e) {
66             throw new IllegalArgumentException("Failed to load sources from " + testFile);
67         }
68         testModels.add(listModelFile);
69         return testModels;
70     }
71
72     /**
73      * Tests methods:
74      * &lt;ul&gt;
75      * &lt;li&gt;moduleNamespaceToPackageName&lt;/li&gt; - with revision
76      * &lt;li&gt;packageNameForGeneratedType&lt;/li&gt;
77      * &lt;ul&gt;
78      * &lt;li&gt;validateJavaPackage&lt;/li&gt;
79      * &lt;/ul&gt;
80      * &lt;li&gt;packageNameForTypeDefinition&lt;/li&gt; &lt;li&gt;moduleNamespaceToPackageName&lt;/li&gt;
81      * - without revision &lt;/ul&gt;
82      * @throws ReactorException Reactor exception
83      * @throws SourceException Source exception
84      */
85     @Test
86     public void testBindingGeneratorUtilMethods() throws IOException, SourceException, ReactorException {
87         List<File> testModels = loadTestResources("/module.yang");
88
89         final Set<Module> modules = TestUtils.parseYangSources(testModels).getModules();
90         String packageName = "";
91         Module module = null;
92         for (Module m : modules) {
93             module = m;
94             break;
95         }
96         assertNotNull("Module can't be null", module);
97
98         // test of the method moduleNamespaceToPackageName()
99         packageName = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
100         assertEquals("Generated package name is incorrect.",
101                 "org.opendaylight.yang.gen.v1.urn.m.o.d.u.l.e.n.a.m.e.t.e.s.t._case._1digit.rev130910", packageName);
102
103         // test of the method packageNameForGeneratedType()
104         DataNodeIterator it = new DataNodeIterator(module);
105         List<ContainerSchemaNode> schemaContainers = it.allContainers();
106         String subPackageNameForDataNode = "";
107         for (ContainerSchemaNode containerSchemaNode : schemaContainers) {
108             if (containerSchemaNode.getQName().getLocalName().equals("cont-inner")) {
109                 subPackageNameForDataNode = BindingGeneratorUtil.packageNameForGeneratedType(packageName,
110                         containerSchemaNode.getPath());
111                 break;
112             }
113         }
114         assertEquals("The name of the subpackage is incorrect.",
115                 "org.opendaylight.yang.gen.v1.urn.m.o.d.u.l.e.n.a.m.e.t.e.s.t._case._1digit.rev130910.cont.outter",
116                 subPackageNameForDataNode);
117
118         // test of the method packageNameForTypeDefinition
119         Set<TypeDefinition<?>> typeDefinitions = module.getTypeDefinitions();
120         String subPackageNameForTypeDefinition = "";
121         TypeDefinition<?> firstTypeDef = null;
122
123         for (TypeDefinition<?> tpDef : typeDefinitions) {
124             if (tpDef.getQName().getLocalName().equals("tpdf")) {
125                 subPackageNameForTypeDefinition = BindingGeneratorUtil.packageNameForTypeDefinition(packageName, tpDef);
126                 firstTypeDef = tpDef;
127                 break;
128             }
129         }
130         assertEquals("The name of the subpackage is incorrect.",
131                 "org.opendaylight.yang.gen.v1.urn.m.o.d.u.l.e.n.a.m.e.t.e.s.t._case._1digit.rev130910",
132                 subPackageNameForTypeDefinition);
133
134         // test method getRestrictions
135         Restrictions restriction = BindingGeneratorUtil.getRestrictions(firstTypeDef);
136         assertNotNull(restriction);
137
138         // test method computeDefaultSUID
139         GeneratedTypeBuilder genTypeBuilder = new GeneratedTypeBuilderImpl("org.opendaylight.yangtools.test", "TestType");
140         genTypeBuilder.addMethod("testMethod");
141         genTypeBuilder.addAnnotation("org.opendaylight.yangtools.test.annotation", "AnnotationTest");
142         genTypeBuilder.addEnclosingTransferObject("testObject");
143         genTypeBuilder.addProperty("newProp");
144         GeneratedTypeBuilder genType = new GeneratedTypeBuilderImpl("org.opendaylight.yangtools.test", "Type2");
145         genTypeBuilder.addImplementsType(genType);
146         long computedSUID = BindingGeneratorUtil.computeDefaultSUID(genTypeBuilder);
147
148         GeneratedTypeBuilder genTypeBuilder2 = new GeneratedTypeBuilderImpl("org.opendaylight.yangtools.test2", "TestType2");
149         long computedSUID2 = BindingGeneratorUtil.computeDefaultSUID(genTypeBuilder2);
150         assertNotEquals(computedSUID, computedSUID2);
151
152         // test of exception part of the method moduleNamespaceToPackageName()
153         Module moduleWithoutRevision = mock(Module.class);
154         doReturn(null).when(moduleWithoutRevision).getQNameModule();
155         try {
156             BindingGeneratorUtil.moduleNamespaceToPackageName(moduleWithoutRevision);
157             fail("Expected IllegalArgumentException");
158         } catch (IllegalArgumentException e) {
159         }
160     }
161
162     /**
163      * Test for the method
164      * &lt;ul&gt;
165      * &lt;li&gt;{@link BindingGeneratorUtil#packageNameForTypeDefinition(String, TypeDefinition)
166      * packageNameForTypeDefinition(String, TypeDefinition)}&lt;/li&gt;
167      * &lt;/ul&gt;
168      */
169     @Test
170     @Deprecated
171     public void testPackageNameForTypeDefinitionNullBasePackageName() {
172         expectedEx.expect(IllegalArgumentException.class);
173         expectedEx.expectMessage("Base Package Name cannot be NULL!");
174         BindingGeneratorUtil.packageNameForTypeDefinition(null, null);
175     }
176
177     /**
178      * Test for the method
179      * &lt;ul&gt;
180      * &lt;li&gt;{@link BindingGeneratorUtil#packageNameForTypeDefinition(String, TypeDefinition)
181      * packageNameForTypeDefinition(String, TypeDefinition)}&lt;/li&gt;
182      * &lt;/ul&gt;
183      */
184     @Test
185     @Deprecated
186     public void testPackageNameForTypeDefinitionNullTypeDefinition() {
187         expectedEx.expect(IllegalArgumentException.class);
188         expectedEx.expectMessage("Type Definition reference cannot be NULL!");
189         BindingGeneratorUtil.packageNameForTypeDefinition("test.package", null);
190     }
191
192     /**
193      * Test for the method
194      * &lt;ul&gt;
195      * &lt;li&gt;{@link BindingGeneratorUtil#packageNameForGeneratedType(String, SchemaPath)
196      * packageNameForGeneratedType(String, SchemaPath)}&lt;/li&gt;
197      * &lt;/ul&gt;
198      */
199     @Test
200     public void testPackageNameForGeneratedTypeNullBasePackageName() {
201         expectedEx.expect(NullPointerException.class);
202         BindingGeneratorUtil.packageNameForGeneratedType(null, null);
203     }
204
205     /**
206      * Test for the method
207      * &lt;ul&gt;
208      * &lt;li&gt;{@link BindingGeneratorUtil#packageNameForGeneratedType(String, SchemaPath)
209      * packageNameForGeneratedType(String, SchemaPath)}&lt;/li&gt;
210      * &lt;/ul&gt;
211      */
212     @Test
213     public void testPackageNameForGeneratedTypeNullSchemaPath() {
214         expectedEx.expect(NullPointerException.class);
215         BindingGeneratorUtil.packageNameForGeneratedType("test.package", null);
216     }
217
218     /**
219      * Test for the method
220      * &lt;ul&gt;
221      * &lt;li&gt;{@link BindingGeneratorUtil#parseToClassName(String)
222      * parseToClassName(String)}&lt;/li&gt;
223      * &lt;/ul&gt;
224      */
225     @Test
226     public void testParseToClassNameNullValue() {
227         String className = BindingGeneratorUtil.parseToClassName("test-class-name");
228         assertEquals("TestClassName", className);
229
230         expectedEx.expect(IllegalArgumentException.class);
231         expectedEx.expectMessage("Name can not be null");
232         className = BindingGeneratorUtil.parseToClassName(null);
233     }
234
235     /**
236      * Test for the method
237      * &lt;ul&gt;
238      * &lt;li&gt;{@link BindingGeneratorUtil#parseToClassName(String)
239      * parseToClassName(String)}&lt;/li&gt;
240      * &lt;/ul&gt;
241      */
242     @Test
243     public void testParseToClassNameEmptyValue() {
244         String className = BindingGeneratorUtil.parseToClassName("test-class-name");
245         assertEquals("TestClassName", className);
246
247         expectedEx.expect(IllegalArgumentException.class);
248         expectedEx.expectMessage("Name can not be empty");
249         className = BindingGeneratorUtil.parseToClassName("");
250     }
251
252     /**
253      * Test for the method
254      * &lt;ul&gt;
255      * &lt;li&gt;{@link BindingGeneratorUtil#resolveJavaReservedWordEquivalency(String)
256      * resolveJavaReservedWordEquivalency(String)}&lt;/li&gt;
257      * &lt;ul&gt;
258      */
259     @Test
260     public void testValidateParameterName() {
261         assertNull("Return value is incorrect.", BindingGeneratorUtil.resolveJavaReservedWordEquivalency(null));
262         assertEquals("Return value is incorrect.", "whatever",
263                 BindingGeneratorUtil.resolveJavaReservedWordEquivalency("whatever"));
264         assertEquals("Return value is incorrect.", "_case",
265                 BindingGeneratorUtil.resolveJavaReservedWordEquivalency("case"));
266     }
267
268     /**
269      * Tests the methods:
270      * &lt;ul&gt;
271      * &lt;li&gt;parseToClassName&lt;/li&gt;
272      * &lt;ul&gt;
273      * &lt;li&gt;parseToCamelCase&lt;/li&gt;
274      * &lt;ul&gt;
275      * &lt;li&gt;replaceWithCamelCase&lt;/li&gt;
276      * &lt;/ul&gt;
277      * &lt;/ul&gt; &lt;li&gt;parseToValidParamName&lt;/li&gt;
278      * &lt;ul&gt;
279      * &lt;li&gt;parseToCamelCase&lt;/li&gt;
280      * &lt;ul&gt;
281      * &lt;li&gt;replaceWithCamelCase&lt;/li&gt;
282      * &lt;/ul&gt;
283      * &lt;/ul&gt;
284      * &lt;ul&gt;
285      */
286     @Test
287     public void testParsingMethods() {
288         // parseToClassName method testing
289         assertEquals("Class name has incorrect format", "SomeTestingClassName",
290                 BindingMapping.getClassName("  some-testing_class name   "));
291         assertEquals("Class name has incorrect format", "_0SomeTestingClassName",
292                 BindingMapping.getClassName("  0 some-testing_class name   "));
293
294         // parseToValidParamName
295         assertEquals("Parameter name has incorrect format", "someTestingParameterName",
296                 BindingGeneratorUtil.parseToValidParamName("  some-testing_parameter   name   "));
297         assertEquals("Parameter name has incorrect format", "_0someTestingParameterName",
298                 BindingGeneratorUtil.parseToValidParamName("  0some-testing_parameter   name   "));
299     }
300
301     @Test
302     public void computeDefaultSUIDTest() {
303         GeneratedTypeBuilderImpl generatedTypeBuilder = new GeneratedTypeBuilderImpl("my.package", "MyName");
304
305         MethodSignatureBuilder method = generatedTypeBuilder.addMethod("myMethodName");
306         method.setAccessModifier(AccessModifier.PUBLIC);
307         generatedTypeBuilder.addProperty("myProperty");
308         generatedTypeBuilder.addImplementsType(Types.typeForClass(Serializable.class));
309
310         assertEquals(6788238694991761868L, BindingGeneratorUtil.computeDefaultSUID(generatedTypeBuilder));
311
312     }
313
314     @Test
315     public void getRestrictionsTest() {
316         final Optional<String> absent = Optional.absent();
317         final StringTypeBuilder builder =
318                 RestrictedTypes.newStringBuilder(BaseTypes.stringType(), ROOT_PATH);
319
320         builder.addPatternConstraint(BaseConstraints.newPatternConstraint(".*", absent, absent));
321         builder.setLengthAlternatives(ImmutableList.of(
322             BaseConstraints.newLengthConstraint(1, 2, absent, absent)));
323
324         Restrictions restrictions = BindingGeneratorUtil.getRestrictions(builder.build());
325
326         assertNotNull(restrictions);
327
328         assertEquals(1, restrictions.getLengthConstraints().size());
329         assertEquals(0, restrictions.getRangeConstraints().size());
330         assertEquals(1, restrictions.getPatternConstraints().size());
331
332         assertFalse(restrictions.isEmpty());
333         assertTrue(restrictions.getLengthConstraints().contains(
334                 BaseConstraints.newLengthConstraint(1, 2, absent, absent)));
335         assertTrue(restrictions.getPatternConstraints().contains(
336                 BaseConstraints.newPatternConstraint(".*", absent, absent)));
337     }
338
339     @Test
340     public void getEmptyRestrictionsTest() {
341         final TypeDefinition<?> type = DerivedTypes.derivedTypeBuilder(BaseTypes.stringType(), ROOT_PATH).build();
342         final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(type);
343
344         assertNotNull(restrictions);
345         assertTrue(restrictions.isEmpty());
346     }
347
348     @Test
349     public void getDefaultIntegerRestrictionsTest() {
350         final TypeDefinition<?> type = DerivedTypes.derivedTypeBuilder(BaseTypes.int16Type(), ROOT_PATH).build();
351         final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(type);
352
353         assertNotNull(restrictions);
354         assertFalse(restrictions.isEmpty());
355         assertEquals(((IntegerTypeDefinition) type.getBaseType()).getRangeConstraints(),
356                 restrictions.getRangeConstraints());
357         assertTrue(restrictions.getLengthConstraints().isEmpty());
358         assertTrue(restrictions.getPatternConstraints().isEmpty());
359     }
360
361     @Test
362     public void getDefaultUnsignedIntegerRestrictionsTest() {
363         final TypeDefinition<?> type = DerivedTypes.derivedTypeBuilder(BaseTypes.uint16Type(), ROOT_PATH).build();
364         final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(type);
365
366         assertNotNull(restrictions);
367         assertFalse(restrictions.isEmpty());
368         assertEquals(((UnsignedIntegerTypeDefinition) type.getBaseType()).getRangeConstraints(),
369                 restrictions.getRangeConstraints());
370         assertTrue(restrictions.getLengthConstraints().isEmpty());
371         assertTrue(restrictions.getPatternConstraints().isEmpty());
372     }
373
374     @Test
375     public void getDefaultDecimalRestrictionsTest() {
376         final DecimalTypeDefinition base = BaseTypes.decimalTypeBuilder(ROOT_PATH).setFractionDigits(10).build();
377         final TypeDefinition<?> type = DerivedTypes.derivedTypeBuilder(base, ROOT_PATH).build();
378
379         final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(type);
380
381         assertNotNull(restrictions);
382         assertFalse(restrictions.isEmpty());
383         assertEquals(base.getRangeConstraints(), restrictions.getRangeConstraints());
384         assertTrue(restrictions.getLengthConstraints().isEmpty());
385         assertTrue(restrictions.getPatternConstraints().isEmpty());
386     }
387 }