From 5bcb37492f9d973a173f9ca7fbb76340f77edb37 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Fri, 27 Nov 2026 15:14:49 +0900 Subject: [PATCH] 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 <26499420+wildcatDownstairs@users.noreply.github.com> --- java/junit-runner/README.md | 5 + java/junit-runner/build.py | 5 + java/junit-runner/openidea-junit-runner.jar | Bin 15201 -> 17741 bytes .../src/ai/openidea/junit/PlatformRunner.java | 122 +++++++++++++++--- .../src/ai/openidea/junit/Reporter.java | 8 ++ java/junit-runner/tests/SampleTest.java | 16 ++- src/features/run/store.ts | 18 +-- src/features/run/testStderr.test.ts | 62 +++++++++ src/features/run/testing/go.test.ts | 9 +- src/features/run/testing/nodeTest.test.ts | 5 +- src/features/run/testing/phpunit.test.ts | 31 +++-- src/features/run/testing/ruby.test.ts | 2 +- src/features/run/testing/teamcity.ts | 5 +- src/features/run/testing/types.ts | 32 +++-- 14 files changed, 264 insertions(+), 56 deletions(-) create mode 100644 src/features/run/testStderr.test.ts diff --git a/java/junit-runner/README.md b/java/junit-runner/README.md index a576e95a1..8537417d0 100644 --- a/java/junit-runner/README.md +++ b/java/junit-runner/README.md @@ -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. diff --git a/java/junit-runner/build.py b/java/junit-runner/build.py index 96cb5f175..ec6a47d81 100644 --- a/java/junit-runner/build.py +++ b/java/junit-runner/build.py @@ -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 diff --git a/java/junit-runner/openidea-junit-runner.jar b/java/junit-runner/openidea-junit-runner.jar index 9250f777f123e761a79f5ab57f9705127e068da9..1a18960b4fca1b3ab1a8932e1f376065ed60826a 100644 GIT binary patch delta 10423 zcmZv?V{9c1&^BD#_SSY!-P3Mu8(Z6Ud$zW9YTGup#%^s}Tf19*_w(cZ-aN@W$Yhe4 zf0N1NnrqMVPc&r1Z)j9P-72F*7zhY8LEf|os2XYw-aO$v;MAV0ew>Wv0*6&{&6O<>Br;Vp*W!N!Oa?5g~$6s zVkrssCexu|k{F!4LGb1MitzqOU?@o>0U_ zXZyslqA@&pmsB4UjL9nnhKps3O##L{deoNgf@kk0DOxr`$Y2e*E|a;!P?zw7ZdkcB zTaI!93UdscB%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av4g}4l-g+sa!}UDNIaQ?s*L@cjX9ir|7r< z-eV1~L1wO}tqCgkpRrN}wi-*;+ATZSPjx^U08k)jlb4d|qjK4U4W)nX}G#Bwu`;AEiclz3I zwD{h-Ocep%3JHoxV2f(&6(EyP1VRAIX;d?|qeX!VE1;bfP@R~@?-i&{yvbf2uCc!Y zbu$#^3qTLxocgbW7QnXuqJM$QyyZRoFLPcLwJQ9F6n4==#Ba2FNSi5H zq_0wK32BpZz)G&J!eTtkaabNARW59;pl!t;6k5U9EEreF`#_%q(5J%q#}YuTj?!gj zI68C%5#MuH5xIsq{kyRzeiMu1*N_-$pF&3wTchSq&-LPUb65NpbboWtBmxY;W7GJ6 zOg`RT#1qqavNTiyNnW03%34Nx9Rsi)tNHpliik2LT7pqAWf<2z#}DHz{E6^QbmMKj zLs?>8H|lR=HG?}tODlocCef~pLj2Bf|J-GN^)mkzoy&x~LWshE4)I5?_@g&!9;vds zZ1n;wuO6j+qr0(QhxPukpkt$t{6@Oig6Ze6KM~rzYVyCun9eW@gw7awT#RO)>K{M>61UGv}@JRL;#DA)25of3Hv1HVIzOIN*9g1JyQ@`D}%(wD&Y>hATZQki`@fY!;`MDy# z@Cq6x(M-HwxrktFNwA2o4#s5J9DKp2P0qYO*OXQCKJYke?g8fF6O6`_*w4IrisQrl zmgBLW+4?Sh?^pN0+w1}Iz+PA}t`+_nK2ZH-LjF}_#D8vM1;-&)#Q*T9F7JKMz#;FV zSXZv(FN@EGnctL>K8>044wc00000000000Du8_8j~?K6qAq| z4wIKe7917|@eKY4003VP001BW0000000000004ji1}u{?H6oMiL@EM8G?Otk6_YGQ T6AlId1_15>003P%00000OAA8b diff --git a/java/junit-runner/src/ai/openidea/junit/PlatformRunner.java b/java/junit-runner/src/ai/openidea/junit/PlatformRunner.java index 0f921d443..1d4e2d845 100644 --- a/java/junit-runner/src/ai/openidea/junit/PlatformRunner.java +++ b/java/junit-runner/src/ai/openidea/junit/PlatformRunner.java @@ -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 started = new HashMap<>(); + /** The tests and classes each thread is running, innermost first: its output belongs to the first. */ + private final ThreadLocal> owners = ThreadLocal.withInitial(ArrayDeque::new); + private final List 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 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 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 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))); + } + } } diff --git a/java/junit-runner/src/ai/openidea/junit/Reporter.java b/java/junit-runner/src/ai/openidea/junit/Reporter.java index e0472750b..52b696ec3 100644 --- a/java/junit-runner/src/ai/openidea/junit/Reporter.java +++ b/java/junit-runner/src/ai/openidea/junit/Reporter.java @@ -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) { diff --git a/java/junit-runner/tests/SampleTest.java b/java/junit-runner/tests/SampleTest.java index 7a071316c..aa5a59715 100644 --- a/java/junit-runner/tests/SampleTest.java +++ b/java/junit-runner/tests/SampleTest.java @@ -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 diff --git a/src/features/run/store.ts b/src/features/run/store.ts index 170969aca..f5c8757e1 100644 --- a/src/features/run/store.ts +++ b/src/features/run/store.ts @@ -127,6 +127,8 @@ interface SessionRuntime { pluginTests: PluginTestOutput | null; /** Machine-readable stdout (`go test -json`, `--teamcity`, the Ruby reporter): fed to the parser, shown decoded. */ stdout: TestStdout | null; + /** "Show console when a message is printed to stderr", for stderr decoded from `stdout` (`testStdErr`). */ + onDecodedStderr?: () => void; queue: OutputChunk[]; /** * rAF id while the page is visible, timeout id while hidden (rAF pauses in @@ -696,10 +698,12 @@ function flush(sessionId: string) { rt.flushedAt = performance.now(); const chunks = rt.queue.splice(0); for (const c of chunks) { - const text = c.kind === "stdout" && rt.stdout ? rt.stdout.feed(c.text) : c.text; - if (!text) continue; - rt.console.append({ ...c, text }); - for (const l of rt.outputListeners) l(c.kind, text); + for (const shown of c.kind === "stdout" && rt.stdout ? rt.stdout.feed(c.text) : [c]) { + if (!shown.text) continue; + rt.console.append(shown); + for (const l of rt.outputListeners) l(shown.kind, shown.text); + if (shown.kind === "stderr" && c.kind === "stdout") rt.onDecodedStderr?.(); + } } bump(sessionId); } @@ -1117,6 +1121,7 @@ async function startRunIn( return getSession(sessionId) ?? null; } + rt.onDecodedStderr = !check && config.showOnStderr ? () => revealSession(sessionId) : undefined; const channel = new Channel(); channel.onmessage = (chunk) => { if (runtimes.get(sessionId)?.generation !== generation) return; @@ -1333,10 +1338,7 @@ function finishSession(sessionId: string, code: number | null) { void (async () => { if (runtimes.get(sessionId) !== rt) return; flush(sessionId); - if (rt.stdout) { - const text = rt.stdout.end(); - if (text) rt.console.append({ kind: "stdout", text }); - } + if (rt.stdout) for (const shown of rt.stdout.end()) rt.console.append(shown); rt.console.flush(); await rt.pluginTests?.end(); if (runtimes.get(sessionId) !== rt) return; diff --git a/src/features/run/testStderr.test.ts b/src/features/run/testStderr.test.ts new file mode 100644 index 000000000..6b4256147 --- /dev/null +++ b/src/features/run/testStderr.test.ts @@ -0,0 +1,62 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import type { OutputChunk, RunConfig } from "@/platform/ipc"; + +const ipc = vi.hoisted(() => ({ + runStart: vi.fn(async (_config: RunConfig, _channel: unknown) => ({ status: "ok", data: { id: 7, pty: false } })), +})); +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } }; +}); +vi.mock("@tauri-apps/api/core", async (importOriginal) => ({ + ...(await importOriginal()), + Channel: class { + onmessage: ((m: unknown) => void) | null = null; + }, +})); + +import { useProject } from "@/platform/project"; +import { provideToolWindowService, type ToolWindowService } from "@/workbench/contributions"; +import { runtime, startRun } from "./store"; + +// OpenIDEA's JUnit runner and Gradle's test init script report through the same service messages. +const gradle = { + id: "gradle:test", + name: "test", + kind: "gradle", + command: "./gradlew", + args: ["test"], + cwd: null, + env: {}, + isTest: true, + showOnStderr: true, +} as unknown as RunConfig; + +beforeEach(() => { + useProject.setState({ settings: null, project: { root: "/p" } as never }); +}); + +it("shows a test's stderr (`testStdErr`) as stderr and reveals the console for it", async () => { + const show = vi.fn(); + provideToolWindowService({ show, hide: vi.fn(), isVisible: () => false } as unknown as ToolWindowService); + const session = await startRun(gradle, undefined, undefined, { prepared: true }); + const channel = ipc.runStart.mock.calls[0]![1] as { onmessage: (chunk: OutputChunk) => void }; + show.mockClear(); + channel.onmessage({ + kind: "stdout", + text: [ + "##teamcity[testStarted name='prints' className='demo.GreeterTest']", + "##teamcity[testStdOut name='prints' className='demo.GreeterTest' out='out|n']", + "##teamcity[testStdErr name='prints' className='demo.GreeterTest' out='err|n']", + "##teamcity[testFinished name='prints' className='demo.GreeterTest' duration='1']", + "", + ].join("\n"), + }); + await vi.waitFor(() => + expect(runtime(session!.id)!.console.textChunks()).toEqual([ + { kind: "stdout", text: "out\n" }, + { kind: "stderr", text: "err\n" }, + ]), + ); + expect(show).toHaveBeenCalledWith("run"); +}); diff --git a/src/features/run/testing/go.test.ts b/src/features/run/testing/go.test.ts index 41226b5e3..adb560669 100644 --- a/src/features/run/testing/go.test.ts +++ b/src/features/run/testing/go.test.ts @@ -130,12 +130,15 @@ describe("Go JSON tests", () => { const line = record("p", "output", "TestFail", { Output: " main_test.go:6: failure " + "x".repeat(9000) + "\n", }); - expect(output.feed(line.slice(0, 22))).toBe(""); - const text = output.feed(line.slice(22) + "\n" + record("p", "fail", "TestFail")); + expect(output.feed(line.slice(0, 22))).toEqual([]); + const text = output + .feed(line.slice(22) + "\n" + record("p", "fail", "TestFail")) + .map((c) => c.text) + .join(""); expect(text).toContain("main_test.go:6: failure"); expect(text).not.toContain('"Action"'); expect(findOutputLinks(text.slice(0, 100)).some((link) => link.kind === "file")).toBe(true); - expect(output.end()).toBe(""); + expect(output.end()).toEqual([]); expect(results.counts().failed).toBe(1); }); diff --git a/src/features/run/testing/nodeTest.test.ts b/src/features/run/testing/nodeTest.test.ts index ed5e3e324..4795a1497 100644 --- a/src/features/run/testing/nodeTest.test.ts +++ b/src/features/run/testing/nodeTest.test.ts @@ -75,7 +75,10 @@ describe("node:test reporter records", () => { it("are hidden from the console", () => { const fed: string[] = []; - const console = new RecordsOutput((line) => fed.push(line)).feed(OUTPUT + "\n"); + const console = new RecordsOutput((line) => fed.push(line)) + .feed(OUTPUT + "\n") + .map((c) => c.text) + .join(""); expect(console).not.toContain("@@openidea"); expect(console).toContain(" ✔ adds items (0.4259ms)\n"); expect(fed.filter((l) => l.startsWith("@@openidea"))).toHaveLength(8); diff --git a/src/features/run/testing/phpunit.test.ts b/src/features/run/testing/phpunit.test.ts index 79b0b9614..6ea116aaa 100644 --- a/src/features/run/testing/phpunit.test.ts +++ b/src/features/run/testing/phpunit.test.ts @@ -111,17 +111,21 @@ describe("TeamcityOutput", () => { const results = new TestResults(); const parser = phpunitParser(); const output = new TeamcityOutput((line) => results.apply(parser.feed(line))); - const shown = - output.feed( + const shown = [ + ...output.feed( "PHPUnit 11.5 by Sebastian Bergmann\n##teamcity[testSuiteStarted name='CalcTest']\n##teamcity[testStar", - ) + - output.feed("ted name='testAdd']\r\n##teamcity[testFinished name='testAdd' duration='1']\nOK (1 test") + - output.end(); - expect(shown).toBe("PHPUnit 11.5 by Sebastian Bergmann\nOK (1 test\n"); + ), + ...output.feed("ted name='testAdd']\r\n##teamcity[testFinished name='testAdd' duration='1']\nOK (1 test"), + ...output.end(), + ]; + expect(shown).toEqual([ + { kind: "stdout", text: "PHPUnit 11.5 by Sebastian Bergmann\n" }, + { kind: "stdout", text: "OK (1 test\n" }, + ]); expect(results.counts()).toMatchObject({ passed: 1 }); }); - it("shows a test's own output and failures in the console when asked (JVM runs)", () => { + it("shows a test's own output, its stderr as stderr, and failures in the console when asked (JVM runs)", () => { const lines = [ "##teamcity[testStarted name='prints' className='demo.GreeterTest']", "##teamcity[testStdOut name='prints' className='demo.GreeterTest' out='输出结果:OpenIdea|n']", @@ -134,11 +138,16 @@ describe("TeamcityOutput", () => { "", ].join("\n"); const fed: string[] = []; - expect(new TeamcityOutput((line) => fed.push(line), true).feed(lines)).toBe( - "输出结果:OpenIdea\nwarn [x]\njava.lang.AssertionError: no\n\tat demo.GreeterTest.fails(GreeterTest.java:15)\n1 test completed\n", - ); + expect(new TeamcityOutput((line) => fed.push(line), true).feed(lines)).toEqual([ + { kind: "stdout", text: "输出结果:OpenIdea\n" }, + { kind: "stderr", text: "warn [x]\n" }, + { + kind: "stdout", + text: "java.lang.AssertionError: no\n\tat demo.GreeterTest.fails(GreeterTest.java:15)\n1 test completed\n", + }, + ]); expect(fed).toHaveLength(8); - expect(new TeamcityOutput(() => {}).feed(lines)).toBe("1 test completed\n"); + expect(new TeamcityOutput(() => {}).feed(lines)).toEqual([{ kind: "stdout", text: "1 test completed\n" }]); }); }); diff --git a/src/features/run/testing/ruby.test.ts b/src/features/run/testing/ruby.test.ts index 1139bc54d..a4e294d7f 100644 --- a/src/features/run/testing/ruby.test.ts +++ b/src/features/run/testing/ruby.test.ts @@ -152,7 +152,7 @@ describe("the IDE's Minitest reporter", () => { const collect = (chunks: string[]) => { const lines: string[] = []; const out = new RubyTestOutput((line) => lines.push(line)); - const text = chunks.map((c) => out.feed(c)).join("") + out.end(); + const text = [...chunks.flatMap((c) => out.feed(c)), ...out.end()].map((c) => c.text).join(""); return { text, records: lines.filter((l) => l.includes(M)), lines }; }; diff --git a/src/features/run/testing/teamcity.ts b/src/features/run/testing/teamcity.ts index 600c9b2a7..67d3aa440 100644 --- a/src/features/run/testing/teamcity.ts +++ b/src/features/run/testing/teamcity.ts @@ -33,7 +33,7 @@ export function serviceMessage(line: string): ServiceMessage | null { * Console text of a run reporting through service messages: the messages feed the test tree. With * `testOutput`, a test's own stdout / stderr (`testStdOut`, `testStdErr`) and its failure are shown in * the console too, so the run reads like the program's output with no test selected (OpenIDEA's JUnit - * runner and the Gradle init script report them only through these messages). + * runner and the Gradle init script report them only through these messages), `testStdErr` as stderr. */ export class TeamcityOutput extends TestStdout { constructor(feedLine: (line: string) => void, testOutput = false) { @@ -41,7 +41,8 @@ export class TeamcityOutput extends TestStdout { if (!MESSAGE_RE.test(line)) return line + "\n"; if (!testOutput) return ""; const message = serviceMessage(line); - if (message?.kind === "testStdOut" || message?.kind === "testStdErr") return message.attrs.out ?? ""; + if (message?.kind === "testStdOut") return message.attrs.out ?? ""; + if (message?.kind === "testStdErr") return { kind: "stderr", text: message.attrs.out ?? "" }; if (message?.kind !== "testFailed") return ""; const failure = (message.attrs.details || message.attrs.message || "").replace(/\n$/, ""); return failure ? failure + "\n" : ""; diff --git a/src/features/run/testing/types.ts b/src/features/run/testing/types.ts index 6291f3fd2..cc9071a1c 100644 --- a/src/features/run/testing/types.ts +++ b/src/features/run/testing/types.ts @@ -2,6 +2,7 @@ * Test runner output parsing. Each framework parser turns plain output lines * (ANSI already stripped) into events; `TestResults` folds them into a tree. */ +import type { OutputChunk } from "@/bindings"; export type TestStatus = "running" | "passed" | "failed" | "skipped"; @@ -60,28 +61,39 @@ export function formatDuration(ms: number | undefined): string { /** * Stdout of a runner that prints machine-readable records (`go test -json`, PHPUnit `--teamcity`): - * feeds complete, unsplit lines to the test parser and returns each line's console text. + * feeds complete, unsplit lines to the test parser and returns their console text. A line shows as + * stdout, or as a chunk of its own kind (a test's stderr reported on stdout, `testStdErr`). */ export class TestStdout { private pending = ""; constructor( private readonly feedLine: (line: string) => void, - private readonly display: (line: string) => string, + private readonly display: (line: string) => string | OutputChunk, ) {} - feed(text: string): string { + feed(text: string): OutputChunk[] { this.pending += text; const lines = this.pending.split("\n"); this.pending = lines.pop()!; - return lines.map((line) => this.line(line)).join(""); + return this.chunks(lines); } - end(): string { + end(): OutputChunk[] { const pending = this.pending; this.pending = ""; - return pending ? this.line(pending) : ""; + return pending ? this.chunks([pending]) : []; } - private line(raw: string): string { - const line = raw.replace(/\r$/, ""); - this.feedLine(line); - return this.display(line); + /** Consecutive lines of one kind in one chunk. */ + private chunks(lines: string[]): OutputChunk[] { + const out: OutputChunk[] = []; + for (const raw of lines) { + const line = raw.replace(/\r$/, ""); + this.feedLine(line); + const shown = this.display(line); + const chunk = typeof shown === "string" ? { kind: "stdout" as const, text: shown } : shown; + if (!chunk.text) continue; + const last = out[out.length - 1]; + if (last?.kind === chunk.kind) last.text += chunk.text; + else out.push({ ...chunk }); + } + return out; } }