Search in sources :

Example 41 with Statement

use of org.junit.runners.model.Statement in project spring-framework by spring-projects.

the class SpringJUnit4ClassRunner method methodBlock.

/**
	 * Augment the default JUnit behavior
	 * {@linkplain #withPotentialRepeat with potential repeats} of the entire
	 * execution chain.
	 * <p>Furthermore, support for timeouts has been moved down the execution
	 * chain in order to include execution of {@link org.junit.Before @Before}
	 * and {@link org.junit.After @After} methods within the timed execution.
	 * Note that this differs from the default JUnit behavior of executing
	 * {@code @Before} and {@code @After} methods in the main thread while
	 * executing the actual test method in a separate thread. Thus, the net
	 * effect is that {@code @Before} and {@code @After} methods will be
	 * executed in the same thread as the test method. As a consequence,
	 * JUnit-specified timeouts will work fine in combination with Spring
	 * transactions. However, JUnit-specific timeouts still differ from
	 * Spring-specific timeouts in that the former execute in a separate
	 * thread while the latter simply execute in the main thread (like regular
	 * tests).
	 * @see #methodInvoker(FrameworkMethod, Object)
	 * @see #withBeforeTestExecutionCallbacks(FrameworkMethod, Object, Statement)
	 * @see #withAfterTestExecutionCallbacks(FrameworkMethod, Object, Statement)
	 * @see #possiblyExpectingExceptions(FrameworkMethod, Object, Statement)
	 * @see #withBefores(FrameworkMethod, Object, Statement)
	 * @see #withAfters(FrameworkMethod, Object, Statement)
	 * @see #withRulesReflectively(FrameworkMethod, Object, Statement)
	 * @see #withPotentialRepeat(FrameworkMethod, Object, Statement)
	 * @see #withPotentialTimeout(FrameworkMethod, Object, Statement)
	 */
@Override
protected Statement methodBlock(FrameworkMethod frameworkMethod) {
    Object testInstance;
    try {
        testInstance = new ReflectiveCallable() {

            @Override
            protected Object runReflectiveCall() throws Throwable {
                return createTest();
            }
        }.run();
    } catch (Throwable ex) {
        return new Fail(ex);
    }
    Statement statement = methodInvoker(frameworkMethod, testInstance);
    statement = withBeforeTestExecutionCallbacks(frameworkMethod, testInstance, statement);
    statement = withAfterTestExecutionCallbacks(frameworkMethod, testInstance, statement);
    statement = possiblyExpectingExceptions(frameworkMethod, testInstance, statement);
    statement = withBefores(frameworkMethod, testInstance, statement);
    statement = withAfters(frameworkMethod, testInstance, statement);
    statement = withRulesReflectively(frameworkMethod, testInstance, statement);
    statement = withPotentialRepeat(frameworkMethod, testInstance, statement);
    statement = withPotentialTimeout(frameworkMethod, testInstance, statement);
    return statement;
}
Also used : ReflectiveCallable(org.junit.internal.runners.model.ReflectiveCallable) Statement(org.junit.runners.model.Statement) Fail(org.junit.internal.runners.statements.Fail)

Example 42 with Statement

use of org.junit.runners.model.Statement in project spring-framework by spring-projects.

the class SpringJUnit4ClassRunner method runChild.

/**
	 * Perform the same logic as
	 * {@link BlockJUnit4ClassRunner#runChild(FrameworkMethod, RunNotifier)},
	 * except that tests are determined to be <em>ignored</em> by
	 * {@link #isTestMethodIgnored(FrameworkMethod)}.
	 */
@Override
protected void runChild(FrameworkMethod frameworkMethod, RunNotifier notifier) {
    Description description = describeChild(frameworkMethod);
    if (isTestMethodIgnored(frameworkMethod)) {
        notifier.fireTestIgnored(description);
    } else {
        Statement statement;
        try {
            statement = methodBlock(frameworkMethod);
        } catch (Throwable ex) {
            statement = new Fail(ex);
        }
        runLeaf(statement, description, notifier);
    }
}
Also used : Description(org.junit.runner.Description) Statement(org.junit.runners.model.Statement) Fail(org.junit.internal.runners.statements.Fail)

Example 43 with Statement

use of org.junit.runners.model.Statement in project spring-framework by spring-projects.

the class SpringClassRule method apply.

/**
	 * Apply <em>class-level</em> features of the <em>Spring TestContext
	 * Framework</em> to the supplied {@code base} statement.
	 * <p>Specifically, this method retrieves the {@link TestContextManager}
	 * used by this rule and its associated {@link SpringMethodRule} and
	 * invokes the {@link TestContextManager#beforeTestClass() beforeTestClass()}
	 * and {@link TestContextManager#afterTestClass() afterTestClass()} methods
	 * on the {@code TestContextManager}.
	 * <p>In addition, this method checks whether the test is enabled in
	 * the current execution environment. This prevents classes with a
	 * non-matching {@code @IfProfileValue} annotation from running altogether,
	 * even skipping the execution of {@code beforeTestClass()} methods
	 * in {@code TestExecutionListeners}.
	 * @param base the base {@code Statement} that this rule should be applied to
	 * @param description a {@code Description} of the current test execution
	 * @return a statement that wraps the supplied {@code base} with class-level
	 * features of the Spring TestContext Framework
	 * @see #getTestContextManager
	 * @see #withBeforeTestClassCallbacks
	 * @see #withAfterTestClassCallbacks
	 * @see #withProfileValueCheck
	 * @see #withTestContextManagerCacheEviction
	 */
@Override
public Statement apply(Statement base, Description description) {
    Class<?> testClass = description.getTestClass();
    if (logger.isDebugEnabled()) {
        logger.debug("Applying SpringClassRule to test class [" + testClass.getName() + "]");
    }
    validateSpringMethodRuleConfiguration(testClass);
    TestContextManager testContextManager = getTestContextManager(testClass);
    Statement statement = base;
    statement = withBeforeTestClassCallbacks(statement, testContextManager);
    statement = withAfterTestClassCallbacks(statement, testContextManager);
    statement = withProfileValueCheck(statement, testClass);
    statement = withTestContextManagerCacheEviction(statement, testClass);
    return statement;
}
Also used : Statement(org.junit.runners.model.Statement) TestContextManager(org.springframework.test.context.TestContextManager)

Example 44 with Statement

use of org.junit.runners.model.Statement in project indy by Commonjava.

the class ThreadDumper method timeoutRule.

public static TestRule timeoutRule(int timeout, TimeUnit units) {
    return (base, description) -> new Statement() {

        public void evaluate() throws Throwable {
            System.out.printf("Setting up timeout: %d %s to wrap: %s\n", timeout, units, base);
            AtomicReference<Throwable> error = new AtomicReference<>();
            CountDownLatch latch = new CountDownLatch(1);
            FutureTask<Void> task = new FutureTask<>(() -> {
                try {
                    latch.countDown();
                    base.evaluate();
                } catch (Throwable t) {
                    error.set(t);
                }
                return null;
            });
            ThreadGroup tg = new ThreadGroup("Test Timeout Group");
            Thread t = new Thread(tg, task, "Test Timeout Thread");
            t.setDaemon(true);
            t.start();
            try {
                System.out.println("Waiting for test to start.");
                latch.await();
            } catch (InterruptedException e) {
                error.set(e);
            }
            if (error.get() == null) {
                try {
                    System.out.println("Waiting for test to complete (or timeout)");
                    task.get(timeout, units);
                } catch (InterruptedException e) {
                    error.set(e);
                } catch (ExecutionException e) {
                    error.set(e.getCause());
                } catch (TimeoutException e) {
                    System.out.printf("Test timeout %d %s expired!\n", timeout, units.name());
                    dumpThreads();
                    StackTraceElement[] stackTrace = t.getStackTrace();
                    Exception currThreadException = new TestTimedOutException(timeout, units);
                    if (stackTrace != null) {
                        currThreadException.setStackTrace(stackTrace);
                        t.interrupt();
                    }
                    throw currThreadException;
                }
            }
            Throwable throwable = error.get();
            if (throwable != null) {
                throw throwable;
            }
        }
    };
}
Also used : Statement(org.junit.runners.model.Statement) TestRule(org.junit.rules.TestRule) MonitorInfo(java.lang.management.MonitorInfo) TestTimedOutException(org.junit.runners.model.TestTimedOutException) FutureTask(java.util.concurrent.FutureTask) TimeoutException(java.util.concurrent.TimeoutException) ThreadMXBean(java.lang.management.ThreadMXBean) StringUtils.join(org.apache.commons.lang.StringUtils.join) AtomicReference(java.util.concurrent.atomic.AtomicReference) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) ThreadInfo(java.lang.management.ThreadInfo) Stream(java.util.stream.Stream) ManagementFactory(java.lang.management.ManagementFactory) Statement(org.junit.runners.model.Statement) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) TestTimedOutException(org.junit.runners.model.TestTimedOutException) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException) FutureTask(java.util.concurrent.FutureTask) ExecutionException(java.util.concurrent.ExecutionException) TestTimedOutException(org.junit.runners.model.TestTimedOutException) TimeoutException(java.util.concurrent.TimeoutException)

Example 45 with Statement

use of org.junit.runners.model.Statement in project indy by Commonjava.

the class ThreadDumper method timeoutRule.

public static TestRule timeoutRule(int timeout, TimeUnit units) {
    return (base, description) -> new Statement() {

        public void evaluate() throws Throwable {
            System.out.printf("Setting up timeout: %d %s to wrap: %s\n", timeout, units, base);
            AtomicReference<Throwable> error = new AtomicReference<>();
            CountDownLatch latch = new CountDownLatch(1);
            FutureTask<Void> task = new FutureTask<>(() -> {
                try {
                    latch.countDown();
                    base.evaluate();
                } catch (Throwable t) {
                    error.set(t);
                }
                return null;
            });
            ThreadGroup tg = new ThreadGroup("Test Timeout Group");
            Thread t = new Thread(tg, task, "Test Timeout Thread");
            t.setDaemon(true);
            t.start();
            try {
                System.out.println("Waiting for test to start.");
                latch.await();
            } catch (InterruptedException e) {
                error.set(e);
            }
            if (error.get() == null) {
                try {
                    System.out.println("Waiting for test to complete (or timeout)");
                    task.get(timeout, units);
                } catch (InterruptedException e) {
                    error.set(e);
                } catch (ExecutionException e) {
                    error.set(e.getCause());
                } catch (TimeoutException e) {
                    System.out.printf("Test timeout %d %s expired!\n", timeout, units.name());
                    dumpThreads();
                    StackTraceElement[] stackTrace = t.getStackTrace();
                    Exception currThreadException = new TestTimedOutException(timeout, units);
                    if (stackTrace != null) {
                        currThreadException.setStackTrace(stackTrace);
                        t.interrupt();
                    }
                    throw currThreadException;
                }
            }
            Throwable throwable = error.get();
            if (throwable != null) {
                throw throwable;
            }
        }
    };
}
Also used : Statement(org.junit.runners.model.Statement) TestRule(org.junit.rules.TestRule) MonitorInfo(java.lang.management.MonitorInfo) TestTimedOutException(org.junit.runners.model.TestTimedOutException) FutureTask(java.util.concurrent.FutureTask) TimeoutException(java.util.concurrent.TimeoutException) ThreadMXBean(java.lang.management.ThreadMXBean) StringUtils.join(org.apache.commons.lang.StringUtils.join) AtomicReference(java.util.concurrent.atomic.AtomicReference) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) ThreadInfo(java.lang.management.ThreadInfo) Stream(java.util.stream.Stream) ManagementFactory(java.lang.management.ManagementFactory) Statement(org.junit.runners.model.Statement) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) TestTimedOutException(org.junit.runners.model.TestTimedOutException) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException) FutureTask(java.util.concurrent.FutureTask) ExecutionException(java.util.concurrent.ExecutionException) TestTimedOutException(org.junit.runners.model.TestTimedOutException) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

Statement (org.junit.runners.model.Statement)138 Test (org.junit.Test)22 FrameworkMethod (org.junit.runners.model.FrameworkMethod)15 Method (java.lang.reflect.Method)11 AssumptionViolatedException (org.junit.internal.AssumptionViolatedException)11 Fail (org.junit.internal.runners.statements.Fail)9 Description (org.junit.runner.Description)8 TestRule (org.junit.rules.TestRule)7 MultipleFailureException (org.junit.runners.model.MultipleFailureException)6 ExecutorService (java.util.concurrent.ExecutorService)5 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)5 ReflectiveCallable (org.junit.internal.runners.model.ReflectiveCallable)5 MethodRule (org.junit.rules.MethodRule)5 ArrayList (java.util.ArrayList)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 EmptyStatement (com.hazelcast.util.EmptyStatement)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 TestExecutorService (org.apache.beam.fn.harness.test.TestExecutors.TestExecutorService)3 CompositeConfiguration (org.apache.logging.log4j.core.config.composite.CompositeConfiguration)3 LoggerContextRule (org.apache.logging.log4j.junit.LoggerContextRule)3