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