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.
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
Flows
_case_status
tuple[str, str] clew.wiki.evidence._case_status(ET.Element case)
The status and skip message of one JUnit testcase element.
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
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.
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
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.
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
Requirements
_root
ET.Element clew.wiki.evidence._root(Path path)
Parse one report, refusing an oversized one; recover a runner's control characters.
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
Flows
check_report_size
None clew.wiki.evidence.check_report_size(Path path)
Refuse a report over this build's size limit.
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
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.
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
Requirements
parse_cobertura
dict[str, dict[int, int]] clew.wiki.evidence.parse_cobertura(Path path)
Read a Cobertura XML report into line hits per file.
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
Requirements
parse_junit
dict[str, CaseResult] clew.wiki.evidence.parse_junit(list[Path] paths)
Read JUnit XML reports into one folded result per test.
Called by _build_site, _test_results, read
Tested by 7 tests
test_a_failure_s_location_is_read_from_its_traceback, test_a_googletest_notrun_case_is_a_skip, test_an_unreadable_report_is_refused_naming_file_and_line, test_catch2_section_cases_fold_into_their_test_case, test_junit_variants_name_the_function_and_classify_honestly, test_parametrized_cases_fold_and_statuses_are_distinct, test_terminal_colour_codes_in_a_report_are_stripped_and_said
Calls _case_name, _case_status, _case_where, _root, fold_cases
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
Requirements
Flows
parse_mutations
list[tuple[str, str, bool]] clew.wiki.evidence.parse_mutations(Path path)
Read a mutation record: (mechanism, test, killed) per entry.
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
Requirements
report_limit
Iterator[None] clew.wiki.evidence.report_limit(int megabytes)
Hold this build's report size limit for the readers below.
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
Requirements
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.
Called by _trace, gather
Tested by 13 tests
test_a_catch2_scenario_reaching_an_implementer_is_linked_by_its_name, test_a_declared_report_that_is_not_there_is_unmeasured_not_a_crash, test_a_measured_link_carries_its_extent, test_by_default_inference_is_the_full_transitive_closure, test_contexts_are_read_from_coverage_s_own_data_file, test_each_requirement_gets_its_tier, test_imports_join_the_trace, test_mutation_records_attach_to_the_requirement_their_mechanism_implements, test_per_test_coverage_contexts_link_tests_by_measurement, test_tests_named_by_the_catalog_evidence_field_are_linked, test_tests_that_reach_an_implementer_are_inferred_within_the_depth, test_without_coverage_nothing_claims_to_be_uncovered
Calls _covered, _implementer_spans, _mutations_for, _of_kind, _requirement_ids, _tier, connect
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