1a1052baa14838f604e6d1d6a068d785911ea126
[mdsal.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         URL[] urls = new URL[2];
86         urls[0] = compiledOutputDir.toURI().toURL();
87         urls[1] = new File(System.getProperty("user.dir")).toURI().toURL();
88         ClassLoader loader = new URLClassLoader(urls);
89
90         // Load class
91         Class<?> yangModuleInfoClass = Class.forName(BASE_PKG + ".yang.test.main.rev140630.$YangModuleInfoImpl", true,
92                 loader);
93
94         // Test generated $YangModuleInfoImpl class
95         assertFalse(yangModuleInfoClass.isInterface());
96         Method getInstance = assertContainsMethod(yangModuleInfoClass, YangModuleInfo.class, "getInstance");
97         Object yangModuleInfo = getInstance.invoke(null);
98
99         // Test getImportedModules method
100         Method getImportedModules = assertContainsMethod(yangModuleInfoClass, Set.class, "getImportedModules");
101         Object importedModules = getImportedModules.invoke(yangModuleInfo);
102         assertTrue(importedModules instanceof Set);
103
104         YangModuleInfo infoImport = null;
105         YangModuleInfo infoSub1 = null;
106         YangModuleInfo infoSub2 = null;
107         YangModuleInfo infoSub3 = null;
108         for (Object importedModule : (Set<?>) importedModules) {
109             assertTrue(importedModule instanceof YangModuleInfo);
110             YangModuleInfo ymi = (YangModuleInfo) importedModule;
111             String name = ymi.getName();
112
113             switch (name) {
114             case "import-module":
115                 infoImport = ymi;
116                 break;
117             case "submodule1":
118                 infoSub1 = ymi;
119                 break;
120             case "submodule2":
121                 infoSub2 = ymi;
122                 break;
123             case "submodule3":
124                 infoSub3 = ymi;
125             }
126         }
127         assertNotNull(infoImport);
128         assertNotNull(infoSub1);
129         assertNotNull(infoSub2);
130         assertNotNull(infoSub3);
131
132         cleanUp(sourcesOutputDir, compiledOutputDir);
133     }
134
135     private void generateTestSources(String resourceDirPath, File sourcesOutputDir) throws Exception {
136         final List<File> sourceFiles = getSourceFiles(resourceDirPath);
137         YangContextParser parser = new YangParserImpl();
138         final SchemaContext context = parser.parseFiles(sourceFiles);
139         CodeGeneratorImpl codegen = new CodeGeneratorImpl();
140         codegen.setBuildContext(new DefaultBuildContext());
141         codegen.generateSources(context, sourcesOutputDir, context.getModules());
142     }
143
144     private static void testCompilation(File sourcesOutputDir, File compiledOutputDir) {
145         JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
146         StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
147         List<File> filesList = getJavaFiles(sourcesOutputDir);
148         Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(filesList);
149         Iterable<String> options = Arrays.asList("-d", compiledOutputDir.getAbsolutePath());
150         boolean compiled = compiler.getTask(null, null, null, options, null, compilationUnits).call();
151         assertTrue(compiled);
152     }
153
154     private static List<File> getJavaFiles(File directory) {
155         List<File> result = new ArrayList<>();
156         File[] filesToRead = directory.listFiles();
157         if (filesToRead != null) {
158             for (File file : filesToRead) {
159                 if (file.isDirectory()) {
160                     result.addAll(getJavaFiles(file));
161                 } else {
162                     String absPath = file.getAbsolutePath();
163                     if (absPath.endsWith(".java")) {
164                         result.add(file);
165                     }
166                 }
167             }
168         }
169         return result;
170     }
171
172     private static List<File> getSourceFiles(String path) throws Exception {
173         final URI resPath = YangModuleInfoCompilationTest.class.getResource(path).toURI();
174         final File sourcesDir = new File(resPath);
175         final URI currentDir = new File(System.getProperty("user.dir")).toURI();
176         if (sourcesDir.exists()) {
177             final List<File> sourceFiles = new ArrayList<>();
178             final File[] fileArray = sourcesDir.listFiles();
179             if (fileArray == null) {
180                 throw new IllegalArgumentException("Unable to locate files in " + sourcesDir);
181             }
182             for (File sourceFile : fileArray) {
183                 sourceFiles.add(new File(currentDir.relativize(sourceFile.toURI()).toString()));
184             }
185             return sourceFiles;
186         } else {
187             throw new FileNotFoundException("Testing files were not found(" + sourcesDir.getName() + ")");
188         }
189     }
190
191     private static void deleteTestDir(File file) {
192         if (file.isDirectory()) {
193             File[] filesToDelete = file.listFiles();
194             if (filesToDelete != null) {
195                 for (File f : filesToDelete) {
196                     deleteTestDir(f);
197                 }
198             }
199         }
200         if (!file.delete()) {
201             throw new RuntimeException("Failed to clean up after test");
202         }
203     }
204
205     private static Method assertContainsMethod(Class<?> clazz, Class<?> returnType, String name, Class<?>... args) {
206         try {
207             Method m = clazz.getDeclaredMethod(name, args);
208             assertEquals(returnType, m.getReturnType());
209             return m;
210         } catch (NoSuchMethodException e) {
211             throw new AssertionError("Method " + name + " with args " + Arrays.toString(args)
212                     + " does not exists in class " + clazz.getSimpleName());
213         }
214     }
215
216     private static void cleanUp(File... resourceDirs) {
217         for (File resourceDir : resourceDirs) {
218             if (resourceDir.exists()) {
219                 deleteTestDir(resourceDir);
220             }
221         }
222     }
223
224 }