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