testfacts.py

clew/wiki/testfacts.py

What a test tests (round 3, P2a).

_context

list[str] clew.wiki.testfacts._context(list[str] lines, int at)

The Feature and Rule lines (with their tags) above a scenario.

clew/wiki/testfacts.py:146

Source · 14 lines
def _context(lines: list[str], at: int) -> list[str]:
    """@brief Heading lines. @return Lines."""
    keep: list[str] = []
    for i in range(at):
        match = _BLOCK.match(lines[i].strip())
        if match and match.group(1) in ("Feature", "Rule"):
            if match.group(1) == "Feature":
                keep = []
            keep = [k for k in keep if not _is_rule(k)] if match.group(1) == "Rule" else keep
            keep += _tags_above(lines, i) + [lines[i]]
    tags = _tags_above(lines, at)
    return keep + tags

Activity · 10 steps
lines 148–148keep: list[str] = []lines 149–149◇ for i in range(at)lines 150–150match = _BLOCK.match(lines[i].strip())lines 151–151◇ if match and match.group(1) in ("Feature", "Rule")lines 152–152◇ if match.group(1) == "Feature"lines 153–153keep = []lines 154–154keep = [k for k in keep if not _is_rule(k)] if match.group(1) == "Rule" else keeplines 155–155keep += _tags_above(lines, i) + [lines[i]]lines 156–156tags = _tags_above(lines, at)lines 157–157return keep + tags

Flows

_is_rule

bool clew.wiki.testfacts._is_rule(str line)

Whether a line opens a Rule.

clew/wiki/testfacts.py:165

Show on the map →

Called by _context

Calls none

Source · 5 lines
def _is_rule(line: str) -> bool:
    """@brief Rule? @return Bool."""
    return line.strip().startswith("Rule:")

Activity · 1 steps
lines 167–167return line.strip().startswith("Rule:")

Flows

_scenario_end

int clew.wiki.testfacts._scenario_end(list[str] lines, int at)

How many lines the scenario at at spans.

clew/wiki/testfacts.py:192

Source · 18 lines
def _scenario_end(lines: list[str], at: int) -> int:
    """THE NEXT SCENARIO, RULE OR FEATURE ends it — and the tag lines just above that block
    belong to it, not to this scenario.

    @brief Span.
    @return Count.
    """
    end = len(lines)
    for i in range(at + 1, len(lines)):
        match = _BLOCK.match(lines[i].strip())
        if match and match.group(1) not in ("Examples", "Scenarios"):
            end = i
            break
    while end > at + 1 and lines[end - 1].strip().startswith("@"):
        end -= 1
    return end - at

Activity · 9 steps
lines 199–199end = len(lines)lines 200–200◇ for i in range(at + 1, len(lines))lines 201–201match = _BLOCK.match(lines[i].strip())lines 202–202◇ if match and match.group(1) not in ("Examples", "Scenarios")lines 203–203end = ilines 204–204breaklines 205–205◇ while end > at + 1 and lines[end - 1].strip().startswith("@")lines 206–206end -= 1lines 207–207return end - at

Flows

_tags_above

list[str] clew.wiki.testfacts._tags_above(list[str] lines, int at)

The tag lines directly above a line.

clew/wiki/testfacts.py:176

Show on the map →

Called by _context

Calls none

Source · 10 lines
def _tags_above(lines: list[str], at: int) -> list[str]:
    """@brief Tags. @return Lines."""
    out = []
    i = at - 1
    while i >= 0 and lines[i].strip().startswith("@"):
        out.insert(0, lines[i])
        i -= 1
    return out

Activity · 6 steps
lines 178–178out = []lines 179–179i = at - 1lines 180–180◇ while i >= 0 and lines[i].strip().startswith("@")lines 181–181out.insert(0, lines[i])lines 182–182i -= 1lines 183–183return out

Flows

assertions

list[str] clew.wiki.testfacts.assertions(list[str] lines)

The assertion statements in a body, per framework, each read whole.

clew/wiki/testfacts.py:95

Show on the map →

Called by _checkpoints, _definition, _test_block

Tested by

1 teststest_assertions_are_read_per_framework

Calls none

Source · 24 lines
def assertions(lines: list[str]) -> list[str]:
    """A STATEMENT OPEN AT ITS LINE'S END continues: lines are joined while parentheses are
    unbalanced, at most `_MAX_SPAN` lines — never into the next statement.

    @brief Read assertions.
    @return Statements.
    """
    out, i = [], 0
    while i < len(lines):
        if not _ASSERT.match(lines[i]):
            i += 1
            continue
        parts, depth, j = [], 0, i
        while j < len(lines) and j < i + _MAX_SPAN:
            parts.append(lines[j].strip())
            depth += lines[j].count("(") - lines[j].count(")")
            j += 1
            if depth <= 0:
                break
        out.append(" ".join(" ".join(parts).replace("( ", "(").split()))
        i = j
    return out

Activity · 15 steps
lines 102–102out, i = [], 0lines 103–103◇ while i < len(lines)lines 104–104◇ if not _ASSERT.match(lines[i])lines 105–105i += 1lines 106–106continuelines 107–107parts, depth, j = [], 0, ilines 108–108◇ while j < len(lines) and j < i + _MAX_SPANlines 109–109parts.append(lines[j].strip())lines 110–110depth += lines[j].count("(") - lines[j].count(")")lines 111–111j += 1lines 112–112◇ if depth <= 0lines 113–113breaklines 114–114out.append(" ".join(" ".join(parts).replace("( ", "(").split()))lines 115–115i = jlines 116–116return out

Requirements

REQ-DDB-WIKI-026

Flows

feature_pages

dict[tuple[str, str], str] clew.wiki.testfacts.feature_pages(Path repo_root, list scenarios, dict[str, TestFacts] facts, Path source)

Write a page per feature file, a section per scenario the site's tests name.

clew/wiki/testfacts.py:286

Source · 39 lines
def feature_pages(
    repo_root: Path, scenarios: list, facts: dict[str, TestFacts], source: Path
) -> dict[tuple[str, str], str]:
    """@brief Write feature pages. @return Hrefs."""
    from .symbols import anchor, page_for, symbol_href

    by_file: dict[str, list] = {}
    for sc in scenarios:
        by_file.setdefault(sc.file, []).append(sc)
    written: dict[tuple[str, str], str] = {}
    for rel, items in sorted(by_file.items()):
        try:
            text = (Path(repo_root) / rel).read_text(encoding="utf-8", errors="replace")
        except OSError:
            continue
        sections = []
        for sc in items:
            f = facts.get(sc.test_id, TestFacts())
            sections.append(
                f'<section class="symbol" id="{anchor(sc.name)}"><h2>{escape(sc.name)}</h2>'
                f"{verifies_block(f, {})}{render_scenario(text, sc.line)}</section>"
            )
            written[(sc.test_id, rel)] = symbol_href(sc.name, rel)
        page = [
            "---",
            "orphan: true",
            "---",
            "",
            f"# `{rel}`",
            "",
            "```{raw} html",
            *sections,
            "```",
            "",
        ]
        (Path(source) / f"{page_for(rel)}.md").write_text("\n".join(page), encoding="utf-8")
    return written

Activity · 18 steps
lines 290–290from .symbols import anchor, page_for, symbol_hreflines 292–292by_file: dict[str, list] = {}lines 293–293◇ for sc in scenarioslines 294–294by_file.setdefault(sc.file, []).append(sc)lines 295–295written: dict[tuple[str, str], str] = {}lines 296–296◇ for rel, items in sorted(by_file.items())lines 297–297trylines 298–298text = (Path(repo_root) / rel).read_text(encoding="utf-8", errors="replace")lines 299–299except OSErrorlines 300–300continuelines 301–301sections = []lines 302–302◇ for sc in itemslines 303–303f = facts.get(sc.test_id, TestFacts())lines 304–307sections.append( f'<section class="symbol" id="{anchor(sc.name)}"><h2>{escape(sc.name)}</h2>' f"{verifies_block(f, {})}{render_scenario(text, sc.line)}</section>" )lines 308–308written[(sc.test_id, rel)] = symbol_href(sc.name, rel)lines 309–320page = [ "---", "orphan: true", "---", "", f"# `{rel}`", "", "```{raw} html", *sections, "```", "", ]lines 321–321(Path(source) / f"{page_for(rel)}.md").write_text("\n".join(page), encoding="utf-8")lines 322–322return written

Requirements

REQ-DDB-WIKI-026

Flows

gather

dict[str, TestFacts] clew.wiki.testfacts.gather(list evidence)

Invert the evidence: each test's status, requirements and mutation outcomes.

clew/wiki/testfacts.py:60

Source · 12 lines
def gather(evidence: list) -> dict[str, TestFacts]:
    """@brief Facts per test. @return Map."""
    out: dict[str, TestFacts] = {}
    for row in evidence:
        for test, status in row.tests:
            facts = out.setdefault(test, TestFacts(status=status))
            facts.verifies.append((row.req_id, link_kind(row, test)))
        for mechanism, test, outcome in row.mutations or ():
            out.setdefault(test, TestFacts()).mutations.append((mechanism, outcome))
    return out

Activity · 8 steps
lines 62–62out: dict[str, TestFacts] = {}lines 63–63◇ for row in evidencelines 64–64◇ for test, status in row.testslines 65–65facts = out.setdefault(test, TestFacts(status=status))lines 66–66facts.verifies.append((row.req_id, link_kind(row, test)))lines 67–67◇ for mechanism, test, outcome in row.mutations or ()lines 68–68out.setdefault(test, TestFacts()).mutations.append((mechanism, outcome))lines 69–69return out

Requirements

REQ-DDB-WIKI-026

Flows

render_scenario

str clew.wiki.testfacts.render_scenario(str text, int line)

One scenario of a feature file, rendered as Gherkin with its Feature and Rule.

clew/wiki/testfacts.py:125

Source · 15 lines
def render_scenario(text: str, line: int) -> str:
    """THE SCENARIO IN ITS CONTEXT: the Feature line and the Rule it sits under head it, with
    their tags; the scenario runs until the next block at its level.

    @brief Render Gherkin.
    @return HTML.
    """
    lines = text.splitlines()
    head = _context(lines, line - 1)
    body = []
    for raw in lines[line - 1 :][: _scenario_end(lines, line - 1)]:
        body.append(raw)
    return f'<div class="gherkin">{_render(head + body)}</div>'

Activity · 6 steps
lines 132–132lines = text.splitlines()lines 133–133head = _context(lines, line - 1)lines 134–134body = []lines 135–135◇ for raw in lines[line - 1 :][: _scenario_end(lines, line - 1)]lines 136–136body.append(raw)lines 137–137return f'<div class="gherkin">{_render(head + body)}</div>'

Requirements

REQ-DDB-WIKI-026

Flows

verifies_block

str clew.wiki.testfacts.verifies_block(TestFacts facts, dict[str, list[str]] paths)

A test's result, the requirements it verifies (with the call path to an implementer when one is known) and its mutation outcomes.

clew/wiki/testfacts.py:332

Source · 23 lines
def verifies_block(facts: TestFacts, paths: dict[str, list[str]]) -> str:
    """@brief Verifies block. @return HTML."""
    from .htmltable import tag

    rows = "".join(
        f'<tr><td><a class="req-badge" href="requirements.html#{escape(r)}">{escape(r)}</a></td>'
        f'<td><span class="via via-{kind}">{kind}</span></td>'
        f"<td>{' → '.join(f'<code>{escape(n)}</code>' for n in paths.get(r, []))}</td></tr>"
        for r, kind in facts.verifies
    )
    out = f'<p class="result">Result: {tag(facts.status)}</p>'
    if rows:
        out += (
            '<h4>Verifies</h4><table class="verifies"><thead><tr><th>requirement</th><th>linked'
            f"</th><th>path to the implementer</th></tr></thead><tbody>{rows}</tbody></table>"
        )
    if facts.mutations:
        out += (
            '<h4>Mutations</h4><ul class="modal-list">'
            + "".join(f"<li><code>{escape(m)}</code> {escape(o)}</li>" for m, o in facts.mutations)
            + "</ul>"
        )
    return out

1 more lines, not shown

Activity · 8 steps
lines 334–334from .htmltable import taglines 336–341rows = "".join( f'<tr><td><a class="req-badge" href="requirements.html#{escape(r)}">{escape(r)}</a></td>' f'<td><span class="via via-{kind}">{kind}</span></td>' f"<td>{' → '.join(f'<code>{escape(n)}</code>' for n in paths.get(r, []))}</td></tr>" for r, kind in facts.verifies )lines 342–342out = f'<p class="result">Result: {tag(facts.status)}</p>'lines 343–343◇ if rowslines 344–347out += ( '<h4>Verifies</h4><table class="verifies"><thead><tr><th>requirement</th><th>linked' f"</th><th>path to the implementer</th></tr></thead><tbody>{rows}</tbody></table>" )lines 348–348◇ if facts.mutationslines 349–353out += ( '<h4>Mutations</h4><ul class="modal-list">' + "".join(f"<li><code>{escape(m)}</code> {escape(o)}</li>" for m, o in facts.mutations) + "</ul>" )lines 354–354return out

Requirements

REQ-DDB-WIKI-026

Flows