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