fix(run): group pytest parametrized cases under their test (#6384)

Parametrized pytest cases now appear as children of their test, with the combined status on the parent, and Run / Rerun Failed on either runs exactly that node id. The parser split node ids at every :: and failure titles at every dot and only matched ids without spaces, so cases were flat siblings, cases with spaces were missing, and a failing [v1.2 ...] case became a bogus chain under the run root. The [id] part is now kept whole. Tests without a failure line, and the grouping node, now navigate to the test's def.

Closes #6360

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-27 15:15:04 +08:00
1 джерело 0dae111b2d
коміт 661124d0d4
7 files changed
+159 -14

No files matched your search

+8
Переглянути файл
@@ -21,6 +21,14 @@ def test_complete_and_overdue():
assert tasks.overdue(date(2024, 1, 1)) == []
@pytest.mark.parametrize(
("title", "expected"),
[("write docs", "write docs"), (" padded ", "padded"), ("v1.2 notes", "v1.2 notes")],
)
def test_add_strips_titles(title, expected):
assert TaskList().add(title).title == expected
def test_rejects_empty_titles():
with pytest.raises(ValueError):
TaskList().add(" ")
+1 -1
Переглянути файл
@@ -122,7 +122,7 @@ const CASES: Record<string, Case | Case[]> = {
tests: {
config: "pytest",
failing: (c) => env(c, { OPENIDEA_FAIL: "1" }),
passed: 4,
passed: 7,
failed: "test_intentionally_failing",
file: "tests/test_models.py",
},
+4 -1
Переглянути файл
@@ -19,7 +19,10 @@ export interface FileTarget {
resolve: "path" | "name" | "rubyTest";
/** JVM frames: the class's binary name (`com.acme.OrderController$Inner`). */
className?: string;
/** No line: the describe chain and name of a JS test, found in the file (Cypress prints no line). */
/**
* No line: the describe chain and name of a JS test (Cypress prints no line), or the class chain
* and name of a pytest test, found in the file.
*/
test?: string[];
}
+72 -1
Переглянути файл
@@ -345,11 +345,82 @@ FAILED tests/test_math.py::test_sub - assert 0 == 1
it("parses verbose node ids into a tree", () => {
const r = results(pytestParser(), verbose);
expect(leaf(r, "tests/test_math.py", "test_add")?.own).toBe("passed");
expect(leaf(r, "tests/test_math.py", "TestDiv", "test_zero[1]")?.own).toBe("skipped");
expect(leaf(r, "tests/test_math.py", "TestDiv", "test_zero", "[1]")?.own).toBe("skipped");
expect(leaf(r, "tests/test_math.py", "TestDiv", "test_ok")?.own).toBe("passed");
expect(nodeStatus(r.get("tests/test_math.py")!)).toBe("failed");
});
it("locates tests without a failure line at their def", () => {
const r = results(pytestParser(), verbose);
expect(leaf(r, "tests/test_math.py", "test_add")?.location).toEqual({
path: "tests/test_math.py",
resolve: "path",
test: ["test_add"],
});
expect(leaf(r, "tests/test_math.py", "TestDiv", "test_zero", "[1]")?.location?.test).toEqual([
"TestDiv",
"test_zero",
]);
expect(leaf(r, "tests/test_math.py", "TestDiv", "test_zero")?.location?.test).toEqual(["TestDiv", "test_zero"]);
});
it("groups parametrized cases under their test", () => {
const r = results(
pytestParser(),
`tests/test_p.py::test_div[1.5] FAILED [ 20%]
tests/test_p.py::test_div[a::b] PASSED [ 40%]
tests/test_p.py::test_div[x[0]] PASSED [ 60%]
tests/test_p.py::test_div[two words] SKIPPED (later) [ 80%]
tests/test_p.py::TestK::test_m[0-0] PASSED [100%]
=================================== FAILURES ===================================
________________________________ test_div[1.5] _________________________________
def test_div(x):
> assert x == 2
E assert 1.5 == 2
tests/test_p.py:4: AssertionError
=========================== short test summary info ============================
FAILED tests/test_p.py::test_div[1.5] - assert 1.5 == 2
=================== 1 failed, 3 passed, 1 skipped in 0.02s ====================
`,
);
const div = leaf(r, "tests/test_p.py", "test_div")!;
expect(div.children.map((c) => c.name)).toEqual(["[1.5]", "[a::b]", "[x[0]]", "[two words]"]);
expect(nodeStatus(div)).toBe("failed");
expect(div.location?.test).toEqual(["test_div"]);
const failed = leaf(r, "tests/test_p.py", "test_div", "[1.5]")!;
expect(failed.location).toEqual({
path: "tests/test_p.py",
line: 4,
resolve: "path",
});
expect(failed.output.some((l) => l.includes("assert 1.5 == 2"))).toBe(true);
expect(leaf(r, "tests/test_p.py", "test_div", "[two words]")?.own).toBe("skipped");
expect(leaf(r, "tests/test_p.py", "TestK", "test_m", "[0-0]")?.own).toBe("passed");
expect(r.roots.map((n) => n.name)).toEqual(["tests/test_p.py"]);
expect(r.counts()).toMatchObject({ passed: 3, failed: 1, skipped: 1 });
});
it("attaches a case's failure printed before its node id (non-verbose)", () => {
const r = results(
pytestParser(),
`tests/test_p.py F. [100%]
=================================== FAILURES ===================================
_____________________________ TestK.test_m[1.5] ______________________________
tests/test_p.py:9: AssertionError
=========================== short test summary info ============================
FAILED tests/test_p.py::TestK::test_m[1.5] - assert False
========================= 1 failed, 1 passed in 0.02s =========================
`,
);
expect(leaf(r, "tests/test_p.py", "TestK", "test_m", "[1.5]")?.location?.line).toBe(9);
expect(r.roots.map((n) => n.name)).toEqual(["tests/test_p.py"]);
});
it("attaches failure sections and locations", () => {
const r = results(pytestParser(), verbose);
const failed = leaf(r, "tests/test_math.py", "test_sub")!;
+63 -9
Переглянути файл
@@ -5,10 +5,10 @@ type Outcome = "PASSED" | "FAILED" | "ERROR" | "SKIPPED" | "XFAIL" | "XPASS";
const OUTCOME = String.raw`(PASSED|FAILED|ERROR|SKIPPED|XFAIL|XPASS)`;
// `tests/test_x.py::TestC::test_y[1] PASSED [ 50%]`
const VERBOSE_RE = new RegExp(String.raw`^(\S+\.py::\S+)\s+${OUTCOME}(?:\s|$)`);
const VERBOSE_RE = new RegExp(String.raw`^(\S+\.py::.+?)\s+${OUTCOME}(?:\s|$)`);
// `[gw0] PASSED tests/test_x.py::test_add` (xdist) and short summary `FAILED tests/test_x.py::test_sub - msg`
const PREFIX_RE = new RegExp(
String.raw`^(?:\[gw\d+\]\s+(?:\[\s*\d+%\]\s+)?)?${OUTCOME}\s+(\S+\.py::\S+?)(?:\s+-\s+.*)?$`,
String.raw`^(?:\[gw\d+\]\s+(?:\[\s*\d+%\]\s+)?)?${OUTCOME}\s+(\S+\.py::.+?)(?:\s+-\s+.*)?$`,
);
// `tests/test_x.py .F.s [100%]`
const PROGRESS_RE = /^(\S+\.py) ([.FEsxX]+)\s*(?:\[\s*\d+%\])?$/;
@@ -29,7 +29,45 @@ function status(outcome: Outcome): Exclude<TestStatus, "running"> {
}
}
const split = (nodeid: string) => nodeid.split("::").filter(Boolean);
/**
* `file.py::Class::test[id]` → `[file.py, Class, test, [id]]`: a parametrized case is a child of its
* test. The id is kept whole (it may hold `::`, `.` or `[`); test names never contain `[`.
*/
const split = (nodeid: string) => {
const file = nodeid.indexOf("::");
const open = nodeid.indexOf("[", file + 2);
const parts = (open < 0 ? nodeid : nodeid.slice(0, open)).split("::").filter(Boolean);
if (open >= 0 && parts.length > 1) parts.push(nodeid.slice(open));
return parts;
};
const isCase = (part: string | undefined) => !!part?.startsWith("[");
/** pytest node id of a test path: a case's `[id]` follows its test without `::`. */
export function pytestNodeId(path: readonly string[]): string {
return isCase(path[path.length - 1]) && path.length > 2
? `${path.slice(0, -1).join("::")}${path[path.length - 1]}`
: path.join("::");
}
/**
* Where a test is declared, for a test that has no failure line to go to (and for the node
* grouping a test's cases): its `def` in the file.
*/
function declarations(path: string[], status: TestStatus): TestEvent[] {
if (path.length < 2) return [];
const test = path.slice(1).filter((p) => !isCase(p));
const at = (p: string[]): TestEvent => ({
type: "location",
path: p,
location: { path: path[0]!, resolve: "path", test },
});
const out: TestEvent[] = [];
if (isCase(path[path.length - 1])) out.push(at(path.slice(0, -1)));
// A failure's own line comes with its section.
if (status !== "failed") out.push(at(path));
return out;
}
export function pytestParser(): TestOutputParser {
/** Node ids reported so far, used to resolve failure section titles. */
@@ -61,8 +99,14 @@ export function pytestParser(): TestOutputParser {
return out;
};
/** Section titles are `test_name` or `TestClass.test_name`. */
const titleParts = (title: string) => title.replace(/^(ERROR at \w+ of |ERROR collecting )/, "").split(".");
/** Section titles are `test_name`, `TestClass.test_name` or either with a case id (`test_name[1.5]`). */
const titleParts = (title: string) => {
const name = title.replace(/^(ERROR at \w+ of |ERROR collecting )/, "");
const open = name.indexOf("[");
const parts = (open < 0 ? name : name.slice(0, open)).split(".");
if (open > 0) parts.push(name.slice(open));
return parts;
};
return {
feed(line) {
@@ -70,12 +114,14 @@ export function pytestParser(): TestOutputParser {
let m: RegExpExecArray | null;
if ((m = VERBOSE_RE.exec(line))) {
const path = split(m[1]!);
events.push({ type: "result", path, status: status(m[2] as Outcome) }, ...remember(path));
const outcome = status(m[2] as Outcome);
events.push({ type: "result", path, status: outcome }, ...declarations(path, outcome), ...remember(path));
return events;
}
if ((m = PREFIX_RE.exec(line))) {
const path = split(m[2]!);
events.push({ type: "result", path, status: status(m[1] as Outcome) }, ...remember(path));
const outcome = status(m[1] as Outcome);
events.push({ type: "result", path, status: outcome }, ...declarations(path, outcome), ...remember(path));
failure = null;
pending = null;
return events;
@@ -83,7 +129,11 @@ export function pytestParser(): TestOutputParser {
if ((m = PROGRESS_RE.exec(line))) {
const failed = /[FE]/.test(m[2]!);
const allSkipped = /^[sx]+$/.test(m[2]!);
events.push({ type: "result", path: [m[1]!], status: failed ? "failed" : allSkipped ? "skipped" : "passed" });
events.push({
type: "result",
path: [m[1]!],
status: failed ? "failed" : allSkipped ? "skipped" : "passed",
});
return events;
}
if ((m = SUMMARY_RE.exec(line))) {
@@ -96,7 +146,11 @@ export function pytestParser(): TestOutputParser {
else counts.failed = (counts.failed ?? 0) + n;
}
const d = / in ([\d.]+s)/.exec(m[1]!);
events.push({ type: "summary", ...counts, durationMs: parseDuration(d?.[1]) });
events.push({
type: "summary",
...counts,
durationMs: parseDuration(d?.[1]),
});
return events;
}
if ((m = SECTION_RE.exec(line))) {
+9 -1
Переглянути файл
@@ -122,12 +122,20 @@ describe("rerunFailedConfig", () => {
it("pytest: node ids replace explicit paths", async () => {
const c = (await rerunFailedConfig(cfg("pytest", ".venv/bin/pytest", ["-q", "tests/", "-k", "slow"]), [
["tests/test_x.py", "TestC", "test_y[1]"],
["tests/test_x.py", "TestC", "test_y", "[1]"],
["tests/test_z.py", "test_a"],
]))!;
expect(c.args).toEqual(["-q", "tests/test_x.py::TestC::test_y[1]", "tests/test_z.py::test_a"]);
});
it("pytest: a parametrized test reruns all of its cases, a case only itself", async () => {
const c = (await rerunFailedConfig(cfg("pytest", "pytest", []), [
["tests/test_x.py", "test_div"],
["tests/test_x.py", "test_div", "[a::b.c]"],
]))!;
expect(c.args).toEqual(["tests/test_x.py::test_div", "tests/test_x.py::test_div[a::b.c]"]);
});
it("django: dotted labels in place of the run's target, options kept", async () => {
const c = (await rerunFailedConfig(
cfg("django-test", ".venv/bin/python", ["manage.py", "test", "polls", "--keepdb", "-v", "2"]),
+2 -1
Переглянути файл
@@ -14,6 +14,7 @@ import { goTestParts, withoutGoSelection } from "../goArguments";
import { withMavenTests } from "../mavenTests";
import { frameworkFor } from "./index";
import { dotnetFilter } from "./dotnet";
import { pytestNodeId } from "./pytest";
import { cypressSelection } from "./cypress";
import { playwrightProject, playwrightTitles } from "./playwright";
import { withNodeTestNamePattern } from "./nodeTest";
@@ -113,7 +114,7 @@ function playwrightArgs(config: RunConfig, paths: string[][]): string[] | null {
}
function pytestArgs(base: string[], paths: string[][]): string[] | null {
const ids = unique(paths.map((p) => p.join("::")));
const ids = unique(paths.map(pytestNodeId));
if (!ids.length) return null;
// Drop explicit test paths / -k expressions of the original run; keep options and `-m pytest` prefixes.
const kept = dropFlag(base, ["-k"]).filter((a) => !/\.py(::|$)/.test(a) && !/^tests?\/?$/.test(a));