feat(run): Export Test Results to HTML or XML from the test results toolbar (#4413)

The test results toolbar and Find Action get Export Test Results…: a dialog with HTML or XML format, the output file (default "<working directory>/Test Results - <configuration>.html") and an option to open the HTML report in the browser. HTML is a self-contained report (summary, suites, per-test status, duration, output and location, no scripts); XML uses the <testrun> format with count, suite, test, output and expected/actual diff. An existing file is replaced only after confirmation. Both entry points are disabled while tests run and when there are no results.

Closes #4412

Co-authored-by: mansur-akhmadi <10739460+mansur-akhmadi@users.noreply.github.com>
This commit is contained in:
Mansur Akhmadi
2026-11-19 17:57:29 +08:00
committed by GitHub
co-authored by mansur-akhmadi
parent 8edab7b8e6
commit 77503e5fee
15 changed files with 937 additions and 32 deletions
@@ -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<object>()), executeAction: actions.executeAction }));
const notify = vi.hoisted(() => vi.fn());
vi.mock("@/workbench/contributions", async (orig) => ({
...(await orig<typeof import("@/workbench/contributions")>()),
notifications: () => ({ notify }),
}));
const messages = vi.hoisted(() => ({ confirm: vi.fn(async () => true) }));
vi.mock("@/workbench/messages", async (orig) => ({ ...(await orig<object>()), confirm: messages.confirm }));
const dialog = vi.hoisted(() => ({ save: vi.fn(async (): Promise<string | null> => null) }));
vi.mock("@/platform/dialog", () => dialog);
const ok = { status: "ok", data: null } as const;
let onDisk: Record<string, "file" | "dir"> = {};
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(<ExportTestResultsDialog results={results()} name="go test ./calc" cwd="/work/app/" onClose={onClose} />);
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("<title>Test Results - go test ./calc</title>");
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<testrun /);
expect(commands.fsOpenWithSystem).not.toHaveBeenCalled();
expect(loadExportOptions()).toEqual({ format: "xml", openInBrowser: true });
});
it("doesn't open the browser when unticked", async () => {
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"g<h>i|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");
});
});
@@ -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<ExportOptions>;
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 - <configuration>.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<boolean> {
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<void> {
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<string | null>(null);
const [busy, setBusy] = useState(false);
const html = options.format === "html";
const update = (next: Partial<ExportOptions>) => {
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 (
<Dialog
open
title="Export Test Results"
onClose={onClose}
width={520}
buttons={[
{ label: "OK", role: "default", disabled: busy || !path.trim(), onClick: () => void run() },
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.dialogBody}>
<div className={styles.exportFormats} role="radiogroup" aria-label="Export format">
<span>
<T>Export format:</T>
</span>
<Radio name="test-export-format" label="HTML" checked={html} onChange={() => update({ format: "html" })} />
<Radio name="test-export-format" label="XML" checked={!html} onChange={() => update({ format: "xml" })} />
</div>
<label className={styles.exportField}>
<span>
<T>Output file:</T>
</span>
<div className={styles.inputWithButton}>
<Input mono aria-label="Output file" value={path} onChange={(e) => setPath(e.target.value)} />
<IconButton icon="folder" title="Browse…" onClick={() => void browse()} />
</div>
</label>
<Checkbox
checked={html && options.openInBrowser}
disabled={!html}
onChange={(v) => update({ openInBrowser: v })}
label="Open exported file in browser"
/>
</div>
</Dialog>
);
}
+11
View File
@@ -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 ("<N internal lines>"). */
.fold {
+3 -2
View File
@@ -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)}
+46
View File
@@ -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) => (
<TestTreeView
results={results}
version={1}
cwd="/p"
name="calc tests"
selected={null}
onSelect={() => {}}
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();
});
});
+22 -24
View File
@@ -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<boolean>;
@@ -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<Set<string> | null>(null);
const [exporting, setExporting] = useState(false);
const [selection, setSelection] = useState<Set<string>>(new Set());
const tree = useRef<TreeHandle>(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}
/>
<IconButton
icon="export"
size="small"
iconSize={16}
title="Export Test Results…"
disabled={!canExport}
onClick={() => setExporting(true)}
/>
</div>
{exporting && (
<ExportTestResultsDialog results={results} name={name} cwd={cwd} onClose={() => setExporting(false)} />
)}
<Tree<TestNode>
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 (
<span className={styles.testRow}>
<StatusIcon status={s} />
+11
View File
@@ -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",
+8 -2
View File
@@ -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,
};
+152
View File
@@ -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(
[
'<?xml version="1.0" encoding="UTF-8"?>',
`<testrun duration="15" footerText="Generated by OpenIDEA on ${info.date.toLocaleString()}" name="go test ./calc">`,
' <count name="total" value="3"/>',
' <count name="passed" value="1"/>',
' <count name="failed" value="1"/>',
' <count name="ignored" value="1"/>',
' <suite name="calc" status="failed" duration="15">',
' <test name="TestAdd" status="passed" duration="3"/>',
' <test locationUrl="file:///work/app/calc/sub_test.go:9" name="TestSub" status="failed" duration="12">',
' <diff actual="2" expected="1"/>',
' <output type="stdout">expected: &lt;1&gt; but was: &lt;2&gt;</output>',
" </test>",
// A file name to look up in the project is no location to link to.
' <test name="TestDiv" status="ignored"/>',
" </suite>",
"</testrun>",
"",
].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('<testrun duration="1500"');
expect(xml).toContain('locationUrl="file://C:/src/a_test.go:2"');
expect(xml).toContain('locationUrl="file:///abs/b_test.go"');
});
it("escapes markup, quotes and line breaks, and drops characters XML can't hold", () => {
const r = new TestResults();
r.apply([
{ type: "result", path: ['Test "quotes" & <tags>'], status: "failed" },
{ type: "output", path: ['Test "quotes" & <tags>'], line: "bell\u0007 and \u001b[31mred</output>" },
{ type: "output", path: ['Test "quotes" & <tags>'], line: 'expected: <"a\tb"> but was: <x & y>' },
]);
r.finish(1);
const xml = testResultsXml(r, { ...info, name: "it's <all>" });
expect(xml).toContain('name="it\'s &lt;all&gt;"');
expect(xml).toContain('<test name="Test &quot;quotes&quot; &amp; &lt;tags&gt;" status="failed">');
expect(xml).toContain('<diff actual="x &amp; y" expected="&quot;a&#9;b&quot;"/>');
expect(xml).toContain("bell and [31mred&lt;/output&gt;\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('<suite name="S" status="passed" duration="1">');
expect(xml).toContain('<test name="a" status="passed" duration="0"/>');
expect(xml).toContain('<test name="b" status="passed" duration="1"/>');
});
it("writes an empty run, and marks tests the run never finished as terminated", () => {
expect(testResultsXml(new TestResults(), info)).toContain('<count name="total" value="0"/>\n</testrun>');
const r = new TestResults();
r.apply([{ type: "start", path: ["Slow"] }]);
expect(testResultsXml(r, info)).toContain('<test name="Slow" status="terminated"/>');
});
});
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("<!DOCTYPE html>")).toBe(true);
expect(html).toContain("<title>Test Results - go test ./calc</title>");
expect(html).toContain(
'<p class="summary"><b>3</b> tests · <b>1</b> passed · <b>1</b> failed · <b>1</b> ignored · 15 ms</p>',
);
expect(html).toContain(
'<details open class="failed"><summary><span class="status">Failed</span><span class="name">calc</span>',
);
expect(html).toContain(
'<span class="name">TestSub</span><span class="location">sub_test.go:9</span><span class="duration">12 ms</span>',
);
expect(html).toContain("<pre>expected: &lt;1&gt; but was: &lt;2&gt;</pre>");
expect(html).toContain(
'<div class="test ignored"><span class="status">Ignored</span><span class="name">TestDiv</span><span class="location">div_test.go:4</span></div>',
);
// 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: ["<script>alert(1)</script>"], status: "failed" },
{ type: "output", path: ["<script>alert(1)</script>"], line: "<img src=x onerror=alert(1)>" },
]);
r.finish(1);
const html = testResultsHtml(r, { ...info, name: "<b>run</b>" });
expect(html).not.toContain("<script>alert");
expect(html).not.toContain("<img");
expect(html).toContain("<title>Test Results - &lt;b&gt;run&lt;/b&gt;</title>");
expect(html).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
});
it("leaves out ignored and duration from the summary when there are none", () => {
const r = new TestResults();
r.apply([{ type: "result", path: ["A"], status: "passed" }]);
r.finish(0);
expect(testResultsHtml(r, info)).toContain(
'<p class="summary"><b>1</b> tests · <b>1</b> passed · <b>0</b> failed</p>',
);
});
});
describe("exportTestResults", () => {
it("picks the writer by format", () => {
const r = results();
expect(exportTestResults("html", r, info)).toBe(testResultsHtml(r, info));
expect(exportTestResults("xml", r, info)).toBe(testResultsXml(r, info));
});
});
+231
View File
@@ -0,0 +1,231 @@
/**
* IDEA's Export Test Results: the results tree as a self-contained HTML report,
* or as XML in IDEA's `<testrun>` format (counts, suites, tests, output, diff).
*/
import { parseComparison } from "./comparison";
import { nodeDuration, nodeStatus, type TestNode, type TestResults } from "./results";
import { formatDuration } from "./types";
export type TestExportFormat = "html" | "xml";
export interface TestExportInfo {
/** The run configuration's name. */
name: string;
/** Working directory: relative test locations are resolved against it. */
cwd: string;
date: Date;
}
/** Status words as IDEA writes them (`skipped` tests are `ignored`). */
function statusOf(node: TestNode): "passed" | "failed" | "ignored" | "terminated" | "skipped" {
switch (nodeStatus(node)) {
case "passed":
return "passed";
case "failed":
return "failed";
case "skipped":
return "ignored";
case "running":
return "terminated";
default:
return "skipped";
}
}
function totalDuration(results: TestResults): number | undefined {
if (results.summary.durationMs !== undefined) return results.summary.durationMs;
let sum: number | undefined;
for (const r of results.roots) {
const d = nodeDuration(r);
if (d !== undefined) sum = (sum ?? 0) + d;
}
return sum;
}
export const isAbsolutePath = (path: string) => /^([a-zA-Z]:)?[\\/]/.test(path);
/** IDEA's `file://<path>:<line>` location of a test; only for locations that name a real path. */
function locationUrl(node: TestNode, cwd: string): string | undefined {
const loc = node.location;
if (!loc || loc.resolve !== "path") return undefined;
const abs = isAbsolutePath(loc.path) ? loc.path : `${cwd.replace(/[\\/]+$/, "")}/${loc.path}`;
return `file://${abs.replace(/\\/g, "/")}${loc.line !== undefined ? `:${loc.line}` : ""}`;
}
/** Where a test is, as the report shows it: `sub_test.go:9`. */
function locationText(node: TestNode): string | undefined {
const loc = node.location;
if (!loc) return undefined;
const file = loc.path.split(/[\\/]/).pop() ?? loc.path;
return loc.line !== undefined ? `${file}:${loc.line}` : file;
}
/** IDEA's importer reads durations as whole milliseconds. */
const ms = (d: number | undefined) => (d === undefined ? undefined : Math.round(d));
// XML 1.0 can't hold most control characters even escaped; test output may contain them.
// eslint-disable-next-line no-control-regex
const XML_INVALID = /[\u0000-\u0008\u000B\u000C\u000E-\u001F￾￿]/g;
function escapeXml(s: string): string {
return s
.replace(XML_INVALID, "")
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/\n/g, "&#10;")
.replace(/\r/g, "&#13;")
.replace(/\t/g, "&#9;");
}
/** Text content: line breaks stay as they are. */
const escapeText = (s: string) =>
s.replace(XML_INVALID, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
function attrs(values: Record<string, string | number | undefined>): string {
return Object.entries(values)
.filter(([, v]) => v !== undefined)
.map(([k, v]) => ` ${k}="${escapeXml(String(v))}"`)
.join("");
}
function counts(results: TestResults) {
const c = results.counts();
return { total: c.total, passed: c.passed, failed: c.failed, ignored: c.skipped };
}
/** IDEA's export XML (`TestResultsXmlFormatter`): the same tags, so IDEA's Import Tests from File can read it. */
export function testResultsXml(results: TestResults, info: TestExportInfo): string {
const out = ['<?xml version="1.0" encoding="UTF-8"?>'];
out.push(
`<testrun${attrs({
duration: ms(totalDuration(results)),
footerText: `Generated by OpenIDEA on ${info.date.toLocaleString()}`,
name: info.name,
})}>`,
);
for (const [name, value] of Object.entries(counts(results)))
if (value > 0 || name === "total") out.push(` <count${attrs({ name, value })}/>`);
const visit = (node: TestNode, depth: number) => {
const pad = " ".repeat(depth);
const tag = node.children.length > 0 ? "suite" : "test";
const head = `${pad}<${tag}${attrs({
locationUrl: locationUrl(node, info.cwd),
name: node.name,
status: statusOf(node),
duration: ms(nodeDuration(node)),
})}`;
const comparison = tag === "test" && nodeStatus(node) === "failed" ? parseComparison(node.output) : null;
if (node.children.length === 0 && node.output.length === 0 && !comparison) {
out.push(`${head}/>`);
return;
}
out.push(`${head}>`);
if (comparison) out.push(`${pad} <diff${attrs({ actual: comparison.actual, expected: comparison.expected })}/>`);
if (node.output.length > 0)
out.push(`${pad} <output type="stdout">${escapeText(node.output.join("\n"))}</output>`);
for (const c of node.children) visit(c, depth + 1);
out.push(`${pad}</${tag}>`);
};
for (const r of results.roots) visit(r, 1);
out.push("</testrun>", "");
return out.join("\n");
}
const STYLE = `
:root { color-scheme: light dark; --fg: #1f2328; --muted: #6a737d; --bg: #ffffff; --line: #d8dee4;
--passed: #1a7f37; --failed: #cf222e; --ignored: #9a6700; --code: #f6f8fa; }
@media (prefers-color-scheme: dark) { :root { --fg: #dfe1e5; --muted: #8c9199; --bg: #1e1f22; --line: #393b40;
--passed: #5fb865; --failed: #f75464; --ignored: #c9a23f; --code: #2b2d30; } }
body { margin: 24px; background: var(--bg); color: var(--fg); font: 13px/1.5 -apple-system, "Segoe UI", sans-serif; }
h1 { font-size: 18px; margin: 0 0 4px; }
.summary { margin: 0 0 16px; color: var(--muted); }
.summary b { color: var(--fg); }
ul { list-style: none; margin: 0; padding-left: 20px; }
body > ul { padding-left: 0; }
summary, .test { display: flex; gap: 8px; align-items: baseline; padding: 1px 0; }
summary { cursor: pointer; list-style: none; }
summary::-webkit-details-marker { display: none; }
summary::before { content: "\\25B8"; width: 10px; color: var(--muted); }
details[open] > summary::before { content: "\\25BE"; }
.test::before { content: ""; width: 10px; }
.status { font-weight: 600; min-width: 64px; }
.passed > .status, .passed > summary > .status { color: var(--passed); }
.failed > .status, .failed > summary > .status { color: var(--failed); }
.ignored > .status, .ignored > summary > .status, .skipped > .status, .terminated > .status { color: var(--ignored); }
.location, .duration { color: var(--muted); }
.duration { margin-left: auto; padding-left: 16px; }
pre { margin: 4px 0 8px 18px; padding: 8px; background: var(--code); border: 1px solid var(--line); border-radius: 4px;
overflow: auto; font: 12px/1.45 ui-monospace, Menlo, Consolas, monospace; white-space: pre-wrap; }
footer { margin-top: 24px; color: var(--muted); font-size: 12px; }
`;
const STATUS_TEXT = {
passed: "Passed",
failed: "Failed",
ignored: "Ignored",
terminated: "Terminated",
skipped: "Skipped",
};
/** A report that opens in any browser: summary, then the tree with each test's status, duration and output. */
export function testResultsHtml(results: TestResults, info: TestExportInfo): string {
const c = counts(results);
const total = totalDuration(results);
const title = `Test Results - ${info.name}`;
const parts = [`<b>${c.total}</b> tests`, `<b>${c.passed}</b> passed`, `<b>${c.failed}</b> failed`];
if (c.ignored > 0) parts.push(`<b>${c.ignored}</b> ignored`);
if (total !== undefined) parts.push(escapeText(formatDuration(total)));
const out = [
"<!DOCTYPE html>",
'<html lang="en">',
"<head>",
'<meta charset="utf-8">',
'<meta name="viewport" content="width=device-width, initial-scale=1">',
`<title>${escapeText(title)}</title>`,
`<style>${STYLE}</style>`,
"</head>",
"<body>",
`<h1>${escapeText(title)}</h1>`,
`<p class="summary">${parts.join(" · ")}</p>`,
];
const row = (node: TestNode, status: keyof typeof STATUS_TEXT) => {
const d = nodeDuration(node);
const where = locationText(node);
return [
`<span class="status">${STATUS_TEXT[status]}</span>`,
`<span class="name">${escapeText(node.name)}</span>`,
where ? `<span class="location">${escapeText(where)}</span>` : "",
d !== undefined ? `<span class="duration">${escapeText(formatDuration(d))}</span>` : "",
].join("");
};
const visit = (nodes: readonly TestNode[]) => {
out.push("<ul>");
for (const n of nodes) {
const status = statusOf(n);
const output = n.output.length > 0 ? `<pre>${escapeText(n.output.join("\n"))}</pre>` : "";
if (n.children.length === 0) {
out.push(`<li><div class="test ${status}">${row(n, status)}</div>${output}</li>`);
continue;
}
// Suites start open; a click on one folds it.
out.push(`<li><details open class="${status}"><summary>${row(n, status)}</summary>${output}`);
visit(n.children);
out.push("</details></li>");
}
out.push("</ul>");
};
visit(results.roots);
out.push(
`<footer>Generated by OpenIDEA on ${escapeText(info.date.toLocaleString())}</footer>`,
"</body>",
"</html>",
"",
);
return out.join("\n");
}
export function exportTestResults(format: TestExportFormat, results: TestResults, info: TestExportInfo): string {
return format === "html" ? testResultsHtml(results, info) : testResultsXml(results, info);
}
+2 -2
View File
@@ -12,8 +12,8 @@ import { zigParser } from "./zig";
import type { TestEvent, TestOutputParser } from "./types";
export type { TestEvent, TestOutputParser, TestStatus } from "./types";
export { parseDuration } from "./types";
export { TestResults, nodeOutput, nodeStatus, type TestNode } from "./results";
export { formatDuration, parseDuration } from "./types";
export { TestResults, nodeDuration, nodeOutput, nodeStatus, type TestNode } from "./results";
export {
cargoParser,
goParser,
+15
View File
@@ -19,6 +19,21 @@ export function nodeOutput(node: TestNode): string[] {
return [...node.output, ...node.children.flatMap(nodeOutput)];
}
/** A test's duration, or the sum of its children's for a group. */
export function nodeDuration(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 = nodeDuration(c);
if (d !== undefined) {
sum += d;
any = true;
}
}
return any ? sum : undefined;
}
export interface TestCounts {
passed: number;
failed: number;
+9
View File
@@ -43,6 +43,15 @@ export function parseDuration(text: string | undefined): number | undefined {
return matched ? Math.round(total * 1000) / 1000 : undefined;
}
/** Formats a duration the way the test tree shows it: `850 ms`, `1.25 s`, `2 m 5 s`. */
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`;
}
/**
* 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.
+12 -1
View File
@@ -2635,5 +2635,16 @@
"Selected branches are up-to-date": "Selected branches are up-to-date",
"Use application title as tab name": "Use application title as tab name",
"When command is running": "When command is running",
"Horizontal Scrolling": "Horizontal Scrolling"
"Horizontal Scrolling": "Horizontal Scrolling",
"Export Test Results…": "Export Test Results…",
"Save the test results as an HTML report or IDEA's XML": "Save the test results as an HTML report or IDEA's XML",
"Export Test Results": "Export Test Results",
"Export format:": "Export format:",
"HTML": "HTML",
"XML": "XML",
"Open exported file in browser": "Open exported file in browser",
"File '{name}' already exists. Do you want to overwrite it?": "File '{name}' already exists. Do you want to overwrite it?",
"{path} is a directory": "{path} is a directory",
"Cannot export test results": "Cannot export test results",
"Test results exported": "Test results exported"
}
+12 -1
View File
@@ -9014,5 +9014,16 @@
"Selected branches are up-to-date": "所选分支都是最新的",
"Use application title as tab name": "使用应用标题作为标签页名称",
"When command is running": "命令运行时",
"Horizontal Scrolling": "横向滚动"
"Horizontal Scrolling": "横向滚动",
"Export Test Results…": "导出测试结果…",
"Save the test results as an HTML report or IDEA's XML": "将测试结果保存为 HTML 报告或 IDEA 的 XML",
"Export Test Results": "导出测试结果",
"Export format:": "导出格式:",
"HTML": "HTML",
"XML": "XML",
"Open exported file in browser": "在浏览器中打开导出的文件",
"File '{name}' already exists. Do you want to overwrite it?": "文件 '{name}' 已存在。是否覆盖?",
"{path} is a directory": "{path} 是目录",
"Cannot export test results": "无法导出测试结果",
"Test results exported": "测试结果已导出"
}