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