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;
14 import static org.junit.Assert.fail;
16 import com.google.common.collect.ImmutableMap;
18 import java.io.FileNotFoundException;
19 import java.lang.reflect.Method;
22 import java.net.URLClassLoader;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.List;
27 import java.util.Optional;
29 import javax.tools.Diagnostic;
30 import javax.tools.JavaCompiler;
31 import javax.tools.JavaFileObject;
32 import javax.tools.StandardJavaFileManager;
33 import javax.tools.ToolProvider;
34 import org.apache.maven.project.MavenProject;
35 import org.junit.BeforeClass;
36 import org.junit.Test;
37 import org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl;
38 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
39 import org.opendaylight.yangtools.yang.common.YangConstants;
40 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
41 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
42 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
45 * Test correct generation of YangModuleInfo class.
48 // TODO: most of private static methods are copied from
49 // binding-java-api-generator project - reorganize compilation tests
50 public class YangModuleInfoCompilationTest {
51 public static final String FS = File.separator;
52 private static final String BASE_PKG = "org.opendaylight.yang.gen.v1";
54 private static final String TEST_PATH = "target" + FS + "test";
55 private static final File TEST_DIR = new File(TEST_PATH);
57 private static final String GENERATOR_OUTPUT_PATH = TEST_PATH + FS + "src";
58 private static final File GENERATOR_OUTPUT_DIR = new File(GENERATOR_OUTPUT_PATH);
59 private static final String COMPILER_OUTPUT_PATH = TEST_PATH + FS + "bin";
60 private static final File COMPILER_OUTPUT_DIR = new File(COMPILER_OUTPUT_PATH);
63 public static void createTestDirs() {
64 if (TEST_DIR.exists()) {
65 deleteTestDir(TEST_DIR);
67 assertTrue(GENERATOR_OUTPUT_DIR.mkdirs());
68 assertTrue(COMPILER_OUTPUT_DIR.mkdirs());
72 public void compilationTest() throws Exception {
73 final File sourcesOutputDir = new File(GENERATOR_OUTPUT_PATH + FS + "yang");
74 assertTrue("Failed to create test file '" + sourcesOutputDir + "'", sourcesOutputDir.mkdirs());
75 final File compiledOutputDir = new File(COMPILER_OUTPUT_PATH + FS + "yang");
76 assertTrue("Failed to create test file '" + compiledOutputDir + "'", compiledOutputDir.mkdirs());
78 generateTestSources("/yang-module-info", sourcesOutputDir);
80 // Test if $YangModuleInfoImpl.java file is generated
81 final String BASE_PATH = "org" + FS + "opendaylight" + FS + "yang" + FS + "gen" + FS + "v1";
82 final String NS_TEST = BASE_PATH + FS + "yang" + FS + "test" + FS + "main" + FS + "rev140630";
83 File parent = new File(sourcesOutputDir, NS_TEST);
84 File keyArgs = new File(parent, "$YangModuleInfoImpl.java");
85 assertTrue(keyArgs.exists());
87 // Test if sources are compilable
88 testCompilation(sourcesOutputDir, compiledOutputDir);
90 // Create URLClassLoader
91 URL[] urls = new URL[2];
92 urls[0] = compiledOutputDir.toURI().toURL();
93 urls[1] = new File(System.getProperty("user.dir")).toURI().toURL();
94 ClassLoader loader = new URLClassLoader(urls);
97 Class<?> yangModuleInfoClass = Class.forName(BASE_PKG + ".yang.test.main.rev140630.$YangModuleInfoImpl", true,
100 // Test generated $YangModuleInfoImpl class
101 assertFalse(yangModuleInfoClass.isInterface());
102 Method getInstance = assertContainsMethod(yangModuleInfoClass, YangModuleInfo.class, "getInstance");
103 Object yangModuleInfo = getInstance.invoke(null);
105 // Test getImportedModules method
106 Method getImportedModules = assertContainsMethod(yangModuleInfoClass, Set.class, "getImportedModules");
107 Object importedModules = getImportedModules.invoke(yangModuleInfo);
108 assertTrue(importedModules instanceof Set);
110 YangModuleInfo infoImport = null;
111 YangModuleInfo infoSub1 = null;
112 YangModuleInfo infoSub2 = null;
113 YangModuleInfo infoSub3 = null;
114 for (Object importedModule : (Set<?>) importedModules) {
115 assertTrue(importedModule instanceof YangModuleInfo);
116 YangModuleInfo ymi = (YangModuleInfo) importedModule;
117 String name = ymi.getName().getLocalName();
120 case "import-module":
136 assertNotNull(infoImport);
137 assertNotNull(infoSub1);
138 assertNotNull(infoSub2);
139 assertNotNull(infoSub3);
141 cleanUp(sourcesOutputDir, compiledOutputDir);
144 private static void generateTestSources(final String resourceDirPath, final File sourcesOutputDir)
146 final List<File> sourceFiles = getSourceFiles(resourceDirPath);
147 final EffectiveModelContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
148 CodeGeneratorImpl codegen = new CodeGeneratorImpl();
149 codegen.setBuildContext(new DefaultBuildContext());
150 codegen.generateSources(context, sourcesOutputDir, context.getModules(),
151 module -> Optional.of(resourceDirPath + File.separator + module.getName()
152 + YangConstants.RFC6020_YANG_FILE_EXTENSION));
156 public void generateTestSourcesWithAdditionalConfig() throws Exception {
157 final List<File> sourceFiles = getSourceFiles("/yang-module-info");
158 final EffectiveModelContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
159 CodeGeneratorImpl codegen = new CodeGeneratorImpl();
160 codegen.setBuildContext(new DefaultBuildContext());
161 codegen.setResourceBaseDir(null);
162 codegen.setMavenProject(new MavenProject());
163 codegen.setAdditionalConfig(ImmutableMap.of("test", "test"));
164 Collection<File> files = codegen.generateSources(context, null, context.getModules(),
165 module -> Optional.of(module.getName()));
166 assertFalse(files.isEmpty());
167 files.forEach(file -> {
169 assertFalse(file.exists());
173 private static void testCompilation(final File sourcesOutputDir, final File compiledOutputDir) {
174 JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
175 StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
176 List<File> filesList = getJavaFiles(sourcesOutputDir);
177 Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(filesList);
178 Iterable<String> options = Arrays.asList("-d", compiledOutputDir.getAbsolutePath());
179 List<Diagnostic<?>> diags = new ArrayList<>();
180 boolean compiled = compiler.getTask(null, null, diags::add, options, null, compilationUnits).call();
182 fail("Compilation failed with " + diags);
186 private static List<File> getJavaFiles(final File directory) {
187 List<File> result = new ArrayList<>();
188 File[] filesToRead = directory.listFiles();
189 if (filesToRead != null) {
190 for (File file : filesToRead) {
191 if (file.isDirectory()) {
192 result.addAll(getJavaFiles(file));
194 String absPath = file.getAbsolutePath();
195 if (absPath.endsWith(".java")) {
204 private static List<File> getSourceFiles(final String path) throws Exception {
205 final URI resPath = YangModuleInfoCompilationTest.class.getResource(path).toURI();
206 final File sourcesDir = new File(resPath);
207 final URI currentDir = new File(System.getProperty("user.dir")).toURI();
208 if (sourcesDir.exists()) {
209 final List<File> sourceFiles = new ArrayList<>();
210 final File[] fileArray = sourcesDir.listFiles();
211 if (fileArray == null) {
212 throw new IllegalArgumentException("Unable to locate files in " + sourcesDir);
214 for (File sourceFile : fileArray) {
215 sourceFiles.add(new File(currentDir.relativize(sourceFile.toURI()).toString()));
219 throw new FileNotFoundException("Testing files were not found(" + sourcesDir.getName() + ")");
223 private static void deleteTestDir(final File file) {
224 if (file.isDirectory()) {
225 File[] filesToDelete = file.listFiles();
226 if (filesToDelete != null) {
227 for (File ftd : filesToDelete) {
232 if (!file.delete()) {
233 throw new RuntimeException("Failed to clean up after test");
237 private static Method assertContainsMethod(final Class<?> clazz, final Class<?> returnType, final String name,
238 final Class<?>... args) {
240 Method method = clazz.getDeclaredMethod(name, args);
241 assertEquals(returnType, method.getReturnType());
243 } catch (NoSuchMethodException e) {
244 throw new AssertionError("Method " + name + " with args " + Arrays.toString(args)
245 + " does not exists in class " + clazz.getSimpleName(), e);
249 private static void cleanUp(final File... resourceDirs) {
250 for (File resourceDir : resourceDirs) {
251 if (resourceDir.exists()) {
252 deleteTestDir(resourceDir);