Search in sources :

Example 6 with BlockJUnit4ClassRunner

use of org.junit.runners.BlockJUnit4ClassRunner in project junit5 by junit-team.

the class TestRunTests method returnsEmptyOptionalForUnknownDescriptions.

@Test
void returnsEmptyOptionalForUnknownDescriptions() throws Exception {
    Class<?> testClass = PlainJUnit4TestCaseWithSingleTestWhichFails.class;
    UniqueId runnerId = engineId().append(SEGMENT_TYPE_RUNNER, testClass.getName());
    RunnerTestDescriptor runnerTestDescriptor = new RunnerTestDescriptor(runnerId, testClass, new BlockJUnit4ClassRunner(testClass));
    Description unknownDescription = createTestDescription(testClass, "dynamicTest");
    TestRun testRun = new TestRun(runnerTestDescriptor);
    Optional<VintageTestDescriptor> testDescriptor = testRun.lookupTestDescriptor(unknownDescription);
    assertThat(testDescriptor).isEmpty();
}
Also used : PlainJUnit4TestCaseWithSingleTestWhichFails(org.junit.vintage.engine.samples.junit4.PlainJUnit4TestCaseWithSingleTestWhichFails) UniqueId(org.junit.platform.engine.UniqueId) RunnerTestDescriptor(org.junit.vintage.engine.descriptor.RunnerTestDescriptor) Description.createTestDescription(org.junit.runner.Description.createTestDescription) Description(org.junit.runner.Description) BlockJUnit4ClassRunner(org.junit.runners.BlockJUnit4ClassRunner) VintageTestDescriptor(org.junit.vintage.engine.descriptor.VintageTestDescriptor) Test(org.junit.jupiter.api.Test)

Example 7 with BlockJUnit4ClassRunner

use of org.junit.runners.BlockJUnit4ClassRunner in project evosuite by EvoSuite.

the class PostProcessor method process.

/**
 * @param logs   logs of captured interaction
 * @param packages  package names associated with logs. Mapping logs.get(i) belongs to packages.get(i)
 * @throws IOException
 */
public static void process(final List<CaptureLog> logs, final List<String> packages, final List<Class<?>[]> observedClasses) throws IOException {
    if (logs == null) {
        throw new NullPointerException("list of CaptureLogs must not be null");
    }
    if (packages == null) {
        throw new NullPointerException("list of package names associated with logs must not be null");
    }
    if (observedClasses == null) {
        throw new NullPointerException("list of classes to be observed must not be null");
    }
    final int size = logs.size();
    if (packages.size() != size || observedClasses.size() != size) {
        throw new IllegalArgumentException("given lists must have same size");
    }
    // create post-processing sources in os specific temp folder
    final File tempDir = new File(System.getProperty("java.io.tmpdir"), "postprocessing_" + System.currentTimeMillis());
    tempDir.mkdir();
    CaptureLog log;
    String packageName;
    Class<?>[] classes;
    String targetFolder;
    File targetFile;
    final StringBuilder testClassNameBuilder = new StringBuilder();
    String testClassName;
    for (int i = 0; i < size; i++) {
        // =============== prepare carved test for post-processing ================================================
        packageName = packages.get(i);
        targetFolder = packageName.replace(".", File.separator);
        classes = observedClasses.get(i);
        if (classes.length == 0) {
            throw new IllegalArgumentException("there must be at least one class to be observed");
        }
        // for(int j = 0; j < classes.length; j++)
        // {
        // testClassNameBuilder.append(classes[j].getSimpleName());
        // if(testClassNameBuilder.length() >= 10)
        // {
        // break;
        // }
        // }
        testClassNameBuilder.append("CarvedTest");
        log = logs.get(i);
        long s = System.currentTimeMillis();
        logger.debug(">>>> (postprocess) start test create ");
        targetFile = new File(tempDir, targetFolder);
        targetFile.mkdirs();
        testClassName = getFreeClassName(targetFile, testClassNameBuilder.toString());
        targetFile = new File(targetFile, testClassName + ".java");
        // write out test files containing post-processing statements
        writeTest(log, packageName, testClassName, classes, targetFile, true);
        logger.debug(">>>> (postprocess) end test creation -> " + (System.currentTimeMillis() - s) / 1000);
        // =============== compile generated post-processing test ================================================
        final JavaCompiler compiler = new EclipseCompiler();
        // final JavaCompiler 			  compiler    = ToolProvider.getSystemJavaCompiler();
        final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(new File[] { targetFile }));
        // --- add modified bins (see Transformer and ClassPreparer.createPreparedBin()) to class path
        String classPath = Configuration.INSTANCE.getProperty(Configuration.MODIFIED_BIN_LOC);
        classPath += File.pathSeparator + System.getProperty("java.class.path");
        final Boolean wasCompilationSuccess = compiler.getTask(null, fileManager, null, Arrays.asList(new String[] { "-cp", classPath }), null, compilationUnits).call();
        if (!wasCompilationSuccess) {
            logger.error("Compilation was not not successful for " + targetFile);
            fileManager.close();
            continue;
        }
        fileManager.close();
        // =============== execute + observe post-processing test run ================================================
        final PostProcessorClassLoader cl = new PostProcessorClassLoader(tempDir);
        final Class<?> testClass = cl.findClass(packageName + '.' + testClassName);
        BlockJUnit4ClassRunner testRunner;
        try {
            testRunner = new BlockJUnit4ClassRunner(testClass);
            testRunner.run(new RunNotifier());
        } catch (InitializationError e) {
            logger.error("" + e, e);
        }
        // ============== generate final test file ================================================================
        final String targetDir = Configuration.INSTANCE.getProperty(Configuration.GEN_TESTS_LOC);
        targetFile = new File(new File(targetDir), targetFolder);
        targetFile.mkdirs();
        testClassName = getFreeClassName(targetFile, testClassNameBuilder.toString());
        targetFile = new File(targetFile, testClassName + ".java");
        writeTest(log, packageName, testClassName, classes, targetFile, false);
        // recycle StringBuilder for testClassName
        testClassNameBuilder.setLength(0);
    }
    // clean up post-processing stuff
    tempDir.delete();
}
Also used : RunNotifier(org.junit.runner.notification.RunNotifier) BlockJUnit4ClassRunner(org.junit.runners.BlockJUnit4ClassRunner) InitializationError(org.junit.runners.model.InitializationError) CaptureLog(org.evosuite.testcarver.capture.CaptureLog) EclipseCompiler(org.eclipse.jdt.internal.compiler.tool.EclipseCompiler) File(java.io.File)

Example 8 with BlockJUnit4ClassRunner

use of org.junit.runners.BlockJUnit4ClassRunner in project ceylon by eclipse.

the class ConcurrentScheduler method schedule.

@Override
public void schedule(Runnable r) {
    /* This is disgusting, but JUnit doesn't expose a way to know how
         * the Runnable is related to the thing it's running, and some of 
         * our tests should not run concurrently, so use reflection to 
         * make the association that JUnit doesn't provide and execute 
         * those tests after the executor has finished running the concurrent 
         * ones.
         */
    for (Field f : r.getClass().getDeclaredFields()) {
        if ("val$each".equals(f.getName())) {
            f.setAccessible(true);
            Object runner;
            try {
                runner = f.get(r);
            } catch (IllegalArgumentException e) {
                break;
            } catch (IllegalAccessException e) {
                break;
            }
            if (runner instanceof BlockJUnit4ClassRunner) {
                Class<?> testClass = ((BlockJUnit4ClassRunner) runner).getTestClass().getJavaClass();
                if (testClass.isAnnotationPresent(RunSingleThreaded.class)) {
                    System.out.printf("Submitting task into to run single threaded: %s%n", r);
                    sequential.add(r);
                    return;
                }
            }
        }
    }
    System.out.printf("Submitting task into pool: %s%n", r);
    tpool.execute(r);
}
Also used : Field(java.lang.reflect.Field) BlockJUnit4ClassRunner(org.junit.runners.BlockJUnit4ClassRunner)

Example 9 with BlockJUnit4ClassRunner

use of org.junit.runners.BlockJUnit4ClassRunner in project junit4 by junit-team.

the class CategoryTest method categoryFilterRejectsIncompatibleCategory.

@Test
public void categoryFilterRejectsIncompatibleCategory() throws InitializationError, NoTestsRemainException {
    CategoryFilter filter = CategoryFilter.include(SlowTests.class);
    BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(OneFastOneSlow.class);
    filter.apply(runner);
    assertEquals(1, runner.testCount());
}
Also used : BlockJUnit4ClassRunner(org.junit.runners.BlockJUnit4ClassRunner) CategoryFilter(org.junit.experimental.categories.Categories.CategoryFilter) Test(org.junit.Test)

Example 10 with BlockJUnit4ClassRunner

use of org.junit.runners.BlockJUnit4ClassRunner in project junit4 by junit-team.

the class CategoryTest method categoryFilterLeavesOnlyMatchingMethods_usingConstructor.

@Test
public void categoryFilterLeavesOnlyMatchingMethods_usingConstructor() throws InitializationError, NoTestsRemainException {
    CategoryFilter filter = new CategoryFilter(SlowTests.class, null);
    BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(A.class);
    filter.apply(runner);
    assertEquals(1, runner.testCount());
}
Also used : BlockJUnit4ClassRunner(org.junit.runners.BlockJUnit4ClassRunner) CategoryFilter(org.junit.experimental.categories.Categories.CategoryFilter) Test(org.junit.Test)

Aggregations

BlockJUnit4ClassRunner (org.junit.runners.BlockJUnit4ClassRunner)14 Test (org.junit.Test)8 Description (org.junit.runner.Description)4 RunNotifier (org.junit.runner.notification.RunNotifier)4 CategoryFilter (org.junit.experimental.categories.Categories.CategoryFilter)3 Field (java.lang.reflect.Field)2 Test (org.junit.jupiter.api.Test)2 UniqueId (org.junit.platform.engine.UniqueId)2 Description.createTestDescription (org.junit.runner.Description.createTestDescription)2 InitializationError (org.junit.runners.model.InitializationError)2 RunnerTestDescriptor (org.junit.vintage.engine.descriptor.RunnerTestDescriptor)2 VintageTestDescriptor (org.junit.vintage.engine.descriptor.VintageTestDescriptor)2 PlainJUnit4TestCaseWithSingleTestWhichFails (org.junit.vintage.engine.samples.junit4.PlainJUnit4TestCaseWithSingleTestWhichFails)2 TestClassLoader (com.alipay.sofa.ark.container.test.TestClassLoader)1 ArkEvent (com.alipay.sofa.ark.spi.event.ArkEvent)1 ArkBootRunner (com.alipay.sofa.ark.springboot.runner.ArkBootRunner)1 File (java.io.File)1 EclipseCompiler (org.eclipse.jdt.internal.compiler.tool.EclipseCompiler)1 CaptureLog (org.evosuite.testcarver.capture.CaptureLog)1 JUnitCore (org.junit.runner.JUnitCore)1