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