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