e2e-reporting-summary.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. /* eslint-disable max-lines -- summary 聚合逻辑含 stability/timing/failureBreakdown 计算,拆分会扩大测试报告模块间耦合。 */
  2. import { appendFileSync, existsSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
  3. import { arch, cpus, platform, totalmem } from "node:os";
  4. import { resolve } from "node:path";
  5. import { createE2EReportViewerUrl } from "@zcode/e2e-report";
  6. import {
  7. BYTES_PER_KB,
  8. BYTES_PER_MB,
  9. numericStats,
  10. parseBytePair,
  11. parsePercent,
  12. } from "./e2e-reporting-stats.js";
  13. import type {
  14. E2ELifecycleEvent,
  15. E2ELifecycleSummary,
  16. FailureBreakdown,
  17. ProcessMetricSample,
  18. StabilityMetrics,
  19. TestResultLine,
  20. TimingMetrics,
  21. } from "./e2e-reporting-types.js";
  22. import { renderUICoverageMarkdownSection } from "./e2e-reporting-coverage.js";
  23. import type { UIRendererCoverageSummary } from "./e2e-ui-coverage.js";
  24. import type { E2ENodeCoverageSummary } from "./e2e-node-coverage.js";
  25. interface ContainerStatsLine {
  26. capturedAt?: string;
  27. stats?: {
  28. BlockIO?: string;
  29. CPUPerc?: string;
  30. MemPerc?: string;
  31. MemUsage?: string;
  32. Name?: string;
  33. NetIO?: string;
  34. PIDs?: string;
  35. };
  36. }
  37. interface WriteSummaryOptions {
  38. artifactDir: string;
  39. containerE2E: boolean;
  40. containerSamplesPath: string;
  41. coverageSummaryPath: string;
  42. exitCode: number;
  43. lifecycleEventsPath: string;
  44. manifestPath: string;
  45. perfDir: string;
  46. requestedSpecs: string[];
  47. runId: string;
  48. startedAt: Date;
  49. summaryJsonPath: string;
  50. summaryMdPath: string;
  51. testsPath: string;
  52. }
  53. export function appendJsonLine(path: string, value: unknown) {
  54. appendFileSync(path, `${JSON.stringify(value)}\n`, "utf-8");
  55. }
  56. export function writeJson(path: string, value: unknown) {
  57. writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, "utf-8");
  58. }
  59. export function normalizeSpecs(specs: string[]) {
  60. return specs.map((spec) => spec.replace(/\\/g, "/"));
  61. }
  62. export function sanitizeFilePart(value: string) {
  63. return value.replace(/[^a-zA-Z0-9_.-]+/g, "-").replace(/^-+|-+$/g, "") || "unknown";
  64. }
  65. export function formatRunId(date: Date) {
  66. const pad = (value: number, size = 2) => String(value).padStart(size, "0");
  67. return [
  68. "desktop-e2e",
  69. `${date.getUTCFullYear()}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}`,
  70. `${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}`,
  71. pad(date.getUTCMilliseconds(), 3),
  72. ].join("-");
  73. }
  74. function readNdjson<T>(path: string): T[] {
  75. if (!existsSync(path)) {
  76. return [];
  77. }
  78. return readFileSync(path, "utf-8")
  79. .split(/\r?\n/u)
  80. .map((line) => line.trim())
  81. .filter((line) => line.length > 0)
  82. .flatMap((line) => {
  83. try {
  84. return [JSON.parse(line) as T];
  85. } catch {
  86. return [];
  87. }
  88. });
  89. }
  90. function readJsonFile<T>(path: string): T | undefined {
  91. if (!existsSync(path)) {
  92. return undefined;
  93. }
  94. try {
  95. return JSON.parse(readFileSync(path, "utf-8")) as T;
  96. } catch {
  97. return undefined;
  98. }
  99. }
  100. function processSampleFiles(perfDir: string) {
  101. if (!existsSync(perfDir)) {
  102. return [];
  103. }
  104. return readdirSync(perfDir)
  105. .filter((name) => name.startsWith("process-samples-") && name.endsWith(".ndjson"))
  106. .map((name) => resolve(perfDir, name))
  107. .sort();
  108. }
  109. function summarizeProcessSamples(perfDir: string) {
  110. const files = processSampleFiles(perfDir);
  111. const samples = files.flatMap((file) => readNdjson<ProcessMetricSample>(file));
  112. if (samples.length === 0) {
  113. return undefined;
  114. }
  115. const cpuTotals = samples.map((sample) =>
  116. sample.metrics.reduce((total, metric) => total + metric.cpuPercent, 0),
  117. );
  118. const memoryTotalsMb = samples.map(
  119. (sample) =>
  120. sample.metrics.reduce((total, metric) => total + metric.memoryWorkingSetKb, 0) / BYTES_PER_KB,
  121. );
  122. const byTypeValues = new Map<string, { cpu: number[]; memoryMb: number[] }>();
  123. for (const sample of samples) {
  124. const sampleTypes = new Map<string, { cpu: number; memoryKb: number }>();
  125. for (const metric of sample.metrics) {
  126. const type = metric.type || "unknown";
  127. const current = sampleTypes.get(type) ?? { cpu: 0, memoryKb: 0 };
  128. current.cpu += metric.cpuPercent;
  129. current.memoryKb += metric.memoryWorkingSetKb;
  130. sampleTypes.set(type, current);
  131. }
  132. for (const [type, value] of sampleTypes) {
  133. const bucket = byTypeValues.get(type) ?? { cpu: [], memoryMb: [] };
  134. bucket.cpu.push(value.cpu);
  135. bucket.memoryMb.push(value.memoryKb / BYTES_PER_KB);
  136. byTypeValues.set(type, bucket);
  137. }
  138. }
  139. return {
  140. byType: Object.fromEntries(
  141. [...byTypeValues.entries()].map(([type, value]) => [
  142. type,
  143. {
  144. cpuPercent: numericStats(value.cpu),
  145. memoryWorkingSetMb: numericStats(value.memoryMb),
  146. },
  147. ]),
  148. ),
  149. cpuTotalPercent: numericStats(cpuTotals),
  150. files,
  151. memoryWorkingSetMb: numericStats(memoryTotalsMb),
  152. sampleCount: samples.length,
  153. };
  154. }
  155. function summarizeContainerSamples(containerSamplesPath: string) {
  156. const samples = readNdjson<ContainerStatsLine>(containerSamplesPath);
  157. if (samples.length === 0) {
  158. return undefined;
  159. }
  160. const statsRows = samples.map((sample) => sample.stats ?? {});
  161. const memPairs = statsRows.map((stats) => parseBytePair(stats.MemUsage));
  162. const netPairs = statsRows.map((stats) => parseBytePair(stats.NetIO));
  163. const blockPairs = statsRows.map((stats) => parseBytePair(stats.BlockIO));
  164. return {
  165. blockReadMb: numericStats(blockPairs.map((pair) => pair.left / BYTES_PER_MB)),
  166. blockWriteMb: numericStats(blockPairs.map((pair) => pair.right / BYTES_PER_MB)),
  167. cpuPercent: numericStats(statsRows.map((stats) => parsePercent(stats.CPUPerc))),
  168. file: containerSamplesPath,
  169. memoryPercent: numericStats(statsRows.map((stats) => parsePercent(stats.MemPerc))),
  170. memoryUsageMb: numericStats(memPairs.map((pair) => pair.left / BYTES_PER_MB)),
  171. networkRxMb: numericStats(netPairs.map((pair) => pair.left / BYTES_PER_MB)),
  172. networkTxMb: numericStats(netPairs.map((pair) => pair.right / BYTES_PER_MB)),
  173. pids: numericStats(
  174. statsRows.map((stats) => {
  175. const value = Number(stats.PIDs ?? 0);
  176. return Number.isFinite(value) ? value : 0;
  177. }),
  178. ),
  179. sampleCount: samples.length,
  180. };
  181. }
  182. function summarizeLifecycleEvents(lifecycleEventsPath: string): E2ELifecycleSummary {
  183. const events = readNdjson<E2ELifecycleEvent>(lifecycleEventsPath);
  184. const byPhase = new Map<string, number[]>();
  185. for (const event of events) {
  186. const durations = byPhase.get(event.phase) ?? [];
  187. durations.push(event.durationMs);
  188. byPhase.set(event.phase, durations);
  189. }
  190. return {
  191. byPhase: Object.fromEntries(
  192. [...byPhase.entries()].map(([phase, durations]) => {
  193. const sorted = durations.filter(Number.isFinite).sort((a, b) => a - b);
  194. const p50Index = Math.max(0, Math.ceil(sorted.length * 0.5) - 1);
  195. const p95Index = Math.max(0, Math.ceil(sorted.length * 0.95) - 1);
  196. return [
  197. phase,
  198. {
  199. count: sorted.length,
  200. p50Ms: sorted[p50Index] ?? 0,
  201. p95Ms: sorted[p95Index] ?? 0,
  202. totalMs: sorted.reduce((total, value) => total + value, 0),
  203. },
  204. ];
  205. }),
  206. ),
  207. };
  208. }
  209. function renderTestRows(results: TestResultLine[]) {
  210. if (results.length === 0) {
  211. return ["| n/a | 0ms | no test results were recorded |"];
  212. }
  213. return results.map(
  214. (test) =>
  215. `| ${test.passed ? "PASS" : isSkippedResult(test) ? "SKIP" : "FAIL"} | ${test.durationMs}ms | ${test.fullTitle.replace(/\|/g, "\\|")} |`,
  216. );
  217. }
  218. function renderSummaryMarkdown(summary: ReturnType<typeof buildSummaryPayload>) {
  219. const processSamples = summary.performance.processSamples;
  220. const containerSamples = summary.performance.containerSamples;
  221. const lifecyclePhases = Object.entries(summary.lifecycle.byPhase);
  222. const lines = [
  223. "# Desktop E2E Report",
  224. "",
  225. `- Run ID: \`${summary.runId}\``,
  226. `- Exit code: \`${summary.exitCode}\``,
  227. `- Duration: \`${summary.durationMs}ms\``,
  228. `- Container: \`${summary.containerE2E ? "yes" : "no"}\``,
  229. `- Artifact dir: \`${summary.artifactDir}\``,
  230. "",
  231. "## Stability",
  232. "",
  233. `- Pass rate: \`${(summary.stability.passRate * 100).toFixed(1)}%\``,
  234. `- First-time pass rate: \`${(summary.stability.firstTimePassRate * 100).toFixed(1)}%\``,
  235. `- Flaky: \`${summary.stability.flakyCount}\` cases (\`${(summary.stability.flakyRate * 100).toFixed(1)}%\`)`,
  236. `- Infra failures: \`${summary.stability.infraFailureCount}\` (\`${(summary.stability.infraFailureRate * 100).toFixed(1)}%\`)`,
  237. "",
  238. "## Timing",
  239. "",
  240. `- Total duration: \`${summary.timing.totalDurationMs}ms\``,
  241. ...(summary.timing.queueTimeMs != null
  242. ? [`- Queue time: \`${summary.timing.queueTimeMs}ms\``]
  243. : []),
  244. `- Case duration P50: \`${summary.timing.caseDurationP50Ms}ms\``,
  245. `- Case duration P95: \`${summary.timing.caseDurationP95Ms}ms\``,
  246. "",
  247. "## Lifecycle",
  248. "",
  249. ...(lifecyclePhases.length > 0
  250. ? lifecyclePhases.map(
  251. ([phase, stats]) =>
  252. `- ${phase}: \`${stats.count}\` runs, total \`${stats.totalMs}ms\`, p50 \`${stats.p50Ms}ms\`, p95 \`${stats.p95Ms}ms\``,
  253. )
  254. : ["- No lifecycle events were recorded."]),
  255. "",
  256. "### Slowest Cases",
  257. "",
  258. "| Duration | Test |",
  259. "| ---: | --- |",
  260. ...summary.timing.slowestCases.map(
  261. (c) => `| ${c.durationMs}ms | ${c.fullTitle.replace(/\|/g, "\\|")} |`,
  262. ),
  263. "",
  264. "## Failure Breakdown",
  265. "",
  266. `- Assertion: \`${summary.failureBreakdown.assertion}\``,
  267. `- Timeout: \`${summary.failureBreakdown.timeout}\``,
  268. `- Crash: \`${summary.failureBreakdown.crash}\``,
  269. `- Infra: \`${summary.failureBreakdown.infra}\``,
  270. `- Unknown: \`${summary.failureBreakdown.unknown}\``,
  271. "",
  272. "## Specs",
  273. "",
  274. ...(summary.requestedSpecs.length > 0
  275. ? summary.requestedSpecs.map((spec) => `- \`${spec}\``)
  276. : ["- all configured desktop e2e specs"]),
  277. "",
  278. "## Tests",
  279. "",
  280. `- Total: \`${summary.tests.total}\``,
  281. `- Passed: \`${summary.tests.passed}\``,
  282. `- Failed: \`${summary.tests.failed}\``,
  283. `- Skipped: \`${summary.tests.skipped}\``,
  284. "",
  285. "| Status | Duration | Test |",
  286. "| --- | ---: | --- |",
  287. ...renderTestRows(summary.tests.results),
  288. "",
  289. "## Performance",
  290. "",
  291. "### Electron Processes",
  292. "",
  293. ];
  294. if (processSamples) {
  295. lines.push(
  296. `- Samples: \`${processSamples.sampleCount}\``,
  297. `- CPU total mean / p95 / peak: \`${processSamples.cpuTotalPercent.mean}%\` / \`${processSamples.cpuTotalPercent.p95}%\` / \`${processSamples.cpuTotalPercent.peak}%\``,
  298. `- Memory working set mean / p95 / peak: \`${processSamples.memoryWorkingSetMb.mean}MB\` / \`${processSamples.memoryWorkingSetMb.p95}MB\` / \`${processSamples.memoryWorkingSetMb.peak}MB\``,
  299. "",
  300. "| Type | CPU Mean | CPU P95 | Memory Mean | Memory Peak |",
  301. "| --- | ---: | ---: | ---: | ---: |",
  302. ...Object.entries(processSamples.byType).map(
  303. ([type, stats]) =>
  304. `| ${type} | ${stats.cpuPercent.mean}% | ${stats.cpuPercent.p95}% | ${stats.memoryWorkingSetMb.mean}MB | ${stats.memoryWorkingSetMb.peak}MB |`,
  305. ),
  306. "",
  307. );
  308. } else {
  309. lines.push("- No process samples were collected.", "");
  310. }
  311. if (containerSamples) {
  312. lines.push(
  313. "### Container",
  314. "",
  315. `- Samples: \`${containerSamples.sampleCount}\``,
  316. `- CPU mean / p95 / peak: \`${containerSamples.cpuPercent.mean}%\` / \`${containerSamples.cpuPercent.p95}%\` / \`${containerSamples.cpuPercent.peak}%\``,
  317. `- Memory mean / p95 / peak: \`${containerSamples.memoryUsageMb.mean}MB\` / \`${containerSamples.memoryUsageMb.p95}MB\` / \`${containerSamples.memoryUsageMb.peak}MB\``,
  318. `- Network RX/TX peak: \`${containerSamples.networkRxMb.peak}MB\` / \`${containerSamples.networkTxMb.peak}MB\``,
  319. `- Block read/write peak: \`${containerSamples.blockReadMb.peak}MB\` / \`${containerSamples.blockWriteMb.peak}MB\``,
  320. "",
  321. );
  322. }
  323. if (summary.coverage.uiRenderer) {
  324. lines.push(...renderUICoverageMarkdownSection(summary.coverage.uiRenderer));
  325. }
  326. if (summary.coverage.node) {
  327. lines.push("## Runtime Coverage", "");
  328. for (const domain of ["main", "host", "cli"] as const) {
  329. const coverage = summary.coverage.node.domains[domain];
  330. const linesTotal = coverage.totals?.lines;
  331. lines.push(
  332. `- ${domain}: \`${formatCoverageMetric(linesTotal)}\`, raw \`${coverage.rawFileCount}\`, missing processes \`${coverage.missingRawProcessCount}\`, pre-entry zero \`${coverage.preEntryProcessCount ?? 0}\`, sources \`${coverage.sourceFileCount}\`, complete \`${coverage.complete ? "yes" : "no"}\``,
  333. );
  334. }
  335. lines.push("");
  336. }
  337. lines.push(
  338. "## Files",
  339. "",
  340. `- Manifest: \`${summary.files.manifest}\``,
  341. `- Test results: \`${summary.files.tests}\``,
  342. `- Viewer URL: \`${summary.files.viewerUrl}\``,
  343. `- Summary JSON: \`${summary.files.summaryJson}\``,
  344. ...(summary.files.coverageSummary
  345. ? [`- Coverage summary: \`${summary.files.coverageSummary}\``]
  346. : []),
  347. ...(summary.files.coverageHeatmap
  348. ? [`- Coverage heatmap: \`${summary.files.coverageHeatmap}\``]
  349. : []),
  350. ...(summary.files.uiRendererCoverage
  351. ? [`- UI renderer coverage: \`${summary.files.uiRendererCoverage}\``]
  352. : []),
  353. `- Process samples: \`${summary.files.processSamplesGlob}\``,
  354. `- Container samples: \`${summary.files.containerSamples}\``,
  355. "",
  356. );
  357. return `${lines.join("\n")}\n`;
  358. }
  359. function computeStabilityMetrics(results: TestResultLine[]): StabilityMetrics {
  360. const countedResults = results.filter((result) => !isSkippedResult(result));
  361. const total = countedResults.length;
  362. if (total === 0) {
  363. return {
  364. passRate: 0,
  365. firstTimePassRate: 0,
  366. flakyCount: 0,
  367. flakyRate: 0,
  368. infraFailureCount: 0,
  369. infraFailureRate: 0,
  370. };
  371. }
  372. const passed = countedResults.filter((r) => r.passed).length;
  373. const firstTimePassed = countedResults.filter((r) => r.passed && !r.passedOnRetry).length;
  374. const flaky = countedResults.filter((r) => r.passedOnRetry).length;
  375. const infraFailures = countedResults.filter(
  376. (r) => !r.passed && r.errorCategory === "infra",
  377. ).length;
  378. return {
  379. passRate: round(passed / total, 4),
  380. firstTimePassRate: round(firstTimePassed / total, 4),
  381. flakyCount: flaky,
  382. flakyRate: round(flaky / total, 4),
  383. infraFailureCount: infraFailures,
  384. infraFailureRate: round(infraFailures / total, 4),
  385. };
  386. }
  387. function computeTimingMetrics(
  388. results: TestResultLine[],
  389. totalDurationMs: number,
  390. queueTimeMs: number | undefined,
  391. ): TimingMetrics {
  392. const countedResults = results.filter((result) => !isSkippedResult(result));
  393. const durations = countedResults
  394. .map((r) => r.durationMs)
  395. .filter((d) => Number.isFinite(d))
  396. .sort((a, b) => a - b);
  397. const p50Index = Math.max(0, Math.ceil(durations.length * 0.5) - 1);
  398. const p95Index = Math.max(0, Math.ceil(durations.length * 0.95) - 1);
  399. const slowestCases = [...countedResults]
  400. .sort((a, b) => b.durationMs - a.durationMs)
  401. .slice(0, 10)
  402. .map((r) => ({ fullTitle: r.fullTitle, durationMs: r.durationMs }));
  403. return {
  404. totalDurationMs,
  405. queueTimeMs,
  406. caseDurationP50Ms: durations[p50Index] ?? 0,
  407. caseDurationP95Ms: durations[p95Index] ?? 0,
  408. slowestCases,
  409. };
  410. }
  411. function computeFailureBreakdown(results: TestResultLine[]): FailureBreakdown {
  412. const failed = results.filter((r) => !r.passed && !isSkippedResult(r));
  413. return {
  414. assertion: failed.filter((r) => r.errorCategory === "assertion").length,
  415. timeout: failed.filter((r) => r.errorCategory === "timeout").length,
  416. crash: failed.filter((r) => r.errorCategory === "crash").length,
  417. infra: failed.filter((r) => r.errorCategory === "infra").length,
  418. unknown: failed.filter((r) => !r.errorCategory || r.errorCategory === "unknown").length,
  419. };
  420. }
  421. function isSkippedResult(
  422. result: Pick<TestResultLine, "error" | "errorCategory" | "errorStack" | "passed" | "status">,
  423. ): boolean {
  424. const status = result.status?.toLowerCase();
  425. // 修复原因:Mocha this.skip() 在 WDIO 结果里 passed=false,但 status=skipped/pending;
  426. // 只按 !passed 聚合会把 Windows 平台跳过的 case 错计为失败。
  427. if (status === "skipped" || status === "pending") {
  428. return true;
  429. }
  430. // 兼容旧报告:历史 test-results 没有写 status,skipped 只留下 passed=false 且没有错误内容。
  431. return (
  432. !result.passed &&
  433. !status &&
  434. !result.error &&
  435. !result.errorStack &&
  436. (!result.errorCategory || result.errorCategory === "unknown")
  437. );
  438. }
  439. function computeQueueTimeMs(): number | undefined {
  440. const startedAt = process.env.CI_JOB_STARTED_AT;
  441. const createdAt = process.env.CI_PIPELINE_CREATED_AT;
  442. if (!startedAt || !createdAt) return undefined;
  443. const diff = new Date(startedAt).getTime() - new Date(createdAt).getTime();
  444. return Number.isFinite(diff) && diff >= 0 ? diff : undefined;
  445. }
  446. function round(value: number, digits = 2) {
  447. if (!Number.isFinite(value)) return 0;
  448. const scale = 10 ** digits;
  449. return Math.round(value * scale) / scale;
  450. }
  451. function formatCoverageMetric(
  452. metric: { covered: number; pct: number | string; total: number } | undefined,
  453. ) {
  454. if (!metric) return "n/a";
  455. return `${metric.pct}% (${metric.covered}/${metric.total})`;
  456. }
  457. function buildSummaryPayload(options: WriteSummaryOptions) {
  458. const completedAt = new Date();
  459. const testResults = readNdjson<TestResultLine>(options.testsPath);
  460. const uiRendererCoveragePath = resolve(options.artifactDir, "coverage/ui-renderer-summary.json");
  461. const uiRendererCoverage = readJsonFile<UIRendererCoverageSummary>(uiRendererCoveragePath);
  462. const coverageHeatmapPath = resolve(options.artifactDir, "coverage/heatmap/index.html");
  463. const nodeCoverage = readJsonFile<{ node?: E2ENodeCoverageSummary }>(
  464. options.coverageSummaryPath,
  465. )?.node;
  466. const viewerUrl = createE2EReportViewerUrl({
  467. summaryJsonPath: options.summaryJsonPath,
  468. });
  469. const totalDurationMs = completedAt.getTime() - options.startedAt.getTime();
  470. const queueTimeMs = computeQueueTimeMs();
  471. const skippedResults = testResults.filter(isSkippedResult);
  472. const countedResults = testResults.filter((result) => !isSkippedResult(result));
  473. return {
  474. artifactDir: options.artifactDir,
  475. completedAt: completedAt.toISOString(),
  476. containerE2E: options.containerE2E,
  477. durationMs: totalDurationMs,
  478. environment: {
  479. arch: arch(),
  480. cpuModel: cpus()[0]?.model ?? "unknown",
  481. node: process.version,
  482. platform: platform(),
  483. totalMemoryBytes: totalmem(),
  484. },
  485. exitCode: options.exitCode,
  486. files: {
  487. containerSamples: options.containerSamplesPath,
  488. coverageHeatmap: existsSync(coverageHeatmapPath)
  489. ? coverageHeatmapPath
  490. : undefined,
  491. coverageSummary: existsSync(options.coverageSummaryPath)
  492. ? options.coverageSummaryPath
  493. : undefined,
  494. lifecycleEvents: options.lifecycleEventsPath,
  495. manifest: options.manifestPath,
  496. processSamplesGlob: resolve(options.perfDir, "process-samples-*.ndjson"),
  497. summaryJson: options.summaryJsonPath,
  498. summaryMd: options.summaryMdPath,
  499. tests: options.testsPath,
  500. uiRendererCoverage: uiRendererCoverage ? uiRendererCoveragePath : undefined,
  501. viewerUrl,
  502. },
  503. coverage: {
  504. node: nodeCoverage,
  505. uiRenderer: uiRendererCoverage,
  506. },
  507. performance: {
  508. containerSamples: summarizeContainerSamples(options.containerSamplesPath),
  509. processSamples: summarizeProcessSamples(options.perfDir),
  510. },
  511. lifecycle: summarizeLifecycleEvents(options.lifecycleEventsPath),
  512. stability: computeStabilityMetrics(testResults),
  513. timing: computeTimingMetrics(testResults, totalDurationMs, queueTimeMs),
  514. failureBreakdown: computeFailureBreakdown(testResults),
  515. requestedSpecs: options.requestedSpecs,
  516. runId: options.runId,
  517. startedAt: options.startedAt.toISOString(),
  518. tests: {
  519. failed: countedResults.filter((result) => !result.passed).length,
  520. passed: countedResults.filter((result) => result.passed).length,
  521. results: testResults,
  522. skipped: skippedResults.length,
  523. total: testResults.length,
  524. },
  525. };
  526. }
  527. export function writeE2ESummary(options: WriteSummaryOptions) {
  528. const summary = buildSummaryPayload(options);
  529. writeJson(options.summaryJsonPath, summary);
  530. writeFileSync(options.summaryMdPath, renderSummaryMarkdown(summary), "utf-8");
  531. console.info(`[desktop-e2e-report] summary: ${options.summaryMdPath}`);
  532. console.info(`[desktop-e2e-report] viewer: ${summary.files.viewerUrl}`);
  533. }