diff --git a/src/features/run/links.ts b/src/features/run/links.ts index f3449f0ef9..e085039b36 100644 --- a/src/features/run/links.ts +++ b/src/features/run/links.ts @@ -14,14 +14,15 @@ export interface FileTarget { * stack frame — look it up in the project (`path` then is the file under its * package directory, `com/acme/OrderController.kt`, when the frame names the class); * `rubyTest`: a Minitest test with no file in its output — `className` is its class, `path` its - * method name — found by searching the project (`rubyTests.ts`). + * method name — found by searching the project (`rubyTests.ts`); + * `pythonModule`: a Python test reported by its dotted module name, not a file path. */ - resolve: "path" | "name" | "rubyTest"; + resolve: "path" | "name" | "rubyTest" | "pythonModule"; /** JVM frames: the class's binary name (`com.acme.OrderController$Inner`). */ className?: string; /** * 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. + * and name of a Python test, found in the file. */ test?: string[]; } diff --git a/src/features/run/navigate.test.ts b/src/features/run/navigate.test.ts index 683e392787..4c8a1a4eac 100644 --- a/src/features/run/navigate.test.ts +++ b/src/features/run/navigate.test.ts @@ -23,7 +23,11 @@ vi.mock("@/platform/ipc", () => ({ commands: { // A host file at a container path (Homebrew's Python on an Intel Mac has this folder too). fsReadDir: async (dir: string) => - dir === "/usr/lib/site-packages/requests" ? [{ name: "api.py", kind: "file" }] : [], + dir === "/usr/lib/site-packages/requests" + ? [{ name: "api.py", kind: "file" }] + : Object.keys(files) + .filter((path) => path.slice(0, path.lastIndexOf("/")) === dir) + .map((path) => ({ name: path.split("/").pop(), kind: "file" })), fsReadText: async (path: string) => files[path] ?? "", findFilesNamed: async (name: string) => Object.keys(files).filter((p) => p.endsWith(`/${name}`)), indexStatus: async () => ({ files: Object.keys(files).length }), @@ -54,6 +58,39 @@ describe("JS tests without a line", () => { }, 60_000); }); +describe("Django test modules without a reported file", () => { + const at = (path: string) => ({ path, resolve: "pythonModule" as const, test: ["ProductPagesTests", "test_detail"] }); + + it("resolves the full module and declaration, not a same-named file", async () => { + const source = "/p/website/shop/tests.py"; + files[source] = + "from django.test import SimpleTestCase\n\nclass ProductPagesTests(SimpleTestCase):\n def test_detail(self):\n pass"; + files["/p/other/tests.py"] = files[source]!; + files["/p/other/shop/tests.py"] = files[source]!; + try { + expect(await resolveTarget(at("shop.tests"), "/p/website")).toBe(source); + expect(await declarationLine(source, at("shop.tests").test, true)).toBe(4); + expect(await resolveTarget(at("shop.tests"), "/p")).toBeNull(); + expect(await resolveTarget(at("missing.tests"), "/p/website")).toBeNull(); + } finally { + delete files[source]; + delete files["/p/other/tests.py"]; + delete files["/p/other/shop/tests.py"]; + } + }); + + it("finds the package module's __init__.py in a src layout", async () => { + const source = "/p/src/shop/tests/__init__.py"; + files[source] = "class ProductPagesTests(SimpleTestCase):\n def test_detail(self):\n pass"; + try { + expect(await resolveTarget(at("shop.tests"), "/p")).toBe(source); + expect(await declarationLine(source, at("shop.tests").test, true)).toBe(2); + } finally { + delete files[source]; + } + }); +}); + describe("paths printed in a container", () => { const at = (path: string) => ({ path, line: 3, resolve: "path" as const }); diff --git a/src/features/run/navigate.ts b/src/features/run/navigate.ts index 1074edf958..c4bf089f72 100644 --- a/src/features/run/navigate.ts +++ b/src/features/run/navigate.ts @@ -38,21 +38,25 @@ async function declaresPackage(path: string, pkg: string): Promise { } } +async function indexedNamedPaths(name: string, module?: string | null): Promise { + const remote = useRemote.getState().session; + // Older remote servers only have fuzzy search: request the whole inventory before filtering. + const found = + remote && !remote.commands.includes("find_files_named") + ? (await call(commands.findFiles(name, (await call(commands.indexStatus())).files))) + .filter((h) => h.relPath.split("/").pop() === name) + .map((h) => h.path) + : await call(commands.findFilesNamed(name)); + // A multi-module build compiles the same class in several modules; the run only has the + // one on its classpath, so its module's folder decides before the name does. + const build = useBuildModel.getState(); + return scopeToRunModule(found, build.root, module, build.model); +} + async function findByName(target: FileTarget, module?: string | null): Promise { const name = target.path.split("/").pop() ?? target.path; try { - const remote = useRemote.getState().session; - // Older remote servers only have fuzzy search: request the whole inventory before filtering. - const found = - remote && !remote.commands.includes("find_files_named") - ? (await call(commands.findFiles(name, (await call(commands.indexStatus())).files))) - .filter((h) => h.relPath.split("/").pop() === name) - .map((h) => h.path) - : await call(commands.findFilesNamed(name)); - // A multi-module build compiles the same class in several modules; the run only has the - // one on its classpath, so its module's folder decides before the name does. - const build = useBuildModel.getState(); - const hits = scopeToRunModule(found, build.root, module, build.model); + const hits = await indexedNamedPaths(name, module); const tail = target.path.replace(/^\.?\//, ""); const exact = hits.find((path) => path === tail || path.endsWith(`/${tail}`)); if (exact) return exact; @@ -68,6 +72,31 @@ async function findByName(target: FileTarget, module?: string | null): Promise { + const stem = dotted.replace(/\./g, "/"); + const relative = [`${stem}/__init__.py`, `${stem}.py`]; + const root = useProject.getState().project?.root; + const roots = root && root !== cwd ? [cwd, root] : [cwd]; + const direct = roots.flatMap((base) => relative.map((file) => joinPath(base, file))); + const present = await Promise.all(direct.map(exists)); + const first = present.indexOf(true); + if (first >= 0) return direct[first]!; + // src-layout packages may be below another source root; the indexed suffix must be unique. + try { + const matches = await Promise.all( + relative.map(async (file) => { + const paths = await indexedNamedPaths(file.split("/").pop()!, module); + return paths.filter((path) => path.endsWith(`/${file}`)); + }), + ); + const unique = [...new Set(matches.flat())]; + return unique.length === 1 ? unique[0]! : null; + } catch { + return null; + } +} + const TYPE_KINDS = new Set(["class", "interface", "enum", "struct", "trait"]); /** @@ -103,6 +132,7 @@ export async function resolveTarget( module?: string | null, container?: string | null, ): Promise { + if (target.resolve === "pythonModule") return findPythonModule(target.path, cwd, module); // An absolute path a container printed: the project folder it mounts or the copy of its // libraries. A file of this machine or of the same name elsewhere would be another file. if (container && target.resolve === "path" && target.path.startsWith("/")) { @@ -141,12 +171,12 @@ async function searchRuby(pattern: string, files?: string[]) { return out.sort((a, b) => a.relPath.localeCompare(b.relPath)); } -/** 1-based line declaring the JS test (or suite) with this describe chain and name. */ -export async function declarationLine(path: string, test: string[]): Promise { +/** 1-based declaration line of a test (or suite) identified by its name chain. */ +export async function declarationLine(path: string, test: string[], django = false): Promise { try { const { detectRunTargets } = await import("./targets"); const text = await call(commands.fsReadText(path)); - const found = detectRunTargets(text, path).find((t) => t.path.join("\u0000") === test.join("\u0000")); + const found = detectRunTargets(text, path, django).find((t) => t.path.join("\u0000") === test.join("\u0000")); return found ? found.line + 1 : undefined; } catch { return undefined; @@ -201,7 +231,9 @@ export async function openTarget( }); return; } - const line = target.line ?? (target.test ? await declarationLine(path, target.test) : undefined); + const line = + target.line ?? + (target.test ? await declarationLine(path, target.test, target.resolve === "pythonModule") : undefined); const selection = line ? { line: line - 1, col: Math.max(0, (target.col ?? 1) - 1) } : undefined; // The copy of a container's library opens read-only, like External Libraries. if (container) await openCodeLocation(path, selection, { focus }); diff --git a/src/features/run/testing/results.ts b/src/features/run/testing/results.ts index 78c257ec88..9408c21000 100644 --- a/src/features/run/testing/results.ts +++ b/src/features/run/testing/results.ts @@ -201,8 +201,12 @@ export class TestResults { } case "location": { const n = this.node(e.path); - // The first location wins, except that a place to search for (Ruby tests) gives way to a real one. - if (!n.location || (n.location.resolve === "rubyTest" && e.location.resolve !== "rubyTest")) + // A guessed declaration (Ruby or Django test) gives way to the real failure site. + if ( + !n.location || + (n.location.resolve === "rubyTest" && e.location.resolve !== "rubyTest") || + (n.location.resolve === "pythonModule" && e.location.resolve === "path") + ) n.location = e.location; break; } diff --git a/src/features/run/testing/types.ts b/src/features/run/testing/types.ts index 67994829a0..5af7480327 100644 --- a/src/features/run/testing/types.ts +++ b/src/features/run/testing/types.ts @@ -11,8 +11,8 @@ export interface TestLocation { /** 1-based, as printed. */ line?: number; col?: number; - /** `name`: a file name to look up in the project (JVM / Go frames); `rubyTest`: a test to search for (`rubyTests.ts`). */ - resolve: "path" | "name" | "rubyTest"; + /** `name`: a file name to look up in the project; `pythonModule` or `rubyTest`: a test without a reported file. */ + resolve: "path" | "name" | "rubyTest" | "pythonModule"; /** JVM frames: the class's binary name; `path` is then the file under its package directory. */ className?: string; /** No line: the describe chain and name of a JS test to find in the file (Cypress reports none). */ diff --git a/src/features/run/testing/unittest.test.ts b/src/features/run/testing/unittest.test.ts index 009639e4a6..3f315ea600 100644 --- a/src/features/run/testing/unittest.test.ts +++ b/src/features/run/testing/unittest.test.ts @@ -300,6 +300,36 @@ describe("unittest (Django) output", () => { expect(results.get([...Q, "test_subtests"].join("\0"))!.output).toContain("AssertionError: 1 == 1"); }); + it("locates passed and skipped Django tests by their full module and method", () => { + const { results } = tree(PY312); + for (const method of ["test_documented", "test_passes", "test_prints", "test_skipped", "test_expected_failure"]) { + expect(results.get([...Q, method].join("\0"))!.location).toEqual({ + path: "polls.tests", + resolve: "pythonModule", + test: ["QuestionModelTests", method], + }); + } + expect(results.get([...Q, "test_fails"].join("\0"))!.location).toEqual({ + path: "/e2e/proj/polls/tests.py", + line: 12, + resolve: "path", + }); + }); + + it("keeps the concrete traceback when a skipped subtest preceded a failure in the same method", () => { + const text = PY312.replace( + " test_subtests (polls.tests.QuestionModelTests.test_subtests) (i=1) ... FAIL", + " test_subtests (polls.tests.QuestionModelTests.test_subtests) (i=0) ... skipped 'not ready'\n" + + " test_subtests (polls.tests.QuestionModelTests.test_subtests) (i=1) ... FAIL", + ); + const { results } = tree(text); + expect(results.get([...Q, "test_subtests"].join("\0"))!.location).toEqual({ + path: "/e2e/proj/polls/tests.py", + line: 43, + resolve: "path", + }); + }); + it("reports failures of a run without -v 2 from their sections", () => { const { results, status } = tree(PY310_DOTS); expect(status(...Q, "test_fails")).toBe("failed"); diff --git a/src/features/run/testing/unittest.ts b/src/features/run/testing/unittest.ts index 510657d1d3..cc4658f72e 100644 --- a/src/features/run/testing/unittest.ts +++ b/src/features/run/testing/unittest.ts @@ -47,6 +47,19 @@ function testPath(name: string, dotted: string): string[] { return name === "setUpClass" || name === "tearDownClass" ? parts : [...parts, name]; } +/** A successful or skipped test has no traceback, but unittest reports its module and method. */ +function finished(path: string[], outcome: string): TestEvent[] { + const result = status(outcome); + const events: TestEvent[] = [{ type: "result", path, status: result }]; + if (path.length === 3 && result !== "failed") + events.push({ + type: "location", + path, + location: { path: path[0]!, resolve: "pythonModule", test: path.slice(1) }, + }); + return events; +} + export function unittestParser(): TestOutputParser { /** A test whose outcome hasn't been printed yet (output, a docstring or subtests came first). */ let pending: string[] | null = null; @@ -83,7 +96,7 @@ export function unittestParser(): TestOutputParser { const path = testPath(m[1]!, m[2]!); rest = after; if (outcome) { - events.push({ type: "result", path, status: status(outcome[1]!) }); + events.push(...finished(path, outcome[1]!)); pending = null; return true; } @@ -158,7 +171,7 @@ export function unittestParser(): TestOutputParser { if (pending) { const outcome = OUTCOME_RE.exec(line) ?? TRAILING_OUTCOME_RE.exec(line); if (outcome) { - events.push({ type: "result", path: pending, status: status(outcome[1]!) }); + events.push(...finished(pending, outcome[1]!)); pending = null; } }