testpages.py¶
clew/wiki/testpages.py
A page per test: what it checks, what it reaches, and what the run said (round 4, R6/R7).
_callflow
str clew.wiki.testpages._callflow(str test, list[tuple[str, str]] callees, dict[str, set[int]] ran, set written, dict|None briefs=None)
The test's call-flow boxes: each function it calls, linked to its activity diagram.
Source · 39 lines
def _callflow(
test: str,
callees: list[tuple[str, str]],
ran: dict[str, set[int]],
written: set,
briefs: dict | None = None,
) -> str:
"""TWO ZOOM LEVELS (owner, round 5): a box per function the test calls; its link opens that
function's activity diagram, on the function's own page, with the lines THIS test executed in
`?lit=` for `clew.js` to light (owner Q/A 2026-11-20). A function without a written page gets a
box and no link, never a broken one; without per-test coverage the link carries no lines.
@brief Call-flow boxes.
@return HTML.
"""
boxes = []
for name, rel in callees:
## X-3: each box says what its function does, for the reader and for the player's caption.
brief = (briefs or {}).get((name, rel), "")
about = f' data-brief="{escape(brief)}" title="{escape(brief)}"' if brief else ""
if (name, rel) not in written:
boxes.append(f'<span class="box"{about}>{escape(name)}</span>')
continue
page, _anchor = symbol_href(name, rel).split("#", 1)
lit = _ranges(ran.get(rel, set()))
query = f"?lit={lit}" if lit else ""
boxes.append(
f'<a class="box"{about} href="{page}{query}#act-{anchor(name)}">{escape(name)}</a>'
)
arrows = '<span class="arrow">→</span>'.join(boxes)
return (
## E-15: a player only where there is something to play — more than five boxes.
'<section class="callflow-block" data-flow-play="callflow"><h2>Call flow</h2>'
f'{_player_controls() if len(callees) > 5 else ""}<div class="callflow"><span class="box test"><code>{escape(test)}'
f'</code></span><span class="arrow">→</span>{arrows}</div></section>'
'<script src="_static/clew-views.js"></script>'
)
Activity · 13 steps
Requirements
_context
str clew.wiki.testpages._context(set[str] candidates, list flows)
How the product reaches the functions a test calls, or that it does not.
Source · 29 lines
def _context(candidates: set[str], flows: list) -> str:
"""CONTEXT PATHS (owner, round 5, P5.5): for each function the test calls, the shortest path a
PRODUCT flow takes from its entry to it, along that flow's own drawn steps, linked to the flow.
A tooling or thread flow is not the product. ABSENCE IS STATED: when no product flow reaches
any of them the page says so — a test of code the product never runs is worth knowing about.
@brief Context paths.
@return HTML.
"""
lines = []
for name in sorted(candidates):
found = _shortest([f for f in flows if f.role == "product"], name)
if found:
page, path = found
chain = (
" → ".join(f"<code>{escape(n)}</code>" for n in path)
if len(path) > 1
else f"<code>{escape(name)}</code> is the entry of the flow"
)
lines.append(f'<li>{chain} <a href="{escape(page)}.html">(flow)</a></li>')
body = (
f"<ul>{''.join(lines)}</ul>"
if lines
else "<p>No product flow reaches this code: no product entry point's flow calls any of "
"the functions this test calls.</p>"
)
return f'<h2>Where the product reaches it</h2><div class="context">{body}</div>'
Activity · 9 steps
Requirements
_exercises
str clew.wiki.testpages._exercises(str name, dict[str, Any] ctx, list|None defs=None)
What a test exercises: its slices of the master flows.
Called by test_pages
Tested by
Source · 35 lines
def _exercises(name: str, ctx: dict[str, Any], defs: list | None = None) -> str:
"""OWNER 2026-11-17: "a test case is testing a portion OF a sequence diagram". Each master
flow the test ran a step of is drawn as the window around its slice, most steps first; the
title opens the whole flow with this test's steps lit.
W11 (2.0.0): `test_x` in two files used to share one key and so one merged set of slices.
The page for a name still holds every definition; each now shows its own, under its file. A
key with no file (an LCOV `TN:` name) is drawn once for the page.
@brief Draw the slices.
@return HTML.
"""
slices = ctx.get("slices") or {}
groups = _slice_groups(name, slices, [d.file for d in defs or ()])
if not groups:
return ""
parts = [
"<h2>What it exercises</h2><p>The parts of the system's flows this test ran, measured by "
"per-test coverage: lit steps ran in this test, dimmed ones did not, and ▶ marks where the "
"test called in. Each title opens the whole flow with these steps lit.</p>",
## W-6 (owner review 2026-11-22): the slices play — the steps this test ran, in order,
## paced to reading speed (clew-views.js; the flow player's pace and speed control).
_player_controls(),
]
for file, key in groups:
if file and len(groups) > 1:
parts.append(f"<h3><code>{escape(file)}</code></h3>")
parts.append(_slices_html(key, slices[key], ctx.get("test_slices") or _SLICES_DRAWN))
return (
'<section class="exercises" data-flow-play="slices">'
+ "".join(parts)
+ '</section><script src="_static/clew-views.js"></script>'
)
Activity · 10 steps
Requirements
Flows
_pinned
str clew.wiki.testpages._pinned(Any pin, str|None value=None)
One pinned check: the statement, what it observes, and its traced value.
Called by _definition
Tested by
Calls none
Source · 24 lines
def _pinned(pin: Any, value: str | None = None) -> str:
"""@brief `observes f`, `observes f via r`, or `not attributed`. @return HTML."""
from .checkpins import DIRECT, VIA_VARIABLE
if pin.kind == DIRECT:
badge = f"observes <code>{escape(pin.target)}</code>"
elif pin.kind == VIA_VARIABLE:
badge = (
f"observes <code>{escape(pin.target)}</code> via <code>{escape(pin.variable)}</code>"
)
else:
badge = "not attributed"
kind = pin.kind.replace(" ", "-")
seen = (
f' <span class="traced">returned <code>{escape(value)}</code> in the recorded run</span>'
if value is not None
else ""
)
return (
f"<li><code>{escape(pin.statement)}</code> "
f'<span class="pin pin-{kind}">{badge}</span>{seen}</li>'
)
Activity · 10 steps
Requirements
_player_controls
str clew.wiki.testpages._player_controls()
The test-page player's controls: play, pause, step, speed and the caption line.
Source · 18 lines
def _player_controls() -> str:
"""ONE SET for the slices and the call flow (W-6, X-3); `clew-views.js` drives both.
@brief Player controls.
@return HTML.
"""
buttons = "".join(
f'<button type="button" data-slice-control="{c}">{c}</button>'
for c in ("play", "pause", "step")
)
return (
f'<div class="flow-controls slice-controls">{buttons}'
'<label class="flow-speed">speed <input type="range" min="0.25" max="2" step="0.25" '
'value="1" data-flow-speed aria-label="playback speed"></label>'
'<p class="slice-now" aria-live="polite"></p></div>'
)
Activity · 2 steps
Flows
_replay
str clew.wiki.testpages._replay(str name, dict[str, Any] ctx)
A link to the test's flow, and whether a recorded run is drawn on it.
Source · 15 lines
def _replay(name: str, ctx: dict[str, Any]) -> str:
"""A PACKAGED RUN IS REPLAYED ON THE FLOW (owner 2026-11-16: "take run results/logs that were
included/packaged with it and replay them"): the expected calls, the calls the run made, and
each assertion as a checkpoint where it was checked — red at the one that failed.
@brief Replay link.
@return HTML.
"""
page = (ctx.get("flow_of") or {}).get(name)
if not page or name not in (ctx.get("traced") or set()):
return ""
words = "Replay its recorded run on its flow: the calls it made and each check, in order"
return f'<p class="replay"><a href="{escape(page)}.html">{words} →</a></p>'
Activity · 5 steps
Flows
_slice_groups
list[tuple[str, str]] clew.wiki.testpages._slice_groups(str name, dict slices, list[str] files)
Which of a name's per-test keys belong to which of its definitions' files.
Source · 22 lines
def _slice_groups(name: str, slices: dict, files: list[str]) -> list[tuple[str, str]]:
"""BY PATH SUFFIX, EITHER WAY: a pytest node id's file is relative to pytest's rootdir, which
need not be the repository root, so `tests/test_a.py` and `pkg/tests/test_a.py` are one file.
NOTHING IS DROPPED: a key matching no definition (an LCOV `TN:` name, a node id from another
rootdir) is drawn for the page as a whole, as every key was before W11.
@brief Group a name's keys by definition.
@return Groups.
"""
from .slices import test_name
keys = sorted(k for k in slices if test_name(k) == name and slices[k])
out: list[tuple[str, str]] = []
for file in dict.fromkeys(files):
for key in keys:
where = key.rsplit("::", 1)[0] if "::" in key else ""
if where and (file.endswith(where) or where.endswith(file)):
out.append((file, key))
claimed = {k for _f, k in out}
return out + [("", k) for k in keys if k not in claimed]
Activity · 10 steps
Flows
_slices_html
str clew.wiki.testpages._slices_html(str key, list cuts, int drawn=_SLICES_DRAWN)
One test key's slices: the first few drawn, the rest linked.
Source · 29 lines
def _slices_html(key: str, cuts: list, drawn: int = _SLICES_DRAWN) -> str:
"""OWNER Q/A 2026-11-20 (after P6): the top `drawn` slices are drawn; the rest are a
`<details>` "N more", each linking its whole flow lit for this test — the V1–V6 pattern. The
slices arrive most steps first.
@brief Draw one key's slices.
@return HTML.
"""
from urllib.parse import quote
from . import slices
def heading(page: Any, cut: Any) -> str:
href = f"{page.name}.html#test={quote(key)}"
return (
f'<a href="{escape(href)}">{escape(page.title)}</a> · {len(cut.exercised)} of '
f"{page.steps} steps"
)
parts = [f"<h4>{heading(p, c)}</h4>{slices.slice_svg(p.flow, c)}" for p, c in cuts[:drawn]]
rest = cuts[drawn:]
if rest:
items = "".join(f"<li>{heading(p, c)}</li>" for p, c in rest)
parts.append(
f'<details class="more-slices"><summary>{len(rest)} more</summary><ul>{items}</ul></details>'
)
return "".join(parts)
Activity · 9 steps
Flows
_test_definitions
list[Definition] clew.wiki.testpages._test_definitions(object conn, set[str]|None names)
Every definition, in test code, of a test the evidence names — by framework.
Source · 37 lines
def _test_definitions(conn: object, names: set[str] | None) -> list[Definition]:
"""RESOLVED AS THE EVIDENCE RESOLVES THEM (`frameworks.recognise_test`): a Catch2 `SCENARIO` /
`TEST_CASE`, a GoogleTest `TEST`, a Boost case is a macro row in the index, named by its
string. Found on entropic: 2,009 Catch2 tests and 11 pages, because only functions literally
named after the test were looked for. Test code only — a namesake in product code is not it.
@brief Resolve tests to definitions.
@return Definitions.
"""
from .frameworks import TestRecognizer
if names is not None and not names or not table_exists(conn, "test_scope"):
return []
rows = conn.execute(
"SELECT m.rowid, m.name, COALESCE(m.argsstring, ''), p.name, m.definition, "
"m.briefdescription, m.bodystart, m.bodyend, m.line FROM memberdef m JOIN path p "
"ON p.rowid = COALESCE(NULLIF(m.bodyfile_id, 0), m.file_id) WHERE m.kind = 'function' "
"AND p.rowid IN (SELECT path_rowid FROM test_scope) ORDER BY p.name, m.line"
)
out = []
for rowid, name, args, rel, definition, brief, start, end, line in rows:
test = TestRecognizer.for_conn(conn)(str(name), str(args), str(rel))
if test and (names is None or test[0] in names):
out.append(
Definition(
int(rowid),
test[0],
str(rel),
f"{definition or ''}{args or ''}".strip(),
re.sub(r"<[^>]+>", " ", str(brief or "")).strip(),
int(start or line or 0),
int(end or 0),
)
)
return out
Activity · 10 steps
Requirements
Flows
test_page_of
str clew.wiki.testpages.test_page_of(str name, str rel)
The page name of a test.
Source · 5 lines
def test_page_of(name: str, rel: str) -> str:
"""@brief Page name. @return Name."""
return "test-" + re.sub(r"[^A-Za-z0-9_]+", "-", f"{rel}-{name}").strip("-")
Activity · 1 steps
Requirements
Flows
test_pages
dict[str, str] clew.wiki.testpages.test_pages(Path db, Path repo_root, dict[str, Any] ctx, Path source)
Write a page per test the evidence names.
Called by _build_site
Calls _briefs, _exercises, _replay, _test_definitions, connect, load_modes, test_page_of
Source · 57 lines
def test_pages(db: Path, repo_root: Path, ctx: dict[str, Any], source: Path) -> dict[str, str]:
"""ONE PAGE PER NAME: every definition of a test name in test code is drawn on it, so a link
from a requirement never has to know which of two namesakes it meant.
@brief Write test-*.md.
@return Hrefs.
"""
from .testfacts import TestFacts
## OWNER Q/A 2026-11-20: `linked` (default) is the tests the evidence names, implicit links
## included; `all` adds every recognised test; `none` writes no per-test page.
mode = ctx.get("test_pages", "linked")
if mode == "none":
return {}
from .entities import _briefs
with connect(db) as conn:
defs = _test_definitions(conn, None if mode == "all" else set(ctx["tests"]))
graph = _Edges(conn)
## X-3: what each function does, for the call-flow boxes.
ctx = {**ctx, "briefs": _briefs(conn)}
## 2.2: each test's declared failure modes, for its flowchart.
from .flowchart import load_modes
ctx = {**ctx, "modes": load_modes(conn)}
## An unlinked test (only under `all`) has no evidence facts: absent, no requirement.
ctx = {**ctx, "tests": {**{d.name: TestFacts() for d in defs}, **ctx["tests"]}}
by_name: dict[str, list] = defaultdict(list)
for d in defs:
by_name[d.name].append(d)
hrefs = {}
for name, ds in sorted(by_name.items()):
page = test_page_of(name, ds[0].file)
body = "".join(_definition(d, graph, ctx, Path(repo_root)) for d in ds)
text = [
"---",
"orphan: true",
"---",
"",
f"# {name}",
"",
"```{raw} html",
## E-21: the trail this page sits in — Tests › its file — not Requirements.
f'<p class="crumbs"><a href="tests.html">Tests</a> › <code>{escape(ds[0].file)}</code></p>',
f'<div class="test-page">{_result(name, ctx)}{_replay(name, ctx)}'
## OWNER REVIEW 3: WHY it exists and WHAT it checks, before anything it ran.
f"{''.join(_card(d, graph, ctx, Path(repo_root)) for d in ds)}"
f"{_exercises(name, ctx, ds)}{body}"
f"{_requirements(name, ctx)}</div>",
"```",
"",
]
(Path(source) / f"{page}.md").write_text("\n".join(text), encoding="utf-8")
hrefs[name] = f"{page}.html"
return hrefs
Activity · 23 steps
Requirements
Flows
tests_index
str clew.wiki.testpages.tests_index(Path db, dict[str, Any] ctx, dict[str, str] hrefs, Path source)
Write the Tests tab: every test the index recognises, linked to its page, filterable.
Called by _build_site
Calls _result_chips, _status, _test_definitions, _tests_groups, connect
Source · 37 lines
def tests_index(db: Path, ctx: dict[str, Any], hrefs: dict[str, str], source: Path) -> str:
"""TESTS ARE THEIR OWN CATEGORY (owner Q/A 2026-11-20): every recognised test, linked or not,
with its file, result and how many requirements it is linked to (implicit links included).
The main search leaves this table and the test pages out; the filter box here is the search
for tests (`clew-views.js`).
@brief Write tests.md.
@return Page name.
"""
with connect(db) as conn:
defs = _test_definitions(conn, None)
results = ctx.get("results") or {}
facts = ctx.get("tests") or {}
counts: dict[str, int] = {}
for d in defs:
status = _status(d, results)
counts[status] = counts.get(status, 0) + 1
lines = [
"# Tests",
"",
f"{len(defs)} tests the index recognises; {len(hrefs)} have a page of their own. Type to "
"filter by name, file, result or requirement count.",
"",
"```{raw} html",
## UX review D-8 (owner Q/A 2026-11-22): result chips, then one collapsed group per file.
_result_chips(counts),
'<input type="search" class="filter" data-filter-table="tests-all" '
'placeholder="Filter tests" aria-label="Filter tests">',
_tests_groups(defs, results, facts, hrefs),
'<script src="_static/clew-views.js"></script>',
"```",
"",
]
(Path(source) / "tests.md").write_text("\n".join(lines), encoding="utf-8")
return "tests"