fix(run): print each line of a JUnit test's output once (#6333)

With Run tests using: OpenIDEA, every line a JUnit Platform test printed showed twice: the runner enabled JUnit's output capture, whose StreamInterceptor also writes each line to the original System.out, and then reported the captured text again as testStdOut.

The runner now captures System.out / System.err per thread itself, as Junit4Runner does: a thread's lines while it runs a test or a class's set-up go only into that test's or class's testStdOut / testStdErr, other output passes through, and JUnit's capture is turned off explicitly. The console now shows testStdErr as stderr, and "Show console when a message is printed to stderr" fires for it (also for Junit4Runner and the Gradle test init script).

Fixes #6332

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-27 14:14:49 +08:00
1 джерело d5bde9af67
коміт 5bcb37492f
14 files changed
+264 -56

No files matched your search

+5
Переглянути файл
@@ -6,6 +6,11 @@ parameterized tests run too) and prints each test as the TeamCity service messag
`src/features/run/gradleTests.gradle`, which the Run window's JVM parser already reads. It exits
with 1 when a test failed or none ran.
A test's stdout and stderr are reported with it (`testStdOut`, `testStdErr`), line by line as they
are written; a class's own output (static initializers, `@BeforeAll`) with the class, and output
outside any test, such as a thread the test started, is printed as is. Each line is printed once:
JUnit's own output capture, which also copies everything to the original stream, stays off.
JUnit Platform tests run on the Platform launcher. JUnit 4 and JUnit 3 tests run on JUnit 4's own
`JUnitCore` (`Junit4Runner`) when the classpath has no JUnit Platform, or one without the Vintage
engine, so a JUnit 4 project needs nothing beyond its `junit` dependency.
+5
Переглянути файл
@@ -58,6 +58,11 @@ with tempfile.TemporaryDirectory() as scratch:
missing = [e for e in expected if e not in out]
assert not missing, missing
assert run.returncode == 1, run.returncode
# Each line once: a test's output only in its messages, a thread outside any test's as is.
assert "##teamcity[testStdErr name='passes' className='sample.SampleTest' out='to stderr|n']" in out, out
assert "##teamcity[testStdOut className='sample.SampleTest' out='class set-up|n']" in out, out
assert all(out.count(text) == 1 for text in ("hello", "to stderr", "loaded", "class set-up")), out
assert "\nfrom a thread\n" in out and out.count("from a thread") == 1, out
method = subprocess.run([tool("java"), "-cp", os.pathsep.join([str(classes), str(sample), cp]),
"ai.openidea.junit.Runner", "sample.SampleTest#parameterized"], capture_output=True)
assert method.stdout.decode().count("testStarted") == 2, method.stdout
Бінарний файл не відображається.
+103 -19
Переглянути файл
@@ -1,7 +1,14 @@
package ai.openidea.junit;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -10,7 +17,6 @@ import org.junit.platform.engine.DiscoverySelector;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.TestSource;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.engine.reporting.ReportEntry;
import org.junit.platform.engine.support.descriptor.ClassSource;
import org.junit.platform.engine.support.descriptor.MethodSource;
import org.junit.platform.launcher.Launcher;
@@ -20,27 +26,47 @@ import org.junit.platform.launcher.TestPlan;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
/** Runs JUnit Platform tests (Jupiter, and JUnit 4 through the Vintage engine when it is on the classpath). */
/**
* Runs JUnit Platform tests (Jupiter, and JUnit 4 through the Vintage engine when it is on the classpath).
* A thread's stdout and stderr while it runs a test (or a class's set-up) are reported with it, line by
* line; any other output is printed as is.
*/
final class PlatformRunner implements TestExecutionListener {
private final Reporter report;
private final Map<String, Long> started = new HashMap<>();
/** The tests and classes each thread is running, innermost first: its output belongs to the first. */
private final ThreadLocal<Deque<String>> owners = ThreadLocal.withInitial(ArrayDeque::new);
private final List<Output> outputs = new ArrayList<>();
private TestPlan plan;
private PlatformRunner(Reporter report) {
this.report = report;
}
static void run(Reporter report, String[] args) {
static void run(Reporter report, String[] args) throws UnsupportedEncodingException {
List<DiscoverySelector> selectors = new ArrayList<>();
for (String arg : args) selectors.addAll(selectors(arg));
Launcher launcher = LauncherFactory.create();
launcher.execute(
LauncherDiscoveryRequestBuilder.request()
.selectors(selectors)
.configurationParameter("junit.platform.output.capture.stdout", "true")
.configurationParameter("junit.platform.output.capture.stderr", "true")
.build(),
new PlatformRunner(report));
PlatformRunner listener = new PlatformRunner(report);
PrintStream stdout = System.out;
PrintStream stderr = System.err;
System.setOut(new PrintStream(listener.new Output("testStdOut", null), true, "UTF-8"));
System.setErr(new PrintStream(listener.new Output("testStdErr", stderr), true, "UTF-8"));
try {
// JUnit's own capture also writes everything to the original stream: each line would show twice.
launcher.execute(
LauncherDiscoveryRequestBuilder.request()
.selectors(selectors)
.configurationParameter("junit.platform.output.capture.stdout", "false")
.configurationParameter("junit.platform.output.capture.stderr", "false")
.build(),
listener);
} finally {
System.out.flush();
System.err.flush();
System.setOut(stdout);
System.setErr(stderr);
}
}
/** Every method named {@code method} (parameterized ones too); the class when there is none. */
@@ -75,6 +101,11 @@ final class PlatformRunner implements TestExecutionListener {
@Override
public void executionStarted(TestIdentifier id) {
String owner = owner(id);
if (owner != null) {
flushOutput();
owners.get().push(owner);
}
if (!id.isTest()) return;
started.put(id.getUniqueId(), System.currentTimeMillis());
report.message("testStarted", id(id));
@@ -90,6 +121,10 @@ final class PlatformRunner implements TestExecutionListener {
@Override
public void executionFinished(TestIdentifier id, TestExecutionResult result) {
if (owner(id) != null) {
flushOutput();
owners.get().pop();
}
TestExecutionResult.Status status = result.getStatus();
if (!id.isTest()) {
// A class whose set-up failed (`@BeforeAll`): reported as a test, like JUnit 4's initializationError.
@@ -108,15 +143,13 @@ final class PlatformRunner implements TestExecutionListener {
report.finished(own, start == null ? 0 : System.currentTimeMillis() - start);
}
@Override
public void reportingEntryPublished(TestIdentifier id, ReportEntry entry) {
for (Map.Entry<String, String> e : entry.getKeyValuePairs().entrySet()) {
String kind = e.getKey().equals("stdout") ? "testStdOut" : e.getKey().equals("stderr") ? "testStdErr" : null;
if (kind == null) continue;
// A class's own output (`@BeforeAll`, `@AfterAll`) carries no test name.
String own = id.isTest() ? id(id) : className(id).map(c -> Reporter.attr("className", c)).orElse(null);
if (own != null) report.message(kind, own + Reporter.attr("out", e.getValue()));
}
/** Whose output a thread's is while it runs {@code id}: the test, or a class (`@BeforeAll`, `@AfterAll`) with no test name. */
private String owner(TestIdentifier id) {
return id.isTest() ? id(id) : className(id).map(c -> Reporter.attr("className", c)).orElse(null);
}
private void flushOutput() {
for (Output o : outputs) o.flushLines(true);
}
/** `name='method' className='a.B$Nested'`, the method and class of the test or its closest source. */
@@ -137,4 +170,55 @@ final class PlatformRunner implements TestExecutionListener {
TestSource source = id.getSource().orElse(null);
return source instanceof ClassSource ? Optional.of(((ClassSource) source).getClassName()) : Optional.empty();
}
/** System.out or System.err: reported with the thread's test, else passed through ({@code null}: the reporter's stdout). */
private final class Output extends OutputStream {
private final String kind;
private final PrintStream passThrough;
private final ThreadLocal<ByteArrayOutputStream> pending = ThreadLocal.withInitial(ByteArrayOutputStream::new);
Output(String kind, PrintStream passThrough) {
this.kind = kind;
this.passThrough = passThrough;
outputs.add(this);
}
@Override
public void write(int b) {
write(new byte[] {(byte) b}, 0, 1);
}
@Override
public void write(byte[] b, int off, int len) {
if (owners.get().isEmpty()) {
if (passThrough == null) report.write(b, off, len);
else {
passThrough.write(b, off, len);
passThrough.flush();
}
return;
}
pending.get().write(b, off, len);
for (int i = off; i < off + len; i++) {
if (b[i] == '\n') {
flushLines(false);
return;
}
}
}
/** The thread's complete lines, or with {@code all} its partial line too, as a message of its test. */
void flushLines(boolean all) {
String owner = owners.get().peek();
ByteArrayOutputStream buffer = pending.get();
if (owner == null || buffer.size() == 0) return;
byte[] bytes = buffer.toByteArray();
int end = bytes.length;
if (!all) while (end > 0 && bytes[end - 1] != '\n') end--;
if (end == 0) return;
buffer.reset();
buffer.write(bytes, end, bytes.length - end);
report.message(kind, owner + Reporter.attr("out", new String(bytes, 0, end, StandardCharsets.UTF_8)));
}
}
}
+8
Переглянути файл
@@ -24,6 +24,14 @@ final class Reporter {
}
}
/** Output written outside any test, as it was written. */
void write(byte[] bytes, int off, int len) {
synchronized (out) {
out.write(bytes, off, len);
out.flush();
}
}
/** Output written outside any test. */
void print(String text) {
synchronized (out) {
+15 -1
Переглянути файл
@@ -3,6 +3,7 @@ package sample;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
@@ -10,9 +11,22 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
class SampleTest {
static {
System.out.println("loaded");
}
@BeforeAll
static void setUp() {
System.out.println("class set-up");
}
@Test
void passes() {
void passes() throws InterruptedException {
System.out.println("hello [ünï]");
System.err.println("to stderr");
Thread other = new Thread(() -> System.out.println("from a thread"));
other.start();
other.join();
}
@Test