Integrate JavaTypeName as Identifier
[mdsal.git] / binding / mdsal-binding-generator-util / src / test / java / org / opendaylight / mdsal / binding / model / 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.mdsal.binding.model.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 static org.junit.Assert.fail;
17 import static org.mockito.Mockito.doReturn;
18 import static org.mockito.Mockito.mock;
19
20 import com.google.common.collect.ImmutableList;
21 import com.google.common.collect.ImmutableSet;
22 import com.google.common.collect.Range;
23 import java.io.Serializable;
24 import java.util.List;
25 import java.util.Optional;
26 import java.util.Set;
27 import org.junit.Rule;
28 import org.junit.Test;
29 import org.junit.rules.ExpectedException;
30 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
31 import org.opendaylight.mdsal.binding.model.api.Restrictions;
32 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
33 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
34 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
35 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.CodegenGeneratedTypeBuilder;
36 import org.opendaylight.yangtools.yang.binding.BindingMapping;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.model.api.ConstraintMetaDefinition;
39 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.Module;
41 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
42 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.stmt.ValueRange;
44 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
45 import org.opendaylight.yangtools.yang.model.api.type.Int16TypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.type.Uint16TypeDefinition;
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.type.BaseTypes;
50 import org.opendaylight.yangtools.yang.model.util.type.DerivedTypes;
51 import org.opendaylight.yangtools.yang.model.util.type.InvalidLengthConstraintException;
52 import org.opendaylight.yangtools.yang.model.util.type.RestrictedTypes;
53 import org.opendaylight.yangtools.yang.model.util.type.StringTypeBuilder;
54 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
55
56 public class BindingGeneratorUtilTest {
57     private static final SchemaPath ROOT_PATH = SchemaPath.create(true, QName.create("test", "/root"));
58
59     @Rule
60     public ExpectedException expectedEx = ExpectedException.none();
61
62     /**
63      * Tests methods:
64      * <ul>
65      * <li>moduleNamespaceToPackageName</li> - with revision
66      * <li>packageNameForGeneratedType</li>
67      * <ul>
68      * <li>validateJavaPackage</li>
69      * </ul>
70      * <li>packageNameForTypeDefinition</li> <li>moduleNamespaceToPackageName</li>
71      * - without revision </ul>
72      */
73     @Test
74     public void testBindingGeneratorUtilMethods() {
75         final Set<Module> modules = YangParserTestUtils.parseYangResources(BindingGeneratorUtilTest.class,
76             "/module.yang").getModules();
77         String packageName = "";
78         Module module = null;
79         for (Module m : modules) {
80             module = m;
81             break;
82         }
83         assertNotNull("Module can't be null", module);
84
85         // test of the method moduleNamespaceToPackageName()
86         packageName = BindingMapping.getRootPackageName(module.getQNameModule());
87         assertEquals("Generated package name is incorrect.",
88                 "org.opendaylight.yang.gen.v1.urn.m.o.d.u.l.e.n.a.m.e.t.e.s.t._case._1digit.rev130910", packageName);
89
90         // test of the method packageNameForGeneratedType()
91         DataNodeIterator it = new DataNodeIterator(module);
92         List<ContainerSchemaNode> schemaContainers = it.allContainers();
93         String subPackageNameForDataNode = "";
94         for (ContainerSchemaNode containerSchemaNode : schemaContainers) {
95             if (containerSchemaNode.getQName().getLocalName().equals("cont-inner")) {
96                 subPackageNameForDataNode = BindingGeneratorUtil.packageNameForGeneratedType(packageName,
97                         containerSchemaNode.getPath());
98                 break;
99             }
100         }
101         assertEquals("The name of the subpackage 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.cont.outter",
103                 subPackageNameForDataNode);
104
105         // test of the method packageNameForTypeDefinition
106         Set<TypeDefinition<?>> typeDefinitions = module.getTypeDefinitions();
107         String subPackageNameForTypeDefinition = "";
108         TypeDefinition<?> firstTypeDef = null;
109
110         for (TypeDefinition<?> tpDef : typeDefinitions) {
111             if (tpDef.getQName().getLocalName().equals("tpdf")) {
112                 subPackageNameForTypeDefinition = BindingGeneratorUtil.packageNameForTypeDefinition(packageName, tpDef);
113                 firstTypeDef = tpDef;
114                 break;
115             }
116         }
117         assertEquals("The name of the subpackage is incorrect.",
118                 "org.opendaylight.yang.gen.v1.urn.m.o.d.u.l.e.n.a.m.e.t.e.s.t._case._1digit.rev130910",
119                 subPackageNameForTypeDefinition);
120
121         // test method getRestrictions
122         Restrictions restriction = BindingGeneratorUtil.getRestrictions(firstTypeDef);
123         assertNotNull(restriction);
124
125         // test method computeDefaultSUID
126         GeneratedTypeBuilder genTypeBuilder = new CodegenGeneratedTypeBuilder(
127             JavaTypeName.create("org.opendaylight.yangtools.test", "TestType"));
128         genTypeBuilder.addMethod("testMethod");
129         genTypeBuilder.addAnnotation("org.opendaylight.yangtools.test.annotation", "AnnotationTest");
130         genTypeBuilder.addEnclosingTransferObject("testObject");
131         genTypeBuilder.addProperty("newProp");
132         GeneratedTypeBuilder genType = new CodegenGeneratedTypeBuilder(
133             JavaTypeName.create("org.opendaylight.yangtools.test", "Type2"));
134         genTypeBuilder.addImplementsType(genType);
135         long computedSUID = BindingGeneratorUtil.computeDefaultSUID(genTypeBuilder);
136
137         GeneratedTypeBuilder genTypeBuilder2 = new CodegenGeneratedTypeBuilder(
138             JavaTypeName.create("org.opendaylight.yangtools.test2", "TestType2"));
139         long computedSUID2 = BindingGeneratorUtil.computeDefaultSUID(genTypeBuilder2);
140         assertNotEquals(computedSUID, computedSUID2);
141
142         // test of exception part of the method moduleNamespaceToPackageName()
143         Module moduleWithoutRevision = mock(Module.class);
144         doReturn(null).when(moduleWithoutRevision).getQNameModule();
145         try {
146             BindingGeneratorUtil.moduleNamespaceToPackageName(moduleWithoutRevision);
147             fail("Expected IllegalArgumentException");
148         } catch (IllegalArgumentException e) {
149         }
150     }
151
152     /**
153      * Test for the method
154      * &lt;ul&gt;
155      * &lt;li&gt;{@link BindingGeneratorUtil#packageNameForTypeDefinition(String, TypeDefinition)
156      * packageNameForTypeDefinition(String, TypeDefinition)}&lt;/li&gt;
157      * &lt;/ul&gt;
158      */
159     @Test
160     @Deprecated
161     public void testPackageNameForTypeDefinitionNullBasePackageName() {
162         expectedEx.expect(IllegalArgumentException.class);
163         expectedEx.expectMessage("Base Package Name cannot be NULL!");
164         BindingGeneratorUtil.packageNameForTypeDefinition(null, null);
165     }
166
167     /**
168      * Test for the method
169      * &lt;ul&gt;
170      * &lt;li&gt;{@link BindingGeneratorUtil#packageNameForTypeDefinition(String, TypeDefinition)
171      * packageNameForTypeDefinition(String, TypeDefinition)}&lt;/li&gt;
172      * &lt;/ul&gt;
173      */
174     @Test
175     @Deprecated
176     public void testPackageNameForTypeDefinitionNullTypeDefinition() {
177         expectedEx.expect(IllegalArgumentException.class);
178         expectedEx.expectMessage("Type Definition reference cannot be NULL!");
179         BindingGeneratorUtil.packageNameForTypeDefinition("test.package", null);
180     }
181
182     /**
183      * Test for the method
184      * &lt;ul&gt;
185      * &lt;li&gt;{@link BindingGeneratorUtil#packageNameForGeneratedType(String, SchemaPath)
186      * packageNameForGeneratedType(String, SchemaPath)}&lt;/li&gt;
187      * &lt;/ul&gt;
188      */
189     @Test
190     public void testPackageNameForGeneratedTypeNullBasePackageName() {
191         expectedEx.expect(NullPointerException.class);
192         BindingGeneratorUtil.packageNameForGeneratedType(null, null);
193     }
194
195     /**
196      * Test for the method
197      * &lt;ul&gt;
198      * &lt;li&gt;{@link BindingGeneratorUtil#packageNameForGeneratedType(String, SchemaPath)
199      * packageNameForGeneratedType(String, SchemaPath)}&lt;/li&gt;
200      * &lt;/ul&gt;
201      */
202     @Test
203     public void testPackageNameForGeneratedTypeNullSchemaPath() {
204         expectedEx.expect(NullPointerException.class);
205         BindingGeneratorUtil.packageNameForGeneratedType("test.package", null);
206     }
207
208     /**
209      * Test for the method
210      * &lt;ul&gt;
211      * &lt;li&gt;{@link BindingGeneratorUtil#parseToClassName(String)
212      * parseToClassName(String)}&lt;/li&gt;
213      * &lt;/ul&gt;
214      */
215     @Test
216     public void testParseToClassNameNullValue() {
217         String className = BindingGeneratorUtil.parseToClassName("test-class-name");
218         assertEquals("TestClassName", className);
219
220         expectedEx.expect(IllegalArgumentException.class);
221         expectedEx.expectMessage("Name can not be null");
222         className = BindingGeneratorUtil.parseToClassName(null);
223     }
224
225     /**
226      * Test for the method
227      * &lt;ul&gt;
228      * &lt;li&gt;{@link BindingGeneratorUtil#parseToClassName(String)
229      * parseToClassName(String)}&lt;/li&gt;
230      * &lt;/ul&gt;
231      */
232     @Test
233     public void testParseToClassNameEmptyValue() {
234         String className = BindingGeneratorUtil.parseToClassName("test-class-name");
235         assertEquals("TestClassName", className);
236
237         expectedEx.expect(IllegalArgumentException.class);
238         expectedEx.expectMessage("Name can not be empty");
239         className = BindingGeneratorUtil.parseToClassName("");
240     }
241
242     /**
243      * Test for the method
244      * &lt;ul&gt;
245      * &lt;li&gt;{@link BindingGeneratorUtil#resolveJavaReservedWordEquivalency(String)
246      * resolveJavaReservedWordEquivalency(String)}&lt;/li&gt;
247      * &lt;ul&gt;
248      */
249     @Test
250     public void testValidateParameterName() {
251         assertNull("Return value is incorrect.", BindingGeneratorUtil.resolveJavaReservedWordEquivalency(null));
252         assertEquals("Return value is incorrect.", "whatever",
253                 BindingGeneratorUtil.resolveJavaReservedWordEquivalency("whatever"));
254         assertEquals("Return value is incorrect.", "_case",
255                 BindingGeneratorUtil.resolveJavaReservedWordEquivalency("case"));
256     }
257
258     /**
259      * Tests the methods:
260      * &lt;ul&gt;
261      * &lt;li&gt;parseToClassName&lt;/li&gt;
262      * &lt;ul&gt;
263      * &lt;li&gt;parseToCamelCase&lt;/li&gt;
264      * &lt;ul&gt;
265      * &lt;li&gt;replaceWithCamelCase&lt;/li&gt;
266      * &lt;/ul&gt;
267      * &lt;/ul&gt; &lt;li&gt;parseToValidParamName&lt;/li&gt;
268      * &lt;ul&gt;
269      * &lt;li&gt;parseToCamelCase&lt;/li&gt;
270      * &lt;ul&gt;
271      * &lt;li&gt;replaceWithCamelCase&lt;/li&gt;
272      * &lt;/ul&gt;
273      * &lt;/ul&gt;
274      * &lt;ul&gt;
275      */
276     @Test
277     public void testParsingMethods() {
278         // parseToClassName method testing
279         assertEquals("Class name has incorrect format", "SomeTestingClassName",
280                 BindingMapping.getClassName("  some-testing_class name   "));
281         assertEquals("Class name has incorrect format", "_0SomeTestingClassName",
282                 BindingMapping.getClassName("  0 some-testing_class name   "));
283
284         // parseToValidParamName
285         assertEquals("Parameter name has incorrect format", "someTestingParameterName",
286                 BindingGeneratorUtil.parseToValidParamName("  some-testing_parameter   name   "));
287         assertEquals("Parameter name has incorrect format", "_0someTestingParameterName",
288                 BindingGeneratorUtil.parseToValidParamName("  0some-testing_parameter   name   "));
289     }
290
291     @Test
292     public void computeDefaultSUIDTest() {
293         CodegenGeneratedTypeBuilder generatedTypeBuilder = new CodegenGeneratedTypeBuilder(
294             JavaTypeName.create("my.package", "MyName"));
295
296         MethodSignatureBuilder method = generatedTypeBuilder.addMethod("myMethodName");
297         method.setAccessModifier(AccessModifier.PUBLIC);
298         generatedTypeBuilder.addProperty("myProperty");
299         generatedTypeBuilder.addImplementsType(Types.typeForClass(Serializable.class));
300
301         assertEquals(6788238694991761868L, BindingGeneratorUtil.computeDefaultSUID(generatedTypeBuilder));
302
303     }
304
305     @Test
306     public void getRestrictionsTest() throws InvalidLengthConstraintException {
307         final Optional<String> absent = Optional.empty();
308         final StringTypeBuilder builder =
309                 RestrictedTypes.newStringBuilder(BaseTypes.stringType(), ROOT_PATH);
310
311         builder.addPatternConstraint(BaseConstraints.newPatternConstraint(".*", absent, absent));
312         builder.setLengthConstraint(mock(ConstraintMetaDefinition.class), ImmutableList.of(ValueRange.of(1, 2)));
313
314         Restrictions restrictions = BindingGeneratorUtil.getRestrictions(builder.build());
315
316         assertNotNull(restrictions);
317         assertEquals(ImmutableSet.of(Range.closed(1, 2)),
318             restrictions.getLengthConstraint().get().getAllowedRanges().asRanges());
319         assertFalse(restrictions.getRangeConstraint().isPresent());
320         assertEquals(1, restrictions.getPatternConstraints().size());
321
322         assertFalse(restrictions.isEmpty());
323         assertTrue(restrictions.getPatternConstraints().contains(
324                 BaseConstraints.newPatternConstraint(".*", absent, absent)));
325     }
326
327     @Test
328     public void getEmptyRestrictionsTest() {
329         final TypeDefinition<?> type = DerivedTypes.derivedTypeBuilder(BaseTypes.stringType(), ROOT_PATH).build();
330         final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(type);
331
332         assertNotNull(restrictions);
333         assertTrue(restrictions.isEmpty());
334     }
335
336     @Test
337     public void getDefaultIntegerRestrictionsTest() {
338         final TypeDefinition<?> type = DerivedTypes.derivedTypeBuilder(BaseTypes.int16Type(), ROOT_PATH).build();
339         final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(type);
340
341         assertNotNull(restrictions);
342         assertFalse(restrictions.isEmpty());
343         assertEquals(((Int16TypeDefinition) type.getBaseType()).getRangeConstraint(),
344                 restrictions.getRangeConstraint());
345         assertFalse(restrictions.getLengthConstraint().isPresent());
346         assertTrue(restrictions.getPatternConstraints().isEmpty());
347     }
348
349     @Test
350     public void getDefaultUnsignedIntegerRestrictionsTest() {
351         final TypeDefinition<?> type = DerivedTypes.derivedTypeBuilder(BaseTypes.uint16Type(), ROOT_PATH).build();
352         final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(type);
353
354         assertNotNull(restrictions);
355         assertFalse(restrictions.isEmpty());
356         assertEquals(((Uint16TypeDefinition) type.getBaseType()).getRangeConstraint(),
357                 restrictions.getRangeConstraint());
358         assertFalse(restrictions.getLengthConstraint().isPresent());
359         assertTrue(restrictions.getPatternConstraints().isEmpty());
360     }
361
362     @Test
363     public void getDefaultDecimalRestrictionsTest() {
364         final DecimalTypeDefinition base = BaseTypes.decimalTypeBuilder(ROOT_PATH).setFractionDigits(10).build();
365         final TypeDefinition<?> type = DerivedTypes.derivedTypeBuilder(base, ROOT_PATH).build();
366
367         final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(type);
368
369         assertNotNull(restrictions);
370         assertFalse(restrictions.isEmpty());
371         assertEquals(base.getRangeConstraint(), restrictions.getRangeConstraint());
372         assertFalse(restrictions.getLengthConstraint().isPresent());
373         assertTrue(restrictions.getPatternConstraints().isEmpty());
374     }
375
376     @Test
377     public void unicodeCharReplaceTest() {
378         String inputString = "abcu\\uuuuu\\uuua\\u\\\\uabc\\\\uuuu\\\\\\uuuu\\\\\\\\uuuu///uu/u/u/u/u/u/u";
379
380         assertEquals("abcu\\\\uuuuu\\\\uuua\\\\u\\\\uabc\\\\uuuu\\\\uuuu\\\\uuuu///uu/u/u/u/u/u/u",
381             BindingGeneratorUtil.replaceAllIllegalChars(inputString));
382     }
383 }