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