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