BUG-4264: do not duplicate strings needlessly
[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
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(NullPointerException.class);
205         BindingGeneratorUtil.packageNameForGeneratedType(null, null);
206     }
207
208     /**
209      * Test for the method
210      * <ul>
211      * <li>{@link BindingGeneratorUtil#packageNameForGeneratedType()
212      * packageNameForGeneratedType()}</li>
213      * </ul>
214      */
215     @Test
216     public void testPackageNameForGeneratedTypeNullSchemaPath() {
217         expectedEx.expect(NullPointerException.class);
218         BindingGeneratorUtil.packageNameForGeneratedType("test.package", null);
219     }
220
221     /**
222      * Test for the method
223      * <ul>
224      * <li>{@link BindingGeneratorUtil#parseToClassName()
225      * parseToClassName()}</li>
226      * </ul>
227      */
228     @Test
229     public void testParseToClassNameNullValue() {
230         String className = BindingGeneratorUtil.parseToClassName("test-class-name");
231         assertEquals("TestClassName", className);
232
233         expectedEx.expect(IllegalArgumentException.class);
234         expectedEx.expectMessage("Name can not be null");
235         className = BindingGeneratorUtil.parseToClassName(null);
236     }
237
238     /**
239      * Test for the method
240      * <ul>
241      * <li>{@link BindingGeneratorUtil#parseToClassName()
242      * parseToClassName()}</li>
243      * </ul>
244      */
245     @Test
246     public void testParseToClassNameEmptyValue() {
247         String className = BindingGeneratorUtil.parseToClassName("test-class-name");
248         assertEquals("TestClassName", className);
249
250         expectedEx.expect(IllegalArgumentException.class);
251         expectedEx.expectMessage("Name can not be empty");
252         className = BindingGeneratorUtil.parseToClassName("");
253     }
254
255     /**
256      * Test for the method
257      * <ul>
258      * <li>{@link BindingGeneratorUtil#validateParameterName()
259      * validateParameterName()}</li>
260      * <ul>
261      */
262     @Test
263     public void testValidateParameterName() {
264         assertNull("Return value is incorrect.", BindingGeneratorUtil.resolveJavaReservedWordEquivalency(null));
265         assertEquals("Return value is incorrect.", "whatever",
266                 BindingGeneratorUtil.resolveJavaReservedWordEquivalency("whatever"));
267         assertEquals("Return value is incorrect.", "_case",
268                 BindingGeneratorUtil.resolveJavaReservedWordEquivalency("case"));
269     }
270
271     /**
272      * Tests the methods:
273      * <ul>
274      * <li>parseToClassName</li>
275      * <ul>
276      * <li>parseToCamelCase</li>
277      * <ul>
278      * <li>replaceWithCamelCase</li>
279      * </ul>
280      * </ul> <li>parseToValidParamName</li>
281      * <ul>
282      * <li>parseToCamelCase</li>
283      * <ul>
284      * <li>replaceWithCamelCase</li>
285      * </ul>
286      * </ul>
287      * <ul>
288      */
289     @Test
290     public void testParsingMethods() {
291         // parseToClassName method testing
292         assertEquals("Class name has incorrect format", "SomeTestingClassName",
293                 BindingMapping.getClassName("  some-testing_class name   "));
294         assertEquals("Class name has incorrect format", "_0SomeTestingClassName",
295                 BindingMapping.getClassName("  0 some-testing_class name   "));
296
297         // parseToValidParamName
298         assertEquals("Parameter name has incorrect format", "someTestingParameterName",
299                 BindingGeneratorUtil.parseToValidParamName("  some-testing_parameter   name   "));
300         assertEquals("Parameter name has incorrect format", "_0someTestingParameterName",
301                 BindingGeneratorUtil.parseToValidParamName("  0some-testing_parameter   name   "));
302     }
303
304     @Test
305     public void computeDefaultSUIDTest() {
306         GeneratedTypeBuilderImpl generatedTypeBuilder = new GeneratedTypeBuilderImpl("my.package", "MyName");
307
308         MethodSignatureBuilder method = generatedTypeBuilder.addMethod("myMethodName");
309         method.setAccessModifier(AccessModifier.PUBLIC);
310         generatedTypeBuilder.addProperty("myProperty");
311         generatedTypeBuilder.addImplementsType(Types.typeForClass(Serializable.class));
312
313         assertEquals(6788238694991761868L, BindingGeneratorUtil.computeDefaultSUID(generatedTypeBuilder));
314
315     }
316
317     @Test
318     public void getRestrictionsTest() {
319
320         Optional<String> absent = Optional.absent();
321
322         Builder extTypeBuilder = ExtendedType.builder(new QName(URI.create("namespace"), "localName"),
323                 Int16.getInstance(), absent, absent, SchemaPath.create(true, QName.create("/root")));
324
325         ArrayList<LengthConstraint> lenght = new ArrayList<LengthConstraint>();
326         ArrayList<RangeConstraint> range = new ArrayList<RangeConstraint>();
327         ArrayList<PatternConstraint> pattern = new ArrayList<PatternConstraint>();
328
329         lenght.add(BaseConstraints.newLengthConstraint(1, 2, absent, absent));
330         range.add(BaseConstraints.newRangeConstraint(1, 2, absent, absent));
331         pattern.add(BaseConstraints.newPatternConstraint(".*", absent, absent));
332
333         extTypeBuilder.lengths(lenght);
334         extTypeBuilder.ranges(range);
335         extTypeBuilder.patterns(pattern);
336
337         Restrictions restrictions = BindingGeneratorUtil.getRestrictions(extTypeBuilder.build());
338
339         assertNotNull(restrictions);
340
341         assertEquals(1, restrictions.getLengthConstraints().size());
342         assertEquals(1, restrictions.getRangeConstraints().size());
343         assertEquals(1, restrictions.getPatternConstraints().size());
344
345         assertFalse(restrictions.isEmpty());
346         assertTrue(restrictions.getLengthConstraints().contains(
347                 BaseConstraints.newLengthConstraint(1, 2, absent, absent)));
348         assertTrue(restrictions.getRangeConstraints()
349                 .contains(BaseConstraints.newRangeConstraint(1, 2, absent, absent)));
350         assertTrue(restrictions.getPatternConstraints().contains(
351                 BaseConstraints.newPatternConstraint(".*", absent, absent)));
352     }
353
354     @Test
355     public void getEmptyRestrictionsTest() {
356
357         Optional<String> absent = Optional.absent();
358
359         Builder extTypeBuilder = ExtendedType.builder(new QName(URI.create("namespace"), "localName"),
360                 StringType.getInstance(), absent, absent, SchemaPath.create(true, QName.create("/root")));
361
362         Restrictions restrictions = BindingGeneratorUtil.getRestrictions(extTypeBuilder.build());
363
364         assertNotNull(restrictions);
365         assertTrue(restrictions.isEmpty());
366
367     }
368
369     @Test
370     public void getDefaultIntegerRestrictionsTest() {
371
372         Optional<String> absent = Optional.absent();
373
374         Builder extTypeBuilder = ExtendedType.builder(new QName(URI.create("namespace"), "localName"),
375                 Int16.getInstance(), absent, absent, SchemaPath.create(true, QName.create("/root")));
376
377         ExtendedType extType = extTypeBuilder.build();
378         Restrictions restrictions = BindingGeneratorUtil.getRestrictions(extType);
379
380         assertNotNull(restrictions);
381         assertFalse(restrictions.isEmpty());
382         assertEquals(((IntegerTypeDefinition) extType.getBaseType()).getRangeConstraints(),
383                 restrictions.getRangeConstraints());
384         assertTrue(restrictions.getLengthConstraints().isEmpty());
385         assertTrue(restrictions.getPatternConstraints().isEmpty());
386
387     }
388
389     @Test
390     public void getDefaultUnsignedIntegerRestrictionsTest() {
391
392         Optional<String> absent = Optional.absent();
393
394         Builder extTypeBuilder = ExtendedType.builder(new QName(URI.create("namespace"), "localName"),
395                 Uint16.getInstance(), absent, absent, SchemaPath.create(true, QName.create("/root")));
396
397         ExtendedType extType = extTypeBuilder.build();
398         Restrictions restrictions = BindingGeneratorUtil.getRestrictions(extType);
399
400         assertNotNull(restrictions);
401         assertFalse(restrictions.isEmpty());
402         assertEquals(((UnsignedIntegerTypeDefinition) extType.getBaseType()).getRangeConstraints(),
403                 restrictions.getRangeConstraints());
404         assertTrue(restrictions.getLengthConstraints().isEmpty());
405         assertTrue(restrictions.getPatternConstraints().isEmpty());
406     }
407
408     @Test
409     public void getDefaultDecimalRestrictionsTest() {
410
411         Optional<String> absent = Optional.absent();
412         SchemaPath path = SchemaPath.create(true, QName.create("/root"));
413
414         Builder extTypeBuilder = ExtendedType.builder(new QName(URI.create("namespace"), "localName"),
415                 Decimal64.create(path, 10), absent, absent, path);
416
417         ExtendedType extType = extTypeBuilder.build();
418         Restrictions restrictions = BindingGeneratorUtil.getRestrictions(extType);
419
420         assertNotNull(restrictions);
421         assertFalse(restrictions.isEmpty());
422         assertEquals(((DecimalTypeDefinition) extType.getBaseType()).getRangeConstraints(),
423                 restrictions.getRangeConstraints());
424         assertTrue(restrictions.getLengthConstraints().isEmpty());
425         assertTrue(restrictions.getPatternConstraints().isEmpty());
426
427     }
428
429 }