/** * IDEA's Export Test Results: the results tree as a self-contained HTML report, * or as XML in IDEA's `` 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://:` 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, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/\n/g, " ") .replace(/\r/g, " ") .replace(/\t/g, " "); } /** Text content: line breaks stay as they are. */ const escapeText = (s: string) => s.replace(XML_INVALID, "").replace(/&/g, "&").replace(//g, ">"); function attrs(values: Record): 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 = ['']; out.push( ``, ); for (const [name, value] of Object.entries(counts(results))) if (value > 0 || name === "total") out.push(` `); 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} `); if (node.output.length > 0) out.push(`${pad} ${escapeText(node.output.join("\n"))}`); for (const c of node.children) visit(c, depth + 1); out.push(`${pad}`); }; for (const r of results.roots) visit(r, 1); out.push("", ""); 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 = [`${c.total} tests`, `${c.passed} passed`, `${c.failed} failed`]; if (c.ignored > 0) parts.push(`${c.ignored} ignored`); if (total !== undefined) parts.push(escapeText(formatDuration(total))); const out = [ "", '', "", '', '', `${escapeText(title)}`, ``, "", "", `

${escapeText(title)}

`, `

${parts.join(" · ")}

`, ]; const row = (node: TestNode, status: keyof typeof STATUS_TEXT) => { const d = nodeDuration(node); const where = locationText(node); return [ `${STATUS_TEXT[status]}`, `${escapeText(node.name)}`, where ? `${escapeText(where)}` : "", d !== undefined ? `${escapeText(formatDuration(d))}` : "", ].join(""); }; const visit = (nodes: readonly TestNode[]) => { out.push(""); }; visit(results.roots); out.push( ``, "", "", "", ); return out.join("\n"); } export function exportTestResults(format: TestExportFormat, results: TestResults, info: TestExportInfo): string { return format === "html" ? testResultsHtml(results, info) : testResultsXml(results, info); }