Fix checkstyle in maven-sal-api-gen-plugin
[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                     break;
128                 default:
129                     // no-op
130             }
131         }
132         assertNotNull(infoImport);
133         assertNotNull(infoSub1);
134         assertNotNull(infoSub2);
135         assertNotNull(infoSub3);
136
137         cleanUp(sourcesOutputDir, compiledOutputDir);
138     }
139
140     private static void generateTestSources(final String resourceDirPath, final File sourcesOutputDir)
141             throws Exception {
142         final List<File> sourceFiles = getSourceFiles(resourceDirPath);
143         final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
144         CodeGeneratorImpl codegen = new CodeGeneratorImpl();
145         codegen.setBuildContext(new DefaultBuildContext());
146         codegen.generateSources(context, sourcesOutputDir, context.getModules());
147     }
148
149     @Test
150     public void generateTestSourcesWithAdditionalConfig() throws Exception {
151         final List<File> sourceFiles = getSourceFiles("/yang-module-info");
152         final SchemaContext context = YangParserTestUtils.parseYangSources(sourceFiles);
153         CodeGeneratorImpl codegen = new CodeGeneratorImpl();
154         codegen.setBuildContext(new DefaultBuildContext());
155         codegen.setResourceBaseDir(null);
156         codegen.setMavenProject(new MavenProject());
157         codegen.setAdditionalConfig(ImmutableMap.of("test", "test"));
158         Collection<File> files = codegen.generateSources(context, null, context.getModules());
159         assertFalse(files.isEmpty());
160         files.forEach(file -> {
161             deleteTestDir(file);
162             assertFalse(file.exists());
163         });
164     }
165
166     private static void testCompilation(final File sourcesOutputDir, final File compiledOutputDir) {
167         JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
168         StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
169         List<File> filesList = getJavaFiles(sourcesOutputDir);
170         Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(filesList);
171         Iterable<String> options = Arrays.asList("-d", compiledOutputDir.getAbsolutePath());
172         boolean compiled = compiler.getTask(null, null, null, options, null, compilationUnits).call();
173         assertTrue(compiled);
174     }
175
176     private static List<File> getJavaFiles(final File directory) {
177         List<File> result = new ArrayList<>();
178         File[] filesToRead = directory.listFiles();
179         if (filesToRead != null) {
180             for (File file : filesToRead) {
181                 if (file.isDirectory()) {
182                     result.addAll(getJavaFiles(file));
183                 } else {
184                     String absPath = file.getAbsolutePath();
185                     if (absPath.endsWith(".java")) {
186                         result.add(file);
187                     }
188                 }
189             }
190         }
191         return result;
192     }
193
194     private static List<File> getSourceFiles(final String path) throws Exception {
195         final URI resPath = YangModuleInfoCompilationTest.class.getResource(path).toURI();
196         final File sourcesDir = new File(resPath);
197         final URI currentDir = new File(System.getProperty("user.dir")).toURI();
198         if (sourcesDir.exists()) {
199             final List<File> sourceFiles = new ArrayList<>();
200             final File[] fileArray = sourcesDir.listFiles();
201             if (fileArray == null) {
202                 throw new IllegalArgumentException("Unable to locate files in " + sourcesDir);
203             }
204             for (File sourceFile : fileArray) {
205                 sourceFiles.add(new File(currentDir.relativize(sourceFile.toURI()).toString()));
206             }
207             return sourceFiles;
208         } else {
209             throw new FileNotFoundException("Testing files were not found(" + sourcesDir.getName() + ")");
210         }
211     }
212
213     private static void deleteTestDir(final File file) {
214         if (file.isDirectory()) {
215             File[] filesToDelete = file.listFiles();
216             if (filesToDelete != null) {
217                 for (File ftd : filesToDelete) {
218                     deleteTestDir(ftd);
219                 }
220             }
221         }
222         if (!file.delete()) {
223             throw new RuntimeException("Failed to clean up after test");
224         }
225     }
226
227     private static Method assertContainsMethod(final Class<?> clazz, final Class<?> returnType, final String name,
228             final Class<?>... args) {
229         try {
230             Method method = clazz.getDeclaredMethod(name, args);
231             assertEquals(returnType, method.getReturnType());
232             return method;
233         } catch (NoSuchMethodException e) {
234             throw new AssertionError("Method " + name + " with args " + Arrays.toString(args)
235                     + " does not exists in class " + clazz.getSimpleName());
236         }
237     }
238
239     private static void cleanUp(final File... resourceDirs) {
240         for (File resourceDir : resourceDirs) {
241             if (resourceDir.exists()) {
242                 deleteTestDir(resourceDir);
243             }
244         }
245     }
246
247 }