-->

During gradle test show standard out and err only

2020-07-10 09:24发布

问题:

I have a large test suite running on travis-ci, which has a textual output. I would like to configure gradle in a way that only for failed tests, the standard output and standard error streams are displayed. For all other tests which have been executed correctly, this should not happen so that the console is not polluted with that noise.

I am aware how to enable or disable the standard output/error logging, but I am unsure how to make this dependend on the test result.

回答1:

This can be archived with following gradle config

project.test {
  def outputCache = new LinkedList<String>()

  beforeTest { TestDescriptor td -> outputCache.clear() }    // clear everything right before the test starts

  onOutput { TestDescriptor td, TestOutputEvent toe ->       // when output is coming put it in the cache
    outputCache.add(toe.getMessage())
    while (outputCache.size() > 1000) outputCache.remove() // if we have more than 1000 lines -> drop first
  }

  /** after test -> decide what to print */
  afterTest { TestDescriptor td, TestResult tr ->
    if (tr.resultType == TestResult.ResultType.FAILURE && outputCache.size() > 0) {
        println()
        println(" Output of ${td.className}.${td.name}:")
        outputCache.each { print(" > $it") }
    }
  }
}

Git repo: https://github.com/calliduslynx/gradle-log-on-failure

Original found here: https://discuss.gradle.org/t/show-stderr-for-failed-tests/8463/7



回答2:

Add the following configuration block to your build.gradle file:

import org.gradle.api.tasks.testing.logging.TestExceptionFormat
import org.gradle.api.tasks.testing.logging.TestLogEvent

tasks.withType(Test) {
    testLogging {
        events TestLogEvent.FAILED,
               TestLogEvent.SKIPPED,
               TestLogEvent.STANDARD_ERROR,
               TestLogEvent.STANDARD_OUT
        exceptionFormat TestExceptionFormat.FULL
        showCauses true
        showExceptions true
        showStackTraces true
        showStandardStreams true
    }
}

Documentation can be found here.