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