diff --git a/src/features/run/ExportTestResultsDialog.test.tsx b/src/features/run/ExportTestResultsDialog.test.tsx new file mode 100644 index 000000000..5b6c65ced --- /dev/null +++ b/src/features/run/ExportTestResultsDialog.test.tsx @@ -0,0 +1,201 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { commands } from "@/platform/ipc"; +import { ExportTestResultsDialog, defaultExportPath, loadExportOptions } from "./ExportTestResultsDialog"; +import { TestResults } from "./testing"; + +const actions = vi.hoisted(() => ({ executeAction: vi.fn(async () => {}) })); +vi.mock("@/platform/actions", async (orig) => ({ ...(await orig()), executeAction: actions.executeAction })); +const notify = vi.hoisted(() => vi.fn()); +vi.mock("@/workbench/contributions", async (orig) => ({ + ...(await orig()), + notifications: () => ({ notify }), +})); +const messages = vi.hoisted(() => ({ confirm: vi.fn(async () => true) })); +vi.mock("@/workbench/messages", async (orig) => ({ ...(await orig()), confirm: messages.confirm })); +const dialog = vi.hoisted(() => ({ save: vi.fn(async (): Promise => null) })); +vi.mock("@/platform/dialog", () => dialog); + +const ok = { status: "ok", data: null } as const; +let onDisk: Record = {}; +let written: { path: string; text: string }[] = []; + +beforeEach(() => { + localStorage.clear(); + onDisk = {}; + written = []; + vi.spyOn(commands, "fsEntryKind").mockImplementation(async (path) => + onDisk[path] + ? { status: "ok", data: onDisk[path] } + : { status: "error", error: { kind: "NotFound", message: path } as never }, + ); + vi.spyOn(commands, "fsDelete").mockImplementation(async (path) => { + delete onDisk[path]; + return ok; + }); + vi.spyOn(commands, "fsOpenWithSystem").mockResolvedValue(ok); + vi.spyOn(commands, "fsCreateFileBytes").mockImplementation(async (path, data) => { + written.push({ path, text: new TextDecoder().decode(new Uint8Array(data)) }); + return ok; + }); +}); +afterEach(() => vi.restoreAllMocks()); + +function results() { + const r = new TestResults(); + r.apply([ + { type: "result", path: ["calc", "TestAdd"], status: "passed", durationMs: 3 }, + { type: "result", path: ["calc", "TestSub"], status: "failed", durationMs: 12 }, + ]); + r.finish(1); + return r; +} + +function open(onClose = vi.fn()) { + render(); + return onClose; +} + +const file = () => screen.getByLabelText("Output file"); +const press = (name: string) => fireEvent.click(screen.getByRole("button", { name })); + +describe("ExportTestResultsDialog", () => { + it("writes an HTML report to the project folder under IDEA's name and opens it in the browser", async () => { + const onClose = open(); + expect(file()).toHaveValue("/work/app/Test Results - go test _calc.html"); + expect(screen.getByRole("radio", { name: "HTML" })).toBeChecked(); + press("OK"); + await waitFor(() => expect(onClose).toHaveBeenCalled()); + expect(written).toHaveLength(1); + expect(written[0]!.path).toBe("/work/app/Test Results - go test _calc.html"); + expect(written[0]!.text).toContain("Test Results - go test ./calc"); + expect(commands.fsDelete).not.toHaveBeenCalled(); + expect(notify).toHaveBeenCalledWith(expect.objectContaining({ level: "info", body: written[0]!.path })); + expect(commands.fsOpenWithSystem).toHaveBeenCalledWith(written[0]!.path); + expect(actions.executeAction).not.toHaveBeenCalled(); + }); + + it("opens a report outside the project through the built-in server", async () => { + vi.mocked(commands.fsOpenWithSystem).mockResolvedValueOnce({ + status: "error", + error: { kind: "PermissionDenied", message: "outside the project" } as never, + }); + const onClose = open(); + fireEvent.change(file(), { target: { value: "/tmp/out.html" } }); + press("OK"); + await waitFor(() => + expect(actions.executeAction).toHaveBeenCalledWith("web.openInBrowser", { path: "/tmp/out.html" }), + ); + expect(onClose).toHaveBeenCalled(); + }); + + it("switches the extension with the format, keeps XML out of the browser, and remembers the choice", async () => { + const onClose = open(); + fireEvent.click(screen.getByRole("radio", { name: "XML" })); + expect(file()).toHaveValue("/work/app/Test Results - go test _calc.xml"); + // Only an HTML report opens in the browser. + expect(screen.getByRole("checkbox", { name: "Open exported file in browser" })).toBeDisabled(); + press("OK"); + await waitFor(() => expect(onClose).toHaveBeenCalled()); + expect(written[0]!.text).toMatch(/^<\?xml version="1.0" encoding="UTF-8"\?>\n { + const onClose = open(); + fireEvent.click(screen.getByRole("checkbox", { name: "Open exported file in browser" })); + press("OK"); + await waitFor(() => expect(onClose).toHaveBeenCalled()); + expect(written).toHaveLength(1); + expect(commands.fsOpenWithSystem).not.toHaveBeenCalled(); + expect(loadExportOptions().openInBrowser).toBe(false); + }); + + it("resolves a relative path against the working directory", async () => { + const onClose = open(); + fireEvent.change(file(), { target: { value: " reports/out.html " } }); + press("OK"); + await waitFor(() => expect(onClose).toHaveBeenCalled()); + expect(written[0]!.path).toBe("/work/app/reports/out.html"); + }); + + it("asks before replacing a file, and keeps it when the answer is no", async () => { + onDisk["/work/app/out.html"] = "file"; + messages.confirm.mockResolvedValueOnce(false); + const onClose = open(); + fireEvent.change(file(), { target: { value: "/work/app/out.html" } }); + press("OK"); + await waitFor(() => expect(messages.confirm).toHaveBeenCalledTimes(1)); + expect(messages.confirm).toHaveBeenCalledWith( + expect.objectContaining({ message: "File 'out.html' already exists. Do you want to overwrite it?" }), + ); + await waitFor(() => expect(screen.getByRole("button", { name: "OK" })).toBeEnabled()); + expect(written).toHaveLength(0); + expect(commands.fsDelete).not.toHaveBeenCalled(); + expect(onClose).not.toHaveBeenCalled(); + + messages.confirm.mockResolvedValueOnce(true); + press("OK"); + await waitFor(() => expect(onClose).toHaveBeenCalled()); + expect(commands.fsDelete).toHaveBeenCalledWith("/work/app/out.html"); + expect(written.map((w) => w.path)).toEqual(["/work/app/out.html"]); + }); + + it("doesn't ask again for a file the save dialog already confirmed", async () => { + onDisk["/tmp/picked.html"] = "file"; + dialog.save.mockResolvedValueOnce("/tmp/picked.html"); + const onClose = open(); + press("Browse…"); + await waitFor(() => expect(file()).toHaveValue("/tmp/picked.html")); + expect(dialog.save).toHaveBeenCalledWith( + expect.objectContaining({ filters: [{ name: "HTML", extensions: ["html"] }] }), + ); + press("OK"); + await waitFor(() => expect(onClose).toHaveBeenCalled()); + expect(messages.confirm).not.toHaveBeenCalled(); + expect(written.map((w) => w.path)).toEqual(["/tmp/picked.html"]); + }); + + it("reports a directory or a failed write and stays open", async () => { + onDisk["/work/app/reports"] = "dir"; + const onClose = open(); + fireEvent.change(file(), { target: { value: "/work/app/reports" } }); + press("OK"); + await waitFor(() => + expect(notify).toHaveBeenCalledWith( + expect.objectContaining({ level: "error", body: "/work/app/reports is a directory" }), + ), + ); + expect(written).toHaveLength(0); + + vi.mocked(commands.fsCreateFileBytes).mockResolvedValueOnce({ + status: "error", + error: { kind: "PermissionDenied", message: "permission denied" } as never, + }); + fireEvent.change(file(), { target: { value: "/ro/out.html" } }); + press("OK"); + await waitFor(() => expect(notify).toHaveBeenCalledTimes(2)); + expect(onClose).not.toHaveBeenCalled(); + expect(actions.executeAction).not.toHaveBeenCalled(); + }); + + it("can't export to an empty path", () => { + open(); + fireEvent.change(file(), { target: { value: " " } }); + expect(screen.getByRole("button", { name: "OK" })).toBeDisabled(); + }); +}); + +describe("defaultExportPath", () => { + it("replaces characters file systems refuse in the configuration's name", () => { + expect(defaultExportPath("C:\\proj\\", 'a/b\\c:d*e?f"gi|j', "xml")).toBe( + "C:\\proj/Test Results - a_b_c_d_e_f_g_h_i_j.xml", + ); + expect(defaultExportPath("/p", "go test ./...", "html")).toBe("/p/Test Results - go test.html"); + expect(defaultExportPath("/p", "Tests in 'com.acme.Cart'", "html")).toBe( + "/p/Test Results - Tests in 'com_acme_Cart'.html", + ); + expect(defaultExportPath("/p", "...", "html")).toBe("/p/Test Results - Tests.html"); + }); +}); diff --git a/src/features/run/ExportTestResultsDialog.tsx b/src/features/run/ExportTestResultsDialog.tsx new file mode 100644 index 000000000..34dab76cc --- /dev/null +++ b/src/features/run/ExportTestResultsDialog.tsx @@ -0,0 +1,202 @@ +/** + * IDEA's Export Test Results dialog: HTML or XML, the output file, and whether to + * open an HTML report in the browser once it is written. + */ +import { useState } from "react"; +import { executeAction } from "@/platform/actions"; +import { tx } from "@/platform/i18n"; +import { call, commands } from "@/platform/ipc"; +import { Checkbox, Dialog, IconButton, Input, Radio, T } from "@/ui"; +import { notifications } from "@/workbench/contributions"; +import { confirm } from "@/workbench/messages"; +import { exportTestResults, isAbsolutePath, type TestExportFormat } from "./testing/export"; +import type { TestResults } from "./testing"; +import styles from "./Run.module.css"; + +/** The format and "open in browser" choice, kept across exports (IDEA remembers them). */ +const OPTIONS_KEY = "openidea.run.testExport"; + +interface ExportOptions { + format: TestExportFormat; + openInBrowser: boolean; +} + +export function loadExportOptions(): ExportOptions { + try { + const v = JSON.parse(globalThis.localStorage?.getItem(OPTIONS_KEY) ?? "{}") as Partial; + return { format: v.format === "xml" ? "xml" : "html", openInBrowser: v.openInBrowser !== false }; + } catch { + return { format: "html", openInBrowser: true }; + } +} + +function saveExportOptions(o: ExportOptions) { + try { + globalThis.localStorage?.setItem(OPTIONS_KEY, JSON.stringify(o)); + } catch { + /* storage unavailable */ + } +} + +/** + * IDEA's default name, `Test Results - .html`. Like IDEA's `PathUtil.suggestFileName`, runs of + * dots and characters file systems refuse become one `_` (`go test ./...` gives `go test`). + */ +export function defaultExportPath(dir: string, name: string, format: TestExportFormat): string { + const safe = name.replace(/[/\\:*?"<>|.]+/g, "_").replace(/^[\s_]+|[\s_]+$/g, ""); + return `${dir.replace(/[\\/]+$/, "")}/Test Results - ${safe || "Tests"}.${format}`; +} + +async function exists(path: string): Promise<"file" | "dir" | null> { + try { + const kind = await call(commands.fsEntryKind(path)); + return kind === "dir" ? "dir" : "file"; + } catch { + return null; + } +} + +/** Writes the report; false when the user kept an existing file or the write failed. */ +export async function writeTestReport(path: string, text: string, confirmed: boolean): Promise { + const name = path.split(/[\\/]/).pop() ?? path; + try { + const kind = await exists(path); + if (kind === "dir") throw new Error(tx`${path} is a directory`); + if (kind === "file") { + if ( + !confirmed && + !(await confirm({ + title: "Export Test Results", + message: tx`File '${name}' already exists. Do you want to overwrite it?`, + ok: "Overwrite", + })) + ) + return false; + await call(commands.fsDelete(path)); + } + await call(commands.fsCreateFileBytes(path, Array.from(new TextEncoder().encode(text)))); + return true; + } catch (e) { + notifications().notify({ + group: "run", + level: "error", + title: "Cannot export test results", + body: e instanceof Error ? e.message : String(e), + key: "run-test-export", + }); + return false; + } +} + +/** + * Opens the report with the system's browser as a file, without saving open editors; a file outside the project + * (which that refuses) goes through the built-in server instead. + */ +async function openReport(path: string): Promise { + try { + await call(commands.fsOpenWithSystem(path)); + } catch { + await executeAction("web.openInBrowser", { path }); + } +} + +export function ExportTestResultsDialog({ + results, + name, + cwd, + onClose, +}: { + results: TestResults; + name: string; + cwd: string; + onClose: () => void; +}) { + const [options, setOptions] = useState(loadExportOptions); + const [path, setPath] = useState(() => defaultExportPath(cwd, name, options.format)); + // The save dialog already asked before replacing this file. + const [picked, setPicked] = useState(null); + const [busy, setBusy] = useState(false); + const html = options.format === "html"; + + const update = (next: Partial) => { + const merged = { ...options, ...next }; + setOptions(merged); + saveExportOptions(merged); + // The file follows the format's extension, as in the Export Data dialog. + if (next.format) setPath((p) => p.replace(/\.(html|xml)$/i, `.${next.format}`)); + }; + + const browse = async () => { + try { + const { save } = await import("@/platform/dialog"); + const chosen = await save({ + defaultPath: path, + filters: [{ name: html ? "HTML" : "XML", extensions: [options.format] }], + }); + if (chosen) { + setPath(chosen); + setPicked(chosen); + } + } catch { + // No dialog (tests): keep typing the path. + } + }; + + const run = async () => { + const raw = path.trim(); + if (!raw) return; + const target = isAbsolutePath(raw) ? raw : `${cwd.replace(/[\\/]+$/, "")}/${raw}`; + setBusy(true); + const text = exportTestResults(options.format, results, { name, cwd, date: new Date() }); + const ok = await writeTestReport(target, text, picked === raw); + setBusy(false); + if (!ok) return; + onClose(); + notifications().notify({ + group: "run", + level: "info", + title: "Test results exported", + body: target, + key: "run-test-export", + }); + if (html && options.openInBrowser) void openReport(target); + }; + + return ( + void run() }, + { label: "Cancel", role: "cancel" }, + ]} + > +
+
+ + Export format: + + update({ format: "html" })} /> + update({ format: "xml" })} /> +
+ + update({ openInBrowser: v })} + label="Open exported file in browser" + /> +
+
+ ); +} diff --git a/src/features/run/Run.module.css b/src/features/run/Run.module.css index e2d517975..42d540838 100644 --- a/src/features/run/Run.module.css +++ b/src/features/run/Run.module.css @@ -953,6 +953,17 @@ gap: var(--space-2); padding: 12px 16px; } +.exportFormats { + display: flex; + align-items: center; + gap: var(--space-4); +} +.exportField { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + align-items: center; + gap: var(--space-2); +} /* Folded console lines (""). */ .fold { diff --git a/src/features/run/RunView.tsx b/src/features/run/RunView.tsx index 503d29bd8..faade49bd 100644 --- a/src/features/run/RunView.tsx +++ b/src/features/run/RunView.tsx @@ -45,8 +45,8 @@ import { pinSession, } from "./store"; import { rerunFailedConfigs } from "./testing/rerun"; -import { nodeOutput } from "./testing"; -import { TestTreeView, formatDuration } from "./TestTreeView"; +import { formatDuration, nodeOutput } from "./testing"; +import { TestTreeView } from "./TestTreeView"; import { StackTracePanel, useStackTraces, type StackTraceTab } from "./stackTrace"; import { closeRunTab, runTabMenu } from "./runTabs"; import { showApplicationUpdate, useApplicationUpdates } from "./applicationUpdate"; @@ -280,6 +280,7 @@ export function SessionPanel({ version={version} cwd={cwd} running={running} + name={session.config.name} selected={selectedTest} onSelect={setSelectedTest} canRunTests={(ids) => canRunSelectedTests(session.id, ids)} diff --git a/src/features/run/TestTreeView.test.tsx b/src/features/run/TestTreeView.test.tsx index bd1a15200..da928cdaf 100644 --- a/src/features/run/TestTreeView.test.tsx +++ b/src/features/run/TestTreeView.test.tsx @@ -286,3 +286,49 @@ describe("Expand All / Collapse All", () => { expect(screen.getByRole("button", { name: "Collapse All" })).toBeDisabled(); }); }); + +describe("Export Test Results", () => { + function finished() { + const r = new TestResults(); + r.apply([{ type: "result", path: ["calc", "TestAdd"], status: "passed" }]); + r.finish(0); + return r; + } + const view = (results: TestResults, running: boolean) => ( + {}} + running={running} + /> + ); + + it("the button and the action open the dialog for the finished run", () => { + const { unmount } = render(view(finished(), false)); + fireEvent.click(screen.getByRole("button", { name: "Export Test Results…" })); + expect(screen.getByRole("dialog", { name: "Export Test Results" })).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Cancel" })); + act(() => testTree.exportResults!()); + expect(screen.getByRole("dialog", { name: "Export Test Results" })).toBeInTheDocument(); + expect(screen.getByLabelText("Output file")).toHaveValue("/p/Test Results - calc tests.html"); + fireEvent.click(screen.getByRole("button", { name: "Cancel" })); + expect(screen.queryByRole("dialog", { name: "Export Test Results" })).toBeNull(); + unmount(); + expect(testTree.exportResults).toBeNull(); + }); + + it("is unavailable while the tests run and without results", () => { + const { rerender } = render(view(finished(), true)); + expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeDisabled(); + expect(testTree.exportResults).toBeNull(); + rerender(view(new TestResults(), false)); + expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeDisabled(); + expect(testTree.exportResults).toBeNull(); + rerender(view(finished(), false)); + expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeEnabled(); + expect(testTree.exportResults).not.toBeNull(); + }); +}); diff --git a/src/features/run/TestTreeView.tsx b/src/features/run/TestTreeView.tsx index ee8fd3004..d8674964d 100644 --- a/src/features/run/TestTreeView.tsx +++ b/src/features/run/TestTreeView.tsx @@ -14,9 +14,10 @@ import { } from "@/ui"; import { useOccurrenceNavigator } from "@/workbench/contributions"; import { openTarget } from "./navigate"; -import { nodeStatus, type TestNode, type TestResults, type TestStatus } from "./testing"; +import { formatDuration, nodeDuration, nodeStatus, type TestNode, type TestResults, type TestStatus } from "./testing"; import { parseComparison } from "./testing/comparison"; import { TEST_TREE_FOCUS, testTree } from "./testTree"; +import { ExportTestResultsDialog } from "./ExportTestResultsDialog"; import styles from "./Run.module.css"; import { tx } from "@/platform/i18n"; @@ -59,28 +60,6 @@ export function showTestDiff(node: TestNode): boolean { return true; } -export function formatDuration(ms: number | undefined): string { - if (ms === undefined) return ""; - if (ms < 1000) return `${Math.round(ms)} ms`; - if (ms < 60_000) return `${(ms / 1000).toFixed(ms < 10_000 ? 2 : 1).replace(/\.?0+$/, "")} s`; - const m = Math.floor(ms / 60_000); - return `${m} m ${Math.round((ms % 60_000) / 1000)} s`; -} - -function totalDuration(node: TestNode): number | undefined { - if (node.durationMs !== undefined) return node.durationMs; - let sum = 0; - let any = false; - for (const c of node.children) { - const d = totalDuration(c); - if (d !== undefined) { - sum += d; - any = true; - } - } - return any ? sum : undefined; -} - export function StatusIcon({ status }: { status: TestStatus | null }) { switch (status) { case "passed": @@ -134,6 +113,8 @@ export interface TestTreeViewProps { selected: string | null; onSelect: (id: string | null) => void; running: boolean; + /** The run configuration's name (Export Test Results names the file after it). */ + name?: string; /** Run / Debug the selected tests (context menu); absent when the configuration can't be narrowed. */ onRunTests?: (ids: string[], debug: boolean) => void; canRunTests?: (ids: string[]) => boolean | Promise; @@ -146,6 +127,7 @@ export function TestTreeView({ selected, onSelect, running, + name = "Tests", onRunTests, canRunTests, }: TestTreeViewProps) { @@ -158,6 +140,7 @@ export function TestTreeView({ return next; }); const [expanded, setExpanded] = useState | null>(null); + const [exporting, setExporting] = useState(false); const [selection, setSelection] = useState>(new Set()); const tree = useRef(null); const selectedKeys = useMemo( @@ -240,13 +223,17 @@ export function TestTreeView({ return set; }, [expanded, roots]); + // Export Test Results waits for the run to finish. + const canExport = !running && !results.isEmpty; // Collapse All leaves the top-level suites in view, as IDEA's test tree does. useEffect(() => { testTree.expandAll = () => setExpanded(suiteIds(results.roots)); testTree.collapseAll = () => setExpanded(new Set()); + testTree.exportResults = canExport ? () => setExporting(true) : null; return () => { testTree.expandAll = null; testTree.collapseAll = null; + testTree.exportResults = null; }; }); const hasSuites = roots.some((n) => n.children.length > 0); @@ -317,7 +304,18 @@ export function TestTreeView({ title="Next Failed Test" disabled={!hasNextFailed} /> + setExporting(true)} + /> + {exporting && ( + setExporting(false)} /> + )} aria-label="Test results" className={styles.testTree} @@ -342,7 +340,7 @@ export function TestTreeView({ onContextMenu={contextMenu} renderNode={(n) => { const s = nodeStatus(n); - const d = totalDuration(n); + const d = nodeDuration(n); return ( diff --git a/src/features/run/index.ts b/src/features/run/index.ts index ac03c9060..0c2e17ce4 100644 --- a/src/features/run/index.ts +++ b/src/features/run/index.ts @@ -748,6 +748,17 @@ export function activate(): () => void { keyWhen: TEST_TREE_FOCUS, run: () => testTree.collapseAll?.(), }, + { + id: "run.exportTestResults", + title: "Export Test Results…", + description: "Save the test results as an HTML report or IDEA's XML", + category: "Run", + icon: "export", + when: "projectOpen && activeToolWindow == 'run'", + keywords: ["test", "results", "report", "html", "xml", "save"], + enabled: () => testTree.exportResults !== null, + run: () => testTree.exportResults?.(), + }, { id: "run.reloadConfigs", title: "Reload Run Configurations", diff --git a/src/features/run/testTree.ts b/src/features/run/testTree.ts index 3bd83b04f..0da868512 100644 --- a/src/features/run/testTree.ts +++ b/src/features/run/testTree.ts @@ -1,8 +1,14 @@ /** Context key: the test results tree has focus. */ export const TEST_TREE_FOCUS = "testTreeFocus"; -/** Set while a test results tree is shown: Expand All / Collapse All act on it. */ -export const testTree: { expandAll: (() => void) | null; collapseAll: (() => void) | null } = { +/** Set while a test results tree is shown: Expand All / Collapse All / Export Test Results act on it. */ +export const testTree: { + expandAll: (() => void) | null; + collapseAll: (() => void) | null; + /** Null while the run is in progress or has no results. */ + exportResults: (() => void) | null; +} = { expandAll: null, collapseAll: null, + exportResults: null, }; diff --git a/src/features/run/testing/export.test.ts b/src/features/run/testing/export.test.ts new file mode 100644 index 000000000..5cbe9a3fe --- /dev/null +++ b/src/features/run/testing/export.test.ts @@ -0,0 +1,152 @@ +// @vitest-environment node +import { describe, expect, it } from "vitest"; +import { exportTestResults, testResultsHtml, testResultsXml } from "./export"; +import { TestResults } from "./results"; + +const info = { name: "go test ./calc", cwd: "/work/app", date: new Date(2026, 10, 19, 5, 40) }; + +function results() { + const r = new TestResults(); + r.apply([ + { type: "result", path: ["calc", "TestAdd"], status: "passed", durationMs: 3 }, + { type: "result", path: ["calc", "TestSub"], status: "failed", durationMs: 12 }, + { type: "output", path: ["calc", "TestSub"], line: "expected: <1> but was: <2>" }, + { type: "location", path: ["calc", "TestSub"], location: { path: "calc/sub_test.go", line: 9, resolve: "path" } }, + { type: "result", path: ["calc", "TestDiv"], status: "skipped" }, + { type: "location", path: ["calc", "TestDiv"], location: { path: "div_test.go", line: 4, resolve: "name" } }, + ]); + r.finish(1); + return r; +} + +describe("testResultsXml", () => { + it("writes IDEA's testrun format: counts, suites, tests, statuses, durations, output and the diff", () => { + expect(testResultsXml(results(), info)).toBe( + [ + '', + ``, + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' expected: <1> but was: <2>', + " ", + // A file name to look up in the project is no location to link to. + ' ', + " ", + "", + "", + ].join("\n"), + ); + }); + + it("prefers the runner's total duration and keeps absolute and Windows locations as they are", () => { + const r = new TestResults(); + r.apply([ + { type: "result", path: ["A"], status: "passed" }, + { type: "location", path: ["A"], location: { path: "C:\\src\\a_test.go", line: 2, resolve: "path" } }, + { type: "result", path: ["B"], status: "passed" }, + { type: "location", path: ["B"], location: { path: "/abs/b_test.go", resolve: "path" } }, + { type: "summary", durationMs: 1500 }, + ]); + r.finish(0); + const xml = testResultsXml(r, info); + expect(xml).toContain(' { + const r = new TestResults(); + r.apply([ + { type: "result", path: ['Test "quotes" & '], status: "failed" }, + { type: "output", path: ['Test "quotes" & '], line: "bell\u0007 and \u001b[31mred" }, + { type: "output", path: ['Test "quotes" & '], line: 'expected: <"a\tb"> but was: ' }, + ]); + r.finish(1); + const xml = testResultsXml(r, { ...info, name: "it's " }); + expect(xml).toContain('name="it\'s <all>"'); + expect(xml).toContain(''); + expect(xml).toContain(''); + expect(xml).toContain("bell and [31mred</output>\nexpected:"); + for (const c of ["\u0000", "\u0007", "\u001b"]) expect(xml).not.toContain(c); + }); + + it("rounds durations to whole milliseconds", () => { + const r = new TestResults(); + r.apply([ + { type: "result", path: ["S", "a"], status: "passed", durationMs: 0.1 }, + { type: "result", path: ["S", "b"], status: "passed", durationMs: 1.2 }, + ]); + r.finish(0); + const xml = testResultsXml(r, info); + expect(xml).toContain(''); + expect(xml).toContain(''); + expect(xml).toContain(''); + }); + + it("writes an empty run, and marks tests the run never finished as terminated", () => { + expect(testResultsXml(new TestResults(), info)).toContain('\n'); + const r = new TestResults(); + r.apply([{ type: "start", path: ["Slow"] }]); + expect(testResultsXml(r, info)).toContain(''); + }); +}); + +describe("testResultsHtml", () => { + it("is a standalone page with the summary, the tree, failures' output and source locations", () => { + const html = testResultsHtml(results(), info); + expect(html.startsWith("")).toBe(true); + expect(html).toContain("Test Results - go test ./calc"); + expect(html).toContain( + '

3 tests · 1 passed · 1 failed · 1 ignored · 15 ms

', + ); + expect(html).toContain( + '
Failedcalc', + ); + expect(html).toContain( + 'TestSubsub_test.go:912 ms', + ); + expect(html).toContain("
expected: <1> but was: <2>
"); + expect(html).toContain( + '
IgnoredTestDivdiv_test.go:4
', + ); + // Nothing loads from outside the file. + expect(html).not.toMatch(/<(script|link)\b/); + }); + + it("escapes test names and output", () => { + const r = new TestResults(); + r.apply([ + { type: "result", path: [""], status: "failed" }, + { type: "output", path: [""], line: "" }, + ]); + r.finish(1); + const html = testResultsHtml(r, { ...info, name: "run" }); + expect(html).not.toContain("