org.junit.platform.launcher.TestIdentifier Java Examples

The following examples show how to use org.junit.platform.launcher.TestIdentifier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Configuration.java    From sbt-jupiter-interface with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts the class-name from the specified test identifier.
 *
 * @param identifier The identifier from which to extract the class-name.
 * @return The class-name of the specified test identifier.
 */
public String extractClassName(TestIdentifier identifier) {

    TestSource testSource = identifier.getSource().orElseThrow(() ->
            new RuntimeException("Test identifier without source: " + identifier));

    if (testSource instanceof ClassSource) {
        return ((ClassSource)testSource).getClassName();
    }

    if (testSource instanceof MethodSource) {
        return ((MethodSource)testSource).getClassName();
    }

    throw new RuntimeException("Test identifier with unknown source: " + identifier);
}
 
Example #2
Source File: OutputCapturingTestListener.java    From sbt-jupiter-interface with Apache License 2.0 6 votes vote down vote up
@Override
public void executionStarted(TestIdentifier identifier) {

    outputStreamMap.computeIfAbsent(identifier.getUniqueId(), key -> {

        final CapturedOutputStream outputStream = new CapturedOutputStream(outputConsumer);
        final CapturedOutputStream errorStream = new CapturedOutputStream(errorConsumer);

        OutputCapture.register(
                new PrintStream(outputStream, true),
                new PrintStream(errorStream, true)
        );

        return outputStream;
    });
}
 
Example #3
Source File: OutputCapturingTestListener.java    From sbt-jupiter-interface with Apache License 2.0 6 votes vote down vote up
@Override
public void executionFinished(TestIdentifier identifier, TestExecutionResult result) {

    CapturedOutputStream outputStream = outputStreamMap.remove(identifier.getUniqueId());
    if (null == outputStream) {
        return;
    }

    OutputCapture.deregister();

    if (isQuiet) {
        if (identifier.isTest()) {
            if (!SUCCESSFUL.equals(result.getStatus())) {
                outputStream.output.forEach(testLogger::info);
                outputStream.output.clear();
            }
        }
    }
}
 
Example #4
Source File: TestPlanExecutionReport.java    From junit5-extensions with MIT License 6 votes vote down vote up
private DisplayName getDisplayName(TestIdentifier testIdentifier) {
  LinkedList<String> names = new LinkedList<>();
  Optional<TestIdentifier> id = Optional.of(testIdentifier);
  do {
    TestIdentifier identifier = id.get();
    Optional<ClassSource> classSource = identifier.getSource()
        .filter(source -> source instanceof ClassSource)
        .map(source -> (ClassSource) source)
        .filter(source -> !source.getPosition().isPresent())
        .filter(source -> classesToSkip.contains(source.getJavaClass()));
    if (classSource.isPresent()) {
      break;
    }

    names.addFirst(identifier.getDisplayName());

    id = id.flatMap(testPlan::getParent);
  } while (id.isPresent());

  return DisplayName.create(names);
}
 
Example #5
Source File: FlatPrintingTestListener.java    From sbt-jupiter-interface with Apache License 2.0 6 votes vote down vote up
@Override
public void executionStarted(TestIdentifier testIdentifier) {

    startTimes.putIfAbsent(testIdentifier.getUniqueId(), System.currentTimeMillis());

    if (!testIdentifier.getParentId().isPresent()) {
        if (!testPlan.getChildren(testIdentifier).isEmpty()) {
            String message = "Test run started (" + testIdentifier.getDisplayName() + ")";
            debugOrInfo(colorTheme.info().format(message));
        }
    }

    if (testIdentifier.isTest()) {

        String testName = configuration.formatIdentifier(testPlan, testIdentifier);
        debugOrInfo("Test " + testName + " started");
    }
}
 
Example #6
Source File: JupiterTestCollector.java    From sbt-jupiter-interface with Apache License 2.0 6 votes vote down vote up
private String fullyQualifiedName(TestIdentifier testIdentifier) {

        TestSource testSource = testIdentifier.getSource().orElse(null);

        if (testSource instanceof ClassSource) {

            ClassSource classSource = (ClassSource)testSource;
            return classSource.getClassName();
        }

        if (testSource instanceof MethodSource) {

            MethodSource methodSource = (MethodSource)testSource;
            return methodSource.getClassName()
                    + '#' + methodSource.getMethodName()
                    + '(' + methodSource.getMethodParameterTypes() + ')';
        }

        return testIdentifier.getLegacyReportingName();
    }
 
Example #7
Source File: AllureJunitPlatform.java    From allure-java with Apache License 2.0 6 votes vote down vote up
private void stopTestCase(final TestIdentifier testIdentifier,
                          final Status status,
                          final StatusDetails statusDetails) {
    final Optional<String> maybeUuid = tests.get(testIdentifier);
    if (!maybeUuid.isPresent()) {
        return;
    }
    final String uuid = maybeUuid.get();
    getLifecycle().updateTestCase(uuid, result -> {
        result.setStage(Stage.FINISHED);
        result.setStatus(status);
        result.setStatusDetails(statusDetails);
    });
    getLifecycle().stopTestCase(uuid);
    getLifecycle().writeTestCase(uuid);
}
 
Example #8
Source File: TaskName.java    From sbt-jupiter-interface with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a task name for the specified {@code identifier}.
 *
 * @param testSuite The name of the test suite.
 * @param identifier The test identifier.
 * @return A task name representing the given identifier.
 */
static TaskName of(String testSuite, TestIdentifier identifier) {

    TaskName result = new TaskName();
    result.fullyQualifiedName = testSuite;

    TestSource testSource = identifier.getSource().orElse(null);

    if (testSource instanceof ClassSource) {

        ClassSource classSource = (ClassSource)testSource;
        result.nestedSuiteId = nestedSuiteId(testSuite, classSource.getClassName());
    }

    if (testSource instanceof MethodSource) {

        MethodSource methodSource = (MethodSource)testSource;
        result.nestedSuiteId = nestedSuiteId(testSuite, methodSource.getClassName());
        result.invocation = invocation(UniqueId.parse(identifier.getUniqueId()));
        result.testName = testName(methodSource.getMethodName(),
                methodSource.getMethodParameterTypes());
    }

    return result;
}
 
Example #9
Source File: AllureJunitPlatform.java    From allure-java with Apache License 2.0 6 votes vote down vote up
private void stopTestContainer(final TestIdentifier testIdentifier) {
    final Optional<String> maybeUuid = containers.get(testIdentifier);
    if (!maybeUuid.isPresent()) {
        return;
    }
    final String uuid = maybeUuid.get();
    final TestPlan context = testPlanStorage.get();
    final Set<String> children = Optional.ofNullable(context)
            .map(tp -> tp.getDescendants(testIdentifier))
            .orElseGet(Collections::emptySet)
            .stream()
            .filter(TestIdentifier::isTest)
            .map(tests::get)
            .filter(Optional::isPresent)
            .map(Optional::get)
            .collect(Collectors.toCollection(HashSet::new));

    if (testIdentifier.isTest()) {
        tests.get(testIdentifier).ifPresent(children::add);
    }

    getLifecycle().updateTestContainer(uuid, container -> container.setChildren(children));
    getLifecycle().stopTestContainer(uuid);
    getLifecycle().writeTestContainer(uuid);
}
 
Example #10
Source File: TestPlanExecutionReport.java    From junit5-extensions with MIT License 6 votes vote down vote up
public final Builder addResult(TestIdentifier identifier, TestExecutionResult result) {
  DisplayName displayName = getDisplayName(identifier);

  if (identifier.isTest()) {
    testsBuilder().add(displayName);
  }

  switch (result.getStatus()) {
    case SUCCESSFUL:
      successfulBuilder().add(displayName);
      return this;
    case FAILED:
      failuresBuilder().put(displayName, result.getThrowable().orElse(null));
      return this;
    default:
      throw new AssertionError("Unhandled case in enum: " + result.getStatus());
  }
}
 
Example #11
Source File: Configuration.java    From sbt-jupiter-interface with Apache License 2.0 6 votes vote down vote up
/**
 * @return A formatted display name on success, {@code NULL} if the given
 *  identifier should be ignored.
 */
private String toName(TestIdentifier identifier) {

    String name = identifier.getDisplayName();
    List<Segment> segments = UniqueId.parse(identifier.getUniqueId()).getSegments();

    if (!segments.isEmpty()) {
        Segment lastSegment = segments.get(segments.size() - 1);

        name = VINTAGE_ENGINE.equals(testEngine)
                ? toVintageName(identifier, lastSegment)
                : toName(lastSegment);
    }

    return name;
}
 
Example #12
Source File: AllureJunitPlatform.java    From allure-java with Apache License 2.0 6 votes vote down vote up
@Override
public void executionSkipped(final TestIdentifier testIdentifier,
                             final String reason) {
    // skip root
    if (!testIdentifier.getParentId().isPresent()) {
        return;
    }
    final TestPlan testPlan = testPlanStorage.get();
    if (Objects.isNull(testPlan)) {
        return;
    }
    reportNested(
            testPlan,
            testIdentifier,
            SKIPPED,
            new StatusDetails().setMessage(reason),
            new HashSet<>()
    );
}
 
Example #13
Source File: AllureJunitPlatform.java    From allure-java with Apache License 2.0 6 votes vote down vote up
@Override
public void executionFinished(final TestIdentifier testIdentifier,
                              final TestExecutionResult testExecutionResult) {
    // skip root
    if (!testIdentifier.getParentId().isPresent()) {
        return;
    }
    final Status status = extractStatus(testExecutionResult);
    final StatusDetails statusDetails = testExecutionResult.getThrowable()
            .flatMap(ResultsUtils::getStatusDetails)
            .orElse(null);

    if (testIdentifier.isTest()) {
        stopTestCase(testIdentifier, status, statusDetails);
    } else if (testExecutionResult.getStatus() != TestExecutionResult.Status.SUCCESSFUL) {
        // report failed containers as fake test results
        startTestCase(testIdentifier);
        stopTestCase(testIdentifier, status, statusDetails);
    }
    stopTestContainer(testIdentifier);
}
 
Example #14
Source File: TestHelper.java    From sbt-jupiter-interface with Apache License 2.0 6 votes vote down vote up
public TestIdentifier findByMethodName(String testMethodName) {

        final Set<TestIdentifier> descendantIdentifiers = getAllDescendants();
        return descendantIdentifiers.stream()
                .filter(testIdentifier -> {

                    TestSource testSource = testIdentifier.getSource().orElse(null);
                    if (testSource instanceof MethodSource) {
                        return ((MethodSource) testSource).getMethodName().equals(testMethodName);
                    }
                    return false;
                })
                .findAny()
                .orElseThrow(() -> {
                    String message = "Could not find test method " + testMethodName + " in:\n";
                    String identifiers = descendantIdentifiers.stream()
                            .map(TestIdentifier::getUniqueId)
                            .collect(Collectors.joining(",\n"));

                    return new AssertionError(message + identifiers);
                });
    }
 
Example #15
Source File: TreePrintingTestListener.java    From sbt-jupiter-interface with Apache License 2.0 5 votes vote down vote up
/**
 * Decreases current indent if the specified identifier has a parent container.
 *
 * @param identifier The test identifier.
 */
private void maybeDecreaseIndent(TestIdentifier identifier) {

    if (hasParentContainer(identifier)) {
        indent = indent.length() > 1 ? indent.substring(2) : "";
    }
}
 
Example #16
Source File: TreePrintingTestListener.java    From sbt-jupiter-interface with Apache License 2.0 5 votes vote down vote up
/**
 * Increases current indent if the specified identifier has a parent container.
 *
 * @param identifier The test identifier.
 */
private void maybeIncreaseIndent(TestIdentifier identifier) {

    if (hasParentContainer(identifier)) {
        indent += "  ";
    }
}
 
Example #17
Source File: JupiterLoadProcessor.java    From zerocode with Apache License 2.0 5 votes vote down vote up
public void updatePassFailCount(SummaryGeneratingListener summaryListener) {
    TestExecutionSummary summary = summaryListener.getSummary();
    if (summary.getTotalFailureCount() > 0) {
        getFailedCounter().incrementAndGet();
        summary.getFailures().forEach(thisFailure -> {
            TestIdentifier testIdentifier = thisFailure.getTestIdentifier();
            String exceptionMessage = thisFailure.getException().getMessage();
            LOGGER.info("\n----------------------------------------------------------------------\n");
            LOGGER.info("\n###JUnit5: Test Failed Due To --> {}, \ntestIdentifier={}", exceptionMessage, testIdentifier);
            LOGGER.info("\n----------------------------------------------------------------------\n");
        });
    } else {
        getPassedCounter().incrementAndGet();
    }
}
 
Example #18
Source File: FlatPrintingTestListener.java    From sbt-jupiter-interface with Apache License 2.0 5 votes vote down vote up
@Override
public void executionFinished(TestIdentifier identifier, TestExecutionResult result) {

    String duration = calculateDurationSuffix(identifier.getUniqueId());
    Throwable throwable = result.getThrowable().orElse(null);
    String fqn, message;

    switch (result.getStatus()) {
        case ABORTED:
            fqn = configuration.buildErrorName(identifier);
            message = configuration.buildErrorMessage(throwable);
            message = "Test assumption in test " + fqn + " failed: " + message + duration;
            logger.warn(message);
            break;
        case FAILED:
            fqn = configuration.buildErrorName(identifier);
            message = configuration.buildErrorMessage(throwable);
            message = "Test " + fqn + " failed: " + message + duration;
            logger.error(configuration.extractClassName(identifier), message, throwable);
            break;
        case SUCCESSFUL:
            fqn = configuration.formatIdentifier(testPlan, identifier);
            message = "Test " + fqn + " finished" + duration;
            logger.debug(message);
            break;
    }
}
 
Example #19
Source File: Dispatcher.java    From sbt-jupiter-interface with Apache License 2.0 5 votes vote down vote up
@Override
public void executionFinished(TestIdentifier identifier, TestExecutionResult result) {

    reportedIds.computeIfAbsent(identifier, key -> {

        final Status status;
        final Throwable throwable = result.getThrowable().orElse(null);
        final TaskName taskName = TaskName.of(testSuiteName, identifier);
        final long duration = calculateDuration(identifier);

        // dispatch only tests by default so that number of executed tests
        // match those from junit-interface

        boolean dispatch = identifier.isTest();

        switch (result.getStatus()) {
            case ABORTED:
                status = Status.Canceled;
                dispatch = true;
                break;
            case FAILED:
                status = Status.Failure;
                dispatch = true;
                break;
            case SUCCESSFUL:
                status = Status.Success;
                break;
            default:
                status = Status.Pending;
                dispatch = true;
                break;
        }

        if (dispatch) {
            eventHandler.handle(new DispatchEvent(taskName, status, duration, throwable));
        }

        return true;
    });
}
 
Example #20
Source File: FlatPrintingTestListener.java    From sbt-jupiter-interface with Apache License 2.0 5 votes vote down vote up
@Override
public void executionSkipped(TestIdentifier testIdentifier, String reason) {

    String fqn = configuration.formatIdentifier(testPlan, testIdentifier);
    String message = "Test " + fqn + " ignored" + Optional.ofNullable(reason)
            .map(s -> ": " + s).orElse("");

    logger.info(message);
}
 
Example #21
Source File: TestInfo.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private boolean isSameSharedTag(TestIdentifier test1, ExtensionContext test2) {
    List<String> nextTestTags = getTags(test1);
    Set<String> currentTestTags = test2.getTags();

    return (nextTestTags.contains(TestTag.SHARED_BROKERED) && currentTestTags.contains(TestTag.SHARED_BROKERED))
            || (nextTestTags.contains(TestTag.SHARED_STANDARD) && currentTestTags.contains(TestTag.SHARED_STANDARD))
            || (nextTestTags.contains(TestTag.SHARED_IOT) && currentTestTags.contains(TestTag.SHARED_IOT));
}
 
Example #22
Source File: Configuration.java    From sbt-jupiter-interface with Apache License 2.0 5 votes vote down vote up
/**
 * @return The formatted test name using the configured color theme.
 */
public String format() {

    final List<TestIdentifier> path = getPath(testPlan, identifier);

    testEngine = UniqueId.parse(identifier.getUniqueId())
            .getEngineId()
            .orElse(null);

    return path.stream()
            .skip(1)
            .map(this::toName)
            .filter(Objects::nonNull)
            .collect(Collectors.joining());
}
 
Example #23
Source File: TreePrintingTestListener.java    From sbt-jupiter-interface with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param identifier The test identifier to check.
 * @return True, if the specified identifier has a parent container.
 */
private boolean hasParentContainer(TestIdentifier identifier) {

    return Optional.of(identifier)
            .flatMap(testPlan::getParent)
            .filter(Objects::nonNull)
            .filter(TestIdentifier::isContainer)
            .map(t -> true)
            .orElse(false);
}
 
Example #24
Source File: TestHelper.java    From sbt-jupiter-interface with Apache License 2.0 5 votes vote down vote up
/**
 * @return Descendant test identifiers from all available roots (test engines).
 */
private Set<TestIdentifier> getAllDescendants() {

    return testPlan.getRoots().stream()
            .map(r -> testPlan().getDescendants(r).stream())
            .flatMap(s -> s)
            .collect(Collectors.toSet());
}
 
Example #25
Source File: TreePrintingTestListener.java    From sbt-jupiter-interface with Apache License 2.0 5 votes vote down vote up
@Override
public void executionFinished(TestIdentifier identifier, TestExecutionResult result) {

    Throwable throwable = result.getThrowable().orElse(null);
    String fqn, message;

    switch (result.getStatus()) {
        case ABORTED:
            fqn = configuration.buildErrorName(identifier);
            message = configuration.buildErrorMessage(throwable);
            message = "Test assumption in test " + fqn + " failed: " + message;
            logger.warn(message);
            break;
        case FAILED:
            fqn = configuration.buildErrorName(identifier);
            message = configuration.buildErrorMessage(throwable);
            message = "Test " + fqn + " failed: " + message;
            logger.error(configuration.extractClassName(identifier), message, throwable);
            break;
        case SUCCESSFUL:
            fqn = identifier.getLegacyReportingName();
            message = "Test " + fqn + " finished";
            logger.debug(message);
            break;
    }

    maybeDecreaseIndent(identifier);
}
 
Example #26
Source File: TestInfo.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private int getCurrentTestIndex() {
    if (currentTest != null && tests.size() > 0) {
        TestIdentifier test = tests.stream()
                .filter(testIdentifier -> isSameTestMethod(testIdentifier, currentTest) && isSameClass(testIdentifier, currentTest))
                .findFirst()
                .get();
        return tests.indexOf(test);
    }
    return 0;
}
 
Example #27
Source File: Dispatcher.java    From sbt-jupiter-interface with Apache License 2.0 5 votes vote down vote up
@Override
public void executionSkipped(TestIdentifier identifier, String reason) {

    reportedIds.computeIfAbsent(identifier, key -> {

        final long duration = calculateDuration(key);
        final TaskName taskName = TaskName.of(testSuiteName, identifier);
        eventHandler.handle(new DispatchEvent(taskName, Status.Skipped, duration));
        return true;
    });
}
 
Example #28
Source File: Configuration.java    From sbt-jupiter-interface with Apache License 2.0 5 votes vote down vote up
private String toVintageName(TestIdentifier identifier, Segment lastSegment) {

            final String type = lastSegment.getType();

            if ("runner".equals(type)) {

                String className = identifier.getDisplayName();
                return colorClassName(className, colorTheme.container());
            }

            if ("test".equals(type)) {

                final TestSource source = identifier.getSource().orElse(null);

                if (null == source) {
                    // Caused by Parameterized test runner, display name usually is the index name in brackets.
                    // Ignored since the index name is repeated in the display name of the test method.
                    return null;
                }

                if (source instanceof ClassSource) {
                    String nestedClassName = "$" + identifier.getDisplayName().replaceFirst(".*?\\$", "");
                    return colorTheme.container().format(nestedClassName);
                }

                if (source instanceof MethodSource) {
                    String testName = "#" + identifier.getDisplayName();
                    return colorTheme.testMethod().format(testName);
                }
            }

            return "/" + identifier.getDisplayName();
        }
 
Example #29
Source File: Configuration.java    From sbt-jupiter-interface with Apache License 2.0 5 votes vote down vote up
private List<TestIdentifier> getPath(TestPlan testPlan, TestIdentifier identifier) {

            List<TestIdentifier> result = new ArrayList<>();

            do {
                result.add(identifier);
                identifier = testPlan.getParent(identifier).orElse(null);
            }
            while (null != identifier);

            Collections.reverse(result);
            return result;
        }
 
Example #30
Source File: Configuration.java    From sbt-jupiter-interface with Apache License 2.0 5 votes vote down vote up
public String buildErrorName(TestIdentifier identifier) {
    return buildColoredName(identifier,
            colorTheme.errorName1(),
            colorTheme.errorName2(),
            colorTheme.errorName3()
    );
}