Public Beta
Not set

Experience

Changes how pages explain things, never what you can do.

More

Experience

Changes how pages explain things, never what you can do.

Sign inGet started

Test Report Analyst v0.1.2 · generic

Archive SHA-256 fba54e81797c6ddd3ec2a06040e9ec6a873d453b25506d5d5076e01979293da3 · 66.2 KB · built Dec 1, 2026

src/parsers.js

// Readers for test result formats: JUnit XML, TAP (13/14, node:test style subtests), Jest / Vitest
// JSON reporter output, and lcov coverage. All input is untrusted data: text is only parsed,
// trimmed and returned, never executed or followed.
import { ToolError } from "./errors.js";
import { parseXml } from "./xml.js";

const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
export const cleanText = (s) => String(s ?? "").replace(ANSI, "").replace(/\r\n?/g, "\n");

function num(v) {
  if (v === undefined || v === null || v === "") return null;
  const x = typeof v === "number" ? v : Number(String(v).trim().replace(/,(?=\d{3}(\D|$))/g, ""));
  return Number.isFinite(x) && x >= 0 ? x : null;
}
const ms = (seconds) => (seconds === null ? null : Math.round(seconds * 1000 * 1000) / 1000);

function makeCase(c) {
  return {
    suite: c.suite || "(no suite)",
    name: c.name || "(unnamed test)",
    classname: c.classname || null,
    file: c.file || null,
    status: c.status,
    duration_ms: c.duration_ms === null || c.duration_ms === undefined ? null : Math.round(c.duration_ms * 1000) / 1000,
    message: c.message ? cleanText(c.message).trim() : null,
    retried: !!c.retried,
  };
}

// ---------------------------------------------------------------------------------------------
// Detection
// ---------------------------------------------------------------------------------------------
export function detectFormat(path, text) {
  const lower = (path ?? "").toLowerCase();
  if (lower.endsWith(".xml")) return "junit";
  if (lower.endsWith(".tap")) return "tap";
  if (lower.endsWith(".info") || lower.endsWith(".lcov") || /(^|\/)lcov[^/]*$/.test(lower)) return "lcov";
  const head = text.slice(0, 4000).replace(/^/, "").trimStart();
  if (head.startsWith("<")) return "junit";
  if (head.startsWith("{")) return "jest";
  if (/^(TN:|SF:)/m.test(head)) return "lcov";
  if (/^(TAP version \d+|1\.\.\d+|(not )?ok\b)/m.test(head)) return "tap";
  if (lower.endsWith(".json")) return "jest";
  return null;
}

// ---------------------------------------------------------------------------------------------
// JUnit XML (Surefire, pytest, Jest/Vitest junit reporters, go-junit-report, PHPUnit nested suites)
// ---------------------------------------------------------------------------------------------
export function parseJunit(text, { field, tick } = {}) {
  const { root, unknownEntities } = parseXml(text, { field, tick });
  const warnings = [];
  if (unknownEntities) warnings.push(`${field}: ${unknownEntities} unknown entity reference(s) were kept as literal text (entities are never expanded).`);
  if (root.name !== "testsuites" && root.name !== "testsuite") throw new ToolError("invalid_input", `${field}: the root element is <${root.name.slice(0, 40)}>, not <testsuites> or <testsuite>; this does not look like a JUnit report.`);
  const cases = [];
  let declared = 0;
  let declaredSuites = 0;
  let suiteCases = 0;
  const caseOf = (tc, suiteName, suiteFile) => {
    const byName = (n) => tc.children.find((c) => c.name === n);
    const failure = byName("failure");
    const error = byName("error");
    const skipped = byName("skipped");
    const rerun = tc.children.filter((c) => /^(flaky|rerun)(Failure|Error)$/.test(c.name));
    const problem = failure ?? error;
    const message = problem ? [problem.attrs.message, problem.attrs.type && !String(problem.attrs.message ?? "").includes(problem.attrs.type) ? `(${problem.attrs.type})` : null, problem.text].filter((x) => x && String(x).trim()).join("\n") : skipped ? skipped.attrs.message || skipped.text || null : null;
    return makeCase({
      suite: suiteName,
      name: tc.attrs.name,
      classname: tc.attrs.classname,
      file: tc.attrs.file || suiteFile || null,
      status: failure ? "failed" : error ? "error" : skipped ? "skipped" : "passed",
      duration_ms: ms(num(tc.attrs.time)),
      message,
      retried: rerun.length > 0,
    });
  };
  // Every <testcase>, wherever it is: inside the nearest <testsuite>, or directly under <testsuites>
  // (node:test writes top-level tests that way).
  const walk = (el, suite) => {
    const isSuite = el.name === "testsuite";
    const here = isSuite ? { name: el.attrs.name || el.attrs.file || "(unnamed suite)", file: el.attrs.file ?? suite?.file } : suite;
    if (isSuite && !el.children.some((c) => c.name === "testsuite")) {
      const t = num(el.attrs.tests);
      if (t !== null) {
        declared += t;
        declaredSuites++;
      }
    }
    for (const c of el.children) {
      if (c.name === "testcase") {
        cases.push(caseOf(c, here ? here.name : "(top level)", here?.file));
        if (isSuite) suiteCases++;
      } else if (c.name === "testsuite" || c.name === "testsuites") walk(c, here);
    }
  };
  walk(root, null);
  if (declaredSuites && declared !== suiteCases) warnings.push(`${field}: the suites declare ${declared} tests but ${suiteCases} test cases are present in them; counts below use the test cases.`);
  return { cases, warnings };
}

// ---------------------------------------------------------------------------------------------
// TAP
// ---------------------------------------------------------------------------------------------
function parsePoint(line) {
  const t = line.trimStart();
  const notOk = t.startsWith("not ok");
  if (!notOk && !(t.startsWith("ok") && (t.length === 2 || /\s/.test(t[2])))) return null;
  let rest = t.slice(notOk ? 6 : 2).trimStart();
  const numM = /^\d+/.exec(rest);
  if (numM) rest = rest.slice(numM[0].length).trimStart();
  if (rest.startsWith("-")) rest = rest.slice(1).trimStart();
  let directive = null;
  let reason = null;
  const hash = rest.search(/\s#\s|^#\s/);
  if (hash >= 0) {
    const d = rest.slice(hash).replace(/^\s*#\s*/, "");
    const dm = /^(skip|todo)\S*\s*(.*)$/i.exec(d);
    if (dm) {
      directive = dm[1].toLowerCase();
      reason = dm[2] || null;
      rest = rest.slice(0, hash);
    }
  }
  return { ok: !notOk, num: numM ? Number(numM[0]) : null, name: rest.trim().replace(/\\#/g, "#"), directive, reason, indent: line.length - t.length };
}

export function parseTap(text, { field, fileLabel } = {}) {
  const lines = cleanText(text).split("\n");
  const warnings = [];
  const done = []; // finished cases
  const pending = []; // nested cases waiting for their parent's summary line
  let plan = null;
  let bail = null;
  let last = null; // last point (for YAML diagnostics), test or parent
  let points = 0;
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const t = line.trim();
    if (!t) continue;
    const indent = line.length - line.trimStart().length;
    if (/^Bail out!/i.test(t)) {
      bail = t.slice(9).trim() || "no reason given";
      continue;
    }
    if (indent === 0 && /^1\.\.\d+/.test(t)) {
      plan = Number(/^1\.\.(\d+)/.exec(t)[1]);
      continue;
    }
    if (t === "---" && last) {
      // YAML diagnostics: duration_ms and message/error are read; other lines become message text for failures.
      const block = [];
      let k = i + 1;
      for (; k < lines.length && lines[k].trim() !== "..."; k++) block.push(lines[k]);
      i = k;
      const msg = [];
      for (const b of block) {
        const kv = /^\s*([A-Za-z_]+)\s*:\s*(.*)$/.exec(b);
        if (kv && kv[1] === "duration_ms") last.duration_ms = num(kv[2].replace(/^["']|["']$/g, ""));
        else if (kv && (kv[1] === "message" || kv[1] === "error")) msg.unshift(kv[2].replace(/^["'|>-]+\s*|["']\s*$/g, ""));
        else if (last.status === "failed" && b.trim() && !(kv && ["failureType", "code", "name", "location", "type", "exitCode", "signal"].includes(kv[1]))) msg.push(kv && /^[|>][-+]?$/.test(kv[2].trim()) ? `${kv[1]}:` : b.trim());
      }
      if (last.status === "failed" && msg.some(Boolean)) last.message = msg.filter(Boolean).join("\n");
      continue;
    }
    const p = parsePoint(line);
    if (!p) continue;
    points++;
    const status = p.directive === "skip" ? "skipped" : p.directive === "todo" ? "todo" : p.ok ? "passed" : "failed";
    // A point whose deeper points came just before it is a subtest summary (node:test style): it names
    // the suite of those points and is not counted as a test itself.
    const children = pending.filter((c) => c.indent > indent && (c.claimed === undefined || c.claimed > indent));
    if (children.length) {
      for (const c of children) {
        c.path.unshift(p.name);
        c.claimed = indent;
      }
      last = { status, duration_ms: null, message: null }; // diagnostics of the summary are not kept
      if (indent === 0) for (const c of pending.splice(0)) done.push(c);
      continue;
    }
    last = { indent, path: [], name: p.name, status, duration_ms: null, message: p.directive ? p.reason : null };
    if (indent === 0) done.push(last);
    else pending.push(last);
  }
  done.push(...pending.splice(0));
  if (bail) warnings.push(`${field}: the run bailed out ("${bail.slice(0, 200)}"); later tests did not run.`);
  const topLevel = done.filter((c) => c.indent === 0).length + new Set(done.filter((c) => c.indent > 0).map((c) => c.path[0])).size;
  if (plan !== null && plan !== topLevel && !bail) warnings.push(`${field}: the plan says 1..${plan} but ${topLevel} top-level test points were found.`);
  if (!points) throw new ToolError("invalid_input", `${field}: no TAP test points ("ok" / "not ok" lines) were found.`);
  return { cases: done.map((c) => makeCase({ suite: c.path.length ? c.path.join(" > ") : "(top level)", name: c.name, file: fileLabel, status: c.status, duration_ms: c.duration_ms, message: c.message })), warnings, incomplete: !!bail };
}

// ---------------------------------------------------------------------------------------------
// Jest / Vitest JSON reporter
// ---------------------------------------------------------------------------------------------
export function parseJestJson(text, { field } = {}) {
  let doc;
  try {
    doc = JSON.parse(text);
  } catch (e) {
    throw new ToolError("invalid_input", `${field}: not valid JSON (${String(e.message).slice(0, 120)}).`);
  }
  if (!doc || typeof doc !== "object" || !Array.isArray(doc.testResults)) throw new ToolError("invalid_input", `${field}: no testResults array; this does not look like Jest or Vitest JSON reporter output (use --json / --reporter=json).`);
  const cases = [];
  const warnings = [];
  const statusOf = (s) => (s === "passed" ? "passed" : s === "failed" ? "failed" : s === "todo" ? "todo" : ["pending", "skipped", "disabled", "focused"].includes(s) ? "skipped" : "error");
  for (const r of doc.testResults.slice(0, 100_000)) {
    if (!r || typeof r !== "object") continue;
    const file = typeof r.name === "string" ? r.name : typeof r.testFilePath === "string" ? r.testFilePath : null;
    const list = Array.isArray(r.assertionResults) ? r.assertionResults : Array.isArray(r.testResults) ? r.testResults : [];
    if (!list.length && (r.status === "failed" || r.failureMessage || r.message)) {
      cases.push(makeCase({ suite: file, file, name: "(test file failed to run)", status: "error", message: r.failureMessage || r.message || "The test file failed before any test ran." }));
      continue;
    }
    for (const a of list) {
      if (!a || typeof a !== "object") continue;
      const anc = Array.isArray(a.ancestorTitles) ? a.ancestorTitles.filter((x) => typeof x === "string" && x) : [];
      const title = typeof a.title === "string" ? a.title : typeof a.fullName === "string" ? a.fullName : "";
      const name = [...anc, title].join(" > ");
      const msgs = Array.isArray(a.failureMessages) ? a.failureMessages.filter((m) => typeof m === "string") : [];
      cases.push(makeCase({
        suite: file,
        file,
        name,
        status: statusOf(a.status),
        duration_ms: num(a.duration),
        message: msgs.join("\n") || null,
        retried: Array.isArray(a.retryReasons) && a.retryReasons.length > 0 && a.status === "passed",
      }));
    }
  }
  if (typeof doc.numTotalTests === "number" && doc.numTotalTests !== cases.filter((c) => c.name !== "(test file failed to run)").length) warnings.push(`${field}: the report says numTotalTests ${doc.numTotalTests} but ${cases.length} results are present.`);
  return { cases, warnings };
}

// ---------------------------------------------------------------------------------------------
// lcov
// ---------------------------------------------------------------------------------------------
export function parseLcov(text, { field, tick } = {}) {
  const files = new Map();
  let cur = null;
  const warnings = [];
  let badLines = 0;
  const lines = text.split(/\r?\n/);
  for (let i = 0; i < lines.length; i++) {
    if (i % 50000 === 0) tick?.();
    const l = lines[i].trim();
    if (!l) continue;
    if (l.startsWith("SF:")) {
      const path = l.slice(3).trim();
      cur = files.get(path);
      if (!cur) files.set(path, (cur = { path, lines: new Map(), fns: new Map(), branches: new Map(), lf: null, lh: null }));
      continue;
    }
    if (l === "end_of_record") {
      cur = null;
      continue;
    }
    if (!cur) continue;
    const [tag, val = ""] = [l.slice(0, l.indexOf(":")), l.slice(l.indexOf(":") + 1)];
    if (tag === "DA") {
      const [ln, cnt] = val.split(",");
      const n = Number(ln);
      const c = Number(cnt);
      if (!Number.isInteger(n) || n < 1 || !Number.isFinite(c)) {
        badLines++;
        continue;
      }
      cur.lines.set(n, Math.max(cur.lines.get(n) ?? 0, c));
    } else if (tag === "FNDA") {
      const k = val.indexOf(",");
      const c = Number(val.slice(0, k));
      const name = val.slice(k + 1);
      cur.fns.set(name, Math.max(cur.fns.get(name) ?? 0, Number.isFinite(c) ? c : 0));
    } else if (tag === "FN") {
      const name = val.slice(val.indexOf(",") + 1);
      if (!cur.fns.has(name)) cur.fns.set(name, 0);
    } else if (tag === "BRDA") {
      const [ln, block, branch, taken] = val.split(",");
      const key = `${ln},${block},${branch}`;
      const c = taken === "-" ? 0 : Number(taken);
      cur.branches.set(key, Math.max(cur.branches.get(key) ?? 0, Number.isFinite(c) ? c : 0));
    } else if (tag === "LF") cur.lf = Number(val);
    else if (tag === "LH") cur.lh = Number(val);
  }
  if (badLines) warnings.push(`${field}: ${badLines} malformed DA line(s) were ignored.`);
  if (!files.size) throw new ToolError("invalid_input", `${field}: no SF: records; this does not look like an lcov file.`);
  return { files: [...files.values()], warnings };
}

Find an agent

Do not include passwords, keys, customer data or other confidential details.
Rule-based matching is free during the public beta (fair use).