Merge "Resolved some sonar issues: Simplify Boolean Expression"
[yangtools.git] / code-generator / 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.*;
11
12 import java.io.File;
13 import java.io.IOException;
14 import java.io.Serializable;
15 import java.net.URI;
16 import java.net.URISyntaxException;
17 import java.util.ArrayList;
18 import java.util.List;
19 import java.util.Set;
20
21 import com.google.common.base.Optional;
22
23 import org.junit.Test;
24 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
25 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
26 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
27 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
28 import org.opendaylight.yangtools.yang.binding.BindingMapping;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.Module;
32 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
33 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
34 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
35 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
36 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
37 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
38 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
39 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
40 import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
41 import org.opendaylight.yangtools.yang.model.util.BaseConstraints;
42 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
43 import org.opendaylight.yangtools.yang.model.util.Decimal64;
44 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
45 import org.opendaylight.yangtools.yang.model.util.ExtendedType.Builder;
46 import org.opendaylight.yangtools.yang.model.util.Int16;
47 import org.opendaylight.yangtools.yang.model.util.StringType;
48 import org.opendaylight.yangtools.yang.model.util.Uint16;
49 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
50 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
51
52 public class BindingGeneratorUtilTest {
53
54     private static List<File> loadTestResources(String testFile) {
55         final List<File> testModels = new ArrayList<File>();
56         File listModelFile;
57         try {
58             listModelFile = new File(BindingGeneratorUtilTest.class.getResource(testFile).toURI());
59         } catch (URISyntaxException e) {
60             throw new IllegalArgumentException("Failed to load sources from " + testFile);
61         }
62         testModels.add(listModelFile);
63         return testModels;
64     }
65
66     /**
67      * Tests methods:
68      * <ul>
69      * <li>moduleNamespaceToPackageName</li> - with revision
70      * <li>packageNameForGeneratedType</li>
71      * <ul>
72      * <li>validateJavaPackage</li>
73      * </ul>
74      * <li>packageNameForTypeDefinition</li> <li>moduleNamespaceToPackageName</li>
75      * - without revision </ul>
76      */
77     @Test
78     public void testBindingGeneratorUtilMethods() throws IOException {
79         List<File> testModels = loadTestResources("/module.yang");
80         final YangContextParser parser = new YangParserImpl();
81         final Set<Module> modules = parser.parseFiles(testModels).getModules();
82         String packageName = "";
83         Module module = null;
84         for (Module m : modules) {
85             module = m;
86             break;
87         }
88         assertNotNull("Module can't be null", module);
89
90         // test of the method moduleNamespaceToPackageName()
91         packageName = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
92         assertEquals("Generated package name is incorrect.",
93                 "org.opendaylight.yang.gen.v1.urn.m.o.d.u.l.e.n.a.m.e.t.e.s.t._case._1digit.rev130910", packageName);
94
95         // test of the method packageNameForGeneratedType()
96         DataNodeIterator it = new DataNodeIterator(module);
97         List<ContainerSchemaNode> schemaContainers = it.allContainers();
98         String subPackageNameForDataNode = "";
99         for (ContainerSchemaNode containerSchemaNode : schemaContainers) {
100             if (containerSchemaNode.getQName().getLocalName().equals("cont-inner")) {
101                 subPackageNameForDataNode = BindingGeneratorUtil.packageNameForGeneratedType(packageName,
102                         containerSchemaNode.getPath());
103                 break;
104             }
105         }
106         assertEquals("The name of the subpackage 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.cont.outter",
108                 subPackageNameForDataNode);
109
110         // test of the method packageNameForTypeDefinition
111         Set<TypeDefinition<?>> typeDefinitions = module.getTypeDefinitions();
112         String subPackageNameForTypeDefinition = "";
113         for (TypeDefinition<?> tpDef : typeDefinitions) {
114             if (tpDef.getQName().getLocalName().equals("tpdf")) {
115                 subPackageNameForTypeDefinition = BindingGeneratorUtil.packageNameForTypeDefinition(packageName, tpDef);
116                 break;
117             }
118         }
119         assertEquals("The name of the subpackage is incorrect.",
120                 "org.opendaylight.yang.gen.v1.urn.m.o.d.u.l.e.n.a.m.e.t.e.s.t._case._1digit.rev130910",
121                 subPackageNameForTypeDefinition);
122
123         // test of exception part of the method moduleNamespaceToPackageName()
124         ModuleBuilder moduleBuilder = new ModuleBuilder("module-withut-revision", null);
125         moduleBuilder.setSource("");
126         Module moduleWithoutRevision = moduleBuilder.build();
127         boolean passedSuccesfully = false;
128         try {
129             BindingGeneratorUtil.moduleNamespaceToPackageName(moduleWithoutRevision);
130             passedSuccesfully = true;
131         } catch (IllegalArgumentException e) {
132         }
133         assertFalse("Exception 'IllegalArgumentException' wasn't raised", passedSuccesfully);
134
135     }
136
137     /**
138      * Test for the method
139      * <ul>
140      * <li>{@link BindingGeneratorUtil#validateParameterName()
141      * validateParameterName()}</li>
142      * <ul>
143      */
144     @Test
145     public void testValidateParameterName() {
146         assertNull("Return value is incorrect.", BindingGeneratorUtil.resolveJavaReservedWordEquivalency(null));
147         assertEquals("Return value is incorrect.", "whatever",
148                 BindingGeneratorUtil.resolveJavaReservedWordEquivalency("whatever"));
149         assertEquals("Return value is incorrect.", "_case",
150                 BindingGeneratorUtil.resolveJavaReservedWordEquivalency("case"));
151     }
152
153     /**
154      * Tests the methods:
155      * <ul>
156      * <li>parseToClassName</li>
157      * <ul>
158      * <li>parseToCamelCase</li>
159      * <ul>
160      * <li>replaceWithCamelCase</li>
161      * </ul>
162      * </ul> <li>parseToValidParamName</li>
163      * <ul>
164      * <li>parseToCamelCase</li>
165      * <ul>
166      * <li>replaceWithCamelCase</li>
167      * </ul>
168      * </ul>
169      * <ul>
170      */
171     @Test
172     public void testParsingMethods() {
173         // parseToClassName method testing
174         assertEquals("Class name has incorrect format", "SomeTestingClassName",
175                 BindingMapping.getClassName("  some-testing_class name   "));
176         assertEquals("Class name has incorrect format", "_0SomeTestingClassName",
177                 BindingMapping.getClassName("  0 some-testing_class name   "));
178
179         // parseToValidParamName
180         assertEquals("Parameter name has incorrect format", "someTestingParameterName",
181                 BindingGeneratorUtil.parseToValidParamName("  some-testing_parameter   name   "));
182         assertEquals("Parameter name has incorrect format", "_0someTestingParameterName",
183                 BindingGeneratorUtil.parseToValidParamName("  0some-testing_parameter   name   "));
184     }
185
186     @Test
187     public void computeDefaultSUIDTest() {
188         GeneratedTypeBuilderImpl generatedTypeBuilder = new GeneratedTypeBuilderImpl("my.package", "MyName");
189
190         MethodSignatureBuilder method = generatedTypeBuilder.addMethod("myMethodName");
191         method.setAccessModifier(AccessModifier.PUBLIC);
192         generatedTypeBuilder.addProperty("myProperty");
193         generatedTypeBuilder.addImplementsType(Types.typeForClass(Serializable.class));
194
195         assertEquals(6788238694991761868L, BindingGeneratorUtil.computeDefaultSUID(generatedTypeBuilder));
196
197     }
198
199     @Test
200     public void getRestrictionsTest() {
201
202         Optional<String> absent = Optional.absent();
203
204         Builder extTypeBuilder = ExtendedType.builder(new QName(URI.create("namespace"), "localName"),
205                 Int16.getInstance(), absent, absent, SchemaPath.create(true, QName.create("/root")));
206
207         ArrayList<LengthConstraint> lenght = new ArrayList<LengthConstraint>();
208         ArrayList<RangeConstraint> range = new ArrayList<RangeConstraint>();
209         ArrayList<PatternConstraint> pattern = new ArrayList<PatternConstraint>();
210
211         lenght.add(BaseConstraints.newLengthConstraint(1, 2, absent, absent));
212         range.add(BaseConstraints.newRangeConstraint(1, 2, absent, absent));
213         pattern.add(BaseConstraints.newPatternConstraint(".*", absent, absent));
214
215         extTypeBuilder.lengths(lenght);
216         extTypeBuilder.ranges(range);
217         extTypeBuilder.patterns(pattern);
218
219         Restrictions restrictions = BindingGeneratorUtil.getRestrictions(extTypeBuilder.build());
220
221         assertNotNull(restrictions);
222
223         assertEquals(1, restrictions.getLengthConstraints().size());
224         assertEquals(1, restrictions.getRangeConstraints().size());
225         assertEquals(1, restrictions.getPatternConstraints().size());
226
227         assertFalse(restrictions.isEmpty());
228         assertTrue(restrictions.getLengthConstraints().contains(
229                 BaseConstraints.newLengthConstraint(1, 2, absent, absent)));
230         assertTrue(restrictions.getRangeConstraints()
231                 .contains(BaseConstraints.newRangeConstraint(1, 2, absent, absent)));
232         assertTrue(restrictions.getPatternConstraints().contains(
233                 BaseConstraints.newPatternConstraint(".*", absent, absent)));
234     }
235
236     @Test
237     public void getEmptyRestrictionsTest() {
238
239         Optional<String> absent = Optional.absent();
240
241         Builder extTypeBuilder = ExtendedType.builder(new QName(URI.create("namespace"), "localName"),
242                 StringType.getInstance(), absent, absent, SchemaPath.create(true, QName.create("/root")));
243
244         Restrictions restrictions = BindingGeneratorUtil.getRestrictions(extTypeBuilder.build());
245
246         assertNotNull(restrictions);
247         assertTrue(restrictions.isEmpty());
248
249     }
250
251     @Test
252     public void getDefaultIntegerRestrictionsTest() {
253
254         Optional<String> absent = Optional.absent();
255
256         Builder extTypeBuilder = ExtendedType.builder(new QName(URI.create("namespace"), "localName"),
257                 Int16.getInstance(), absent, absent, SchemaPath.create(true, QName.create("/root")));
258
259         ExtendedType extType = extTypeBuilder.build();
260         Restrictions restrictions = BindingGeneratorUtil.getRestrictions(extType);
261
262         assertNotNull(restrictions);
263         assertFalse(restrictions.isEmpty());
264         assertEquals(((IntegerTypeDefinition) extType.getBaseType()).getRangeConstraints(),
265                 restrictions.getRangeConstraints());
266         assertTrue(restrictions.getLengthConstraints().isEmpty());
267         assertTrue(restrictions.getPatternConstraints().isEmpty());
268
269     }
270
271     @Test
272     public void getDefaultUnsignedIntegerRestrictionsTest() {
273
274         Optional<String> absent = Optional.absent();
275
276         Builder extTypeBuilder = ExtendedType.builder(new QName(URI.create("namespace"), "localName"),
277                 Uint16.getInstance(), absent, absent, SchemaPath.create(true, QName.create("/root")));
278
279         ExtendedType extType = extTypeBuilder.build();
280         Restrictions restrictions = BindingGeneratorUtil.getRestrictions(extType);
281
282         assertNotNull(restrictions);
283         assertFalse(restrictions.isEmpty());
284         assertEquals(((UnsignedIntegerTypeDefinition) extType.getBaseType()).getRangeConstraints(),
285                 restrictions.getRangeConstraints());
286         assertTrue(restrictions.getLengthConstraints().isEmpty());
287         assertTrue(restrictions.getPatternConstraints().isEmpty());
288     }
289
290     @Test
291     public void getDefaultDecimalRestrictionsTest() {
292
293         Optional<String> absent = Optional.absent();
294         SchemaPath path = SchemaPath.create(true, QName.create("/root"));
295
296         Builder extTypeBuilder = ExtendedType.builder(new QName(URI.create("namespace"), "localName"),
297                 Decimal64.create(path, 10), absent, absent, path);
298
299         ExtendedType extType = extTypeBuilder.build();
300         Restrictions restrictions = BindingGeneratorUtil.getRestrictions(extType);
301
302         assertNotNull(restrictions);
303         assertFalse(restrictions.isEmpty());
304         assertEquals(((DecimalTypeDefinition) extType.getBaseType()).getRangeConstraints(),
305                 restrictions.getRangeConstraints());
306         assertTrue(restrictions.getLengthConstraints().isEmpty());
307         assertTrue(restrictions.getPatternConstraints().isEmpty());
308
309     }
310
311 }