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.

clew/wiki/imports.py:219

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
lines 228–228nodeid, _, phase = context.partition("|")lines 229–229◇ if phase and phase != "run"lines 230–230return ""lines 231–231parts = nodeid.split("[", 1)[0].split("::")lines 234–234return f"{parts[0]}::{parts[-1]}" if len(parts) > 1 else parts[0]

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).

clew/wiki/imports.py:280

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
lines 287–287from coverage import CoverageDatalines 289–289data = CoverageData(basename=str(path))lines 290–290data.read()lines 291–291out: dict[str, dict[int, set[str]]] = {}lines 292–292◇ for name in data.measured_files()lines 293–293lines = out.setdefault(_relative(name, path.parent, root), {})lines 294–294◇ for line, contexts in (data.contexts_by_lineno(name) or {}).items()lines 295–295tests = {_context_test(c) for c in contexts}lines 296–296lines.setdefault(int(line), set()).update(t for t in tests if t)lines 297–297return out

Requirements

REQ-DDB-WIKI-002

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.

clew/wiki/imports.py:247

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
lines 257–257out: dict[str, dict[int, set[str]]] = {}lines 258–258test, lines = "", Nonelines 259–259◇ for raw in _text(path).splitlines()lines 260–260tag, _, value = raw.strip().partition(":")lines 261–261◇ if tag == "TN"lines 262–262test = value.strip()lines 263–263◇ elif tag == "SF"lines 264–264lines = out.setdefault(_relative(value, path.parent, root), {})lines 265–265◇ elif tag == "DA" and test and lines is not Nonelines 266–266line, _, rest = value.partition(",")lines 267–267◇ if int(rest.split(",", 1)[0] or 0) > 0lines 268–268lines.setdefault(int(line), set()).add(test)lines 269–269◇ elif tag == "end_of_record"lines 270–270lines = Nonelines 271–271return {rel: lines for rel, lines in out.items() if lines}

Requirements

REQ-DDB-WIKI-016

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.

clew/wiki/imports.py:100

Show on the map →

Called by fold_cases

Calls none

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
lines 102–102from .evidence import CaseResultlines 104–104worst = sorted(rows, key=lambda r: _RANK[r[0]])lines 105–111return 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), ()), )

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.

clew/wiki/imports.py:576

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
lines 583–583name = name.strip()lines 584–584◇ if Path(name).is_absolute()lines 585–585resolved = Path(name).resolve()lines 586–586return resolved.relative_to(root).as_posix() if resolved.is_relative_to(root) else namelines 587–587◇ for candidate in (root / name, base / name)lines 588–588resolved = candidate.resolve()lines 589–589◇ if resolved.is_relative_to(root) and resolved.exists()lines 590–590return resolved.relative_to(root).as_posix()lines 591–591return name.removeprefix("./")

Flows

_scenarios

list[Scenario] clew.wiki.imports._scenarios(str rel, str text)

The scenarios of one feature file.

clew/wiki/imports.py:322

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
lines 329–329pending: list[str] = []lines 330–330scopes = {"Feature": (), "Rule": ()}lines 331–331out = []lines 332–332◇ for number, raw in enumerate(text.splitlines(), start=1)lines 333–333line = raw.strip()lines 334–334◇ if line.startswith("@")lines 335–335pending += [_tag(t) for t in line.split() if t.startswith("@")]lines 336–336continuelines 337–337keyword = line.split(":", 1)[0]lines 338–338match = _SCENARIO.match(line)lines 339–339◇ if matchlines 340–340tags = (*scopes["Feature"], *scopes["Rule"], *pending)lines 341–341out.append(Scenario(rel, number, match.group(2).strip(), tuple(dict.fromkeys(tags))))lines 342–342◇ elif keyword in scopeslines 343–343scopes[keyword] = tuple(pending)lines 344–344◇ if line and not line.startswith("#")lines 345–345pending = []lines 346–346return out

Flows

_tag

str clew.wiki.imports._tag(str token)

A tag without its @ and an optional req: / req= prefix.

clew/wiki/imports.py:354

Show on the map →

Called by _scenarios

Calls none

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
lines 356–356tag = token[1:]lines 357–357return tag[4:] if tag.lower().startswith(("req:", "req=")) else tag

Flows

_text

str clew.wiki.imports._text(Path path)

A report's text, refused when oversized; .gz is decompressed.

clew/wiki/imports.py:366

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
lines 368–368from .evidence import check_report_sizelines 370–370check_report_size(path)lines 371–371data = path.read_bytes()lines 372–372◇ if path.suffix == ".gz"lines 373–373data = gzip.decompress(data)lines 374–374return data.decode("utf-8", errors="replace")

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.

clew/wiki/imports.py:83

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
lines 87–87folded: dict[str, list[tuple[str, str, tuple]]] = {}lines 88–88◇ for name, status, message, *rest in caseslines 89–89◇ if namelines 90–90folded.setdefault(name, []).append((status, message, rest[0] if rest else ()))lines 91–91return {name: _folded(name, rows) for name, rows in folded.items()}

Requirements

REQ-DDB-WIKI-010

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.

clew/wiki/imports.py:191

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
lines 198–198root = Path(repo_root).resolve()lines 199–199◇ if path.suffix in _LCOV_SUFFIXESlines 200–200return _contexts_from_lcov(path, root)lines 201–201◇ if path.suffix != ".json"lines 202–202return _contexts_from_data_file(path, root)lines 203–203out: dict[str, dict[int, set[str]]] = {}lines 204–204◇ for name, data in (json.loads(_text(path)).get("files") or {}).items()lines 205–205lines = out.setdefault(_relative(name, path.parent, root), {})lines 206–206◇ for line, contexts in ((data or {}).get("contexts") or {}).items()lines 207–207tests = {_context_test(c) for c in contexts}lines 208–208lines.setdefault(int(line), set()).update(t for t in tests if t)lines 209–209return out

Requirements

REQ-DDB-WIKI-016

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.

clew/wiki/imports.py:306

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
lines 308–308root = Path(repo_root)lines 309–309files = sorted({p for g in globs for p in root.glob(g) if p.is_file()})lines 310–310out: list[Scenario] = []lines 311–311◇ for path in fileslines 312–312out += _scenarios(path.relative_to(root).as_posix(), _text(path))lines 313–313return out

Requirements

REQ-DDB-WIKI-010

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.

clew/wiki/imports.py:144

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
lines 146–146hits: dict[str, dict[int, int]] = {}lines 147–147root = Path(repo_root).resolve()lines 148–148◇ for path in pathslines 149–149is_json = path.name.endswith((".json", ".json.gz"))lines 150–150rows = _gcov_json(path, root) if is_json else _gcov_text(path, root)lines 151–151◇ for rel, line, count in rowslines 152–152lines = hits.setdefault(rel, {})lines 153–153lines[line] = lines.get(line, 0) + countlines 154–154return hits

Requirements

REQ-DDB-WIKI-009

parse_mapping

dict[str, tuple[str, ...]] clew.wiki.imports.parse_mapping(Path path)

Read a requirement → test mapping file.

clew/wiki/imports.py:162

Show on the map →

Called by _mapping_problems, read

Tested by

1 teststest_a_mapping_file_reads_yaml_and_csv

Calls _text

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
lines 164–164text = _text(path)lines 165–165out: dict[str, list[str]] = {}lines 166–166◇ if path.suffix.lower() == ".csv"lines 167–167◇ for row in csv.DictReader(io.StringIO(text))lines 168–168◇ if row.get("req") and row.get("test")lines 169–169out.setdefault(row["req"].strip(), []).append(row["test"].strip())lines 170–170return {k: tuple(v) for k, v in out.items()}lines 171–171import yamllines 173–173doc = yaml.safe_load(text) or {}lines 174–174◇ if not isinstance(doc, dict)lines 175–175raise ValueError(f"{path}: a mapping file maps a requirement id to its tests")lines 176–179return { 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() }

Requirements

REQ-DDB-WIKI-010

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.

clew/wiki/imports.py:486

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
lines 493–493doc = json.loads(_text(path))lines 494–494versions = doc.get("versions") or {}lines 495–495version = versions.get(str(doc.get("current_version"))) or next(iter(versions.values()), {})lines 496–496out = {}lines 497–497◇ for nid, need in (version.get("needs") or {}).items()lines 498–498◇ if str(need.get("type") or "") not in ("req", "requirement")lines 499–499continuelines 500–504entry = { "name": str(need.get("title") or ""), "acceptance_criteria": str(need.get("content") or ""), "status": str(need.get("status") or ""), }lines 505–505out[str(need.get("id") or nid)] = {k: v for k, v in entry.items() if v}lines 506–506return out

Requirements

REQ-DDB-WIKI-030

parse_results

dict[str, Any] clew.wiki.imports.parse_results(str fmt, Path path)

Read one result report of a declared format.

clew/wiki/imports.py:122

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
lines 124–132readers = { "ctest": _ctest, "tap": _tap, "catch2": _catch2, "pytest-json": _pytest_json, "ceedling": _ceedling, "unity": _unity, "ctrf": _ctrf, }lines 133–133◇ if fmt not in readerslines 134–134raise ValueError(f"unknown result format {fmt!r} (known: {', '.join(RESULT_FORMATS)})")lines 135–135return fold_cases(readers[fmt](_text(path)))

Requirements

REQ-DDB-WIKI-010

test_id

str clew.wiki.imports.Scenario.test_id(self)

The test id the trace shows: :: .

clew/wiki/imports.py:71

Show on the map →

Called by none

Calls none

Source · 5 lines
    def test_id(self) -> str:
        """@brief Id. @return `file::name`."""
        return f"{self.file}::{self.name}"

Activity · 1 steps
lines 73–73return f"{self.file}::{self.name}"

Requirements

REQ-DDB-WIKI-010