Merge changes I4b3820fd,Ib225745c
[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      * <ul>
77      * <li>moduleNamespaceToPackageName</li> - with revision
78      * <li>packageNameForGeneratedType</li>
79      * <ul>
80      * <li>validateJavaPackage</li>
81      * </ul>
82      * <li>packageNameForTypeDefinition</li> <li>moduleNamespaceToPackageName</li>
83      * - without revision </ul>
84      */
85     @Test
86     public void testBindingGeneratorUtilMethods() throws IOException {
87         List<File> testModels = loadTestResources("/module.yang");
88         final YangContextParser parser = new YangParserImpl();
89         final Set<Module> modules = parser.parseFiles(testModels).getModules();
90         String packageName = "";
91         Module module = null;
92         for (Module m : modules) {
93             module = m;
94             break;
95         }
96         assertNotNull("Module can't be null", module);
97
98         // test of the method moduleNamespaceToPackageName()
99         packageName = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
100         assertEquals("Generated package name is incorrect.",
101                 "org.opendaylight.yang.gen.v1.urn.m.o.d.u.l.e.n.a.m.e.t.e.s.t._case._1digit.rev130910", packageName);
102
103         // test of the method packageNameForGeneratedType()
104         DataNodeIterator it = new DataNodeIterator(module);
105         List<ContainerSchemaNode> schemaContainers = it.allContainers();
106         String subPackageNameForDataNode = "";
107         for (ContainerSchemaNode containerSchemaNode : schemaContainers) {
108             if (containerSchemaNode.getQName().getLocalName().equals("cont-inner")) {
109                 subPackageNameForDataNode = BindingGeneratorUtil.packageNameForGeneratedType(packageName,
110                         containerSchemaNode.getPath());
111                 break;
112             }
113         }
114         assertEquals("The name of the subpackage is incorrect.",
115                 "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",
116                 subPackageNameForDataNode);
117
118         // test of the method packageNameForTypeDefinition
119         Set<TypeDefinition<?>> typeDefinitions = module.getTypeDefinitions();
120         String subPackageNameForTypeDefinition = "";
121         TypeDefinition<?> firstTypeDef = null;
122
123         for (TypeDefinition<?> tpDef : typeDefinitions) {
124             if (tpDef.getQName().getLocalName().equals("tpdf")) {
125                 subPackageNameForTypeDefinition = BindingGeneratorUtil.packageNameForTypeDefinition(packageName, tpDef);
126                 firstTypeDef = tpDef;
127                 break;
128             }
129         }
130         assertEquals("The name of the subpackage is incorrect.",
131                 "org.opendaylight.yang.gen.v1.urn.m.o.d.u.l.e.n.a.m.e.t.e.s.t._case._1digit.rev130910",
132                 subPackageNameForTypeDefinition);
133
134         // test method getRestrictions
135         Restrictions restriction = BindingGeneratorUtil.getRestrictions(firstTypeDef);
136         assertNotNull(restriction);
137
138         // test method computeDefaultSUID
139         GeneratedTypeBuilder genTypeBuilder = new GeneratedTypeBuilderImpl("org.opendaylight.yangtools.test", "TestType");
140         genTypeBuilder.addMethod("testMethod");
141         genTypeBuilder.addAnnotation("org.opendaylight.yangtools.test.annotation", "AnnotationTest");
142         genTypeBuilder.addEnclosingTransferObject("testObject");
143         genTypeBuilder.addProperty("newProp");
144         GeneratedTypeBuilder genType = new GeneratedTypeBuilderImpl("org.opendaylight.yangtools.test", "Type2");
145         genTypeBuilder.addImplementsType(genType);
146         long computedSUID = BindingGeneratorUtil.computeDefaultSUID(genTypeBuilder);
147
148         GeneratedTypeBuilder genTypeBuilder2 = new GeneratedTypeBuilderImpl("org.opendaylight.yangtools.test2", "TestType2");
149         long computedSUID2 = BindingGeneratorUtil.computeDefaultSUID(genTypeBuilder2);
150         assertNotEquals(computedSUID, computedSUID2);
151
152         // test of exception part of the method moduleNamespaceToPackageName()
153         ModuleBuilder moduleBuilder = new ModuleBuilder("module-withut-revision", null);
154         moduleBuilder.setSource("");
155         Module moduleWithoutRevision = moduleBuilder.build();
156         boolean passedSuccesfully = false;
157         try {
158             BindingGeneratorUtil.moduleNamespaceToPackageName(moduleWithoutRevision);
159             passedSuccesfully = true;
160         } catch (IllegalArgumentException e) {
161         }
162         assertFalse("Exception 'IllegalArgumentException' wasn't raised", passedSuccesfully);
163
164     }
165
166     /**
167      * Test for the method
168      * <ul>
169      * <li>{@link BindingGeneratorUtil#packageNameForTypeDefinition()
170      * packageNameForTypeDefinition()}</li>
171      * </ul>
172      */
173     @Test
174     @Deprecated
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     @Deprecated
190     public void testPackageNameForTypeDefinitionNullTypeDefinition() {
191         expectedEx.expect(IllegalArgumentException.class);
192         expectedEx.expectMessage("Type Definition reference cannot be NULL!");
193         BindingGeneratorUtil.packageNameForTypeDefinition("test.package", null);
194     }
195
196     /**
197      * Test for the method
198      * <ul>
199      * <li>{@link BindingGeneratorUtil#packageNameForGeneratedType()
200      * packageNameForGeneratedType()}</li>
201      * </ul>
202      */
203     @Test
204     public void testPackageNameForGeneratedTypeNullBasePackageName() {
205         expectedEx.expect(NullPointerException.class);
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(NullPointerException.class);
219         BindingGeneratorUtil.packageNameForGeneratedType("test.package", null);
220     }
221
222     /**
223      * Test for the method
224      * <ul>
225      * <li>{@link BindingGeneratorUtil#parseToClassName()
226      * parseToClassName()}</li>
227      * </ul>
228      */
229     @Test
230     public void testParseToClassNameNullValue() {
231         String className = BindingGeneratorUtil.parseToClassName("test-class-name");
232         assertEquals("TestClassName", className);
233
234         expectedEx.expect(IllegalArgumentException.class);
235         expectedEx.expectMessage("Name can not be null");
236         className = BindingGeneratorUtil.parseToClassName(null);
237     }
238
239     /**
240      * Test for the method
241      * <ul>
242      * <li>{@link BindingGeneratorUtil#parseToClassName()
243      * parseToClassName()}</li>
244      * </ul>
245      */
246     @Test
247     public void testParseToClassNameEmptyValue() {
248         String className = BindingGeneratorUtil.parseToClassName("test-class-name");
249         assertEquals("TestClassName", className);
250
251         expectedEx.expect(IllegalArgumentException.class);
252         expectedEx.expectMessage("Name can not be empty");
253         className = BindingGeneratorUtil.parseToClassName("");
254     }
255
256     /**
257      * Test for the method
258      * <ul>
259      * <li>{@link BindingGeneratorUtil#validateParameterName()
260      * validateParameterName()}</li>
261      * <ul>
262      */
263     @Test
264     public void testValidateParameterName() {
265         assertNull("Return value is incorrect.", BindingGeneratorUtil.resolveJavaReservedWordEquivalency(null));
266         assertEquals("Return value is incorrect.", "whatever",
267                 BindingGeneratorUtil.resolveJavaReservedWordEquivalency("whatever"));
268         assertEquals("Return value is incorrect.", "_case",
269                 BindingGeneratorUtil.resolveJavaReservedWordEquivalency("case"));
270     }
271
272     /**
273      * Tests the methods:
274      * <ul>
275      * <li>parseToClassName</li>
276      * <ul>
277      * <li>parseToCamelCase</li>
278      * <ul>
279      * <li>replaceWithCamelCase</li>
280      * </ul>
281      * </ul> <li>parseToValidParamName</li>
282      * <ul>
283      * <li>parseToCamelCase</li>
284      * <ul>
285      * <li>replaceWithCamelCase</li>
286      * </ul>
287      * </ul>
288      * <ul>
289      */
290     @Test
291     public void testParsingMethods() {
292         // parseToClassName method testing
293         assertEquals("Class name has incorrect format", "SomeTestingClassName",
294                 BindingMapping.getClassName("  some-testing_class name   "));
295         assertEquals("Class name has incorrect format", "_0SomeTestingClassName",
296                 BindingMapping.getClassName("  0 some-testing_class name   "));
297
298         // parseToValidParamName
299         assertEquals("Parameter name has incorrect format", "someTestingParameterName",
300                 BindingGeneratorUtil.parseToValidParamName("  some-testing_parameter   name   "));
301         assertEquals("Parameter name has incorrect format", "_0someTestingParameterName",
302                 BindingGeneratorUtil.parseToValidParamName("  0some-testing_parameter   name   "));
303     }
304
305     @Test
306     public void computeDefaultSUIDTest() {
307         GeneratedTypeBuilderImpl generatedTypeBuilder = new GeneratedTypeBuilderImpl("my.package", "MyName");
308
309         MethodSignatureBuilder method = generatedTypeBuilder.addMethod("myMethodName");
310         method.setAccessModifier(AccessModifier.PUBLIC);
311         generatedTypeBuilder.addProperty("myProperty");
312         generatedTypeBuilder.addImplementsType(Types.typeForClass(Serializable.class));
313
314         assertEquals(6788238694991761868L, BindingGeneratorUtil.computeDefaultSUID(generatedTypeBuilder));
315
316     }
317
318     @Test
319     public void getRestrictionsTest() {
320
321         Optional<String> absent = Optional.absent();
322
323         Builder extTypeBuilder = ExtendedType.builder(new QName(URI.create("namespace"), "localName"),
324                 Int16.getInstance(), absent, absent, SchemaPath.create(true, QName.create("/root")));
325
326         ArrayList<LengthConstraint> lenght = new ArrayList<LengthConstraint>();
327         ArrayList<RangeConstraint> range = new ArrayList<RangeConstraint>();
328         ArrayList<PatternConstraint> pattern = new ArrayList<PatternConstraint>();
329
330         lenght.add(BaseConstraints.newLengthConstraint(1, 2, absent, absent));
331         range.add(BaseConstraints.newRangeConstraint(1, 2, absent, absent));
332         pattern.add(BaseConstraints.newPatternConstraint(".*", absent, absent));
333
334         extTypeBuilder.lengths(lenght);
335         extTypeBuilder.ranges(range);
336         extTypeBuilder.patterns(pattern);
337
338         Restrictions restrictions = BindingGeneratorUtil.getRestrictions(extTypeBuilder.build());
339
340         assertNotNull(restrictions);
341
342         assertEquals(1, restrictions.getLengthConstraints().size());
343         assertEquals(1, restrictions.getRangeConstraints().size());
344         assertEquals(1, restrictions.getPatternConstraints().size());
345
346         assertFalse(restrictions.isEmpty());
347         assertTrue(restrictions.getLengthConstraints().contains(
348                 BaseConstraints.newLengthConstraint(1, 2, absent, absent)));
349         assertTrue(restrictions.getRangeConstraints()
350                 .contains(BaseConstraints.newRangeConstraint(1, 2, absent, absent)));
351         assertTrue(restrictions.getPatternConstraints().contains(
352                 BaseConstraints.newPatternConstraint(".*", absent, absent)));
353     }
354
355     @Test
356     public void getEmptyRestrictionsTest() {
357
358         Optional<String> absent = Optional.absent();
359
360         Builder extTypeBuilder = ExtendedType.builder(new QName(URI.create("namespace"), "localName"),
361                 StringType.getInstance(), absent, absent, SchemaPath.create(true, QName.create("/root")));
362
363         Restrictions restrictions = BindingGeneratorUtil.getRestrictions(extTypeBuilder.build());
364
365         assertNotNull(restrictions);
366         assertTrue(restrictions.isEmpty());
367
368     }
369
370     @Test
371     public void getDefaultIntegerRestrictionsTest() {
372
373         Optional<String> absent = Optional.absent();
374
375         Builder extTypeBuilder = ExtendedType.builder(new QName(URI.create("namespace"), "localName"),
376                 Int16.getInstance(), absent, absent, SchemaPath.create(true, QName.create("/root")));
377
378         ExtendedType extType = extTypeBuilder.build();
379         Restrictions restrictions = BindingGeneratorUtil.getRestrictions(extType);
380
381         assertNotNull(restrictions);
382         assertFalse(restrictions.isEmpty());
383         assertEquals(((IntegerTypeDefinition) extType.getBaseType()).getRangeConstraints(),
384                 restrictions.getRangeConstraints());
385         assertTrue(restrictions.getLengthConstraints().isEmpty());
386         assertTrue(restrictions.getPatternConstraints().isEmpty());
387
388     }
389
390     @Test
391     public void getDefaultUnsignedIntegerRestrictionsTest() {
392
393         Optional<String> absent = Optional.absent();
394
395         Builder extTypeBuilder = ExtendedType.builder(new QName(URI.create("namespace"), "localName"),
396                 Uint16.getInstance(), absent, absent, SchemaPath.create(true, QName.create("/root")));
397
398         ExtendedType extType = extTypeBuilder.build();
399         Restrictions restrictions = BindingGeneratorUtil.getRestrictions(extType);
400
401         assertNotNull(restrictions);
402         assertFalse(restrictions.isEmpty());
403         assertEquals(((UnsignedIntegerTypeDefinition) extType.getBaseType()).getRangeConstraints(),
404                 restrictions.getRangeConstraints());
405         assertTrue(restrictions.getLengthConstraints().isEmpty());
406         assertTrue(restrictions.getPatternConstraints().isEmpty());
407     }
408
409     @Test
410     public void getDefaultDecimalRestrictionsTest() {
411
412         Optional<String> absent = Optional.absent();
413         SchemaPath path = SchemaPath.create(true, QName.create("/root"));
414
415         Builder extTypeBuilder = ExtendedType.builder(new QName(URI.create("namespace"), "localName"),
416                 Decimal64.create(path, 10), absent, absent, path);
417
418         ExtendedType extType = extTypeBuilder.build();
419         Restrictions restrictions = BindingGeneratorUtil.getRestrictions(extType);
420
421         assertNotNull(restrictions);
422         assertFalse(restrictions.isEmpty());
423         assertEquals(((DecimalTypeDefinition) extType.getBaseType()).getRangeConstraints(),
424                 restrictions.getRangeConstraints());
425         assertTrue(restrictions.getLengthConstraints().isEmpty());
426         assertTrue(restrictions.getPatternConstraints().isEmpty());
427
428     }
429
430 }