2 * Copyright (c) 2013 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.yangtools.sal.java.api.generator.test;
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.assertTrue;
13 import static org.junit.Assert.fail;
15 import java.io.FileNotFoundException;
16 import java.lang.reflect.Constructor;
17 import java.lang.reflect.Field;
18 import java.lang.reflect.InvocationTargetException;
19 import java.lang.reflect.Method;
20 import java.lang.reflect.Modifier;
21 import java.lang.reflect.ParameterizedType;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.List;
26 import javax.tools.JavaCompiler;
27 import javax.tools.JavaFileObject;
28 import javax.tools.StandardJavaFileManager;
29 import javax.tools.ToolProvider;
31 public class CompilationTestUtils {
32 public static final String FS = File.separator;
33 static final String BASE_PKG = "org.opendaylight.yang.gen.v1";
35 static final String TEST_PATH = "target" + FS + "test";
36 static final File TEST_DIR = new File(TEST_PATH);
38 static final String GENERATOR_OUTPUT_PATH = TEST_PATH + FS + "src";
39 static final File GENERATOR_OUTPUT_DIR = new File(GENERATOR_OUTPUT_PATH);
40 static final String COMPILER_OUTPUT_PATH = TEST_PATH + FS + "bin";
41 static final File COMPILER_OUTPUT_DIR = new File(COMPILER_OUTPUT_PATH);
43 static final String AUGMENTATION = "interface org.opendaylight.yangtools.yang.binding.Augmentation";
45 static final String BASE_PATH = "org" + FS + "opendaylight" + FS + "yang" + FS + "gen" + FS + "v1";
46 static final String NS_TEST = BASE_PATH + FS + "urn" + FS + "opendaylight" + FS + "test" + FS + "rev131008";
47 static final String NS_FOO = BASE_PATH + FS + "urn" + FS + "opendaylight" + FS + "foo" + FS + "rev131008";
48 static final String NS_BAR = BASE_PATH + FS + "urn" + FS + "opendaylight" + FS + "bar" + FS + "rev131008";
49 static final String NS_BAZ = BASE_PATH + FS + "urn" + FS + "opendaylight" + FS + "baz" + FS + "rev131008";
52 * Method to clean resources. It is manually called at the end of each test
53 * instead of marking it with @After annotation to prevent removing
54 * generated code if test fails.
56 static void cleanUp(final File... resourceDirs) {
57 for (File resourceDir : resourceDirs) {
58 if (resourceDir.exists()) {
59 deleteTestDir(resourceDir);
65 * Asserts that class contains field with fiven name and type.
73 * @return field with given name if present in class
75 static Field assertContainsField(final Class<?> clazz, final String name, final Class<?> type) {
77 Field f = clazz.getDeclaredField(name);
78 assertEquals(type, f.getType());
80 } catch (NoSuchFieldException e) {
81 throw new AssertionError("Field " + name + " does not exist in class " + clazz.getSimpleName());
86 * Asserts that class contains field with given name and value. Method tries
87 * to create new instance of class and get value of field. If class
88 * constructor contains any arguments, class is instantiated with null
96 * return type of field
97 * @param expectedValue
98 * expected value of field
99 * @param constructorArgs
100 * constructor arguments of class to test
102 static void assertContainsFieldWithValue(final Class<?> clazz, final String name, final Class<?> returnType, final Object expectedValue,
103 final Class<?>... constructorArgs) {
104 Object[] initargs = null;
105 if (constructorArgs != null && constructorArgs.length > 0) {
106 initargs = new Object[constructorArgs.length];
107 for (int i = 0; i < constructorArgs.length; i++) {
111 assertContainsFieldWithValue(clazz, name, returnType, expectedValue, constructorArgs, initargs);
115 * Asserts that class contains field with given name, return type and value.
122 * return type of field
123 * @param expectedValue
124 * expected value of field
125 * @param constructorArgs
126 * array of constructor arguments classes
128 * array of constructor values
130 static void assertContainsFieldWithValue(final Class<?> clazz, final String name, final Class<?> returnType, final Object expectedValue,
131 final Class<?>[] constructorArgs, final Object... initargs) {
132 Field f = assertContainsField(clazz, name, returnType);
133 f.setAccessible(true);
136 if ((f.getModifiers() & Modifier.STATIC) == 0) {
138 Constructor<?> c = clazz.getDeclaredConstructor(constructorArgs);
139 obj = c.newInstance(initargs);
140 } catch (Exception e) {
141 throw new AssertionError("Failed to instantiate object for " + clazz, e);
148 assertEquals(expectedValue, f.get(obj));
149 } catch (IllegalArgumentException | IllegalAccessException e) {
150 throw new AssertionError("Failed to get field " + name + " of class " + clazz, e);
155 * Asserts that class contains constructor with parameter types.
160 * array of argument classes
162 static Constructor<?> assertContainsConstructor(final Class<?> clazz, final Class<?>... args) {
164 return clazz.getDeclaredConstructor(args);
165 } catch (NoSuchMethodException e) {
166 throw new AssertionError("Constructor with args " + Arrays.toString(args) + " does not exists in class "
167 + clazz.getSimpleName());
172 * Asserts that class contains method with given name, return type and
182 * array of parameter type classes
183 * @return method with given name, return type and parameter types
185 static Method assertContainsMethod(final Class<?> clazz, final Class<?> returnType, final String name, final Class<?>... args) {
187 Method m = clazz.getDeclaredMethod(name, args);
188 assertEquals(returnType, m.getReturnType());
190 } catch (NoSuchMethodException e) {
191 throw new AssertionError("Method " + name + " with args " + Arrays.toString(args)
192 + " does not exists in class " + clazz.getSimpleName());
197 * Asserts that class contains method with given name and return type.
201 * @param returnTypeStr
202 * name of method return type
206 * current class loader
208 static void assertContainsMethod(final Class<?> clazz, final String returnTypeStr, final String name, final ClassLoader loader) {
211 returnType = Class.forName(returnTypeStr, true, loader);
212 Method method = clazz.getMethod(name);
213 assertEquals(returnType, method.getReturnType());
214 } catch (ClassNotFoundException e) {
215 throw new AssertionError("Return type of method '" + name + "' not found");
216 } catch (NoSuchMethodException e) {
217 throw new AssertionError("Method " + name + " does not exists in class " + clazz.getSimpleName());
222 * Asserts that class contains hashCode, equals and toString methods.
227 static void assertContainsDefaultMethods(final Class<?> clazz) {
228 assertContainsMethod(clazz, Integer.TYPE, "hashCode");
229 assertContainsMethod(clazz, Boolean.TYPE, "equals", Object.class);
230 assertContainsMethod(clazz, String.class, "toString");
234 * Asserts that constructor contains check for illegal argument.
237 * constructor to invoke
239 * expected error message
241 * constructor arguments
244 static void assertContainsRestrictionCheck(final Constructor<?> constructor, final String errorMsg, final Object... args)
247 constructor.newInstance(args);
248 fail("constructor invocation should fail");
249 } catch (InvocationTargetException e) {
250 Throwable cause = e.getCause();
251 assertTrue(cause instanceof IllegalArgumentException);
252 assertEquals(errorMsg, cause.getMessage());
257 * Asserts that method contains check for illegal argument.
260 * object to test (can be null, if method is static)
264 * expected error message
266 * constructor arguments
269 static void assertContainsRestrictionCheck(final Object obj, final Method method, final String errorMsg, final Object... args)
272 method.invoke(obj, args);
273 fail("method invocation should fail");
274 } catch (InvocationTargetException e) {
275 Throwable cause = e.getCause();
276 assertTrue(cause instanceof IllegalArgumentException);
277 assertEquals(errorMsg, cause.getMessage());
282 * Asserts that class implements given interface.
289 static void assertImplementsIfc(final Class<?> clazz, final Class<?> ifc) {
290 Class<?>[] interfaces = clazz.getInterfaces();
291 List<Class<?>> ifcsList = Arrays.asList(interfaces);
292 if (!ifcsList.contains(ifc)) {
293 throw new AssertionError(clazz + " should implement " + ifc);
298 * Test if interface generated from augment extends Augmentation interface
299 * with correct generic type.
302 * interface generated from augment
303 * @param genericTypeName
304 * fully qualified name of expected parameter type
306 static void testAugmentation(final Class<?> clazz, final String genericTypeName) {
307 assertImplementsParameterizedIfc(clazz, AUGMENTATION, genericTypeName);
311 * Asserts that class implements interface with given name and generic type
318 * @param genericTypeName
319 * name of generic type
321 static void assertImplementsParameterizedIfc(final Class<?> clazz, final String ifcName, final String genericTypeName) {
322 ParameterizedType ifcType = null;
323 for (java.lang.reflect.Type ifc : clazz.getGenericInterfaces()) {
324 if (ifc instanceof ParameterizedType) {
325 ParameterizedType pt = (ParameterizedType) ifc;
326 if (ifcName.equals(pt.getRawType().toString())) {
331 assertNotNull(ifcType);
333 java.lang.reflect.Type[] typeArguments = ifcType.getActualTypeArguments();
334 assertEquals(1, typeArguments.length);
335 assertEquals("interface " + genericTypeName, typeArguments[0].toString());
339 * Test if source code is compilable.
341 * @param sourcesOutputDir
342 * directory containing source files
343 * @param compiledOutputDir
344 * compiler output directory
346 static void testCompilation(final File sourcesOutputDir, final File compiledOutputDir) {
347 JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
348 StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
349 List<File> filesList = getJavaFiles(sourcesOutputDir);
350 Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(filesList);
351 Iterable<String> options = Arrays.asList("-d", compiledOutputDir.getAbsolutePath());
352 boolean compiled = compiler.getTask(null, null, null, options, null, compilationUnits).call();
353 assertTrue("Compilation failed", compiled);
357 * Asserts that directory contains exactly given count of files.
362 * expected count of files in directory
364 static void assertFilesCount(final File dir, final int count) {
365 File[] dirContent = dir.listFiles();
366 if (dirContent == null) {
367 throw new AssertionError("File " + dir + " doesn't exists or it's not a directory");
369 assertEquals("Unexpected count of generated files", count, dirContent.length);
374 * Search recursively given directory for *.java files.
377 * directory to search
378 * @return List of java files found
380 private static List<File> getJavaFiles(final File directory) {
381 List<File> result = new ArrayList<>();
382 File[] filesToRead = directory.listFiles();
383 if (filesToRead != null) {
384 for (File file : filesToRead) {
385 if (file.isDirectory()) {
386 result.addAll(getJavaFiles(file));
388 String absPath = file.getAbsolutePath();
389 if (absPath.endsWith(".java")) {
398 static List<File> getSourceFiles(final String path) throws Exception {
399 final URI resPath = BaseCompilationTest.class.getResource(path).toURI();
400 final File sourcesDir = new File(resPath);
401 if (sourcesDir.exists()) {
402 final List<File> sourceFiles = new ArrayList<>();
403 final File[] fileArray = sourcesDir.listFiles();
404 if (fileArray == null) {
405 throw new IllegalArgumentException("Unable to locate files in " + sourcesDir);
407 sourceFiles.addAll(Arrays.asList(fileArray));
410 throw new FileNotFoundException("Testing files were not found(" + sourcesDir.getName() + ")");
414 static void deleteTestDir(final File file) {
415 if (file.isDirectory()) {
416 File[] filesToDelete = file.listFiles();
417 if (filesToDelete != null) {
418 for (File f : filesToDelete) {
423 if (!file.delete()) {
424 throw new RuntimeException("Failed to clean up after test");