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