Added tests for yang.model.util
[yangtools.git] / code-generator / maven-sal-api-gen-plugin / src / test / java / org / opendaylight / yangtools / yang / unified / doc / generator / maven / YangModuleInfoCompilationTest.java
1 /*
2  * Copyright (c) 2013 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.yang.unified.doc.generator.maven;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertFalse;
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertTrue;
14
15 import java.io.File;
16 import java.io.FileNotFoundException;
17 import java.lang.reflect.Method;
18 import java.net.URI;
19 import java.net.URL;
20 import java.net.URLClassLoader;
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.List;
24 import java.util.Set;
25 import javax.tools.JavaCompiler;
26 import javax.tools.JavaFileObject;
27 import javax.tools.StandardJavaFileManager;
28 import javax.tools.ToolProvider;
29 import org.junit.BeforeClass;
30 import org.junit.Test;
31 import org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl;
32 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
33 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
34 import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
35 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
36 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
37
38 /**
39  * Test correct generation of YangModuleInfo class.
40  *
41  */
42 // TODO: most of private static methods are copied from
43 // binding-java-api-generator project - reorganize compilation tests
44 public class YangModuleInfoCompilationTest {
45     public static final String FS = File.separator;
46     private static final String BASE_PKG = "org.opendaylight.yang.gen.v1";
47
48     private static final String TEST_PATH = "target" + FS + "test";
49     private static final File TEST_DIR = new File(TEST_PATH);
50
51     private static final String GENERATOR_OUTPUT_PATH = TEST_PATH + FS + "src";
52     private static final File GENERATOR_OUTPUT_DIR = new File(GENERATOR_OUTPUT_PATH);
53     private static final String COMPILER_OUTPUT_PATH = TEST_PATH + FS + "bin";
54     private static final File COMPILER_OUTPUT_DIR = new File(COMPILER_OUTPUT_PATH);
55
56     @BeforeClass
57     public static void createTestDirs() {
58         if (TEST_DIR.exists()) {
59             deleteTestDir(TEST_DIR);
60         }
61         assertTrue(GENERATOR_OUTPUT_DIR.mkdirs());
62         assertTrue(COMPILER_OUTPUT_DIR.mkdirs());
63     }
64
65     @Test
66     public void compilationTest() throws Exception {
67         final File sourcesOutputDir = new File(GENERATOR_OUTPUT_PATH + FS + "yang");
68         assertTrue("Failed to create test file '" + sourcesOutputDir + "'", sourcesOutputDir.mkdirs());
69         final File compiledOutputDir = new File(COMPILER_OUTPUT_PATH + FS + "yang");
70         assertTrue("Failed to create test file '" + compiledOutputDir + "'", compiledOutputDir.mkdirs());
71
72         generateTestSources("/yang-module-info", sourcesOutputDir);
73
74         // Test if $YangModuleInfoImpl.java file is generated
75         final String BASE_PATH = "org" + FS + "opendaylight" + FS + "yang" + FS + "gen" + FS + "v1";
76         final String NS_TEST = BASE_PATH + FS + "yang" + FS + "test" + FS + "main" + FS + "rev140630";
77         File parent = new File(sourcesOutputDir, NS_TEST);
78         File keyArgs = new File(parent, "$YangModuleInfoImpl.java");
79         assertTrue(keyArgs.exists());
80
81         // Test if sources are compilable
82         testCompilation(sourcesOutputDir, compiledOutputDir);
83
84         // Create URLClassLoader
85         File[] roots = File.listRoots();
86         URL[] urls = new URL[roots.length + 1];
87         for (int i = 0; i < roots.length; i++) {
88             urls[i] = roots[i].toURI().toURL();
89
90         }
91         urls[roots.length] = compiledOutputDir.toURI().toURL();
92         ClassLoader loader = new URLClassLoader(urls);
93
94         // Load class
95         Class<?> yangModuleInfoClass = Class.forName(BASE_PKG + ".yang.test.main.rev140630.$YangModuleInfoImpl", true,
96                 loader);
97
98         // Test generated $YangModuleInfoImpl class
99         assertFalse(yangModuleInfoClass.isInterface());
100         Method getInstance = assertContainsMethod(yangModuleInfoClass, YangModuleInfo.class, "getInstance");
101         Object yangModuleInfo = getInstance.invoke(null);
102
103         // Test getImportedModules method
104         Method getImportedModules = assertContainsMethod(yangModuleInfoClass, Set.class, "getImportedModules");
105         Object importedModules = getImportedModules.invoke(yangModuleInfo);
106         assertTrue(importedModules instanceof Set);
107
108         YangModuleInfo infoImport = null;
109         YangModuleInfo infoSub1 = null;
110         YangModuleInfo infoSub2 = null;
111         YangModuleInfo infoSub3 = null;
112         for (Object importedModule : (Set<?>) importedModules) {
113             assertTrue(importedModule instanceof YangModuleInfo);
114             YangModuleInfo ymi = (YangModuleInfo) importedModule;
115             String name = ymi.getName();
116
117             switch (name) {
118             case "import-module":
119                 infoImport = ymi;
120                 break;
121             case "submodule1":
122                 infoSub1 = ymi;
123                 break;
124             case "submodule2":
125                 infoSub2 = ymi;
126                 break;
127             case "submodule3":
128                 infoSub3 = ymi;
129             }
130         }
131         assertNotNull(infoImport);
132         assertNotNull(infoSub1);
133         assertNotNull(infoSub2);
134         assertNotNull(infoSub3);
135
136         cleanUp(sourcesOutputDir, compiledOutputDir);
137     }
138
139     private void generateTestSources(String resourceDirPath, File sourcesOutputDir) throws Exception {
140         final List<File> sourceFiles = getSourceFiles(resourceDirPath);
141         YangContextParser parser = new YangParserImpl();
142         final SchemaContext context = parser.parseFiles(sourceFiles);
143         CodeGeneratorImpl codegen = new CodeGeneratorImpl();
144         codegen.setBuildContext(new DefaultBuildContext());
145         codegen.generateSources(context, sourcesOutputDir, context.getModules());
146     }
147
148     private static void testCompilation(File sourcesOutputDir, File compiledOutputDir) {
149         JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
150         StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
151         List<File> filesList = getJavaFiles(sourcesOutputDir);
152         Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(filesList);
153         Iterable<String> options = Arrays.asList("-d", compiledOutputDir.getAbsolutePath());
154         boolean compiled = compiler.getTask(null, null, null, options, null, compilationUnits).call();
155         assertTrue(compiled);
156     }
157
158     private static List<File> getJavaFiles(File directory) {
159         List<File> result = new ArrayList<>();
160         File[] filesToRead = directory.listFiles();
161         if (filesToRead != null) {
162             for (File file : filesToRead) {
163                 if (file.isDirectory()) {
164                     result.addAll(getJavaFiles(file));
165                 } else {
166                     String absPath = file.getAbsolutePath();
167                     if (absPath.endsWith(".java")) {
168                         result.add(file);
169                     }
170                 }
171             }
172         }
173         return result;
174     }
175
176     private static List<File> getSourceFiles(String path) throws Exception {
177         final URI resPath = YangModuleInfoCompilationTest.class.getResource(path).toURI();
178         final File sourcesDir = new File(resPath);
179         if (sourcesDir.exists()) {
180             final List<File> sourceFiles = new ArrayList<>();
181             final File[] fileArray = sourcesDir.listFiles();
182             if (fileArray == null) {
183                 throw new IllegalArgumentException("Unable to locate files in " + sourcesDir);
184             }
185             sourceFiles.addAll(Arrays.asList(fileArray));
186             return sourceFiles;
187         } else {
188             throw new FileNotFoundException("Testing files were not found(" + sourcesDir.getName() + ")");
189         }
190     }
191
192     private static void deleteTestDir(File file) {
193         if (file.isDirectory()) {
194             File[] filesToDelete = file.listFiles();
195             if (filesToDelete != null) {
196                 for (File f : filesToDelete) {
197                     deleteTestDir(f);
198                 }
199             }
200         }
201         if (!file.delete()) {
202             throw new RuntimeException("Failed to clean up after test");
203         }
204     }
205
206     private static Method assertContainsMethod(Class<?> clazz, Class<?> returnType, String name, Class<?>... args) {
207         try {
208             Method m = clazz.getDeclaredMethod(name, args);
209             assertEquals(returnType, m.getReturnType());
210             return m;
211         } catch (NoSuchMethodException e) {
212             throw new AssertionError("Method " + name + " with args " + Arrays.toString(args)
213                     + " does not exists in class " + clazz.getSimpleName());
214         }
215     }
216
217     private static void cleanUp(File... resourceDirs) {
218         for (File resourceDir : resourceDirs) {
219             if (resourceDir.exists()) {
220                 deleteTestDir(resourceDir);
221             }
222         }
223     }
224
225 }