coverage.py¶
clew/guard/coverage.py
Requirement coverage analysis for clew guard.
_collect_req_ids
set[str] clew.guard.coverage._collect_req_ids(list[TaggedFunction] all_tagged)
Collect all requirement IDs referenced across tagged functions.
Source · 7 lines
def _collect_req_ids(all_tagged: list[TaggedFunction]) -> set[str]:
result: set[str] = set()
for tf in all_tagged:
result.update(tf.reqs)
return result
Activity · 4 steps
Requirements
Flows
_collect_unmapped_functions
set[str] clew.guard.coverage._collect_unmapped_functions(list[TaggedFunction] all_tagged)
Find documented functions with no requirement mapping, skipping exempt ones.
Source · 5 lines
def _collect_unmapped_functions(all_tagged: list[TaggedFunction]) -> set[str]:
settled = {tf.qualified or tf.name for tf in all_tagged if tf.reqs or tf.is_exempt}
return {tf.name for tf in all_tagged if (tf.qualified or tf.name) not in settled}
Activity · 2 steps
Requirements
Flows
_exempt
list[dict[str, str]] clew.guard.coverage._exempt(dict[str, dict[str, str]] rows, set[str] untagged, dict[str, Any] config)
The untagged requirements whose declared status exempts them from coverage.
Source · 15 lines
def _exempt(
rows: dict[str, dict[str, str]], untagged: set[str], config: dict[str, Any]
) -> list[dict[str, str]]:
from .config import exemption
req = get_requirements(config)
field = req.get("status_field", "status")
out = []
for rid in sorted(untagged):
reason = exemption(rows[rid], req)
if reason is not None:
out.append({"req_id": rid, "status": rows[rid].get(field, ""), "reason": reason})
return out
Activity · 9 steps
Requirements
Flows
_realised
list[tuple[str, str]] clew.guard.coverage._realised(set[str] uncovered, str dep_id, dict[str, Any] row, dict[str, Any] source, dict[str, Any] req)
The uncovered requirements one dependency row realises, and how.
Source · 20 lines
def _realised(
uncovered: set[str],
dep_id: str,
row: dict[str, Any],
source: dict[str, Any],
req: dict[str, Any],
) -> list[tuple[str, str]]:
from ..requirements import link_ids
from .config import exemption
targets = [t.split(":", 1)[-1] for t in link_ids(row) if t.split(":", 1)[-1] in uncovered]
if not targets:
return []
if _tagged_at_pin(source, dep_id):
return [(t, "implemented") for t in targets]
if exemption(row, req) is not None:
return [(t, "exempt") for t in targets]
return []
Activity · 10 steps
Flows
_tagged_at_pin
bool clew.guard.coverage._tagged_at_pin(dict[str, Any] source, str dep_id)
Whether a dependency's code tags a requirement at its pinned revision.
Source · 16 lines
def _tagged_at_pin(source: dict[str, Any], dep_id: str) -> bool:
from ..requirements import git_text
found = git_text(
Path.cwd() / str(source["repo"]),
"grep",
"-l",
"-w",
"-F",
f"@req {dep_id}",
str(source["rev"]),
"--",
)
return bool(found and found.strip())
Activity · 3 steps
Flows
_via
str clew.guard.coverage._via(dict[str, str] row)
One requirement covered through a dependency, as a report line.
Source · 4 lines
def _via(row: dict[str, str]) -> str:
return f"{row['req_id']} via {row['via']} ({row['how']})"
Activity · 1 steps
Flows
_why
str clew.guard.coverage._why(dict[str, Any] row)
Why one exempt requirement is exempt: its reason, else its status.
Source · 4 lines
def _why(row: dict[str, Any]) -> str:
return str(row.get("reason") or row.get("status") or "")
Activity · 1 steps
Flows
analyze_coverage
dict[str, Any] clew.guard.coverage.analyze_coverage(list[str] source_dirs, dict[str, Any] config)
Analyze requirement coverage across all documented functions.
Called by _coverage_gate, run_coverage
Tested by 6 tests
test_a_requirement_implemented_by_a_dependency_at_its_pin_is_covered_via_it, test_an_exempt_status_is_listed_not_counted_as_a_gap, test_analyze_coverage_structure, test_coverage_treats_a_declaration_and_its_definition_as_one, test_off_by_default_nothing_changes, test_without_exempt_status_nothing_is_exempt
Calls _collect_req_ids, _collect_unmapped_functions, _exempt, collect_tagged_functions, covered_via, load_requirements_full, traceability
Source · 30 lines
def analyze_coverage(
source_dirs: list[str],
config: dict[str, Any],
) -> dict[str, Any]:
full_reqs = load_requirements_full(config)
all_tagged = collect_tagged_functions(source_dirs, config)
all_req_ids = set(full_reqs.keys())
tagged_reqs = _collect_req_ids(all_tagged)
unmapped = _collect_unmapped_functions(all_tagged)
exempt = _exempt(full_reqs, all_req_ids - tagged_reqs, config)
uncovered = all_req_ids - tagged_reqs - {e["req_id"] for e in exempt}
report: dict[str, Any] = {
"total_requirements": len(all_req_ids),
"covered": sorted(tagged_reqs & all_req_ids),
"uncovered": sorted(uncovered),
"exempt": exempt,
"orphan_refs": sorted(tagged_reqs - all_req_ids),
"unmapped_functions": sorted(unmapped),
"traceability": traceability(all_tagged, config),
}
## 2.1 (#73 item 2): ABSENT unless opted in, so a report that never looked says nothing.
if (config.get("coverage") or {}).get("through_dependencies"):
via = covered_via(uncovered, config)
report["covered_via"] = via
report["uncovered"] = sorted(uncovered - {v["req_id"] for v in via})
return report
Activity · 13 steps
Requirements
Flows
coverage_gaps
bool clew.guard.coverage.coverage_gaps(dict[str, Any] report)
Whether a coverage report fails the gate.
Source · 3 lines
def coverage_gaps(report: dict[str, Any]) -> bool:
trace = report.get("traceability") or {}
return bool(report["uncovered"] or report["orphan_refs"] or trace.get("below_floor"))1 more lines, not shown
Activity · 2 steps
Requirements
Flows
covered_via
list[dict[str, str]] clew.guard.coverage.covered_via(set[str] uncovered, dict[str, Any] config)
The uncovered requirements a pinned dependency realises: implemented or exempt at its pin.
Source · 20 lines
def covered_via(uncovered: set[str], config: dict[str, Any]) -> list[dict[str, str]]:
from ..requirements import read_catalog_at
req = get_requirements(config)
found: dict[str, dict[str, str]] = {}
for source in req.get("external") or []:
if not isinstance(source, dict) or not {"repo", "rev", "path"} <= set(source):
continue
name = str(source.get("name") or Path(str(source["repo"])).name)
try:
rows = read_catalog_at(Path.cwd(), source)
except ValueError as exc:
logger.warning("coverage through %s skipped: %s", name, exc)
continue
for dep_id, row in rows.items():
for target, how in _realised(uncovered, dep_id, row, source, req):
found.setdefault(target, {"req_id": target, "via": f"{name}:{dep_id}", "how": how})
return [found[r] for r in sorted(found)]
Activity · 16 steps
Requirements
Flows
format_coverage_json
str clew.guard.coverage.format_coverage_json(dict[str, Any] report)
Format coverage report as JSON.
Source · 4 lines
def format_coverage_json(report: dict[str, Any]) -> str:
return json.dumps(report, indent=2)
Activity · 1 steps
Requirements
format_coverage_markdown
str clew.guard.coverage.format_coverage_markdown(dict[str, Any] report)
Format coverage report as markdown.
Source · 25 lines
def format_coverage_markdown(report: dict[str, Any]) -> str:
lines = [f"# Requirements Coverage: {len(report['covered'])}/{report['total_requirements']}"]
if report.get("traceability"):
lines.append(f"\n{traceability_line(report['traceability'])}")
if report["uncovered"]:
lines.append(f"\n## Uncovered ({len(report['uncovered'])})")
for r in report["uncovered"]:
lines.append(f"- {r}")
if report.get("exempt"):
lines.append(f"\n## Exempt by status or field ({len(report['exempt'])})")
lines += [f"- {e['req_id']} ({_why(e)})" for e in report["exempt"]]
if report.get("covered_via"):
lines.append(f"\n## Covered through dependencies ({len(report['covered_via'])})")
lines += [f"- {_via(v)}" for v in report["covered_via"]]
if report["orphan_refs"]:
lines.append(f"\n## Orphan Refs ({len(report['orphan_refs'])})")
for r in report["orphan_refs"]:
lines.append(f"- `{r}`")
if report["unmapped_functions"]:
lines.append(f"\n## Unmapped Functions ({len(report['unmapped_functions'])})")
for f in report["unmapped_functions"]:
lines.append(f"- `{f}()`")
return "\n".join(lines)
Activity · 22 steps
Requirements
format_coverage_text
str clew.guard.coverage.format_coverage_text(dict[str, Any] report)
Format coverage report as text.
Source · 21 lines
def format_coverage_text(report: dict[str, Any]) -> str:
lines = [f"Requirements coverage: {len(report['covered'])}/{report['total_requirements']}"]
if report.get("traceability"):
lines.append(traceability_line(report["traceability"]))
sections = (
("Uncovered", report["uncovered"]),
(
"Exempt by status or field",
[f"{e['req_id']} ({_why(e)})" for e in report.get("exempt", [])],
),
("Covered through dependencies", [_via(v) for v in report.get("covered_via", [])]),
("Orphan @req refs", report["orphan_refs"]),
("Functions without @req", [f"{f}()" for f in report["unmapped_functions"]]),
)
for title, items in sections:
if items:
lines.append(f"\n{title} ({len(items)}):")
lines += [f" - {i}" for i in items]
return "\n".join(lines)
Activity · 9 steps
Requirements
Flows
run_coverage
int clew.guard.coverage.run_coverage(list[str] source_dirs, dict[str, Any] config, str output_format="text")
Run coverage analysis and return exit code.
Source · 17 lines
def run_coverage(
source_dirs: list[str],
config: dict[str, Any],
output_format: str = "text",
) -> int:
report = analyze_coverage(source_dirs, config)
formatters = {
"json": format_coverage_json,
"markdown": format_coverage_markdown,
}
formatter = formatters.get(output_format, format_coverage_text)
print(formatter(report))
return 1 if coverage_gaps(report) else 0
Activity · 5 steps
Requirements
Flows
traceability
dict[str, Any] clew.guard.coverage.traceability(list[TaggedFunction] all_tagged, dict[str, Any] config)
The requirement ratio: functions with a req tag among those with a req tag or an exemption.
Source · 31 lines
def traceability(all_tagged: list[TaggedFunction], config: dict[str, Any]) -> dict[str, Any]:
from ..testscope import TEST_PATH_FACTS, is_test_path
patterns = tuple(config.get("test_paths") or TEST_PATH_FACTS)
traced: set[str] = set()
tags_of: dict[str, set[str]] = {}
for tf in all_tagged:
if is_test_path(str(tf.file_path).lstrip("./"), patterns):
continue
key = tf.qualified or tf.name
if tf.reqs:
traced.add(key)
tags_of.setdefault(key, set()).update(tf.exemptions)
exempt = {k: tags for k, tags in tags_of.items() if k not in traced and tags}
by_tag: dict[str, int] = {}
for tags in exempt.values():
for tag in tags:
by_tag[tag] = by_tag.get(tag, 0) + 1
total = len(traced) + len(exempt)
ratio = round(len(traced) / total, 4) if total else None
floor = (config.get("coverage") or {}).get("min_req_ratio")
return {
"req": len(traced),
"exempt": len(exempt),
"by_tag": dict(sorted(by_tag.items())),
"ratio": ratio,
"floor": floor,
"below_floor": floor is not None and ratio is not None and ratio < floor,
}
Activity · 20 steps
Requirements
Flows
traceability_line
str clew.guard.coverage.traceability_line(dict[str, Any] trace)
One line stating the requirement ratio, its per-tag counts and the floor.
Source · 15 lines
def traceability_line(trace: dict[str, Any]) -> str:
tags = ", ".join(f"@{t} {n}" for t, n in trace["by_tag"].items()) or "none"
ratio = "n/a" if trace["ratio"] is None else f"{trace['ratio']:g}"
if trace["floor"] is None:
verdict = "no floor declared"
elif trace["below_floor"]:
verdict = f"below the floor {trace['floor']:g}"
else:
verdict = f"floor {trace['floor']:g} met"
return (
f"Traceability: {trace['req']} with @req, {trace['exempt']} exempt ({tags}) — "
f"ratio {ratio} ({verdict})"
)