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":
129 assertNotNull(infoImport);
130 assertNotNull(infoSub1);
131 assertNotNull(infoSub2);
132 assertNotNull(infoSub3);
134 cleanUp(sourcesOutputDir, compiledOutputDir);
137 private static void generateTestSources(final String resourceDirPath, final File sourcesOutputDir) throws Exception {
138 final List<File> sourceFiles = getSourceFiles(resourceDirPath);
139 final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
140 CodeGeneratorImpl codegen = new CodeGeneratorImpl();
141 codegen.setBuildContext(new DefaultBuildContext());
142 codegen.generateSources(context, sourcesOutputDir, context.getModules());
146 public void generateTestSourcesWithAdditionalConfig() throws Exception {
147 final List<File> sourceFiles = getSourceFiles("/yang-module-info");
148 final SchemaContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
149 CodeGeneratorImpl codegen = new CodeGeneratorImpl();
150 codegen.setBuildContext(new DefaultBuildContext());
151 codegen.setResourceBaseDir(null);
152 codegen.setMavenProject(new MavenProject());
153 codegen.setAdditionalConfig(ImmutableMap.of("test", "test"));
154 Collection<File> files = codegen.generateSources(context, null, context.getModules());
155 assertFalse(files.isEmpty());
156 files.forEach((file -> {
158 assertFalse(file.exists());
162 private static void testCompilation(final File sourcesOutputDir, final File compiledOutputDir) {
163 JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
164 StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
165 List<File> filesList = getJavaFiles(sourcesOutputDir);
166 Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(filesList);
167 Iterable<String> options = Arrays.asList("-d", compiledOutputDir.getAbsolutePath());
168 boolean compiled = compiler.getTask(null, null, null, options, null, compilationUnits).call();
169 assertTrue(compiled);
172 private static List<File> getJavaFiles(final File directory) {
173 List<File> result = new ArrayList<>();
174 File[] filesToRead = directory.listFiles();
175 if (filesToRead != null) {
176 for (File file : filesToRead) {
177 if (file.isDirectory()) {
178 result.addAll(getJavaFiles(file));
180 String absPath = file.getAbsolutePath();
181 if (absPath.endsWith(".java")) {
190 private static List<File> getSourceFiles(final String path) throws Exception {
191 final URI resPath = YangModuleInfoCompilationTest.class.getResource(path).toURI();
192 final File sourcesDir = new File(resPath);
193 final URI currentDir = new File(System.getProperty("user.dir")).toURI();
194 if (sourcesDir.exists()) {
195 final List<File> sourceFiles = new ArrayList<>();
196 final File[] fileArray = sourcesDir.listFiles();
197 if (fileArray == null) {
198 throw new IllegalArgumentException("Unable to locate files in " + sourcesDir);
200 for (File sourceFile : fileArray) {
201 sourceFiles.add(new File(currentDir.relativize(sourceFile.toURI()).toString()));
205 throw new FileNotFoundException("Testing files were not found(" + sourcesDir.getName() + ")");
209 private static void deleteTestDir(final File file) {
210 if (file.isDirectory()) {
211 File[] filesToDelete = file.listFiles();
212 if (filesToDelete != null) {
213 for (File f : filesToDelete) {
218 if (!file.delete()) {
219 throw new RuntimeException("Failed to clean up after test");
223 private static Method assertContainsMethod(final Class<?> clazz, final Class<?> returnType, final String name, final Class<?>... args) {
225 Method m = clazz.getDeclaredMethod(name, args);
226 assertEquals(returnType, m.getReturnType());
228 } catch (NoSuchMethodException e) {
229 throw new AssertionError("Method " + name + " with args " + Arrays.toString(args)
230 + " does not exists in class " + clazz.getSimpleName());
234 private static void cleanUp(final File... resourceDirs) {
235 for (File resourceDir : resourceDirs) {
236 if (resourceDir.exists()) {
237 deleteTestDir(resourceDir);