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.java.api.generator;
10 import static org.hamcrest.CoreMatchers.startsWith;
11 import static org.hamcrest.MatcherAssert.assertThat;
12 import static org.junit.Assert.assertEquals;
13 import static org.junit.Assert.assertFalse;
14 import static org.junit.Assert.assertNotNull;
15 import static org.junit.Assert.assertTrue;
16 import static org.junit.Assert.fail;
18 import com.google.common.collect.ImmutableSet;
19 import com.google.common.collect.Table;
21 import java.io.FileNotFoundException;
22 import java.io.OutputStream;
23 import java.lang.reflect.Method;
26 import java.net.URLClassLoader;
27 import java.nio.file.Files;
28 import java.nio.file.Path;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.List;
33 import java.util.Map.Entry;
34 import java.util.Optional;
36 import javax.tools.Diagnostic;
37 import javax.tools.JavaCompiler;
38 import javax.tools.JavaFileObject;
39 import javax.tools.StandardJavaFileManager;
40 import javax.tools.ToolProvider;
41 import org.junit.BeforeClass;
42 import org.junit.Test;
43 import org.opendaylight.yangtools.plugin.generator.api.GeneratedFile;
44 import org.opendaylight.yangtools.plugin.generator.api.GeneratedFilePath;
45 import org.opendaylight.yangtools.plugin.generator.api.GeneratedFileType;
46 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
47 import org.opendaylight.yangtools.yang.common.YangConstants;
48 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
49 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
52 * Test correct generation of YangModuleInfo class.
55 // TODO: most of private static methods are copied from
56 // binding-java-api-generator project - reorganize compilation tests
57 public class YangModuleInfoCompilationTest {
58 public static final String FS = File.separator;
59 private static final String BASE_PKG = "org.opendaylight.yang.gen.v1";
61 private static final String TEST_PATH = "target" + FS + "test";
62 private static final File TEST_DIR = new File(TEST_PATH);
64 private static final String GENERATOR_OUTPUT_PATH = TEST_PATH + FS + "src";
65 private static final File GENERATOR_OUTPUT_DIR = new File(GENERATOR_OUTPUT_PATH);
66 private static final String COMPILER_OUTPUT_PATH = TEST_PATH + FS + "bin";
67 private static final File COMPILER_OUTPUT_DIR = new File(COMPILER_OUTPUT_PATH);
70 public static void createTestDirs() {
71 if (TEST_DIR.exists()) {
72 deleteTestDir(TEST_DIR);
74 assertTrue(GENERATOR_OUTPUT_DIR.mkdirs());
75 assertTrue(COMPILER_OUTPUT_DIR.mkdirs());
79 public void compilationTest() throws Exception {
80 final File sourcesOutputDir = new File(GENERATOR_OUTPUT_PATH + FS + "yang");
81 assertTrue("Failed to create test file '" + sourcesOutputDir + "'", sourcesOutputDir.mkdirs());
82 final File compiledOutputDir = new File(COMPILER_OUTPUT_PATH + FS + "yang");
83 assertTrue("Failed to create test file '" + compiledOutputDir + "'", compiledOutputDir.mkdirs());
85 generateTestSources("/yang-module-info", sourcesOutputDir);
87 // Test if $YangModuleInfoImpl.java file is generated
88 final String BASE_PATH = "org" + FS + "opendaylight" + FS + "yang" + FS + "gen" + FS + "v1";
89 final String NS_TEST = BASE_PATH + FS + "yang" + FS + "test" + FS + "main" + FS + "rev140630";
90 File parent = new File(sourcesOutputDir, NS_TEST);
91 File keyArgs = new File(parent, "$YangModuleInfoImpl.java");
92 assertTrue(keyArgs.exists());
94 // Test if sources are compilable
95 testCompilation(sourcesOutputDir, compiledOutputDir);
97 // Create URLClassLoader
98 URL[] urls = new URL[2];
99 urls[0] = compiledOutputDir.toURI().toURL();
100 urls[1] = new File(System.getProperty("user.dir")).toURI().toURL();
101 ClassLoader loader = new URLClassLoader(urls);
104 Class<?> yangModuleInfoClass = Class.forName(BASE_PKG + ".yang.test.main.rev140630.$YangModuleInfoImpl", true,
107 // Test generated $YangModuleInfoImpl class
108 assertFalse(yangModuleInfoClass.isInterface());
109 Method getInstance = assertContainsMethod(yangModuleInfoClass, YangModuleInfo.class, "getInstance");
110 Object yangModuleInfo = getInstance.invoke(null);
112 // Test getImportedModules method
113 Method getImportedModules = assertContainsMethod(yangModuleInfoClass, ImmutableSet.class, "getImportedModules");
114 Object importedModules = getImportedModules.invoke(yangModuleInfo);
115 assertTrue(importedModules instanceof Set);
117 YangModuleInfo infoImport = null;
118 YangModuleInfo infoSub1 = null;
119 YangModuleInfo infoSub2 = null;
120 YangModuleInfo infoSub3 = null;
121 for (Object importedModule : (Set<?>) importedModules) {
122 assertTrue(importedModule instanceof YangModuleInfo);
123 YangModuleInfo ymi = (YangModuleInfo) importedModule;
124 String name = ymi.getName().getLocalName();
127 case "import-module":
143 assertNotNull(infoImport);
144 assertThat(infoImport.getYangTextCharSource().readFirstLine(), startsWith("module import-module"));
145 assertNotNull(infoSub1);
146 assertThat(infoSub1.getYangTextCharSource().readFirstLine(), startsWith("submodule submodule1"));
147 assertNotNull(infoSub2);
148 assertThat(infoSub2.getYangTextCharSource().readFirstLine(), startsWith("submodule submodule2"));
149 assertNotNull(infoSub3);
150 assertThat(infoSub3.getYangTextCharSource().readFirstLine(), startsWith("submodule submodule3"));
152 cleanUp(sourcesOutputDir, compiledOutputDir);
155 private static void generateTestSources(final String resourceDirPath, final File sourcesOutputDir)
157 final List<File> sourceFiles = getSourceFiles(resourceDirPath);
158 final EffectiveModelContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
159 final Table<GeneratedFileType, GeneratedFilePath, GeneratedFile> codegen = new JavaFileGenerator(Map.of())
160 .generateFiles(context, Set.copyOf(context.getModules()),
161 (module, representation) -> Optional.of(resourceDirPath + File.separator + module.getName()
162 + YangConstants.RFC6020_YANG_FILE_EXTENSION));
164 assertEquals(15, codegen.size());
165 assertEquals(14, codegen.row(GeneratedFileType.SOURCE).size());
166 assertEquals(1, codegen.row(GeneratedFileType.RESOURCE).size());
168 for (Entry<GeneratedFilePath, GeneratedFile> entry : codegen.row(GeneratedFileType.SOURCE).entrySet()) {
169 final Path path = new File(sourcesOutputDir,
170 entry.getKey().getPath().replace(GeneratedFilePath.SEPARATOR, File.separatorChar)).toPath();
172 Files.createDirectories(path.getParent());
173 try (OutputStream out = Files.newOutputStream(path)) {
174 entry.getValue().writeBody(out);
180 public void generateTestSourcesWithAdditionalConfig() throws Exception {
181 final List<File> sourceFiles = getSourceFiles("/yang-module-info");
182 final EffectiveModelContext context = YangParserTestUtils.parseYangFiles(sourceFiles);
183 JavaFileGenerator codegen = new JavaFileGenerator(Map.of("test", "test"));
184 Table<GeneratedFileType, GeneratedFilePath, GeneratedFile> files = codegen.generateFiles(context,
185 Set.copyOf(context.getModules()), (module, representation) -> Optional.of(module.getName()));
186 assertEquals(15, files.size());
187 assertEquals(14, files.row(GeneratedFileType.SOURCE).size());
188 assertEquals(1, files.row(GeneratedFileType.RESOURCE).size());
191 private static void testCompilation(final File sourcesOutputDir, final File compiledOutputDir) {
192 JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
193 StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
194 List<File> filesList = getJavaFiles(sourcesOutputDir);
195 Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(filesList);
196 Iterable<String> options = Arrays.asList("-d", compiledOutputDir.getAbsolutePath());
197 List<Diagnostic<?>> diags = new ArrayList<>();
198 boolean compiled = compiler.getTask(null, null, diags::add, options, null, compilationUnits).call();
200 fail("Compilation failed with " + diags);
204 private static List<File> getJavaFiles(final File directory) {
205 List<File> result = new ArrayList<>();
206 File[] filesToRead = directory.listFiles();
207 if (filesToRead != null) {
208 for (File file : filesToRead) {
209 if (file.isDirectory()) {
210 result.addAll(getJavaFiles(file));
212 String absPath = file.getAbsolutePath();
213 if (absPath.endsWith(".java")) {
222 private static List<File> getSourceFiles(final String path) throws Exception {
223 final URI resPath = YangModuleInfoCompilationTest.class.getResource(path).toURI();
224 final File sourcesDir = new File(resPath);
225 final URI currentDir = new File(System.getProperty("user.dir")).toURI();
226 if (sourcesDir.exists()) {
227 final List<File> sourceFiles = new ArrayList<>();
228 final File[] fileArray = sourcesDir.listFiles();
229 if (fileArray == null) {
230 throw new IllegalArgumentException("Unable to locate files in " + sourcesDir);
232 for (File sourceFile : fileArray) {
233 sourceFiles.add(new File(currentDir.relativize(sourceFile.toURI()).toString()));
237 throw new FileNotFoundException("Testing files were not found(" + sourcesDir.getName() + ")");
241 private static void deleteTestDir(final File file) {
242 if (file.isDirectory()) {
243 File[] filesToDelete = file.listFiles();
244 if (filesToDelete != null) {
245 for (File ftd : filesToDelete) {
250 if (!file.delete()) {
251 throw new RuntimeException("Failed to clean up after test");
255 private static Method assertContainsMethod(final Class<?> clazz, final Class<?> returnType, final String name,
256 final Class<?>... args) {
258 Method method = clazz.getDeclaredMethod(name, args);
259 assertEquals(returnType, method.getReturnType());
261 } catch (NoSuchMethodException e) {
262 throw new AssertionError("Method " + name + " with args " + Arrays.toString(args)
263 + " does not exists in class " + clazz.getSimpleName(), e);
267 private static void cleanUp(final File... resourceDirs) {
268 for (File resourceDir : resourceDirs) {
269 if (resourceDir.exists()) {
270 deleteTestDir(resourceDir);