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