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