From 529cd33ddc5705d5065f13ca6424e36b6b7c11a3 Mon Sep 17 00:00:00 2001 From: ntbang0901 <121003585+ntbang0901@users.noreply.github.com> Date: Sat, 5 Dec 2026 15:44:52 +0530 Subject: [PATCH] fix(run): keep failing tests and their failures in the test tree (#8203) JVM test names were cut at their first parenthesis, so Kotlin tests like `parse (valid input)` and `parse (empty input)`, Spock features and the tests the JUnit runner reports merged into one node `parse` with one gutter icon, and Rerun Failed asked for `ParserTest.parse`, which Gradle and Surefire don't match. Now only a parameter-type list right after the method name (and an invocation's index) is dropped (jvmMethodName / junit::method_name), consistently in the test tree, JUnit XML report names, rerun filters and the gutter's pass/fail icons (JVM files only; pytest and .NET names keep the old rule). A test that printed more than 400 lines lost its failure, because the tree kept the first 400 lines. Failure details are now kept apart from printed output and never cut; long printed output keeps its first 100 and last 300-600 lines with a line counting those left out. JUnit XML output is no longer cut at 200 lines. Co-authored-by: ntbang0901 <121003585+ntbang0901@users.noreply.github.com> --- crates/ide-run/src/junit.rs | 63 ++++++++++++++++- src/features/run/contextRun.test.ts | 13 ++++ src/features/run/java.test.ts | 49 ++++++++++++- src/features/run/runGutter.ts | 1 + src/features/run/store.ts | 9 ++- src/features/run/testing/jvm.ts | 20 ++++-- src/features/run/testing/parsers.test.ts | 87 ++++++++++++++++++++++++ src/features/run/testing/plugin.ts | 8 ++- src/features/run/testing/rerun.test.ts | 27 ++++++++ src/features/run/testing/rerun.ts | 3 +- src/features/run/testing/results.ts | 58 ++++++++++++++-- src/features/run/testing/states.test.ts | 12 ++++ src/features/run/testing/states.ts | 27 +++++--- src/features/run/testing/types.ts | 3 +- src/platform/locales/text/en.json | 3 +- src/platform/locales/text/zh.json | 3 +- 16 files changed, 351 insertions(+), 35 deletions(-) diff --git a/crates/ide-run/src/junit.rs b/crates/ide-run/src/junit.rs index 65386ecce4..f6fde7b438 100644 --- a/crates/ide-run/src/junit.rs +++ b/crates/ide-run/src/junit.rs @@ -98,6 +98,35 @@ fn push_text(buf: &mut Option, text: &str) { } } +/// The method a JUnit test name stands for, as the Run window's test tree names it (`jvmMethodName`): a JUnit +/// display name may carry the parameter types after the method (`shouldX()`, `parse (empty input)()`) and an +/// invocation's indexes (`add(int, int)[1]`). The parentheses of a Kotlin or Spock name such as +/// `parse (empty input)` are part of it. +fn method_name(name: &str) -> &str { + let mut end = name.len(); + while let Some(open) = name[..end].strip_suffix(']').and_then(|rest| rest.rfind('[')) { + let index = &name[open + 1..end - 1]; + if index.is_empty() || !index.bytes().all(|b| b.is_ascii_digit()) { + break; + } + end = open; + } + let Some((method, types)) = name[..end].strip_suffix(')').and_then(|rest| rest.rsplit_once('(')) else { + return name; + }; + let is_type = |t: &str| { + let t = t.strip_suffix("...").unwrap_or(t).trim_end_matches("[]"); + !t.is_empty() && t.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'$' | b'.')) + }; + let types_only = types.is_empty() + || types + .split(',') + .enumerate() + .all(|(i, t)| is_type(if i == 0 { t } else { t.strip_prefix(char::is_whitespace).unwrap_or(t) })); + let after_method = method.chars().next_back().is_some_and(|c| !c.is_whitespace() && c != '('); + if types_only && after_method { method } else { name } +} + /// Test cases of one report file. pub fn parse_report(xml: &str) -> Vec { let mut out = Vec::new(); @@ -154,13 +183,11 @@ pub fn parse_report(xml: &str) -> Vec { out.extend(current.take()); let class_name = attr(&a, "classname").unwrap_or_default().to_owned(); let test = attr(&a, "name").unwrap_or_default(); - // JUnit 5 display names may carry the signature: `shouldX()`, `add(int, int)[1]`. - let base = test.split('(').next().unwrap_or(test).trim().to_owned(); let duration_ms = attr(&a, "time").and_then(|t| t.replace(',', "").parse::().ok()).map(|s| s * 1000.0); let case = TestCaseReport { class_name, - name: if base.is_empty() { test.to_owned() } else { base }, + name: method_name(test).to_owned(), status: TestCaseStatus::Passed, duration_ms, message: None, @@ -369,6 +396,36 @@ mod tests { assert!(parse_report("not xml").is_empty()); } + #[test] + fn keeps_the_parentheses_of_a_test_name() { + // Gradle's report of Kotlin tests named in backticks, Surefire's and Spock features keep + // them; a JUnit signature (and an invocation's index) goes, a JUnit 4 parameter set stays. + let xml = r#" +trace + + + + + + + +"#; + let names: Vec<_> = parse_report(xml).into_iter().map(|c| c.name).collect(); + assert_eq!( + names, + [ + "parse (empty input)", + "parse (valid input)", + "parse (empty input)", + "adds 2 and 2 (unrolled)", + "check", + "check", + "check(x y)", + "adds[1 plus 2]" + ] + ); + } + #[test] fn reads_only_reports_changed_by_the_run() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/features/run/contextRun.test.ts b/src/features/run/contextRun.test.ts index 6102047275..13e9f39c72 100644 --- a/src/features/run/contextRun.test.ts +++ b/src/features/run/contextRun.test.ts @@ -298,6 +298,19 @@ describe("run gutter popup", () => { // `main` targets never show results. expect(gutterTestState({ line: 0, kind: "main", name: "main", path: [] }, path)).toBeNull(); }); + + it("icons of Kotlin tests whose names differ in parentheses follow their own results", () => { + const path = `${ROOT}/src/test/kotlin/ParserTest.kt`; + const test = (name: string): RunTarget => ({ line: 1, kind: "test", name, path: ["ParserTest", name] }); + const r = new TestResults(); + r.apply([ + { type: "result", path: ["com.acme.ParserTest", "parse (valid input)"], status: "passed" }, + { type: "result", path: ["com.acme.ParserTest", "parse (empty input)"], status: "failed" }, + ]); + recordTestStates(r); + expect(markerIcon("test", gutterTestState(test("parse (valid input)"), path))).toBe("gutter-run-passed"); + expect(markerIcon("test", gutterTestState(test("parse (empty input)"), path))).toBe("gutter-run-failed"); + }); }); describe("Debug entry", () => { diff --git a/src/features/run/java.test.ts b/src/features/run/java.test.ts index 821d8e0bb7..b1181438d0 100644 --- a/src/features/run/java.test.ts +++ b/src/features/run/java.test.ts @@ -619,7 +619,7 @@ describe("JUnit XML reports", () => { }, ]); expect(events[0]).toEqual({ type: "result", path: ["a.B", "ok"], status: "passed", durationMs: 3 }); - expect(events).toContainEqual({ type: "output", path: ["a.B$Inner", "bad"], line: "expected 1" }); + expect(events).toContainEqual({ type: "output", path: ["a.B$Inner", "bad"], line: "expected 1", failure: true }); expect(events).toContainEqual({ type: "location", path: ["a.B$Inner", "bad"], @@ -692,7 +692,7 @@ describe("what JUnit XML reports say a test printed", () => { r.apply( parser.feed("##teamcity[testFinished name='later()' className='a.B' reportName='later (not yet)' duration='0']"), ); - applyTestReports(r, [report({ name: "ok" }), report({ name: "later", status: "skipped" })]); + applyTestReports(r, [report({ name: "ok" }), report({ name: "later (not yet)", status: "skipped" })]); expect(r.counts()).toMatchObject({ total: 2, passed: 1, skipped: 1 }); expect(r.roots[0]?.children.map((n) => n.path)).toEqual([ ["a.B", "ok"], @@ -700,6 +700,25 @@ describe("what JUnit XML reports say a test printed", () => { ]); }); + it("matches Kotlin tests named with parentheses to their own XML cases", () => { + const r = new TestResults(); + const parser = jvmParser(); + for (const name of ["parse (empty input)", "parse (valid input)"]) { + const own = `name='${name}()' className='a.B' reportName='${name}()'`; + r.apply(parser.feed(`##teamcity[testStarted ${own}]`)); + if (name.includes("empty")) r.apply(parser.feed(`##teamcity[testFailed ${own} message='no' details='no']`)); + r.apply(parser.feed(`##teamcity[testFinished ${own} duration='1']`)); + } + // The names ide-run's report parser gives Gradle's `parse (empty input)()` and `parse (valid input)()`. + applyTestReports(r, [ + report({ name: "parse (empty input)", status: "failed", stdout: "printed by empty" }), + report({ name: "parse (valid input)", stdout: "printed by valid" }), + ]); + expect(r.counts()).toMatchObject({ total: 2, passed: 1, failed: 1 }); + expect(output(r, "parse (empty input)")).toEqual(["printed by empty", "no"]); + expect(output(r, "parse (valid input)")).toEqual(["printed by valid"]); + }); + it("does not add display-name rows beside parameterized Gradle invocations", () => { const r = new TestResults(); const parser = jvmParser(); @@ -779,6 +798,32 @@ describe("what JUnit XML reports say a test printed", () => { expect(output(r, "bad")).toEqual(["bad says hi", "Error: boom"]); }); + it("keeps the start and the end of long printed output, and the whole failure", () => { + const r = new TestResults(); + const stdout = Array.from({ length: 1000 }, (_, i) => `line ${i}`); + const trace = ["AssertionError: no", ...Array.from({ length: 250 }, (_, i) => `\tat a.B.f${i}(B.java:${i + 1})`)]; + applyTestReports(r, [ + report({ name: "bad", status: "failed", message: "no", output: trace.join("\n"), stdout: stdout.join("\n") }), + ]); + const lines = output(r, "bad")!; + expect(lines.slice(0, 2)).toEqual(["line 0", "line 1"]); + expect(lines.find((l) => l.startsWith("… "))).toMatch(/^… [\d,]+ lines not shown …$/); + expect(lines.slice(-trace.length - 2)).toEqual(["line 999", "no", ...trace]); + }); + + it("is not repeated for a test whose long output the Gradle init script reported", () => { + const r = new TestResults(); + const path = ["a.B", "ok"]; + const printed = Array.from({ length: 1000 }, (_, i) => `line ${i}`); + r.apply([ + ...printed.map((line) => ({ type: "output" as const, path, line })), + { type: "result", path, status: "passed" }, + ]); + const shown = [...output(r, "ok")!]; + applyTestReports(r, [report({ name: "ok", stdout: printed.join("\n") })]); + expect(output(r, "ok")).toEqual(shown); + }); + it("is not repeated for tests the Gradle init script reported with their output", () => { const r = new TestResults(); r.apply([ diff --git a/src/features/run/runGutter.ts b/src/features/run/runGutter.ts index d824c02acb..12fd71c17f 100644 --- a/src/features/run/runGutter.ts +++ b/src/features/run/runGutter.ts @@ -158,6 +158,7 @@ const fileRootedResults = (path: string) => /\.(py|[cm]?[jt]sx?|zig)$/.test(path const stateQuery = (target: RunTarget, path: string): StateQuery => ({ path: target.path, file: fileRootedResults(path) ? path : undefined, + jvm: targetLanguage(path) === "jvm", }); export function gutterTestState(target: RunTarget, path: string): TestState | null { diff --git a/src/features/run/store.ts b/src/features/run/store.ts index 4263362e16..2b8e34ca72 100644 --- a/src/features/run/store.ts +++ b/src/features/run/store.ts @@ -1561,12 +1561,15 @@ export function applyTestReports(tests: TestResults, reports: readonly TestCaseR tests.apply(testReportEvents(additional)); for (const { report, path } of reported) { const printed = printedLines(report); - const shown = new Set(tests.node(path).output); + const node = tests.node(path); + // Printed output long enough to be cut is there already; the report would repeat it. + if (node.omittedLines) continue; + const shown = new Set(node.output); if (printed.length && !printed.every((l) => shown.has(l))) tests.prependOutput(path, printed); } } -const printedLines = (r: TestCaseReport) => (r.stdout ? r.stdout.split("\n").slice(0, 200) : []); +const printedLines = (r: TestCaseReport) => (r.stdout ? r.stdout.split("\n") : []); /** JUnit XML report cases → test tree events (`[class, method]`, printed and failure output, source line). */ export function testReportEvents(reports: readonly TestCaseReport[]): TestEvent[] { @@ -1578,7 +1581,7 @@ export function testReportEvents(reports: readonly TestCaseReport[]): TestEvent[ for (const line of printedLines(r)) events.push({ type: "output", path, line }); if (r.status !== "failed") continue; const text = [r.message, r.output].filter(Boolean).join("\n"); - for (const line of text.split("\n").slice(0, 200)) events.push({ type: "output", path, line }); + for (const line of text.split("\n")) events.push({ type: "output", path, line, failure: true }); const outer = r.className.split("$")[0]!; const frame = new RegExp( `at (?:\\S*/)?(${outer.replace(/[.$]/g, "\\$&")}(?:\\$[\\w$]+)?)\\.[^()\\n]+\\(([\\w$-]+\\.(?:java|kt|groovy|scala)):(\\d+)\\)`, diff --git a/src/features/run/testing/jvm.ts b/src/features/run/testing/jvm.ts index 80740d82bc..7f38df80a2 100644 --- a/src/features/run/testing/jvm.ts +++ b/src/features/run/testing/jvm.ts @@ -22,6 +22,18 @@ const SUREFIRE_TOTAL_RE = /^(?:\[\w+\]\s+)?Tests run: (\d+), Failures: (\d+), Er // `at org.junit…`, also behind a class loader or module (`at app//org.junit…`, `at java.base@21/java.lang…`). const LIBRARY_FRAME_RE = /^\s*at\s+(?:\S*\/)?(?:org\.junit|junit\.|org\.opentest4j|org\.testng|kotlin\.|jdk\.internal|java\.|javax\.|sun\.|org\.gradle)/; +// A JUnit name's parameter types right after the method (`add(int, String[])`, `parse (empty input)()`), and +// an invocation's indexes (`add(int)[1]`). Not the parentheses of a Kotlin or Spock name: `parse (empty input)`. +const PARAMETER_TYPES_RE = + /^(.*[^\s(])\((?:[\w$.]+(?:\[\])*(?:\.{3})?(?:,\s?[\w$.]+(?:\[\])*(?:\.{3})?)*)?\)(?:\[\d+\])*$/; + +/** + * The method a JVM test name stands for, as the XML reports name it (ide-run's `junit::method_name`) and test + * filters select it: `add(int, int)` → `add`, `parse (empty input)()` → `parse (empty input)`. + */ +export function jvmMethodName(name: string): string { + return PARAMETER_TYPES_RE.exec(name)?.[1] ?? name; +} /** The source position of a stack frame in the project's code, null for library frames. */ function frameLocation(line: string): TestLocation | null { @@ -44,7 +56,7 @@ function initScriptEvents({ kind, attrs }: ServiceMessage, outcomes: Map ({ type: "output", path, line })); + const events: TestEvent[] = lines.map((line) => ({ type: "output", path, line, failure: true })); const location = lines.map(frameLocation).find((l) => l); if (location) events.push({ type: "location", path, location }); return events; @@ -71,7 +83,7 @@ function initScriptEvents({ kind, attrs }: ServiceMessage, outcomes: Map fails() FAILED expect(r.hasResult(["demo.CalcTest", "other"])).toBe(false); }); + it("keeps the parentheses of Kotlin and Spock test names", () => { + // As Gradle reports Kotlin tests named in backticks and Spock features, and as OpenIDEA's + // JUnit runner reports a Kotlin test (by its method name alone). + const r = results( + jvmParser(), + `##teamcity[testStarted name='parse (empty input)()' className='a.ParserTest' reportName='parse (empty input)()'] +##teamcity[testFailed name='parse (empty input)()' className='a.ParserTest' reportName='parse (empty input)()' message='no' details='org.opentest4j.AssertionFailedError: no|n\tat app//a.ParserTest.parse (empty input)(ParserTest.kt:16)|n'] +##teamcity[testFinished name='parse (empty input)()' className='a.ParserTest' reportName='parse (empty input)()' duration='11'] +##teamcity[testStarted name='parse (valid input)()' className='a.ParserTest' reportName='parse (valid input)()'] +##teamcity[testFinished name='parse (valid input)()' className='a.ParserTest' reportName='parse (valid input)()' duration='1'] +##teamcity[testStarted name='add(int, int, int)|[2|]' className='a.ParserTest' reportName='2 plus 2' invocation='2 plus 2'] +##teamcity[testFailed name='add(int, int, int)|[2|]' className='a.ParserTest' reportName='2 plus 2' invocation='2 plus 2' message='no' details='no'] +##teamcity[testFinished name='add(int, int, int)|[2|]' className='a.ParserTest' reportName='2 plus 2' invocation='2 plus 2' duration='1'] +##teamcity[testStarted name='parse (valid input)' className='a.ParserSpec' reportName='parse (valid input)'] +##teamcity[testFinished name='parse (valid input)' className='a.ParserSpec' reportName='parse (valid input)' duration='20'] +##teamcity[testStarted name='parse (empty input)' className='a.ParserSpec' reportName='parse (empty input)'] +##teamcity[testFailed name='parse (empty input)' className='a.ParserSpec' reportName='parse (empty input)' message='no' details='no'] +##teamcity[testFinished name='parse (empty input)' className='a.ParserSpec' reportName='parse (empty input)' duration='144'] +##teamcity[testStarted name='parse (empty input)' className='a.RunnerTest'] +##teamcity[testFailed name='parse (empty input)' className='a.RunnerTest' message='no' details='no'] +##teamcity[testFinished name='parse (empty input)' className='a.RunnerTest' duration='3'] +##teamcity[testStarted name='parse (valid input)' className='a.RunnerTest'] +##teamcity[testFinished name='parse (valid input)' className='a.RunnerTest' duration='1'] +`, + ); + const tests = (cls: string) => r.get(cls)!.children.map((n) => [n.name, nodeStatus(n), n.reportName]); + expect(tests("a.ParserTest")).toEqual([ + ["parse (empty input)", "failed", "parse (empty input)"], + ["parse (valid input)", "passed", "parse (valid input)"], + ["add", "failed", undefined], + ]); + expect(tests("a.ParserSpec")).toEqual([ + ["parse (valid input)", "passed", "parse (valid input)"], + ["parse (empty input)", "failed", "parse (empty input)"], + ]); + expect(tests("a.RunnerTest")).toEqual([ + ["parse (empty input)", "failed", undefined], + ["parse (valid input)", "passed", undefined], + ]); + expect(failedTestPaths(r)).toEqual([ + ["a.ParserTest", "parse (empty input)"], + ["a.ParserTest", "add", "2 plus 2"], + ["a.ParserSpec", "parse (empty input)"], + ["a.RunnerTest", "parse (empty input)"], + ]); + }); + it("shows each invocation of a parameterized test under its method", () => { const r = results( jvmParser(), @@ -745,6 +793,45 @@ describe("parser selection", () => { }); describe("TestResults", () => { + it("keeps the failure of a test that printed a lot, and the start and the end of what it printed", () => { + const own = "name='total()' className='a.NoisyTest' reportName='total()'"; + const lines = [`##teamcity[testStarted ${own}]`]; + for (let i = 0; i < 2000; i++) lines.push(`##teamcity[testStdOut ${own} out='step ${i}|n']`); + lines.push( + `##teamcity[testFailed ${own} message='order total ==> expected: <42> but was: <41>' details='org.opentest4j.AssertionFailedError: order total ==> expected: <42> but was: <41>|n\tat app//a.NoisyTest.total(NoisyTest.kt:10)|n']`, + `##teamcity[testFinished ${own} duration='5']`, + ); + const r = results(jvmParser(), lines.join("\n")); + const output = leaf(r, "a.NoisyTest", "total")!.output; + expect(output.slice(0, 2)).toEqual(["step 0", "step 1"]); + const marker = output.find((l) => l.startsWith("… ")); + expect(marker).toMatch(/^… [\d,]+ lines not shown …$/); + // Each printed line is shown or counted. + const shown = output.filter((l) => l.startsWith("step ")).length; + expect(Number(marker!.replace(/\D/g, "")) + shown).toBe(2000); + expect(output.slice(-5)).toEqual([ + "step 1998", + "step 1999", + "org.opentest4j.AssertionFailedError: order total ==> expected: <42> but was: <41>", + "\tat app//a.NoisyTest.total(NoisyTest.kt:10)", + "", + ]); + expect(output.length).toBeLessThan(800); + expect(parseComparison(output)).toEqual({ expected: "42", actual: "41" }); + }); + + it("keeps failure details at the end, whatever is printed after them", () => { + const r = new TestResults(); + const path = ["a.B", "t"]; + r.apply([ + { type: "output", path, line: "before" }, + { type: "output", path, line: "boom", failure: true }, + { type: "output", path, line: "after" }, + ]); + r.prependOutput(path, ["from the report"]); + expect(r.get("a.B\u0000t")!.output).toEqual(["from the report", "before", "after", "boom"]); + }); + it("marks unfinished tests when the process ends", () => { const r = new TestResults(); r.apply([{ type: "start", path: ["s", "a"] }]); diff --git a/src/features/run/testing/plugin.ts b/src/features/run/testing/plugin.ts index f11c23aeb2..15047ecca1 100644 --- a/src/features/run/testing/plugin.ts +++ b/src/features/run/testing/plugin.ts @@ -53,9 +53,11 @@ export class PluginTestEvents { durationMs: event.durationMs ?? undefined, }); if (event.type === "failed") { - out.push({ type: "output", path, line: event.message }); - if (event.expected !== null) out.push({ type: "output", path, line: tx`Expected: ${event.expected}` }); - if (event.actual !== null) out.push({ type: "output", path, line: tx`Actual: ${event.actual}` }); + out.push({ type: "output", path, line: event.message, failure: true }); + if (event.expected !== null) + out.push({ type: "output", path, line: tx`Expected: ${event.expected}`, failure: true }); + if (event.actual !== null) + out.push({ type: "output", path, line: tx`Actual: ${event.actual}`, failure: true }); if (event.location) out.push({ type: "location", diff --git a/src/features/run/testing/rerun.test.ts b/src/features/run/testing/rerun.test.ts index fade5a91c6..519b3b3a0b 100644 --- a/src/features/run/testing/rerun.test.ts +++ b/src/features/run/testing/rerun.test.ts @@ -253,6 +253,33 @@ describe("rerunFailedConfig", () => { ).toEqual(["test", "--tests", "com.a.FooTest.add"]); }); + it("jvm: reruns a Kotlin or Spock test named with parentheses by its whole name", async () => { + const paths = [ + ["a.ParserTest", "parse (empty input)"], + ["a.ParserTest", "add(int, int)"], + ["a.ParserTest", "check", "[1] a (b)"], + ]; + expect((await rerunFailedConfig(cfg("gradle", "./gradlew", ["test"]), paths))!.args).toEqual([ + "test", + "--tests", + "a.ParserTest.parse (empty input)", + "--tests", + "a.ParserTest.add", + "--tests", + "a.ParserTest.check", + ]); + expect((await rerunFailedConfig(cfg("maven", "mvn", ["test"]), paths))!.args.slice(0, 2)).toEqual([ + "test", + "-Dtest=a.ParserTest#parse (empty input)+add+check", + ]); + const runner = cfg("application", "java", ["-ea", "-cp", "${testClasspath}", "ai.openidea.junit.Runner", "a.X"]); + expect((await rerunFailedConfig(runner, paths))!.args.slice(4)).toEqual([ + "a.ParserTest#parse (empty input)", + "a.ParserTest#add", + "a.ParserTest#check", + ]); + }); + it("maven: a rerun replaces the previous selection and lets modules without the tests pass", async () => { const narrowed = cfg("maven", "./mvnw", [ "test", diff --git a/src/features/run/testing/rerun.ts b/src/features/run/testing/rerun.ts index cd94d1483c..6060e543eb 100644 --- a/src/features/run/testing/rerun.ts +++ b/src/features/run/testing/rerun.ts @@ -16,6 +16,7 @@ import { frameworkFor } from "./index"; import { cargoRerunArgs, cargoRunOf, isCargoDoctest } from "./cargoRerun"; import { vitestProject } from "./js"; import { runnerOf } from "./watch"; +import { jvmMethodName } from "./jvm"; import { dotnetFilter } from "./dotnet"; import { xcodeOnlyTesting } from "./xcode"; import { pytestNodeId } from "./pytest"; @@ -167,7 +168,7 @@ function goArgs(base: string[], paths: string[][], file?: string): string[] | nu function jvmArgs(config: RunConfig, paths: string[][]): string[] | null { // `[class, method]`, or `[class, method, invocation]`: an invocation reruns its method. - const tests = paths.filter((p) => p.length >= 2).map((p) => ({ cls: p[0]!, method: p[1]!.replace(/\(.*\)$/, "") })); + const tests = paths.filter((p) => p.length >= 2).map((p) => ({ cls: p[0]!, method: jvmMethodName(p[1]!) })); const classes = unique(paths.filter((p) => p.length === 1).map((p) => p[0]!)); if (!tests.length && !classes.length) return null; if (isJunitRunner(config)) { diff --git a/src/features/run/testing/results.ts b/src/features/run/testing/results.ts index d31771b1d7..78c257ec88 100644 --- a/src/features/run/testing/results.ts +++ b/src/features/run/testing/results.ts @@ -1,4 +1,5 @@ /** Folds parser events into a results tree with aggregated statuses and counts. */ +import { tx } from "@/platform/i18n"; import type { TestEvent, TestLocation, TestStatus } from "./types"; export interface TestNode { @@ -11,8 +12,12 @@ export interface TestNode { durationMs?: number; reportName?: string; location?: TestLocation; - /** Output captured for this node: its console output and failure details. */ + /** Output captured for this node: what it printed, then its failure details. */ output: string[]; + /** How many lines at the end of `output` are failure details, kept whatever the test printed before. */ + failureLines?: number; + /** Printed lines left out after the first `HEAD` lines of `output`; a line there counts them. */ + omittedLines?: number; } /** A node's output followed by its descendants' in tree order: a group shows the output of its tests. */ @@ -44,7 +49,23 @@ export interface TestCounts { } const SEP = "\u0000"; -const MAX_OUTPUT_LINES = 400; +/** What a test printed is kept to its first `HEAD` lines and its last `TAIL` to `2 × TAIL` lines. */ +const HEAD = 100; +const TAIL = 300; + +const omittedLine = (count: number) => tx`… ${count.toLocaleString()} lines not shown …`; + +/** + * Leaves out the middle of what `n` printed once it is longer than `HEAD + 2 × TAIL` lines. Cutting + * `TAIL` lines at a time keeps adding a line cheap, and the count in the marker exact. + */ +function cut(n: TestNode) { + const omitted = n.omittedLines ?? 0; + const end = n.output.length - (n.failureLines ?? 0) - HEAD - (omitted ? 1 : 0); + if (end <= 2 * TAIL) return; + n.omittedLines = omitted + end - TAIL; + n.output.splice(HEAD, end - TAIL + (omitted ? 1 : 0), omittedLine(n.omittedLines)); +} export function nodeStatus(node: TestNode): TestStatus | null { if (node.children.length === 0) return node.own; @@ -98,13 +119,25 @@ export class TestResults { /** Puts lines before a test's output (what it printed, read after the run, goes before its failure). */ prependOutput(path: string[], lines: readonly string[]) { const n = this.node(path); - n.output = [...lines, ...n.output].slice(0, MAX_OUTPUT_LINES); + if (n.omittedLines) { + // The start grows; what no longer fits in it is left out with the rest. + const start = [...lines, ...n.output.slice(0, HEAD)]; + n.omittedLines += start.length - HEAD; + n.output.splice(0, HEAD + 1, ...start.slice(0, HEAD), omittedLine(n.omittedLines)); + } else { + n.output = [...lines, ...n.output]; + cut(n); + } this.version++; } /** Console Clear All: drops every node's captured output; statuses, durations and the tree stay. */ clearOutput() { - for (const n of this.byId.values()) n.output = []; + for (const n of this.byId.values()) { + n.output = []; + n.failureLines = undefined; + n.omittedLines = undefined; + } this.version++; } @@ -138,7 +171,11 @@ export class TestResults { target.durationMs ??= source.durationMs; if (source.reportName !== undefined) target.reportName ??= source.reportName; target.location ??= source.location; - if (target.output.length === 0) target.output = source.output; + if (target.output.length === 0) { + target.output = source.output; + target.failureLines = source.failureLines; + target.omittedLines = source.omittedLines; + } for (const child of source.children) this.mergeInto(child, [...into, child.name]); } @@ -171,7 +208,16 @@ export class TestResults { } case "output": { const n = this.node(e.path); - if (n.output.length < MAX_OUTPUT_LINES) n.output.push(e.line); + const failureLines = n.failureLines ?? 0; + if (e.failure) { + n.output.push(e.line); + n.failureLines = failureLines + 1; + } else { + // Printed lines go before the failure details, which stay whole at the end. + if (failureLines) n.output.splice(n.output.length - failureLines, 0, e.line); + else n.output.push(e.line); + cut(n); + } break; } case "move": diff --git a/src/features/run/testing/states.test.ts b/src/features/run/testing/states.test.ts index 968bdcdc1d..dd868c791b 100644 --- a/src/features/run/testing/states.test.ts +++ b/src/features/run/testing/states.test.ts @@ -34,6 +34,18 @@ describe("test states for the run gutter", () => { expect(testState({ path: ["OrderTest"] })).toBe("failed"); }); + it("keeps the parentheses of JVM test names, but not a JUnit 4 parameter set", () => { + run([ + { type: "result", path: ["com.acme.ParserTest", "parse (valid input)"], status: "passed" }, + { type: "result", path: ["com.acme.ParserTest", "parse (empty input)"], status: "failed" }, + { type: "result", path: ["com.acme.AddTest", "adds[1 plus 2]"], status: "passed" }, + { type: "result", path: ["com.acme.AddTest", "adds[2 plus 2]"], status: "failed" }, + ]); + expect(testState({ path: ["ParserTest", "parse (valid input)"], jvm: true })).toBe("passed"); + expect(testState({ path: ["ParserTest", "parse (empty input)"], jvm: true })).toBe("failed"); + expect(testState({ path: ["AddTest", "adds"], jvm: true })).toBe("failed"); + }); + it("checks the file for results rooted at it, and any parameter failing fails the test", () => { run([ { type: "result", path: ["tests/test_math.py", "test_add[1]"], status: "passed" }, diff --git a/src/features/run/testing/states.ts b/src/features/run/testing/states.ts index a50d9d7f13..f64eb196b3 100644 --- a/src/features/run/testing/states.ts +++ b/src/features/run/testing/states.ts @@ -4,6 +4,7 @@ * Results are matched to gutter targets by their test path (the trailing name * parts), plus the file for frameworks whose results are rooted at the file (or its module). */ +import { jvmMethodName } from "./jvm"; import { nodeStatus, type TestNode, type TestResults } from "./results"; import type { TestStatus } from "./types"; @@ -57,12 +58,16 @@ export function clearTestStates() { for (const l of listeners) l(); } -/** `name()`, `name(int)`, `test_x[param]` → `name` / `test_x`. */ -const norm = (s: string) => s.replace(/\s*(\(.*\)|\[.*\])$/, "").trim(); +/** + * `name()`, `name(int)`, `test_x[param]` → `name` / `test_x`. A JVM name loses only its parameter types + * (`jvmMethodName`) and a JUnit 4 parameter set: `parse (empty input)` is a Kotlin or Spock test of its own. + */ +const norm = (s: string, jvm: boolean) => + (jvm ? jvmMethodName(s).replace(/\s*\[.*\]$/, "") : s.replace(/\s*(\(.*\)|\[.*\])$/, "")).trim(); -function segmentMatches(result: string, target: string): boolean { - const a = norm(result); - const b = norm(target); +function segmentMatches(result: string, target: string, jvm: boolean): boolean { + const a = norm(result, jvm); + const b = norm(target, jvm); // JVM results name the class by its fully qualified name, gutter targets by the simple one. return a === b || a.endsWith(`.${b}`) || b.endsWith(`.${a}`); } @@ -93,13 +98,15 @@ export interface StateQuery { path: string[]; /** Project-relative path of the file, checked when results are rooted at their file. */ file?: string; + /** A test in a JVM language (Java, Kotlin, Groovy, Scala). */ + jvm?: boolean; } /** Whether a result's test path is the gutter target's. */ -export function matchesTarget(result: string[], { path, file }: StateQuery): boolean { +export function matchesTarget(result: string[], { path, file, jvm = false }: StateQuery): boolean { if (!path.length || result.length < path.length) return false; const offset = result.length - path.length; - if (!path.every((p, i) => segmentMatches(result[offset + i]!, p))) return false; + if (!path.every((p, i) => segmentMatches(result[offset + i]!, p, jvm))) return false; return file === undefined || (offset > 0 && sameFile(result[0]!, file)); } @@ -107,11 +114,11 @@ export function matchesTarget(result: string[], { path, file }: StateQuery): boo * Last state of a gutter target: failed when any matching result failed (a * parameterised test failed for one of its parameters), else passed. */ -export function testState({ path, file }: StateQuery): TestState | null { - if (!path.length) return null; +export function testState(query: StateQuery): TestState | null { + if (!query.path.length) return null; let passed = false; for (const e of entries.values()) { - if (!matchesTarget(e.path, { path, file })) continue; + if (!matchesTarget(e.path, query)) continue; if (e.state === "failed") return "failed"; passed = true; } diff --git a/src/features/run/testing/types.ts b/src/features/run/testing/types.ts index d8a16190ea..67994829a0 100644 --- a/src/features/run/testing/types.ts +++ b/src/features/run/testing/types.ts @@ -30,7 +30,8 @@ export type TestEvent = reportName?: string; } | { type: "location"; path: string[]; location: TestLocation } - | { type: "output"; path: string[]; line: string } + /** `failure`: a line of the failure's message or stack trace, which no cap on the test's output leaves out. */ + | { type: "output"; path: string[]; line: string; failure?: boolean } /** The runner named the test at `from` in full: its results and its tests' are now at `into`. */ | { type: "move"; from: string[]; into: string[] } | { type: "summary"; passed?: number; failed?: number; skipped?: number; durationMs?: number } diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index e0ae45e9d4..571ae8423a 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -5857,5 +5857,6 @@ "1 image": "1 image", "{imageCount} images": "{imageCount} images", "{title} actions": "{title} actions", - "{n}/{count} files": "{n}/{count} files" + "{n}/{count} files": "{n}/{count} files", + "… {count} lines not shown …": "… {count} lines not shown …" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index b094456e3c..93a6436973 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -12747,5 +12747,6 @@ "1 image": "1 张图片", "{imageCount} images": "{imageCount} 张图片", "{title} actions": "{title} 操作", - "{n}/{count} files": "{n}/{count} 个文件" + "{n}/{count} files": "{n}/{count} 个文件", + "… {count} lines not shown …": "… {count} 行未显示 …" }