imports.py¶
clew/wiki/imports.py
Evidence imports beyond JUnit and Cobertura (1.4.0 W15, W16; owner 2026-11-15).
_context_test
str clew.wiki.imports._context_test(str context)
The test a coverage context names.
Source · 18 lines
def _context_test(context: str) -> str:
"""PARAMETERS ARE CUT AT THE FIRST "[" before the name is taken: a parameter id may itself
hold "::" and "]" (`test_x[a::b[c]-enhanced]` read as a test called `enhanced]`). ONLY THE
`run` PHASE names a test: what a fixture's setup or teardown ran is not what the test exercised
(clew: an autouse fixture made every test "measured" against REQ-DDB-MCP-004).
@brief Context → test.
@return Name.
"""
nodeid, _, phase = context.partition("|")
if phase and phase != "run":
return ""
parts = nodeid.split("[", 1)[0].split("::")
## W11 (2.0.0): THE FILE STAYS, so `test_x` in two files is two tests; a class between them
## is dropped, as the bare name always dropped it. `slices.test_name` shows the name.
return f"{parts[0]}::{parts[-1]}" if len(parts) > 1 else parts[0]
Activity · 5 steps
Flows
_contexts_from_data_file
dict[str, dict[int, set[str]]] clew.wiki.imports._contexts_from_data_file(Path path, Path root)
Per-test contexts from coverage.py's own data file (SQLite).
Source · 20 lines
def _contexts_from_data_file(path: Path, root: Path) -> dict[str, dict[int, set[str]]]:
"""READ THROUGH COVERAGE'S API, not its schema: the data file is coverage.py's format to
change. Found on clew's own suite: the JSON form of the same contexts was 3.9 GB.
@brief Read contexts.
@return Tests per line.
"""
from coverage import CoverageData
data = CoverageData(basename=str(path))
data.read()
out: dict[str, dict[int, set[str]]] = {}
for name in data.measured_files():
lines = out.setdefault(_relative(name, path.parent, root), {})
for line, contexts in (data.contexts_by_lineno(name) or {}).items():
tests = {_context_test(c) for c in contexts}
lines.setdefault(int(line), set()).update(t for t in tests if t)
return out
Activity · 10 steps
Requirements
Flows
_contexts_from_lcov
dict[str, dict[int, set[str]]] clew.wiki.imports._contexts_from_lcov(Path path, Path root)
Per-test contexts from an LCOV tracefile's TN: sections.
Source · 27 lines
def _contexts_from_lcov(path: Path, root: Path) -> dict[str, dict[int, set[str]]]:
"""THE REPOSITORY'S OWN REPORT (owner 2026-11-17): C/C++ per-test coverage is produced by the
repository's build — a per-test `GCOV_PREFIX` under ctest, then gcovr or lcov — and read here,
never stitched together by clew. A `TN:` line starts a test's section; `DA:<line>,<hits>[,…]`
with hits > 0 ran in it. An unnamed section is unattributed and dropped, as coverage.py's empty
context is.
@brief Read LCOV test sections.
@return Tests per line.
"""
out: dict[str, dict[int, set[str]]] = {}
test, lines = "", None
for raw in _text(path).splitlines():
tag, _, value = raw.strip().partition(":")
if tag == "TN":
test = value.strip()
elif tag == "SF":
lines = out.setdefault(_relative(value, path.parent, root), {})
elif tag == "DA" and test and lines is not None:
line, _, rest = value.partition(",")
if int(rest.split(",", 1)[0] or 0) > 0:
lines.setdefault(int(line), set()).add(test)
elif tag == "end_of_record":
lines = None
return {rel: lines for rel, lines in out.items() if lines}
Activity · 15 steps
Requirements
Flows
_folded
Any clew.wiki.imports._folded(str name, list[tuple[str, str, tuple]] rows)
One test's folded result: its worst case's status, message and failure locations.
Source · 14 lines
def _folded(name: str, rows: list[tuple[str, str, tuple]]) -> Any:
"""@brief Fold one test. @return Result."""
from .evidence import CaseResult
worst = sorted(rows, key=lambda r: _RANK[r[0]])
return CaseResult(
name=name,
status=worst[0][0],
cases=len(rows),
message=next((m for s, m, _w in worst if s != "passed" and m), ""),
where=next((w for s, _m, w in worst if s != "passed" and w), ()),
)
Activity · 3 steps
Flows
_relative
str clew.wiki.imports._relative(str name, Path base, Path root)
A report's source path made repo-relative where it resolves into the repository.
Called by _contexts_from_data_file, _contexts_from_lcov, _gcov_json, _gcov_text, parse_contexts
Calls none
Source · 16 lines
def _relative(name: str, base: Path, root: Path) -> str:
"""AN ABSOLUTE PATH needs only to lie under the repository; a RELATIVE one must resolve to a
file there, from the root first, then from the report's base.
@brief Relativise.
@return Path.
"""
name = name.strip()
if Path(name).is_absolute():
resolved = Path(name).resolve()
return resolved.relative_to(root).as_posix() if resolved.is_relative_to(root) else name
for candidate in (root / name, base / name):
resolved = candidate.resolve()
if resolved.is_relative_to(root) and resolved.exists():
return resolved.relative_to(root).as_posix()
return name.removeprefix("./")1 more lines, not shown
Activity · 9 steps
Flows
_scenarios
list[Scenario] clew.wiki.imports._scenarios(str rel, str text)
The scenarios of one feature file.
Source · 27 lines
def _scenarios(rel: str, text: str) -> list[Scenario]:
"""FEATURE TAGS APPLY TO EVERY SCENARIO, a Rule's to the scenarios under it; an Examples
block's tags select example rows, not requirements, and are dropped.
@brief Walk one file.
@return Scenarios.
"""
pending: list[str] = []
scopes = {"Feature": (), "Rule": ()}
out = []
for number, raw in enumerate(text.splitlines(), start=1):
line = raw.strip()
if line.startswith("@"):
pending += [_tag(t) for t in line.split() if t.startswith("@")]
continue
keyword = line.split(":", 1)[0]
match = _SCENARIO.match(line)
if match:
tags = (*scopes["Feature"], *scopes["Rule"], *pending)
out.append(Scenario(rel, number, match.group(2).strip(), tuple(dict.fromkeys(tags))))
elif keyword in scopes:
scopes[keyword] = tuple(pending)
if line and not line.startswith("#"):
pending = []
return out
Activity · 18 steps
Flows
_tag
str clew.wiki.imports._tag(str token)
A tag without its @ and an optional req: / req= prefix.
Source · 6 lines
def _tag(token: str) -> str:
"""@brief Normalise a tag. @return Tag."""
tag = token[1:]
return tag[4:] if tag.lower().startswith(("req:", "req=")) else tag
Activity · 2 steps
Flows
_text
str clew.wiki.imports._text(Path path)
A report's text, refused when oversized; .gz is decompressed.
Called by _contexts_from_lcov, _gcov_json, _gcov_text, parse_contexts, parse_features, parse_mapping, parse_needs, parse_results
Calls check_report_size
Source · 11 lines
def _text(path: Path) -> str:
"""@brief Read capped. @return Text."""
from .evidence import check_report_size
check_report_size(path)
data = path.read_bytes()
if path.suffix == ".gz":
data = gzip.decompress(data)
return data.decode("utf-8", errors="replace")
Activity · 6 steps
Flows
fold_cases
dict[str, Any] clew.wiki.imports.fold_cases(Iterable[tuple[str, str, str]] cases)
Fold (name, status, message) cases into one result per name, worst status first.
Source · 11 lines
def fold_cases(cases: Iterable[tuple[str, str, str]]) -> dict[str, Any]:
"""@brief Fold. @return Results."""
## A fourth element, the failure's locations, is optional: only the JUnit reader has one.
folded: dict[str, list[tuple[str, str, tuple]]] = {}
for name, status, message, *rest in cases:
if name:
folded.setdefault(name, []).append((status, message, rest[0] if rest else ()))
return {name: _folded(name, rows) for name, rows in folded.items()}
Activity · 5 steps
Requirements
Flows
parse_contexts
dict[str, dict[int, set[str]]] clew.wiki.imports.parse_contexts(Path path, Path repo_root)
Read coverage.py's per-test contexts: which tests ran each line.
Called by _coverage, read
Tested by
Calls _context_test, _contexts_from_data_file, _contexts_from_lcov, _relative, _text
Source · 21 lines
def parse_contexts(path: Path, repo_root: Path) -> dict[str, dict[int, set[str]]]:
"""A CONTEXT IS `<nodeid>|<phase>`; the test is the nodeid's function, parameters dropped,
the same name JUnit folding gives.
@brief Parse contexts.
@return Tests per line.
"""
root = Path(repo_root).resolve()
if path.suffix in _LCOV_SUFFIXES:
return _contexts_from_lcov(path, root)
if path.suffix != ".json":
return _contexts_from_data_file(path, root)
out: dict[str, dict[int, set[str]]] = {}
for name, data in (json.loads(_text(path)).get("files") or {}).items():
lines = out.setdefault(_relative(name, path.parent, root), {})
for line, contexts in ((data or {}).get("contexts") or {}).items():
tests = {_context_test(c) for c in contexts}
lines.setdefault(int(line), set()).update(t for t in tests if t)
return out
Activity · 12 steps
Requirements
Flows
parse_features
list[Scenario] clew.wiki.imports.parse_features(Path repo_root, Iterable[str] globs)
Every scenario of the feature files the globs select.
Source · 10 lines
def parse_features(repo_root: Path, globs: Iterable[str]) -> list[Scenario]:
"""@brief Parse Gherkin. @return Scenarios."""
root = Path(repo_root)
files = sorted({p for g in globs for p in root.glob(g) if p.is_file()})
out: list[Scenario] = []
for path in files:
out += _scenarios(path.relative_to(root).as_posix(), _text(path))
return out
Activity · 6 steps
Requirements
Flows
parse_gcov
dict[str, dict[int, int]] clew.wiki.imports.parse_gcov(Iterable[Path] paths, Path repo_root)
Read gcov reports into line hits per repo-relative file.
Called by read
Tested by
Calls _gcov_json, _gcov_text
Source · 13 lines
def parse_gcov(paths: Iterable[Path], repo_root: Path) -> dict[str, dict[int, int]]:
"""@brief Parse gcov. @return Hits."""
hits: dict[str, dict[int, int]] = {}
root = Path(repo_root).resolve()
for path in paths:
is_json = path.name.endswith((".json", ".json.gz"))
rows = _gcov_json(path, root) if is_json else _gcov_text(path, root)
for rel, line, count in rows:
lines = hits.setdefault(rel, {})
lines[line] = lines.get(line, 0) + count
return hits
Activity · 9 steps
Requirements
parse_mapping
dict[str, tuple[str, ...]] clew.wiki.imports.parse_mapping(Path path)
Read a requirement → test mapping file.
Source · 20 lines
def parse_mapping(path: Path) -> dict[str, tuple[str, ...]]:
"""@brief Parse a mapping. @return Links."""
text = _text(path)
out: dict[str, list[str]] = {}
if path.suffix.lower() == ".csv":
for row in csv.DictReader(io.StringIO(text)):
if row.get("req") and row.get("test"):
out.setdefault(row["req"].strip(), []).append(row["test"].strip())
return {k: tuple(v) for k, v in out.items()}
import yaml
doc = yaml.safe_load(text) or {}
if not isinstance(doc, dict):
raise ValueError(f"{path}: a mapping file maps a requirement id to its tests")
return {
str(k): tuple(str(t) for t in (v if isinstance(v, list) else [v]) if t is not None)
for k, v in doc.items()
}
Activity · 12 steps
Requirements
parse_needs
dict[str, dict[str, str]] clew.wiki.imports.parse_needs(Path path)
Read the requirements of a Sphinx-needs needs.json , as catalog entries.
Source · 23 lines
def parse_needs(path: Path) -> dict[str, dict[str, str]]:
"""THE CURRENT VERSION'S NEEDS (or the only version's), and only those typed `req` or
`requirement` — a spec, a test case or an implementation need is not a requirement.
@brief Read needs.json.
@return Entries.
"""
doc = json.loads(_text(path))
versions = doc.get("versions") or {}
version = versions.get(str(doc.get("current_version"))) or next(iter(versions.values()), {})
out = {}
for nid, need in (version.get("needs") or {}).items():
if str(need.get("type") or "") not in ("req", "requirement"):
continue
entry = {
"name": str(need.get("title") or ""),
"acceptance_criteria": str(need.get("content") or ""),
"status": str(need.get("status") or ""),
}
out[str(need.get("id") or nid)] = {k: v for k, v in entry.items() if v}
return out
Activity · 10 steps
Requirements
parse_results
dict[str, Any] clew.wiki.imports.parse_results(str fmt, Path path)
Read one result report of a declared format.
Source · 16 lines
def parse_results(fmt: str, path: Path) -> dict[str, Any]:
"""@brief Parse a report. @return Results."""
readers = {
"ctest": _ctest,
"tap": _tap,
"catch2": _catch2,
"pytest-json": _pytest_json,
"ceedling": _ceedling,
"unity": _unity,
"ctrf": _ctrf,
}
if fmt not in readers:
raise ValueError(f"unknown result format {fmt!r} (known: {', '.join(RESULT_FORMATS)})")
return fold_cases(readers[fmt](_text(path)))
Activity · 4 steps
Requirements
test_id
str clew.wiki.imports.Scenario.test_id(self)
The test id the trace shows: :: .
Source · 5 lines
def test_id(self) -> str:
"""@brief Id. @return `file::name`."""
return f"{self.file}::{self.name}"