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