evidence.py

clew/wiki/evidence.py

Requirement evidence: test results and coverage, joined to the requirement trace.

_case_name

str clew.wiki.evidence._case_name(ET.Element case)

A JUnit testcase's test name: parameters dropped, a Catch2 section path folded.

clew/wiki/evidence.py:204

Show on the map →

Called by parse_junit

Calls none

Source · 14 lines
def _case_name(case: ET.Element) -> str:
    """CATCH2'S OWN JUNIT REPORTER names one case per SECTION PATH ("Scenario: X/Given: a") under
    classname `<binary>.global`; the test is the part before the first "/". Found on
    sassafras-class, where 230 of 267 tested requirements read NOT_RUN without it.

    @brief Test name.
    @return Name.
    """
    name = _JUNIT_PARAMS.sub("", case.get("name") or "", count=1)
    if (case.get("classname") or "").endswith(".global"):
        name = name.split("/", 1)[0]
    return name

Activity · 4 steps
lines 212–212name = _JUNIT_PARAMS.sub("", case.get("name") or "", count=1)lines 213–213◇ if (case.get("classname") or "").endswith(".global")lines 214–214name = name.split("/", 1)[0]lines 215–215return name

Flows

_case_status

tuple[str, str] clew.wiki.evidence._case_status(ET.Element case)

The status and skip message of one JUnit testcase element.

clew/wiki/evidence.py:644

Show on the map →

Called by parse_junit

Calls none

Source · 16 lines
def _case_status(case: ET.Element) -> tuple[str, str]:
    """GOOGLETEST'S `status="notrun"` (a disabled test) has no child element: it is a skip, not a
    pass.

    @brief Classify a testcase.
    @return Status and message.
    """
    if case.get("status") in _SKIP_STATUS or case.get("result") in ("suppressed", "skipped"):
        return "skipped", case.get("result") or str(case.get("status"))
    for tag, status in (("error", "error"), ("failure", "failed"), ("skipped", "skipped")):
        child = case.find(tag)
        if child is not None:
            return status, child.get("message") or ""
    return "passed", ""

Activity · 7 steps
lines 651–651◇ if case.get("status") in _SKIP_STATUS or case.get("result") in ("suppressed", "skipped")lines 652–652return "skipped", case.get("result") or str(case.get("status"))lines 653–653◇ for tag, status in (("error", "error"), ("failure", "failed"), ("skipped", "skipped"))lines 654–654child = case.find(tag)lines 655–655◇ if child is not Nonelines 656–656return status, child.get("message") or ""lines 657–657return "passed", ""

Flows

_case_where

tuple[tuple[str, int], ...] clew.wiki.evidence._case_where(ET.Element case)

The source locations a failed or errored testcase's report names.

clew/wiki/evidence.py:185

Show on the map →

Called by parse_junit

Calls none

Source · 14 lines
def _case_where(case: ET.Element) -> tuple[tuple[str, int], ...]:
    """2.2 (flowchart F3): read from the failure's message and its text (the traceback).

    @brief Failure locations.
    @return Pairs.
    """
    child = case.find("failure")
    child = case.find("error") if child is None else child
    if child is None:
        return ()
    text = f"{child.get('message') or ''}\n{child.text or ''}"
    return tuple((path, int(line)) for path, line in _WHERE.findall(text))

Activity · 6 steps
lines 191–191child = case.find("failure")lines 192–192child = case.find("error") if child is None else childlines 193–193◇ if child is Nonelines 194–194return ()lines 195–195text = f"{child.get('message') or ''}\n{child.text or ''}"lines 196–196return tuple((path, int(line)) for path, line in _WHERE.findall(text))

Flows

_reaching_tests

dict[str, tuple] clew.wiki.evidence._reaching_tests(object conn, str req_id, int|None depth)

The tests whose calls reach a requirement's implementers, and which ones each reaches.

clew/wiki/evidence.py:756

Show on the map →

Called by linked_tests

Calls _callers_step, table_exists

Source · 29 lines
def _reaching_tests(conn: object, req_id: str, depth: int | None) -> dict[str, tuple]:
    """WALKED BACKWARDS from the implementers over call edges, never through a `binding` edge (a
    function value passed along is not a call) nor a fuzzy one, and never through a test: a test
    found is recorded, not expanded. A test is whatever `frameworks.recognise_test` recognises —
    a `test_*` function or a Catch2 / GoogleTest / Boost case.

    EACH NODE CARRIES THE IMPLEMENTERS IT REACHES (owner 2026-11-17: a test may cover part of one
    requirement or all of it), and is walked again only when that set grows — so the closure
    terminates on a cyclic graph and the extent is exact.

    @brief Infer reaching tests with their extent.
    @return Tests found.
    """
    if depth == 0 or not table_exists(conn, "call_edges") or not table_exists(conn, "req_edges"):
        return {}
    origins: dict[int, set[str]] = {}
    for rowid, name in conn.execute(
        "SELECT r.memberdef_rowid, m.name FROM req_edges r "
        "JOIN memberdef m ON m.rowid = r.memberdef_rowid WHERE r.req_id = ?",
        (req_id,),
    ):
        origins.setdefault(rowid, set()).add(str(name))
    frontier, found, hop = set(origins), {}, 0
    while frontier and (depth is None or hop < depth):
        hop += 1
        frontier = _callers_step(conn, frontier, origins, found, hop)
    return found

Activity · 10 steps
lines 769–769◇ if depth == 0 or not table_exists(conn, "call_edges") or not table_exists(conn, "req_edges")lines 770–770return {}lines 771–771origins: dict[int, set[str]] = {}lines 772–772◇ for rowid, name in conn.execute(lines 777–777origins.setdefault(rowid, set()).add(str(name))lines 778–778frontier, found, hop = set(origins), {}, 0lines 779–779◇ while frontier and (depth is None or hop < depth)lines 780–780hop += 1lines 781–781frontier = _callers_step(conn, frontier, origins, found, hop)lines 782–782return found

Requirements

REQ-DDB-WIKI-016

_root

ET.Element clew.wiki.evidence._root(Path path)

Parse one report, refusing an oversized one; recover a runner's control characters.

clew/wiki/evidence.py:673

Source · 25 lines
def _root(path: Path) -> ET.Element:
    """#72 (an adopter, 2026-11-23): Ceedling copies coloured stdout (`ESC[0m`) into its JUnit, which
    is not XML 1.0, and the raw ParseError either killed `clew wiki trace` or left every linked
    test NOT_RUN. Colour sequences and XML-illegal controls are REMOVED AND COUNTED (a warning names
    the file); what still does not parse is a ValueError naming the file, line and column.

    @brief Read XML with a size cap.
    @return Root element.
    """
    check_report_size(path)
    raw = Path(path).read_bytes().decode("utf-8", errors="replace")
    clean = _XML_ILLEGAL.sub("", _ANSI.sub("", raw))
    if len(clean) != len(raw):
        logger.warning(
            "%s: removed %d terminal-colour or XML-illegal control characters before parsing",
            path,
            len(raw) - len(clean),
        )
    try:
        return ET.fromstring(clean)
    except ET.ParseError as exc:
        line, column = exc.position
        raise ValueError(f"{path}: not valid XML at line {line}, column {column}: {exc}") from exc

Activity · 10 steps
lines 682–682check_report_size(path)lines 683–683raw = Path(path).read_bytes().decode("utf-8", errors="replace")lines 684–684clean = _XML_ILLEGAL.sub("", _ANSI.sub("", raw))lines 685–685◇ if len(clean) != len(raw)lines 686–690logger.warning( "%s: removed %d terminal-colour or XML-illegal control characters before parsing", path, len(raw) - len(clean), )lines 691–691trylines 692–692return ET.fromstring(clean)lines 693–693except ET.ParseError as exclines 694–694line, column = exc.positionlines 695–695raise ValueError(f"{path}: not valid XML at line {line}, column {column}: {exc}") from exc

Flows

check_report_size

None clew.wiki.evidence.check_report_size(Path path)

Refuse a report over this build's size limit.

clew/wiki/evidence.py:81

Source · 10 lines
def check_report_size(path: Path) -> None:
    """@brief Apply the cap. @return None."""
    limit = _REPORT_MB.get() * 1024 * 1024
    if path.stat().st_size > limit:
        raise ValueError(
            f"{path} is larger than {_REPORT_MB.get()} MiB; refusing to parse it "
            f"(raise `tests.max_report_mb` if the report is expected to be this large)"
        )

Activity · 3 steps
lines 83–83limit = _REPORT_MB.get() * 1024 * 1024lines 84–84◇ if path.stat().st_size > limitlines 85–88raise ValueError( f"{path} is larger than {_REPORT_MB.get()} MiB; refusing to parse it " f"(raise `tests.max_report_mb` if the report is expected to be this large)" )

Flows

exempt_by_status

list[RequirementEvidence] clew.wiki.evidence.exempt_by_status(list[RequirementEvidence] evidence, dict[str, dict] declared, dict|None guard)

Re-grade MISSING requirements whose declared status the gate exempts.

clew/wiki/evidence.py:612

Source · 24 lines
def exempt_by_status(
    evidence: list[RequirementEvidence], declared: dict[str, dict], guard: dict | None
) -> list[RequirementEvidence]:
    """ONLY MISSING MOVES: a linked test's measured result outranks a catalogue label, so a
    planned requirement whose test failed is still GAP.

    @brief Apply exempt statuses.
    @return Rows.
    """
    from dataclasses import replace

    from ..guard.config import get_requirements

    from ..guard.config import exemption

    req = get_requirements(guard)

    ## 2.1 (#72 item 14): the gate's own predicate, so `exempt_when` fields exempt here too.
    def exempt(row: RequirementEvidence) -> bool:
        return row.tier == "MISSING" and exemption(declared.get(row.req_id) or {}, req) is not None

    return [replace(r, tier="EXEMPT") if exempt(r) else r for r in evidence]

Activity · 6 steps
lines 621–621from dataclasses import replacelines 623–623from ..guard.config import get_requirementslines 625–625from ..guard.config import exemptionlines 627–627req = get_requirements(guard)lines 630–631def exempt(row: RequirementEvidence) -> bool: return row.tier == "MISSING" and exemption(declared.get(row.req_id) or {}, req) is not Nonelines 633–633return [replace(r, tier="EXEMPT") if exempt(r) else r for r in evidence]

Requirements

REQ-DDB-WIKI-002

parse_cobertura

dict[str, dict[int, int]] clew.wiki.evidence.parse_cobertura(Path path)

Read a Cobertura XML report into line hits per file.

clew/wiki/evidence.py:223

Source · 10 lines
def parse_cobertura(path: Path) -> dict[str, dict[int, int]]:
    """@brief Parse Cobertura. @return Hits per file."""
    hits: dict[str, dict[int, int]] = {}
    for cls in _root(path).iter("class"):
        lines = hits.setdefault(cls.get("filename") or "", {})
        for line in cls.iter("line"):
            lines[int(line.get("number") or 0)] = int(line.get("hits") or 0)
    return hits

Activity · 6 steps
lines 225–225hits: dict[str, dict[int, int]] = {}lines 226–226◇ for cls in _root(path).iter("class")lines 227–227lines = hits.setdefault(cls.get("filename") or "", {})lines 228–228◇ for line in cls.iter("line")lines 229–229lines[int(line.get("number") or 0)] = int(line.get("hits") or 0)lines 230–230return hits

Requirements

REQ-DDB-WIKI-002

parse_junit

dict[str, CaseResult] clew.wiki.evidence.parse_junit(list[Path] paths)

Read JUnit XML reports into one folded result per test.

clew/wiki/evidence.py:158

Source · 17 lines
def parse_junit(paths: list[Path]) -> dict[str, CaseResult]:
    """THE TEST NAME IS THE CASE NAME WITH ITS PARAMETERS DROPPED, the name the index knows as a
    function; a folded test takes its WORST case's status and records how many cases it had.

    @brief Parse JUnit.
    @return Results.
    @version 3
    """
    from .imports import fold_cases

    return fold_cases(
        (_case_name(case), *_case_status(case), _case_where(case))
        for path in paths
        for case in _root(path).iter("testcase")
    )

Activity · 2 steps
lines 166–166from .imports import fold_caseslines 168–172return fold_cases( (_case_name(case), *_case_status(case), _case_where(case)) for path in paths for case in _root(path).iter("testcase") )

Requirements

REQ-DDB-WIKI-002

Flows

parse_mutations

list[tuple[str, str, bool]] clew.wiki.evidence.parse_mutations(Path path)

Read a mutation record: (mechanism, test, killed) per entry.

clew/wiki/evidence.py:239

Show on the map →

Called by _mutation_problems, read

Calls check_report_size

Source · 22 lines
def parse_mutations(path: Path) -> list[tuple[str, str, bool]]:
    """AN ENTRY MISSING A FIELD IS REFUSED, never defaulted: a record that does not say whether
    the mutant was killed is not evidence either way.

    @brief Parse mutation records.
    @return Records.
    @version 1
    """
    import yaml

    check_report_size(path)
    doc = yaml.safe_load(path.read_text(encoding="utf-8")) or []
    if not isinstance(doc, list):
        raise ValueError(f"{path}: a mutation record is a list of {{mechanism, test, killed}}")
    out = []
    for i, entry in enumerate(doc):
        if not isinstance(entry, dict) or not {"mechanism", "test", "killed"} <= set(entry):
            raise ValueError(f"{path}: entry {i} needs `mechanism`, `test` and `killed`")
        out.append((str(entry["mechanism"]), str(entry["test"]), bool(entry["killed"])))
    return out

Activity · 11 steps
lines 247–247import yamllines 249–249check_report_size(path)lines 250–250doc = yaml.safe_load(path.read_text(encoding="utf-8")) or []lines 251–251◇ if not isinstance(doc, list)lines 252–252raise ValueError(f"{path}: a mutation record is a list of {{mechanism, test, killed}}")lines 253–253out = []lines 254–254◇ for i, entry in enumerate(doc)lines 255–255◇ if not isinstance(entry, dict) or not {"mechanism", "test", "killed"} <= set(entry)lines 256–256raise ValueError(f"{path}: entry {i} needs `mechanism`, `test` and `killed`")lines 257–257out.append((str(entry["mechanism"]), str(entry["test"]), bool(entry["killed"])))lines 258–258return out

Requirements

REQ-DDB-WIKI-006

report_limit

Iterator[None] clew.wiki.evidence.report_limit(int megabytes)

Hold this build's report size limit for the readers below.

clew/wiki/evidence.py:67

Show on the map →

Called by build_wiki

Calls none

Source · 9 lines
def report_limit(megabytes: int) -> Iterator[None]:
    """@brief Scope the report limit. @return Context."""
    token = _REPORT_MB.set(megabytes)
    try:
        yield
    finally:
        _REPORT_MB.reset(token)

Activity · 3 steps
lines 69–69token = _REPORT_MB.set(megabytes)lines 70–70trylines 71–71yield

Requirements

REQ-DDB-WIKI-005

Flows

requirement_evidence

list[RequirementEvidence] clew.wiki.evidence.requirement_evidence(Path|str db, *list[Path] junit, Path|None coverage=None, tuple[str,...] target_only=(), Path|None mutations=None, EvidenceInputs|None inputs=None, Path|None repo_root=None)

Grade every requirement the index knows against the given reports.

clew/wiki/evidence.py:277

Source · 44 lines
def requirement_evidence(
    db: Path | str,
    *,
    junit: list[Path],
    coverage: Path | None = None,
    target_only: tuple[str, ...] = (),
    mutations: Path | None = None,
    inputs: EvidenceInputs | None = None,
    repo_root: Path | None = None,
) -> list[RequirementEvidence]:
    """@brief Join reports to the trace. @return Evidence rows."""
    reports = _Reports.read(junit, coverage, mutations, inputs, repo_root)
    with connect(db) as conn:
        out = []
        for req_id, title in _requirement_ids(conn):
            impls = _implementer_spans(conn, req_id)
            linked, kinds, inferred = reports.linked_tests(conn, req_id, impls)
            statuses = tuple((t, reports.status(t, names)) for t, _where, names in linked)
            covered = uncovered = None
            if reports.hits is not None:
                covered = tuple(n for n, f, s, e in impls if _covered(reports.hits, f, s, e))
                uncovered = tuple(n for n, f, s, e in impls if not _covered(reports.hits, f, s, e))
            out.append(
                RequirementEvidence(
                    req_id=req_id,
                    title=title,
                    tier=_tier(statuses, target_only),
                    tests=statuses,
                    implementers=tuple(n for n, _f, _s, _e in impls),
                    implementers_covered=covered,
                    implementers_uncovered=uncovered,
                    mutations=_mutations_for(reports.records, impls),
                    layers=reports.layers_of(linked),
                    implementer_sites=tuple((n, f, s) for n, f, s, _e in impls),
                    declared_tests=_of_kind(kinds, "catalog"),
                    measured_tests=_of_kind(kinds, "measured"),
                    inferred_tests=_of_kind(kinds, "inferred"),
                    extent=reports.extent(impls, inferred),
                    distance=tuple(sorted((t, v[2]) for t, v in inferred.items())),
                )
            )
    return out

Activity · 13 steps
lines 288–288reports = _Reports.read(junit, coverage, mutations, inputs, repo_root)lines 289–289with connect(db) as connlines 290–290out = []lines 291–291◇ for req_id, title in _requirement_ids(conn)lines 292–292impls = _implementer_spans(conn, req_id)lines 293–293linked, kinds, inferred = reports.linked_tests(conn, req_id, impls)lines 294–294statuses = tuple((t, reports.status(t, names)) for t, _where, names in linked)lines 295–295covered = uncovered = Nonelines 296–296◇ if reports.hits is not Nonelines 297–297covered = tuple(n for n, f, s, e in impls if _covered(reports.hits, f, s, e))lines 298–298uncovered = tuple(n for n, f, s, e in impls if not _covered(reports.hits, f, s, e))lines 299–317out.append( RequirementEvidence( req_id=req_id, title=title, tier=_tier(statuses, target_only), tests=statuses, implementers=tuple(n for n, _f, _s, _e in impls), implementers_covered=covered, implementers_uncovered=uncovered, mutations=_mutations_for(reports.records, impls), layers=reports.layers_of(linked), implementer_sites=tuple((n, f, s) for n, f, s, _e in impls), declared_tests=_of_kind(kinds, "catalog"), measured_tests=_of_kind(kinds, "measured"), inferred_tests=_of_kind(kinds, "inferred"), extent=reports.extent(impls, inferred), distance=tuple(sorted((t, v[2]) for t, v in inferred.items())), ) )lines 318–318return out

Requirements

REQ-DDB-WIKI-002