2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.yang.unified.doc.generator.maven;
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;
15 import com.google.common.collect.ImmutableMap;
17 import java.io.FileNotFoundException;
18 import java.lang.reflect.Method;
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;
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;
41 * Test correct generation of YangModuleInfo class.
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";
50 private static final String TEST_PATH = "target" + FS + "test";
51 private static final File TEST_DIR = new File(TEST_PATH);
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);
59 public static void createTestDirs() {
60 if (TEST_DIR.exists()) {
61 deleteTestDir(TEST_DIR);
63 assertTrue(GENERATOR_OUTPUT_DIR.mkdirs());
64 assertTrue(COMPILER_OUTPUT_DIR.mkdirs());
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());
74 generateTestSources("/yang-module-info", sourcesOutputDir);
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());
83 // Test if sources are compilable
84 testCompilation(sourcesOutputDir, compiledOutputDir);
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);
93 Class<?> yangModuleInfoClass = Class.forName(BASE_PKG + ".yang.test.main.rev140630.$YangModuleInfoImpl", true,
96 // Test generated $YangModuleInfoImpl class
97 assertFalse(yangModuleInfoClass.isInterface());
98 Method getInstance = assertContainsMethod(yangModuleInfoClass, YangModuleInfo.class, "getInstance");
99 Object yangModuleInfo = getInstance.invoke(null);
101 // Test getImportedModules method
102 Method getImportedModules = assertContainsMethod(yangModuleInfoClass, Set.class, "getImportedModules");
103 Object importedModules = getImportedModules.invoke(yangModuleInfo);
104 assertTrue(importedModules instanceof Set);
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();
116 case "import-module":
132 assertNotNull(infoImport);
133 assertNotNull(infoSub1);
134 assertNotNull(infoSub2);
135 assertNotNull(infoSub3);
137 cleanUp(sourcesOutputDir, compiledOutputDir);
140 private static void generateTestSources(final String resourceDirPath, final File sourcesOutputDir)
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());
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 -> {
162 assertFalse(file.exists());
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);
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));
184 String absPath = file.getAbsolutePath();
185 if (absPath.endsWith(".java")) {
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);
204 for (File sourceFile : fileArray) {
205 sourceFiles.add(new File(currentDir.relativize(sourceFile.toURI()).toString()));
209 throw new FileNotFoundException("Testing files were not found(" + sourcesDir.getName() + ")");
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) {
222 if (!file.delete()) {
223 throw new RuntimeException("Failed to clean up after test");
227 private static Method assertContainsMethod(final Class<?> clazz, final Class<?> returnType, final String name,
228 final Class<?>... args) {
230 Method method = clazz.getDeclaredMethod(name, args);
231 assertEquals(returnType, method.getReturnType());
233 } catch (NoSuchMethodException e) {
234 throw new AssertionError("Method " + name + " with args " + Arrays.toString(args)
235 + " does not exists in class " + clazz.getSimpleName());
239 private static void cleanUp(final File... resourceDirs) {
240 for (File resourceDir : resourceDirs) {
241 if (resourceDir.exists()) {
242 deleteTestDir(resourceDir);