Files
FabledGrimoire/tests/test_test_guards.py
T
bvandeusenandClaude Opus 5.5 dc9e88aa6d
CI & Build / TypeScript typecheck (push) Successful in 37s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 2m24s
CI & Build / integration (push) Successful in 2m22s
CI & Build / Build & push image (push) Successful in 43s
feat(8247): a test case is accounted for by what it guards, and the coverage line counts the suite by it
A refresh now stamps a test case `test` when it is linked to something it
guards, and withdraws the stamp when its links go; a judgment always wins. A
test case linked to nothing stays in the todo, because nothing says what it is
for. Specs written as it()/test() calls get one ledger row per file, read
whole. The coverage line and card count tests linked, guarding nothing found,
and redundant, and the end-of-turn question no longer asks the writer to call
a test case a one-off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:57:57 -05:00

200 lines
9.2 KiB
Python

"""What a test guards, read from the repo, and the verdicts that act on it.
The coverage refresh links every test (a test-named definition in a test
file) to the product shapes its body exercises, so the ledger can show tests
in different files that guard exactly the same thing. These pin the reading
rules: what counts as a reference, what does not, and how groups form.
"""
from __future__ import annotations
from grimoire.services import shape_ledger
from grimoire.services import test_guards as tg
from grimoire.services.coverage import coverage_line
PRODUCT = [
tg.Def("src/app/billing.py", "charge", "def charge(amount):\n return amount\n"),
tg.Def("src/app/billing.py", "refund", "def refund(amount):\n return -amount\n"),
tg.Def("src/app/runner.py", "run", "def run():\n pass\n"),
]
def _test(path: str, name: str, body: str) -> tg.Def:
return tg.Def(path, name, f"def {name}():\n{body}")
def _links(*tests: tg.Def, files: dict[str, str] | None = None, paths=()):
files = files or {}
read = {p: tg.read_test_file(text) for p, text in files.items()}
return tg.link_tests([*PRODUCT, *tests], read, paths)
IMPORTS = "from app import billing as b\nfrom app.billing import charge\n"
def test_a_test_file_is_recognised_by_its_directory_or_its_name():
for path in ("tests/test_x.py", "pkg/x_test.go", "web/src/a.spec.ts",
"web/src/__tests__/a.ts", "src/FooTest.java"):
assert tg.is_test_path(path), path
for path in ("src/app/billing.py", "src/contest.py", "web/src/latest.ts"):
assert not tg.is_test_path(path), path
def test_a_call_through_the_modules_alias_links_the_test_to_it():
t = _test("tests/test_a.py", "test_pays", " assert b.charge(3) == 3\n")
links = _links(t, files={"tests/test_a.py": IMPORTS})
assert links.shapes[("tests/test_a.py", "test_pays")] == {("src/app/billing.py", "charge")}
def test_a_call_on_something_else_with_a_product_name_does_not_link():
# `subprocess.run` shares a name with app.runner.run, and is not it.
t = _test("tests/test_a.py", "test_shells_out", " subprocess.run(['x'])\n")
links = _links(t, files={"tests/test_a.py": "import subprocess\nfrom app import runner\n"})
assert links.shapes[("tests/test_a.py", "test_shells_out")] == set()
def test_a_bare_name_links_only_when_the_file_imports_it():
t = _test("tests/test_a.py", "test_pays", " assert charge(3) == 3\n refund(1)\n")
links = _links(t, files={"tests/test_a.py": IMPORTS})
# charge is imported by name; refund is not, so a bare `refund` is not it.
assert links.shapes[("tests/test_a.py", "test_pays")] == {("src/app/billing.py", "charge")}
def test_a_mocked_function_is_not_guarded():
body = (
" with patch('app.billing.refund'):\n"
" b.charge(1)\n"
" b.refund(1)\n"
)
t = _test("tests/test_a.py", "test_pays", body)
links = _links(t, files={"tests/test_a.py": IMPORTS})
assert links.shapes[("tests/test_a.py", "test_pays")] == {("src/app/billing.py", "charge")}
def test_reach_follows_a_helper_in_another_test_file():
helper = tg.Def("tests/helpers.py", "_pay", "def _pay():\n return b.charge(1)\n")
t = _test("tests/test_a.py", "test_pays_via_helper", " assert _pay() == 1\n")
links = _links(helper, t, files={
"tests/helpers.py": "from app import billing as b\n",
"tests/test_a.py": "from tests.helpers import _pay\n",
})
assert links.shapes[("tests/test_a.py", "test_pays_via_helper")] == {
("src/app/billing.py", "charge"),
}
def test_a_go_test_reaches_its_own_package_without_an_import():
code = tg.Def("pkg/bill/bill.go", "Charge", "func Charge(n int) int {\n\treturn n\n}\n")
t = tg.Def("pkg/bill/bill_test.go", "TestCharge",
"func TestCharge(t *testing.T) {\n\tif Charge(1) != 1 { t.Fail() }\n}\n")
links = tg.link_tests([code, t], {"pkg/bill/bill_test.go": tg.read_test_file("")})
assert links.shapes[("pkg/bill/bill_test.go", "TestCharge")] == {("pkg/bill/bill.go", "Charge")}
def test_a_shape_reached_from_most_test_files_is_a_hub_and_drops_out():
files, tests = {}, []
for i in range(10):
path = f"tests/test_{i}.py"
files[path] = IMPORTS
# Every file reaches charge; only one reaches refund.
tests.append(_test(path, "test_x", " b.charge(1)\n" + (" b.refund(1)\n" if i == 0 else "")))
links = _links(*tests, files=files)
assert ("src/app/billing.py", "charge") in links.hubs
assert links.shapes[("tests/test_0.py", "test_x")] == {("src/app/billing.py", "refund")}
assert links.shapes[("tests/test_5.py", "test_x")] == set()
def test_a_string_naming_a_repo_file_links_the_test_to_that_path():
t = _test("tests/test_a.py", "test_reads_the_script",
" text = open('scripts/release.sh').read()\n assert 'x' in text\n")
links = _links(t, files={"tests/test_a.py": ""},
paths=["scripts/release.sh", "src/app/billing.py"])
assert links.paths[("tests/test_a.py", "test_reads_the_script")] == {"scripts/release.sh"}
def test_weak_signals_are_read_from_the_body():
assert tg.test_signals(" params = inspect.signature(f).parameters\n assert params\n") == ["signature"]
assert tg.test_signals(" f()\n mock.assert_called_once()\n") == ["mock-only"]
# A plain assert beside a mock check is a real check, so no signal.
assert tg.test_signals(" f()\n mock.assert_called_once()\n assert out == 1\n") == []
assert tg.test_signals(" text = path.read_text()\n assert 'x' in text\n") == ["source-text"]
def test_a_group_spans_files_and_one_file_never_forms_one():
same = frozenset({1, 2})
groups = tg.same_guard_groups([
(10, "tests/test_a.py", same),
(11, "tests/test_b.py", same),
(12, "tests/test_c.py", frozenset({3})),
(13, "tests/test_c.py", frozenset({3})),
(14, "tests/test_d.py", frozenset()),
])
assert groups == [(same, [10, 11])]
def test_a_group_is_named_by_its_members_in_any_order():
a = tg.group_key([("tests/a.py", "test_1"), ("tests/b.py", "test_2")])
assert a == tg.group_key([("tests/b.py", "test_2"), ("tests/a.py", "test_1")])
# A test joining the group makes it a new group, back in front of a reviewer.
assert a != tg.group_key([("tests/a.py", "test_1"), ("tests/b.py", "test_2"), ("tests/c.py", "test_3")])
def _item(**over):
base = {"path": "tests/test_a.py", "symbol": "test_x", "status": "redundant",
"reason": "test_y checks the same call and more",
"covered_by": {"path": "tests/test_b.py", "symbol": "test_y"}}
base.update(over)
return base
def test_a_redundant_verdict_names_its_cover_and_its_reason():
assert shape_ledger.validate_classifications([_item()]) is None
assert "covered_by" in shape_ledger.validate_classifications([_item(covered_by=None)])
assert "reason" in shape_ledger.validate_classifications([_item(reason="")])
assert "itself" in shape_ledger.validate_classifications(
[_item(covered_by={"path": "tests/test_a.py", "symbol": "test_x"})]
)
def test_an_unused_verdict_needs_a_reason():
item = {"path": "src/a.py", "symbol": "f", "status": "unused"}
assert "reason" in shape_ledger.validate_classifications([item])
assert shape_ledger.validate_classifications([{**item, "reason": "nothing calls it"}]) is None
def test_the_coverage_line_names_the_removal_verdicts_and_the_test_groups():
line = coverage_line({
"accounted": 10, "total": 10, "unclassified": 0,
"counts": {"exempt": 7, "redundant": 2, "unused": 1},
"test_groups": 3, "computed_at": "2026-12-01T00:00:00+00:00",
})
assert "2 redundant" in line and "1 unused" in line
assert "3 test groups guarding the same thing" in line
def test_a_test_case_is_a_test_named_definition_or_a_call_style_spec_file():
assert tg.is_test_case("tests/test_a.py", "test_x", "sym")
assert not tg.is_test_case("tests/test_a.py", "_helper", "sym")
assert not tg.is_test_case("src/app/billing.py", "test_mode", "sym")
assert tg.is_test_case("web/src/a.spec.ts", "a.spec", "file")
def test_a_spec_written_as_calls_is_one_test_and_links_by_its_imports():
text = "import { charge } from '../app/billing'\n\nit('charges', () => {\n expect(charge(1)).toBe(1)\n})\n"
assert tg.is_call_style_spec("web/src/billing.spec.ts", text, [])
# A file that defines test-named functions is read per function instead.
assert not tg.is_call_style_spec("tests/test_a.py", "def test_x():\n pass\n", ["test_x"])
spec = tg.Def("web/src/billing.spec.ts", "billing.spec", text)
product = tg.Def("web/app/billing.ts", "charge", "export function charge(n) {\n return n\n}\n")
links = tg.link_tests([product], {spec.path: tg.read_test_file(text)}, file_tests=[spec])
assert links.shapes[(spec.path, "billing.spec")] == {("web/app/billing.ts", "charge")}
def test_the_coverage_line_counts_tests_by_what_they_guard():
line = coverage_line({
"accounted": 10, "total": 12, "unclassified": 2, "counts": {"test": 8},
"tests": {"linked": 8, "unlinked": 2, "redundant": 1},
"computed_at": "2026-12-01T00:00:00+00:00",
})
assert "8 test" in line
assert "tests: 8 linked · 2 guarding nothing found · 1 redundant" in line