javatips.net counter

Java Examples for org.junit.runner.Description

The following java examples will help you to understand the usage of org.junit.runner.Description. These source code samples are taken from different open source projects.

Example 1
Project: eclipselink.runtime-master  File: SerializableDescription.java View source code
/**
     * Create a SerializableDescription objects from an org.junit.runner.Description objects
     * @param description the org.junit.runner.Description object to be converted
     * @return the SerializableDescription object created from an org.junit.runner.Description object
     */
@SuppressWarnings("unchecked")
public static SerializableDescription create(Description description) {
    final List<SerializableDescription> children;
    if (description.getChildren() != null) {
        children = new ArrayList<SerializableDescription>();
        for (Description child : description.getChildren()) {
            children.add(create(child));
        }
    } else {
        children = Collections.EMPTY_LIST;
    }
    return new SerializableDescription(description.getDisplayName(), children);
}
Example 2
Project: org.openntf.domino-master  File: JUnit4TestClassReference.java View source code
private void sendDescriptionTree(final IVisitsTestTrees notified, org.junit.runner.Description description) {
    if (description.isTest()) {
        notified.visitTreeEntry(new JUnit4Identifier(description), false, 1);
    } else {
        notified.visitTreeEntry(new JUnit4Identifier(description), true, description.getChildren().size());
        for (Description child : description.getChildren()) {
            sendDescriptionTree(notified, child);
        }
    }
}
Example 3
Project: RoboBuggy-master  File: MaxStarterTest.java View source code
private void assertFilterLeavesTestUnscathed(Class<?> testClass) {
    Request oneClass = Request.aClass(testClass);
    Request filtered = oneClass.filterWith(new Filter() {

        @Override
        public boolean shouldRun(Description description) {
            return true;
        }

        @Override
        public String describe() {
            return "Everything";
        }
    });
    int filterCount = filtered.getRunner().testCount();
    int coreCount = oneClass.getRunner().testCount();
    assertEquals("Counts match up in " + testClass, coreCount, filterCount);
}
Example 4
Project: fluent-http-master  File: RunMultipleTimes.java View source code
@Override
public Statement apply(Statement statement, Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            for (int i = 0; i < times; i++) {
                System.out.printf("Run #%02d%n", i);
                statement.evaluate();
            }
        }
    };
}
Example 5
Project: eclipse.jdt.ui-master  File: RerunFailFirstTests.java View source code
private String buildDescriptionOrder(Description description) {
    StringBuilder sb = new StringBuilder();
    String displayName = description.getDisplayName();
    if (description.isSuite()) {
        int dollarIndex = displayName.lastIndexOf('$');
        sb.append(displayName.substring(dollarIndex + 1, dollarIndex + 3));
    } else {
        int parenIndex = displayName.indexOf('(');
        sb.append(displayName.substring(parenIndex - 2, parenIndex));
    }
    sb.append(" ");
    for (Description child : description.getChildren()) {
        sb.append(buildDescriptionOrder(child));
    }
    return sb.toString();
}
Example 6
Project: powermock-master  File: PowerMockJUnit44RunnerDelegateImpl.java View source code
protected void invokeTestMethod(final Method method, RunNotifier notifier) {
    Description description = methodDescription(method);
    final Object testInstance;
    try {
        testInstance = createTest();
    } catch (InvocationTargetException e) {
        testAborted(notifier, description, e.getTargetException());
        return;
    } catch (Exception e) {
        testAborted(notifier, description, e);
        return;
    }
    // Check if we extend from TestClass, in that case we must run the setUp
    // and tearDown methods.
    final boolean extendsFromTestCase = TestCase.class.isAssignableFrom(testClass.getJavaClass());
    final TestMethod testMethod = wrapMethod(method);
    createPowerMockRunner(testInstance, testMethod, notifier, description, extendsFromTestCase).run();
}
Example 7
Project: lucene-solr-master  File: BaseDistributedSearchTestCase.java View source code
@Override
public Statement apply(Statement statement, Description description) {
    ShardsFixed fixed = description.getAnnotation(ShardsFixed.class);
    ShardsRepeat repeat = description.getAnnotation(ShardsRepeat.class);
    if (fixed != null && repeat != null) {
        throw new RuntimeException("ShardsFixed and ShardsRepeat annotations can't coexist");
    } else if (fixed != null) {
        return new ShardsFixedStatement(fixed.num(), statement);
    } else if (repeat != null) {
        return new ShardsRepeatStatement(repeat.min(), repeat.max(), statement);
    } else {
        return (isShardCountFixed ? new ShardsFixedStatement(shardCount, statement) : new ShardsRepeatStatement(1, DEFAULT_MAX_SHARD_COUNT, statement));
    }
}
Example 8
Project: CallBuilder-master  File: ParentRunner.java View source code
/**
     * Runs a [email protected] Statement} that represents a leaf (aka atomic) test.
     */
protected final void runLeaf(Statement statement, Description description, RunNotifier notifier) {
    EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description);
    eachNotifier.fireTestStarted();
    try {
        statement.evaluate();
    } catch (AssumptionViolatedException e) {
        eachNotifier.addFailedAssumption(e);
    } catch (Throwable e) {
        eachNotifier.addFailure(e);
    } finally {
        eachNotifier.fireTestFinished();
    }
}
Example 9
Project: js-android-app-master  File: DatabaseRule.java View source code
@Override
public final Statement apply(final Statement base, Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            resetDatabase();
            base.evaluate();
            resetDatabase();
        }
    };
}
Example 10
Project: kouchat-android-master  File: ExpectedSystemOut.java View source code
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            beforeSetUp();
            try {
                base.evaluate();
            } finally {
                afterTearDown();
            }
        }
    };
}
Example 11
Project: keycloak-master  File: SamlPicketlinkSPTest.java View source code
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            if (Environment.IS_IBM_JAVA) {
                System.err.println("Ignore " + description.getDisplayName() + " because executing on IBM JDK");
            } else {
                base.evaluate();
            }
        }
    };
}
Example 12
Project: k3po-master  File: K3poRule.java View source code
@Override
public Statement apply(Statement statement, final Description description) {
    Specification specification = description.getAnnotation(Specification.class);
    String[] scripts = (specification != null) ? specification.value() : null;
    ScriptProperty overriddenProperty = description.getAnnotation(ScriptProperty.class);
    String[] overriddenProperties = (overriddenProperty != null) ? overriddenProperty.value() : null;
    List<String> methodOverridenScriptProperties = new ArrayList<>();
    if (overriddenProperties != null) {
        for (String prop : overriddenProperties) {
            methodOverridenScriptProperties.add(prop);
        }
    }
    if (scripts != null) {
        // decorate with K3PO behavior only if @Specification annotation is present
        List<String> scriptNames = new LinkedList<>();
        for (String script : scripts) {
            // strict compatibility (relax to support fully qualified paths later)
            if (script.startsWith("/")) {
                throw new IllegalArgumentException("Script path must be relative");
            }
            Matcher matcher = NAMED_PACKAGE_PATH_PATTERN.matcher(script);
            if (matcher.matches()) {
                String shortName = matcher.group(1);
                String relativePath = matcher.group(2);
                String packagePath = packagePathsByName.get(shortName);
                if (packagePath == null) {
                    throw new IllegalArgumentException("Script short name not found: " + shortName);
                }
                String scriptName = format("%s/%s", packagePath, relativePath);
                scriptNames.add(scriptName);
            } else {
                String packagePath = getScriptRoot(description);
                String scriptName = format("%s/%s", packagePath, script);
                scriptNames.add(scriptName);
            }
        }
        URL controlURL = this.controlURL;
        if (controlURL == null) {
            // lazy dependency on TCP scheme
            controlURL = createURL("tcp://localhost:11642");
        }
        methodOverridenScriptProperties.addAll(classOverriddenProperties);
        this.statement = new SpecificationStatement(statement, controlURL, scriptNames, latch, methodOverridenScriptProperties);
        statement = this.statement;
    }
    return super.apply(statement, description);
}
Example 13
Project: arquillian-core-master  File: RulesEnrichmentTestCase.java View source code
private void testTestRuleEnrichment(AbstractRuleStatementEnrichment test) throws Throwable {
    Statement invokeStatement = getInvokingStatement(test);
    TestClass testClass = new TestClass(test.getClass());
    Method testMethod = test.getClass().getMethod("verifyEnrichment");
    Description desc = Description.createTestDescription(test.getClass(), "verifyEnrichment");
    fire(new RulesEnrichment(test, testClass, testMethod, LifecycleMethodExecutor.NO_OP));
    final Statement statement = test.getTestRule().apply(invokeStatement, desc);
    LifecycleMethodExecutor testLifecycleMethodExecutor = getTestLifecycleMethodExecutor(statement);
    fire(new BeforeRules(test, testClass, statement, testMethod, testLifecycleMethodExecutor));
    testLifecycleMethodExecutor.invoke();
    verifyEventFired(2);
}
Example 14
Project: keywhiz-master  File: MigrationsRule.java View source code
@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            File yamlFile = new File(Resources.getResource("keywhiz-test.yaml").getFile());
            Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
            ObjectMapper objectMapper = KeywhizService.customizeObjectMapper(Jackson.newObjectMapper());
            KeywhizConfig config = new ConfigurationFactory<>(KeywhizConfig.class, validator, objectMapper, "dw").build(yamlFile);
            DataSource dataSource = config.getDataSourceFactory().build(new MetricRegistry(), "db-migrations");
            Flyway flyway = new Flyway();
            flyway.setDataSource(dataSource);
            flyway.setLocations(config.getMigrationsDir());
            flyway.clean();
            flyway.migrate();
            DSLContext dslContext = DSLContexts.databaseAgnostic(dataSource);
            DbSeedCommand.doImport(dslContext);
            base.evaluate();
        }
    };
}
Example 15
Project: idnadrev-master  File: LauncherRunner.java View source code
@Override
public void run(RunNotifier notifier) {
    System.setProperty("initialActivtiy", "");
    File versionFile = new File(System.getProperty("user.dir"), "version.info");
    Versioning versioning = new Versioning(versionFile, LauncherRunner.class);
    versioning.upgradeToCurrentVersion();
    Launcher launcher = Launcher.instance;
    if (!launcher.isStarted()) {
        launcher.startAll();
        launcher.awaitStart();
    }
    notifier.addListener(new RunListener() {

        @Override
        public void testStarted(Description description) throws Exception {
            super.testStarted(description);
            log.info("@Test:{}.{}", description.getClassName(), description.getMethodName());
        }
    });
    super.run(notifier);
}
Example 16
Project: usergrid-master  File: CoreApplication.java View source code
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            before(description);
            try {
                base.evaluate();
            } finally {
                after(description);
            }
        }
    };
}
Example 17
Project: framework-master  File: ScreenshotTB3Test.java View source code
@Override
protected void starting(org.junit.runner.Description description) {
    Class<?> testClass = description.getTestClass();
    // Runner adds [BrowserName] which we do not want to use in the
    // screenshot name
    String testMethod = description.getMethodName();
    testMethod = testMethod.replaceAll("\\[.*\\]", "");
    String className = testClass.getSimpleName();
    screenshotBaseName = className + "-" + testMethod;
}
Example 18
Project: jumi-master  File: AppRunner.java View source code
// JUnit integration
@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            setup();
            try {
                base.evaluate();
            } finally {
                tearDown();
            }
        }
    };
}
Example 19
Project: flink-master  File: RetryRule.java View source code
@Override
public Statement apply(Statement statement, Description description) {
    RetryOnFailure retryOnFailure = description.getAnnotation(RetryOnFailure.class);
    RetryOnException retryOnException = description.getAnnotation(RetryOnException.class);
    // sanity check that we don't use expected exceptions with the RetryOnX annotations
    if (retryOnFailure != null || retryOnException != null) {
        Test test = description.getAnnotation(Test.class);
        if (test.expected() != Test.None.class) {
            throw new IllegalArgumentException("You cannot combine the RetryOnFailure " + "annotation with the Test(expected) annotation.");
        }
    }
    // sanity check that we don't use both annotations
    if (retryOnFailure != null && retryOnException != null) {
        throw new IllegalArgumentException("You cannot combine the RetryOnFailure and RetryOnException annotations.");
    }
    if (retryOnFailure != null) {
        return new RetryOnFailureStatement(retryOnFailure.times(), statement);
    } else if (retryOnException != null) {
        return new RetryOnExceptionStatement(retryOnException.times(), retryOnException.exception(), statement);
    } else {
        return statement;
    }
}
Example 20
Project: cloudtm-data-platform-master  File: RequiresTransactionalCapabilitiesRule.java View source code
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            if (TestHelper.backendSupportsTransactions()) {
                base.evaluate();
            } else {
                log.info("Skipping test " + description.getMethodName() + " as the current GridDialect doesn't support transactions");
            }
        }
    };
}
Example 21
Project: tinkerpop-master  File: AbstractGremlinSuite.java View source code
@Override
public boolean shouldRun(final Description description) {
    // for a call to shouldRun
    if (description.getTestClass() != null) {
        final boolean ignoreWholeTestCase = entireTestCaseToIgnore.stream().map(this::transformToClass).anyMatch( claxx -> claxx.isAssignableFrom(description.getTestClass()));
        if (ignoreWholeTestCase)
            return false;
    }
    if (description.isTest()) {
        // next check if there is a test group to consider. if not then check for a  specific test to ignore
        return !(!testGroupToIgnore.isEmpty() && testGroupToIgnore.stream().anyMatch( optOut -> optOut.getTestClass().isAssignableFrom(description.getTestClass()) && description.getMethodName().equals(optOut.getMethodName()))) && !individualSpecificTestsToIgnore.contains(description);
    }
    // explicitly check if any children want to run
    for (Description each : description.getChildren()) {
        if (shouldRun(each)) {
            return true;
        }
    }
    return false;
}
Example 22
Project: swtbot-master  File: ScreenshotCaptureNotifier.java View source code
@Override
public void fireTestFinished(Description description) {
    delegate.fireTestFinished(description);
    if (testFailure == null) {
        // Test didn't fail after all -- perhaps some rule let the test
        // pass even though it had raised an exception. Remove a previously
        // taken screenshot, if any.
        screenshotCreator.removeScreenshot(description);
    }
    testFailure = null;
}
Example 23
Project: windowtester-master  File: RunManager.java View source code
@SuppressWarnings("deprecation")
public void run(IRunnable runnable, Description description) throws Throwable {
    System.out.println("run manager running");
    //exec launch (NOTE: should this be in runner?)
    launchApp();
    //start test monitor ---> TODO: this should be in the exec monitor/runner
    TestMonitor.getInstance().beginTest(new JUnit4TestId(description));
    System.out.println("RunManager starting test: " + description);
    //get an execution monitor appropriate for this test type
    IExecutionMonitor execMonitor = getExecutionMonitor();
    ExecutionMonitor.setContext(getExecContext());
    //run the test in a separate monitored thread
    new SequenceRunner(execMonitor).exec(runnable);
    //stop test monitor ---> TODO: this should be in the exec monitor/runner
    TestMonitor.getInstance().endTestCase();
}
Example 24
Project: FreeBuilder-master  File: ModelRule.java View source code
@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            start();
            try {
                base.evaluate();
            } finally {
                destroy();
            }
        }
    };
}
Example 25
Project: modeshape-master  File: SkipTestRule.java View source code
@Override
public Statement apply(Statement base, Description description) {
    SkipLongRunning skipLongRunningAnnotation = hasAnnotation(description, SkipLongRunning.class);
    if (skipLongRunningAnnotation != null) {
        boolean skipLongRunning = Boolean.valueOf(System.getProperty(SkipLongRunning.SKIP_LONG_RUNNING_PROPERTY));
        if (skipLongRunning) {
            return emptyStatement(skipLongRunningAnnotation.value(), description);
        }
    }
    SkipOnOS skipOnOSAnnotation = hasAnnotation(description, SkipOnOS.class);
    if (skipOnOSAnnotation != null) {
        String[] oses = skipOnOSAnnotation.value();
        String osName = System.getProperty("os.name");
        if (!StringUtil.isBlank(osName)) {
            for (String os : oses) {
                if (osName.toLowerCase().startsWith(os.toLowerCase())) {
                    return emptyStatement(skipOnOSAnnotation.description(), description);
                }
            }
        }
    }
    return base;
}
Example 26
Project: selenium-video-node-master  File: AbstractVideoSeleniumTest.java View source code
@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            try {
                // this bit actually runs the test.
                base.evaluate();
            } catch (Throwable e) {
                if (driver != null) {
                    URL remoteServer = ((HttpCommandExecutor) driver.getCommandExecutor()).getAddressOfRemoteServer();
                    URL videoUrl = new URL(remoteServer, "/grid/admin/HubVideoDownloadServlet/?sessionId=" + sessionId);
                    String message = e.getClass().getName();
                    throw new RuntimeException("Test failed due to exception: " + message + ". Video available at " + videoUrl, e);
                } else {
                    throw e;
                }
            }
        }
    };
}
Example 27
Project: jena-master  File: ModelTestSuite.java View source code
@Override
protected void runChild(Test child, RunNotifier notifier) {
    Method setUp = null;
    try {
        setUp = child.getClass().getMethod("setUp");
    } catch (SecurityException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
    } catch (NoSuchMethodException e1) {
    }
    Method tearDown = null;
    try {
        tearDown = child.getClass().getMethod("tearDown");
    } catch (SecurityException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
    } catch (NoSuchMethodException e1) {
    }
    for (Method m : child.getClass().getMethods()) {
        if (m.getName().startsWith("test") && m.getParameterTypes().length == 0) {
            Description desc = Description.createTestDescription(child.getClass(), child.toString());
            notifier.fireTestStarted(desc);
            try {
                if (setUp != null) {
                    setUp.invoke(child);
                }
                m.invoke(child);
                if (tearDown != null) {
                    tearDown.invoke(child);
                }
                notifier.fireTestFinished(desc);
            } catch (IllegalArgumentException e) {
                notifier.fireTestFailure(new Failure(desc, e));
            } catch (IllegalAccessException e) {
                notifier.fireTestFailure(new Failure(desc, e));
            } catch (InvocationTargetException e) {
                notifier.fireTestFailure(new Failure(desc, e.getTargetException()));
            } catch (RuntimeException e) {
                notifier.fireTestFailure(new Failure(desc, e));
                throw e;
            }
        }
    }
}
Example 28
Project: org.eclipse.ecr-master  File: WebDriverFeature.java View source code
@Override
public boolean shouldRun(Description description) {
    SkipBrowser skip = description.getAnnotation(SkipBrowser.class);
    if (skip == null) {
        return true;
    }
    for (BrowserFamily family : skip.value()) {
        if (config.getBrowserFamily().equals(family)) {
            return false;
        }
    }
    return true;
}
Example 29
Project: sql-layer-master  File: MTBase.java View source code
@Override
public void failed(Throwable e, Description description) {
    System.err.printf("Ran with DELAY_BEFORE: %s, DELAY_DDL_STAGE: %s, DELAY_THREAD_STAGE: %s\n", ConcurrentTestBuilderImpl.DELAY_BEFORE, ConcurrentTestBuilderImpl.DELAY_DDL_STAGE, ConcurrentTestBuilderImpl.DELAY_THREAD_STAGE);
}
Example 30
Project: dragome-sdk-master  File: DragomeTestRunner.java View source code
protected void runChild(FrameworkMethod child, RunNotifier notifier) {
    Description spec1 = Description.createTestDescription(clazz, child.getName());
    String sourceCode = "try{new " + NamingUtils.javaToDragomeNotation(clazz) + "()." + javaMethodNameToDragomeNotation(child.getName()) + "(); window.failed=false}catch(e){window.failed=true}";
    ScriptResult executeJavaScript = page.executeJavaScript(sourceCode);
    String resultSource = "window.failed";
    executeJavaScript = page.executeJavaScript(resultSource);
    notifier.fireTestStarted(spec1);
    if (executeJavaScript.getJavaScriptResult().toString().equals("true"))
        notifier.fireTestFailure(new Failure(spec1, new Exception("Test failed in javascript engine")));
    else
        notifier.fireTestFinished(spec1);
    failed = false;
}
Example 31
Project: lettuce-master  File: SentinelRule.java View source code
@Override
public Statement apply(final Statement base, Description description) {
    final Statement before = new Statement() {

        @Override
        public void evaluate() throws Exception {
            if (flushBeforeTest) {
                flush();
            }
        }
    };
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            before.evaluate();
            base.evaluate();
            for (RedisSentinelCommands<String, String> commands : sentinelConnections.values()) {
                commands.close();
            }
        }
    };
}
Example 32
Project: gatein-portal-master  File: KernelLifeCycle.java View source code
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            //
            bootstrap = new KernelBootstrap(Thread.currentThread().getContextClassLoader());
            // Add configuration if any
            ConfiguredBy config = description.getAnnotation(ConfiguredBy.class);
            if (config != null) {
                bootstrap.addConfiguration(config);
            }
            //
            bootstrap.boot();
            //
            try {
                base.evaluate();
            } finally {
                bootstrap.dispose();
                bootstrap = null;
            }
        }
    };
}
Example 33
Project: java-thumbnailer-master  File: LabelledParameterized.java View source code
private void generateLabelledDescription() throws Exception {
    Description originalDescription = super.getDescription();
    labelledDescription = Description.createSuiteDescription(originalDescription.getDisplayName());
    ArrayList<Description> childDescriptions = originalDescription.getChildren();
    int childCount = childDescriptions.size();
    if (childCount != labels.size())
        throw new Exception("Number of labels and number of parameters must match.");
    for (int i = 0; i < childDescriptions.size(); i++) {
        Description childDescription = childDescriptions.get(i);
        String label = labels.get(i);
        Description newDescription = Description.createSuiteDescription(label);
        ArrayList<Description> grandChildren = childDescription.getChildren();
        for (Description grandChild : grandChildren) newDescription.addChild(grandChild);
        labelledDescription.addChild(newDescription);
    }
}
Example 34
Project: wisdom-master  File: RunOnVertxContext.java View source code
@Override
public Statement apply(Statement base, Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            vertx = createVertx.get();
            CountDownLatch lock = new CountDownLatch(1);
            AtomicReference<Throwable> error = new AtomicReference<>();
            vertx.runOnContext(( v) -> {
                try {
                    base.evaluate();
                } catch (Throwable throwable) {
                    error.set(throwable);
                } finally {
                    lock.countDown();
                }
            });
            lock.await();
            CountDownLatch latch = new CountDownLatch(1);
            closeVertx.accept(vertx, latch);
            try {
                if (!latch.await(30 * 1000, TimeUnit.MILLISECONDS)) {
                    System.err.println("Could not close Vert.x in tme");
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            if (error.get() != null) {
                throw error.get();
            }
        }
    };
}
Example 35
Project: jgit-master  File: RepeatRule.java View source code
@Override
public Statement apply(Statement statement, Description description) {
    Statement result = statement;
    Repeat repeat = description.getAnnotation(Repeat.class);
    if (repeat != null) {
        int n = repeat.n();
        result = new RepeatStatement(n, statement);
    }
    return result;
}
Example 36
Project: spring-framework-2.5.x-master  File: SpringJUnit4ClassRunner.java View source code
/**
	 * Invokes the supplied [email protected] Method test method} and notifies the supplied
	 * [email protected] RunNotifier} of the appropriate events.
	 * @see #createTest()
	 * @see JUnit4ClassRunner#invokeTestMethod(Method,RunNotifier)
	 */
@Override
protected void invokeTestMethod(Method method, RunNotifier notifier) {
    if (logger.isDebugEnabled()) {
        logger.debug("Invoking test method [" + method.toGenericString() + "]");
    }
    // The following is a 1-to-1 copy of the original JUnit 4.4 code, except
    // that we use custom implementations for TestMethod and MethodRoadie.
    Description description = methodDescription(method);
    Object testInstance;
    try {
        testInstance = createTest();
    } catch (InvocationTargetException ex) {
        notifier.testAborted(description, ex.getCause());
        return;
    } catch (Exception ex) {
        notifier.testAborted(description, ex);
        return;
    }
    SpringTestMethod testMethod = new SpringTestMethod(method, getTestClass());
    new SpringMethodRoadie(getTestContextManager(), testInstance, testMethod, notifier, description).run();
}
Example 37
Project: lcm-master  File: RunNotifier.java View source code
void run() {
    synchronized (fListeners) {
        List<RunListener> safeListeners = new ArrayList<RunListener>();
        List<Failure> failures = new ArrayList<Failure>();
        for (Iterator<RunListener> all = fCurrentListeners.iterator(); all.hasNext(); ) {
            try {
                RunListener listener = all.next();
                notifyListener(listener);
                safeListeners.add(listener);
            } catch (Exception e) {
                failures.add(new Failure(Description.TEST_MECHANISM, e));
            }
        }
        fireTestFailures(safeListeners, failures);
    }
}
Example 38
Project: FireflowEngine20-master  File: AdvancedTestAll.java View source code
public junit.framework.Test asTest(Description description) {
    return new junit.framework.Test() {

        public void run(TestResult result) {
            throw Lang.noImplement();
        }

        public int countTestCases() {
            return 1;
        }
    };
}
Example 39
Project: rascal-master  File: RascalJUnitCompiledTestRunner.java View source code
@Override
public Description getDescription() {
    if (desc != null)
        return desc;
    Description desc = Description.createSuiteDescription(prefix);
    this.desc = desc;
    URIResolverRegistry resolver = URIResolverRegistry.getInstance();
    try {
        List<String> modules = getRecursiveModuleList(vf.sourceLocation("std", "", "/" + prefix.replaceAll("::", "/")));
        for (String module : modules) {
            String qualifiedName = (prefix.isEmpty() ? "" : prefix + "::") + module;
            RascalExecutionContext rex = RascalExecutionContextBuilder.normalContext(pcfg).build();
            ISourceLocation binary = Rascal.findBinary(pcfg.getBin(), qualifiedName);
            ISourceLocation source = rex.getPathConfig().resolveModule(qualifiedName);
            //  Do a sufficient but not complete check on the binary; changes to imports will go unnoticed!
            if (!resolver.exists(binary) || resolver.lastModified(source) > resolver.lastModified(binary)) {
                System.err.println("Compiling: " + qualifiedName);
                //	        HashMap<String, IValue> kwparams = new HashMap<>();
                //	        kwparams.put("enableAsserts", vf.bool(true));
                IList programs = kernel.compileAndLink(vf.list(vf.string(qualifiedName)), //	            pcfg.getBin(),
                pcfg.asConstructor(kernel), kernel.kw_compileAndLink().enableAsserts(true).reloc(vf.sourceLocation("noreloc", "", "")));
                boolean ok = RascalC.handleMessages(programs, pcfg);
                if (!ok) {
                    System.exit(1);
                }
            }
            RVMExecutable executable = RVMExecutable.read(binary, rex.getTypeStore());
            if (executable.getTests().size() > 0) {
                Description modDesc = Description.createSuiteDescription(qualifiedName);
                desc.addChild(modDesc);
                int ntests = 0;
                int ntests_with_random = 0;
                LinkedList<Description> module_ignored = new LinkedList<Description>();
                for (Function f : executable.getTests()) {
                    String test_name = f.computeTestName();
                    Description d = Description.createTestDescription(getClass(), test_name);
                    modDesc.addChild(d);
                    ntests++;
                    ntests_with_random += f.getTries();
                    if (f.isIgnored()) {
                        module_ignored.add(d);
                    }
                }
                testsPerModule.put(qualifiedName, ntests);
                ignoredPerModule.put(qualifiedName, module_ignored);
                totalTests += ntests;
                totalTestsWithRandom += ntests_with_random;
            }
        }
        int totalIgnored = 0;
        for (String name : testsPerModule.keySet()) {
            int tests = testsPerModule.get(name);
            if (tests > 0) {
                int ignored = ignoredPerModule.get(name).size();
                totalIgnored += ignored;
            //	        System.err.println(name + ": " + testsPerModule.get(name) + (ignored == 0 ? "" : " (ignored: " + ignored + ")"));
            }
        }
        System.err.println(prefix + ":");
        System.err.println("\ttests: " + totalTests);
        System.err.println("\tignored: " + totalIgnored);
        System.err.println("\tto be executed (including random arguments): " + (totalTestsWithRandom - totalIgnored));
        return desc;
    } catch (IOException e) {
        throw new RuntimeException("could not create test suite", e);
    } catch (URISyntaxException e) {
        throw new RuntimeException("could not create test suite", e);
    }
}
Example 40
Project: revapi-master  File: Jar.java View source code
@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            compiledStuff.clear();
            try {
                base.evaluate();
            } finally {
                cleanUp();
            }
        }
    };
}
Example 41
Project: property-db-master  File: AndroidJUnitRunner.java View source code
/**
         * send a status for the start of a each test, so long tests can be seen
         * as "running"
         */
@Override
public void testStarted(Description description) throws Exception {
    String testClass = description.getClassName();
    String testName = description.getMethodName();
    mTestResult = new Bundle(mResultTemplate);
    mTestResult.putString(REPORT_KEY_NAME_CLASS, testClass);
    mTestResult.putString(REPORT_KEY_NAME_TEST, testName);
    mTestResult.putInt(REPORT_KEY_NUM_CURRENT, ++mTestNum);
    // pretty printing
    if (testClass != null && !testClass.equals(mTestClass)) {
        mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT, String.format("\n%s:", testClass));
        mTestClass = testClass;
    } else {
        mTestResult.putString(Instrumentation.REPORT_KEY_STREAMRESULT, "");
    }
    sendStatus(REPORT_VALUE_RESULT_START, mTestResult);
    mTestResultCode = 0;
}
Example 42
Project: commons-old-master  File: JUnitConsoleRunner.java View source code
private void registerTests(Iterable<Description> tests) throws IOException {
    for (Description test : tests) {
        registerTests(test.getChildren());
        if (Util.isRunnable(test)) {
            StreamCapture capture = captures.get(test.getTestClass());
            if (capture == null) {
                String prefix = test.getClassName();
                File out = new File(outdir, prefix + ".out.txt");
                Files.createParentDirs(out);
                File err = new File(outdir, prefix + ".err.txt");
                Files.createParentDirs(err);
                capture = new StreamCapture(out, err);
                captures.put(test.getTestClass(), capture);
            }
            capture.incrementUseCount();
        }
    }
}
Example 43
Project: aokp-gerrit-master  File: AbstractDaemonTest.java View source code
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            boolean mem = description.getAnnotation(UseLocalDisk.class) == null;
            boolean enableHttpd = description.getAnnotation(NoHttpd.class) == null && description.getTestClass().getAnnotation(NoHttpd.class) == null;
            beforeTest(config(description), mem, enableHttpd);
            base.evaluate();
            afterTest();
        }
    };
}
Example 44
Project: dcache-master  File: AbstractFtpDoorV1Test.java View source code
@Override
public Statement apply(final Statement stmnt, Description d) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            try {
                stmnt.evaluate();
                if (checkCode)
                    fail("Expected FTPCommandException '" + _code + "' not thrown.");
            } catch (FTPCommandException commandException) {
                if (checkCode) {
                    assertEquals("Unexpected reply '" + commandException.getCode() + " " + commandException.getReply() + "'", _code, commandException.getCode());
                } else {
                    fail("Caught unexpected exception FTPCommandException '" + _code + "':'" + commandException.getMessage() + "'.");
                }
            }
        }
    };
}
Example 45
Project: android-platform-tools-base-master  File: GradleTestProject.java View source code
@Override
public Statement apply(final Statement base, Description description) {
    testDir = new File(outDir, description.getTestClass().getName());
    // getMethodName() is null if this rule is used as a @ClassRule.
    if (description.getMethodName() != null) {
        String dirName = description.getMethodName();
        dirName = dirName.replaceAll("[^a-zA-Z0-9_]", "_");
        testDir = new File(testDir, dirName);
    }
    testDir = new File(testDir, name);
    buildFile = new File(testDir, "build.gradle");
    sourceDir = new File(testDir, "src");
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            if (testDir.exists()) {
                deleteRecursive(testDir);
            }
            assertTrue(testDir.mkdirs());
            assertTrue(sourceDir.mkdirs());
            Files.copy(new File(Builder.TEST_PROJECT_DIR, COMMON_HEADER), new File(testDir.getParent(), COMMON_HEADER));
            Files.copy(new File(Builder.TEST_PROJECT_DIR, COMMON_LOCAL_REPO), new File(testDir.getParent(), COMMON_LOCAL_REPO));
            Files.copy(new File(Builder.TEST_PROJECT_DIR, COMMON_BUILD_SCRIPT), new File(testDir.getParent(), COMMON_BUILD_SCRIPT));
            Files.copy(new File(Builder.TEST_PROJECT_DIR, COMMON_BUILD_SCRIPT_EXP), new File(testDir.getParent(), COMMON_BUILD_SCRIPT_EXP));
            Files.copy(new File(Builder.TEST_PROJECT_DIR, COMMON_GRADLE_PLUGIN_VERSION), new File(testDir.getParent(), COMMON_GRADLE_PLUGIN_VERSION));
            if (testProject != null) {
                testProject.write(testDir, testProject.containsFullBuildScript() ? "" : getGradleBuildscript());
            } else {
                Files.write(getGradleBuildscript(), buildFile, Charsets.UTF_8);
            }
            createLocalProp(testDir, sdkDir, ndkDir);
            createGradleProp();
            base.evaluate();
        }
    };
}
Example 46
Project: android-sdk-sources-for-api-level-23-master  File: ExprModelTest.java View source code
@Override
protected void failed(Throwable e, Description description) {
    if (mExprModel != null && mExprModel.getFlagMapping() != null) {
        final String[] mapping = mExprModel.getFlagMapping();
        for (int i = 0; i < mapping.length; i++) {
            L.d("flag %d: %s", i, mapping[i]);
        }
    }
}