Файли
openidea/src/features/run/testing/export.ts
T
Mansur Akhmadiтаmansur-akhmadi 77503e5fee 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 <[email protected]>
2026-11-19 17:57:29 +08:00

232 рядки
9.2 KiB
TypeScript

/**
* 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);
}