Search in sources :

Example 1 with TestStatusMessage

use of com.facebook.buck.test.TestStatusMessage in project buck by facebook.

the class TestRunning method runTests.

@SuppressWarnings("PMD.EmptyCatchBlock")
public static int runTests(final CommandRunnerParams params, Iterable<TestRule> tests, ExecutionContext executionContext, final TestRunningOptions options, ListeningExecutorService service, BuildEngine buildEngine, final StepRunner stepRunner, SourcePathResolver sourcePathResolver, SourcePathRuleFinder ruleFinder) throws IOException, ExecutionException, InterruptedException {
    ImmutableSet<JavaLibrary> rulesUnderTestForCoverage;
    // If needed, we first run instrumentation on the class files.
    if (options.isCodeCoverageEnabled()) {
        rulesUnderTestForCoverage = getRulesUnderTest(tests);
        if (!rulesUnderTestForCoverage.isEmpty()) {
            try {
                // We'll use the filesystem of the first rule under test. This will fail if there are any
                // tests from a different repo, but it'll help us bootstrap ourselves to being able to
                // support multiple repos
                // TODO(t8220837): Support tests in multiple repos
                JavaLibrary library = rulesUnderTestForCoverage.iterator().next();
                stepRunner.runStepForBuildTarget(executionContext, new MakeCleanDirectoryStep(library.getProjectFilesystem(), JacocoConstants.getJacocoOutputDir(library.getProjectFilesystem())), Optional.empty());
            } catch (StepFailedException e) {
                params.getBuckEventBus().post(ConsoleEvent.severe(Throwables.getRootCause(e).getLocalizedMessage()));
                return 1;
            }
        }
    } else {
        rulesUnderTestForCoverage = ImmutableSet.of();
    }
    final ImmutableSet<String> testTargets = FluentIterable.from(tests).transform(BuildRule::getBuildTarget).transform(Object::toString).toSet();
    final int totalNumberOfTests = Iterables.size(tests);
    params.getBuckEventBus().post(TestRunEvent.started(options.isRunAllTests(), options.getTestSelectorList(), options.shouldExplainTestSelectorList(), testTargets));
    // Start running all of the tests. The result of each java_test() rule is represented as a
    // ListenableFuture.
    List<ListenableFuture<TestResults>> results = Lists.newArrayList();
    TestRuleKeyFileHelper testRuleKeyFileHelper = new TestRuleKeyFileHelper(buildEngine);
    final AtomicInteger lastReportedTestSequenceNumber = new AtomicInteger();
    final List<TestRun> separateTestRuns = Lists.newArrayList();
    List<TestRun> parallelTestRuns = Lists.newArrayList();
    for (final TestRule test : tests) {
        // Determine whether the test needs to be executed.
        final Callable<TestResults> resultsInterpreter = getCachingCallable(test.interpretTestResults(executionContext, /*isUsingTestSelectors*/
        !options.getTestSelectorList().isEmpty()));
        boolean isTestRunRequired;
        isTestRunRequired = isTestRunRequiredForTest(test, buildEngine, executionContext, testRuleKeyFileHelper, options.getTestResultCacheMode(), resultsInterpreter, !options.getTestSelectorList().isEmpty(), !options.getEnvironmentOverrides().isEmpty());
        final Map<String, UUID> testUUIDMap = new HashMap<>();
        final AtomicReference<TestStatusMessageEvent.Started> currentTestStatusMessageEvent = new AtomicReference<>();
        TestRule.TestReportingCallback testReportingCallback = new TestRule.TestReportingCallback() {

            @Override
            public void testsDidBegin() {
                LOG.debug("Tests for rule %s began", test.getBuildTarget());
            }

            @Override
            public void statusDidBegin(TestStatusMessage didBeginMessage) {
                LOG.debug("Test status did begin: %s", didBeginMessage);
                TestStatusMessageEvent.Started startedEvent = TestStatusMessageEvent.started(didBeginMessage);
                TestStatusMessageEvent.Started previousEvent = currentTestStatusMessageEvent.getAndSet(startedEvent);
                Preconditions.checkState(previousEvent == null, "Received begin status before end status (%s)", previousEvent);
                params.getBuckEventBus().post(startedEvent);
                String message = didBeginMessage.getMessage();
                if (message.toLowerCase().contains("debugger")) {
                    executionContext.getStdErr().println(executionContext.getAnsi().asWarningText(message));
                }
            }

            @Override
            public void statusDidEnd(TestStatusMessage didEndMessage) {
                LOG.debug("Test status did end: %s", didEndMessage);
                TestStatusMessageEvent.Started previousEvent = currentTestStatusMessageEvent.getAndSet(null);
                Preconditions.checkState(previousEvent != null, "Received end status before begin status (%s)", previousEvent);
                params.getBuckEventBus().post(TestStatusMessageEvent.finished(previousEvent, didEndMessage));
            }

            @Override
            public void testDidBegin(String testCaseName, String testName) {
                LOG.debug("Test rule %s test case %s test name %s began", test.getBuildTarget(), testCaseName, testName);
                UUID testUUID = UUID.randomUUID();
                // UUID is immutable and thread-safe as of Java 7, so it's
                // safe to stash in a map and use later:
                //
                // http://bugs.java.com/view_bug.do?bug_id=6611830
                testUUIDMap.put(testCaseName + ":" + testName, testUUID);
                params.getBuckEventBus().post(TestSummaryEvent.started(testUUID, testCaseName, testName));
            }

            @Override
            public void testDidEnd(TestResultSummary testResultSummary) {
                LOG.debug("Test rule %s test did end: %s", test.getBuildTarget(), testResultSummary);
                UUID testUUID = testUUIDMap.get(testResultSummary.getTestCaseName() + ":" + testResultSummary.getTestName());
                Preconditions.checkNotNull(testUUID);
                params.getBuckEventBus().post(TestSummaryEvent.finished(testUUID, testResultSummary));
            }

            @Override
            public void testsDidEnd(List<TestCaseSummary> testCaseSummaries) {
                LOG.debug("Test rule %s tests did end: %s", test.getBuildTarget(), testCaseSummaries);
            }
        };
        List<Step> steps;
        if (isTestRunRequired) {
            params.getBuckEventBus().post(IndividualTestEvent.started(testTargets));
            ImmutableList.Builder<Step> stepsBuilder = ImmutableList.builder();
            Preconditions.checkState(buildEngine.isRuleBuilt(test.getBuildTarget()));
            List<Step> testSteps = test.runTests(executionContext, options, sourcePathResolver, testReportingCallback);
            if (!testSteps.isEmpty()) {
                stepsBuilder.addAll(testSteps);
                stepsBuilder.add(testRuleKeyFileHelper.createRuleKeyInDirStep(test));
            }
            steps = stepsBuilder.build();
        } else {
            steps = ImmutableList.of();
        }
        TestRun testRun = TestRun.of(test, steps, getStatusTransformingCallable(isTestRunRequired, resultsInterpreter), testReportingCallback);
        // commands because the rule is cached, but its results must still be processed.
        if (test.runTestSeparately()) {
            LOG.debug("Running test %s in serial", test);
            separateTestRuns.add(testRun);
        } else {
            LOG.debug("Running test %s in parallel", test);
            parallelTestRuns.add(testRun);
        }
    }
    for (TestRun testRun : parallelTestRuns) {
        ListenableFuture<TestResults> testResults = runStepsAndYieldResult(stepRunner, executionContext, testRun.getSteps(), testRun.getTestResultsCallable(), testRun.getTest().getBuildTarget(), params.getBuckEventBus(), service);
        results.add(transformTestResults(params, testResults, testRun.getTest(), testRun.getTestReportingCallback(), testTargets, lastReportedTestSequenceNumber, totalNumberOfTests));
    }
    ListenableFuture<List<TestResults>> parallelTestStepsFuture = Futures.allAsList(results);
    final List<TestResults> completedResults = Lists.newArrayList();
    final ListeningExecutorService directExecutorService = MoreExecutors.newDirectExecutorService();
    ListenableFuture<Void> uberFuture = MoreFutures.addListenableCallback(parallelTestStepsFuture, new FutureCallback<List<TestResults>>() {

        @Override
        public void onSuccess(List<TestResults> parallelTestResults) {
            LOG.debug("Parallel tests completed, running separate tests...");
            completedResults.addAll(parallelTestResults);
            List<ListenableFuture<TestResults>> separateResultsList = Lists.newArrayList();
            for (TestRun testRun : separateTestRuns) {
                separateResultsList.add(transformTestResults(params, runStepsAndYieldResult(stepRunner, executionContext, testRun.getSteps(), testRun.getTestResultsCallable(), testRun.getTest().getBuildTarget(), params.getBuckEventBus(), directExecutorService), testRun.getTest(), testRun.getTestReportingCallback(), testTargets, lastReportedTestSequenceNumber, totalNumberOfTests));
            }
            ListenableFuture<List<TestResults>> serialResults = Futures.allAsList(separateResultsList);
            try {
                completedResults.addAll(serialResults.get());
            } catch (ExecutionException e) {
                LOG.error(e, "Error fetching serial test results");
                throw new HumanReadableException(e, "Error fetching serial test results");
            } catch (InterruptedException e) {
                LOG.error(e, "Interrupted fetching serial test results");
                try {
                    serialResults.cancel(true);
                } catch (CancellationException ignored) {
                // Rethrow original InterruptedException instead.
                }
                Thread.currentThread().interrupt();
                throw new HumanReadableException(e, "Test cancelled");
            }
            LOG.debug("Done running serial tests.");
        }

        @Override
        public void onFailure(Throwable e) {
            LOG.error(e, "Parallel tests failed, not running serial tests");
            throw new HumanReadableException(e, "Parallel tests failed");
        }
    }, directExecutorService);
    try {
        // Block until all the tests have finished running.
        uberFuture.get();
    } catch (ExecutionException e) {
        e.printStackTrace(params.getConsole().getStdErr());
        return 1;
    } catch (InterruptedException e) {
        try {
            uberFuture.cancel(true);
        } catch (CancellationException ignored) {
        // Rethrow original InterruptedException instead.
        }
        Thread.currentThread().interrupt();
        throw e;
    }
    params.getBuckEventBus().post(TestRunEvent.finished(testTargets, completedResults));
    // Write out the results as XML, if requested.
    Optional<String> path = options.getPathToXmlTestOutput();
    if (path.isPresent()) {
        try (Writer writer = Files.newWriter(new File(path.get()), Charsets.UTF_8)) {
            writeXmlOutput(completedResults, writer);
        }
    }
    // Generate the code coverage report.
    if (options.isCodeCoverageEnabled() && !rulesUnderTestForCoverage.isEmpty()) {
        try {
            JavaBuckConfig javaBuckConfig = params.getBuckConfig().getView(JavaBuckConfig.class);
            DefaultJavaPackageFinder defaultJavaPackageFinder = javaBuckConfig.createDefaultJavaPackageFinder();
            stepRunner.runStepForBuildTarget(executionContext, getReportCommand(rulesUnderTestForCoverage, defaultJavaPackageFinder, javaBuckConfig.getDefaultJavaOptions().getJavaRuntimeLauncher(), params.getCell().getFilesystem(), sourcePathResolver, ruleFinder, JacocoConstants.getJacocoOutputDir(params.getCell().getFilesystem()), options.getCoverageReportFormat(), options.getCoverageReportTitle(), javaBuckConfig.getDefaultJavacOptions().getSpoolMode() == JavacOptions.SpoolMode.INTERMEDIATE_TO_DISK, options.getCoverageIncludes(), options.getCoverageExcludes()), Optional.empty());
        } catch (StepFailedException e) {
            params.getBuckEventBus().post(ConsoleEvent.severe(Throwables.getRootCause(e).getLocalizedMessage()));
            return 1;
        }
    }
    boolean failures = Iterables.any(completedResults, results1 -> {
        LOG.debug("Checking result %s for failure", results1);
        return !results1.isSuccess();
    });
    return failures ? TEST_FAILURES_EXIT_CODE : 0;
}
Also used : HashMap(java.util.HashMap) TestResults(com.facebook.buck.test.TestResults) JavaBuckConfig(com.facebook.buck.jvm.java.JavaBuckConfig) DefaultJavaPackageFinder(com.facebook.buck.jvm.java.DefaultJavaPackageFinder) StepFailedException(com.facebook.buck.step.StepFailedException) BuildRule(com.facebook.buck.rules.BuildRule) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) UUID(java.util.UUID) TestResultSummary(com.facebook.buck.test.TestResultSummary) TestRule(com.facebook.buck.rules.TestRule) TestStatusMessageEvent(com.facebook.buck.rules.TestStatusMessageEvent) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CancellationException(java.util.concurrent.CancellationException) MakeCleanDirectoryStep(com.facebook.buck.step.fs.MakeCleanDirectoryStep) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) File(java.io.File) ImmutableList(com.google.common.collect.ImmutableList) Step(com.facebook.buck.step.Step) GenerateCodeCoverageReportStep(com.facebook.buck.jvm.java.GenerateCodeCoverageReportStep) MakeCleanDirectoryStep(com.facebook.buck.step.fs.MakeCleanDirectoryStep) ExecutionException(java.util.concurrent.ExecutionException) AtomicReference(java.util.concurrent.atomic.AtomicReference) TestStatusMessage(com.facebook.buck.test.TestStatusMessage) JavaLibrary(com.facebook.buck.jvm.java.JavaLibrary) DefaultJavaLibrary(com.facebook.buck.jvm.java.DefaultJavaLibrary) HumanReadableException(com.facebook.buck.util.HumanReadableException) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) StringWriter(java.io.StringWriter)

Example 2 with TestStatusMessage

use of com.facebook.buck.test.TestStatusMessage in project buck by facebook.

the class SuperConsoleEventBusListener method testRunFinished.

@Subscribe
public void testRunFinished(TestRunEvent.Finished finished) {
    boolean set = testRunFinished.compareAndSet(null, finished);
    Preconditions.checkState(set, "Test run should not finish after test run already finished");
    ImmutableList.Builder<String> builder = ImmutableList.builder();
    for (TestResults results : finished.getResults()) {
        testFormatter.reportResult(builder, results);
    }
    ImmutableList<TestStatusMessage> testStatusMessages;
    synchronized (testStatusMessageBuilder) {
        testStatusMessages = testStatusMessageBuilder.build();
    }
    testFormatter.runComplete(builder, finished.getResults(), testStatusMessages);
    String testOutput;
    synchronized (testReportBuilder) {
        testReportBuilder.addAll(builder.build());
        testOutput = Joiner.on('\n').join(testReportBuilder.build());
    }
    // We're about to write to stdout, so make sure we render the final frame before we do.
    render();
    synchronized (console.getStdOut()) {
        console.getStdOut().println(testOutput);
    }
}
Also used : TestStatusMessage(com.facebook.buck.test.TestStatusMessage) ImmutableList(com.google.common.collect.ImmutableList) TestResults(com.facebook.buck.test.TestResults) Subscribe(com.google.common.eventbus.Subscribe)

Example 3 with TestStatusMessage

use of com.facebook.buck.test.TestStatusMessage in project buck by facebook.

the class TestResultFormatter method runComplete.

public void runComplete(ImmutableList.Builder<String> addTo, List<TestResults> completedResults, List<TestStatusMessage> testStatusMessages) {
    // Print whether each test succeeded or failed.
    boolean isDryRun = false;
    boolean hasAssumptionViolations = false;
    int numTestsPassed = 0;
    int numTestsFailed = 0;
    int numTestsSkipped = 0;
    ListMultimap<TestResults, TestCaseSummary> failingTests = ArrayListMultimap.create();
    ImmutableList.Builder<Path> testLogPathsBuilder = ImmutableList.builder();
    for (TestResults summary : completedResults) {
        testLogPathsBuilder.addAll(summary.getTestLogPaths());
        // Get failures up-front to include class-level initialization failures
        if (summary.getFailureCount() > 0) {
            numTestsFailed += summary.getFailureCount();
            failingTests.putAll(summary, summary.getFailures());
        }
        // Get passes/skips by iterating through each case
        for (TestCaseSummary testCaseSummary : summary.getTestCases()) {
            isDryRun = isDryRun || testCaseSummary.isDryRun();
            numTestsPassed += testCaseSummary.getPassedCount();
            numTestsSkipped += testCaseSummary.getSkippedCount();
            hasAssumptionViolations = hasAssumptionViolations || testCaseSummary.hasAssumptionViolations();
        }
    }
    // If no test runs to completion, don't fail, but warn
    if (numTestsPassed == 0 && numTestsFailed == 0) {
        String message;
        if (hasAssumptionViolations) {
            message = "NO TESTS RAN (assumption violations)";
        } else if (numTestsSkipped > 0) {
            message = "NO TESTS RAN (tests skipped)";
        } else {
            message = "NO TESTS RAN";
        }
        if (isDryRun) {
            addTo.add(ansi.asHighlightedSuccessText(message));
        } else {
            addTo.add(ansi.asHighlightedWarningText(message));
        }
        return;
    }
    // When all tests pass...
    if (numTestsFailed == 0) {
        ImmutableList<Path> testLogPaths = testLogPathsBuilder.build();
        if (testLogsPath.isPresent() && verbosity != Verbosity.SILENT) {
            try {
                if (MoreFiles.concatenateFiles(testLogsPath.get(), testLogPaths)) {
                    addTo.add("Updated test logs: " + testLogsPath.get().toString());
                }
            } catch (IOException e) {
                LOG.warn(e, "Could not concatenate test logs %s to %s", testLogPaths, testLogsPath.get());
            }
        }
        if (hasAssumptionViolations) {
            addTo.add(ansi.asHighlightedWarningText("TESTS PASSED (with some assumption violations)"));
        } else {
            addTo.add(ansi.asHighlightedSuccessText("TESTS PASSED"));
        }
        return;
    }
    // When something fails...
    if (!testStatusMessages.isEmpty()) {
        addTo.add("====TEST STATUS MESSAGES====");
        SimpleDateFormat timestampFormat = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss.SSS]", Locale.US);
        timestampFormat.setTimeZone(timeZone);
        for (TestStatusMessage testStatusMessage : testStatusMessages) {
            addTo.add(String.format(locale, "%s[%s] %s", timestampFormat.format(new Date(testStatusMessage.getTimestampMillis())), testStatusMessage.getLevel(), testStatusMessage.getMessage()));
        }
    }
    addTo.add(ansi.asHighlightedFailureText(String.format(locale, "TESTS FAILED: %d %s", numTestsFailed, numTestsFailed == 1 ? "FAILURE" : "FAILURES")));
    for (TestResults results : failingTests.keySet()) {
        addTo.add("Failed target: " + results.getBuildTarget().getFullyQualifiedName());
        for (TestCaseSummary summary : failingTests.get(results)) {
            addTo.add(summary.toString());
        }
    }
}
Also used : Path(java.nio.file.Path) ImmutableList(com.google.common.collect.ImmutableList) TestResults(com.facebook.buck.test.TestResults) IOException(java.io.IOException) Date(java.util.Date) TestStatusMessage(com.facebook.buck.test.TestStatusMessage) TestCaseSummary(com.facebook.buck.test.TestCaseSummary) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

TestResults (com.facebook.buck.test.TestResults)3 TestStatusMessage (com.facebook.buck.test.TestStatusMessage)3 ImmutableList (com.google.common.collect.ImmutableList)3 DefaultJavaLibrary (com.facebook.buck.jvm.java.DefaultJavaLibrary)1 DefaultJavaPackageFinder (com.facebook.buck.jvm.java.DefaultJavaPackageFinder)1 GenerateCodeCoverageReportStep (com.facebook.buck.jvm.java.GenerateCodeCoverageReportStep)1 JavaBuckConfig (com.facebook.buck.jvm.java.JavaBuckConfig)1 JavaLibrary (com.facebook.buck.jvm.java.JavaLibrary)1 BuildRule (com.facebook.buck.rules.BuildRule)1 TestRule (com.facebook.buck.rules.TestRule)1 TestStatusMessageEvent (com.facebook.buck.rules.TestStatusMessageEvent)1 Step (com.facebook.buck.step.Step)1 StepFailedException (com.facebook.buck.step.StepFailedException)1 MakeCleanDirectoryStep (com.facebook.buck.step.fs.MakeCleanDirectoryStep)1 TestCaseSummary (com.facebook.buck.test.TestCaseSummary)1 TestResultSummary (com.facebook.buck.test.TestResultSummary)1 HumanReadableException (com.facebook.buck.util.HumanReadableException)1 Subscribe (com.google.common.eventbus.Subscribe)1 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)1 ListeningExecutorService (com.google.common.util.concurrent.ListeningExecutorService)1