Search in sources :

Example 86 with Statement

use of org.junit.runners.model.Statement in project realm-java by realm.

the class RunInLooperThread method apply.

@Override
public Statement apply(final Statement base, Description description) {
    final RunTestInLooperThread annotation = description.getAnnotation(RunTestInLooperThread.class);
    if (annotation == null) {
        return base;
    }
    return new Statement() {

        private Throwable testException;

        @Override
        public void evaluate() throws Throwable {
            before();
            final String threadName = annotation.threadName();
            Class<? extends RunnableBefore> runnableBefore = annotation.before();
            if (!runnableBefore.isInterface()) {
                runnableBefore.newInstance().run(realmConfiguration);
            }
            try {
                final CountDownLatch signalClosedRealm = new CountDownLatch(1);
                final Throwable[] threadAssertionError = new Throwable[1];
                final Looper[] backgroundLooper = new Looper[1];
                final ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {

                    @Override
                    public Thread newThread(Runnable runnable) {
                        return new Thread(runnable, threadName);
                    }
                });
                executorService.submit(new Runnable() {

                    @Override
                    public void run() {
                        Looper.prepare();
                        backgroundLooper[0] = Looper.myLooper();
                        backgroundHandler = new Handler(backgroundLooper[0]);
                        try {
                            realm = Realm.getInstance(realmConfiguration);
                            base.evaluate();
                            Looper.loop();
                        } catch (Throwable e) {
                            threadAssertionError[0] = e;
                            unitTestFailed = true;
                        } finally {
                            try {
                                looperTearDown();
                            } catch (Throwable t) {
                                if (threadAssertionError[0] == null) {
                                    threadAssertionError[0] = t;
                                }
                                unitTestFailed = true;
                            }
                            signalTestCompleted.countDown();
                            if (realm != null) {
                                realm.close();
                            }
                            if (!testRealms.isEmpty()) {
                                for (Realm testRealm : testRealms) {
                                    testRealm.close();
                                }
                            }
                            signalClosedRealm.countDown();
                        }
                    }
                });
                TestHelper.exitOrThrow(executorService, signalTestCompleted, signalClosedRealm, backgroundLooper, threadAssertionError);
            } catch (Throwable error) {
                // These exceptions should only come from TestHelper.awaitOrFail()
                testException = error;
            } finally {
                // Tries as hard as possible to close down gracefully, while still keeping all exceptions intact.
                try {
                    after();
                } catch (Throwable e) {
                    if (testException != null) {
                        // Both TestHelper.awaitOrFail() and after() threw an exception. Make sure we are aware of
                        // that fact by printing both exceptions.
                        StringWriter testStackTrace = new StringWriter();
                        testException.printStackTrace(new PrintWriter(testStackTrace));
                        StringWriter afterStackTrace = new StringWriter();
                        e.printStackTrace(new PrintWriter(afterStackTrace));
                        StringBuilder errorMessage = new StringBuilder().append("after() threw an error that shadows a test case error").append('\n').append("== Test case exception ==\n").append(testStackTrace.toString()).append('\n').append("== after() exception ==\n").append(afterStackTrace.toString());
                        fail(errorMessage.toString());
                    } else {
                        // Only after() threw an exception
                        throw e;
                    }
                }
                // Only TestHelper.awaitOrFail() threw an exception
                if (testException != null) {
                    //noinspection ThrowFromFinallyBlock
                    throw testException;
                }
            }
        }
    };
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) Statement(org.junit.runners.model.Statement) Handler(android.os.Handler) CountDownLatch(java.util.concurrent.CountDownLatch) Looper(android.os.Looper) StringWriter(java.io.StringWriter) ExecutorService(java.util.concurrent.ExecutorService) Realm(io.realm.Realm) PrintWriter(java.io.PrintWriter)

Example 87 with Statement

use of org.junit.runners.model.Statement in project dex2jar by pxb1988.

the class DexTranslatorRunner method methodInvoker.

@Override
protected Statement methodInvoker(final FrameworkMethod method, final Object test) {
    if (method.getMethod().getParameterTypes().length > 0) {
        return new Statement() {

            @Override
            public void evaluate() throws Throwable {
                // 1.invoke the method
                DexClassNode clzNode = new DexClassNode(DexConstants.ACC_PUBLIC, "La;", "Ljava/lang/Object;", null);
                if (method.isStatic()) {
                    method.invokeExplosively(null, clzNode);
                } else {
                    method.invokeExplosively(test, clzNode);
                }
                // 2. convert and verify
                TestUtils.translateAndCheck(clzNode);
            }
        };
    } else {
        return super.methodInvoker(method, test);
    }
}
Also used : DexClassNode(com.googlecode.d2j.node.DexClassNode) Statement(org.junit.runners.model.Statement)

Example 88 with Statement

use of org.junit.runners.model.Statement in project randomizedtesting by randomizedtesting.

the class RandomizedRunner method wrapBeforeAndAfters.

/**
   * Wrap before and after hooks.
   */
private Statement wrapBeforeAndAfters(Statement s, final TestCandidate c, final Object instance) {
    // Process @Before hooks. The first @Before to fail will immediately stop processing any other @Befores.
    final List<Method> befores = getShuffledMethods(Before.class);
    if (!befores.isEmpty()) {
        final Statement afterBefores = s;
        s = new Statement() {

            @Override
            public void evaluate() throws Throwable {
                for (Method m : befores) {
                    invoke(m, instance);
                }
                afterBefores.evaluate();
            }
        };
    }
    // Process @After hooks. All @After hooks are processed, regardless of their own exceptions.
    final List<Method> afters = getShuffledMethods(After.class);
    if (!afters.isEmpty()) {
        final Statement beforeAfters = s;
        s = new Statement() {

            @Override
            public void evaluate() throws Throwable {
                List<Throwable> cumulative = new ArrayList<Throwable>();
                try {
                    beforeAfters.evaluate();
                } catch (Throwable t) {
                    cumulative.add(t);
                }
                // All @Afters must be called.
                for (Method m : afters) {
                    try {
                        invoke(m, instance);
                    } catch (Throwable t) {
                        cumulative.add(t);
                    }
                }
                // At end, throw the exception or propagete.
                if (cumulative.size() == 1) {
                    throw cumulative.get(0);
                } else if (cumulative.size() > 1) {
                    throw new MultipleFailureException(cumulative);
                }
            }
        };
    }
    return s;
}
Also used : MultipleFailureException(org.junit.runners.model.MultipleFailureException) Statement(org.junit.runners.model.Statement) List(java.util.List) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) FrameworkMethod(org.junit.runners.model.FrameworkMethod)

Example 89 with Statement

use of org.junit.runners.model.Statement in project randomizedtesting by randomizedtesting.

the class ThreadLeakControl method forTest.

/**
   * A {@link Statement} for wrapping test-level execution. 
   */
Statement forTest(final Statement s, final TestCandidate c) {
    final int timeout = determineTimeout(c);
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            checkZombies();
            final StatementRunner sr = new StatementRunner(s);
            final List<Throwable> errors = new ArrayList<Throwable>();
            final Set<Thread> beforeTestState = getThreads(suiteFilters);
            final boolean timedOut = forkTimeoutingTask(sr, timeout, errors);
            if (suiteTimedOut.get()) {
                return;
            }
            if (timedOut) {
                LOGGER.warning("Test execution timed out: " + c.description + formatThreadStacksFull());
            }
            if (timedOut) {
                errors.add(RandomizedRunner.augmentStackTrace(emptyStack(new Exception("Test timeout exceeded (>= " + timeout + " msec)."))));
            }
            final AnnotatedElement[] chain = { c.method, c.getTestClass(), DefaultAnnotationValues.class };
            List<Throwable> threadLeakErrors = timedOut ? new ArrayList<Throwable>() : errors;
            checkThreadLeaks(beforeTestState, threadLeakErrors, LifecycleScope.TEST, c.description, chain);
            processUncaught(errors, runner.handler.getUncaughtAndClear());
            MultipleFailureException.assertEmpty(errors);
        }
    };
}
Also used : Statement(org.junit.runners.model.Statement) ArrayList(java.util.ArrayList) AnnotatedElement(java.lang.reflect.AnnotatedElement) AssumptionViolatedException(org.junit.internal.AssumptionViolatedException) StoppedByUserException(org.junit.runner.notification.StoppedByUserException) MultipleFailureException(org.junit.runners.model.MultipleFailureException) UncaughtException(com.carrotsearch.randomizedtesting.RandomizedRunner.UncaughtException)

Example 90 with Statement

use of org.junit.runners.model.Statement in project randomizedtesting by randomizedtesting.

the class RandomizedRunner method withClassAfters.

private Statement withClassAfters(final Statement s) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            List<Throwable> errors = new ArrayList<Throwable>();
            try {
                s.evaluate();
            } catch (Throwable t) {
                errors.add(augmentStackTrace(t, runnerRandomness));
            }
            for (Method method : getShuffledMethods(AfterClass.class)) {
                try {
                    invoke(method, null);
                } catch (Throwable t) {
                    errors.add(augmentStackTrace(t, runnerRandomness));
                }
            }
            MultipleFailureException.assertEmpty(errors);
        }
    };
}
Also used : Statement(org.junit.runners.model.Statement) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) FrameworkMethod(org.junit.runners.model.FrameworkMethod)

Aggregations

Statement (org.junit.runners.model.Statement)129 Test (org.junit.Test)22 FrameworkMethod (org.junit.runners.model.FrameworkMethod)15 Method (java.lang.reflect.Method)10 AssumptionViolatedException (org.junit.internal.AssumptionViolatedException)10 Fail (org.junit.internal.runners.statements.Fail)9 TestRule (org.junit.rules.TestRule)7 Description (org.junit.runner.Description)7 MethodRule (org.junit.rules.MethodRule)6 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 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