feat(8247): a test case is accounted for by what it guards, and the coverage line counts the suite by it
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
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
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>
This commit is contained in:
@@ -722,6 +722,14 @@ def scan_archive(blob: bytes) -> ArchiveScan:
|
||||
references[path] = refs
|
||||
if test_guards.is_test_path(path):
|
||||
test_files[path] = test_guards.read_test_file(text)
|
||||
# A spec whose cases are calls gets one row of its own, the
|
||||
# whole file as its body, so the linker can read what it
|
||||
# guards.
|
||||
if test_guards.is_call_style_spec(path, text, (d.name for d in defs)) \
|
||||
and not any(d.name == file_stem(path) for d in defs):
|
||||
shapes.append(ArchiveShape(
|
||||
path, "file", file_stem(path), f"file {path}", "", text,
|
||||
))
|
||||
return ArchiveScan(shapes, references, tuple(paths), test_files)
|
||||
|
||||
|
||||
@@ -864,6 +872,10 @@ async def compute_coverage(
|
||||
links = test_guards.link_tests(
|
||||
[test_guards.Def(d.path, d.name, d.body) for d in definitions if d.kind == "sym"],
|
||||
scan.test_files or {}, scan.paths,
|
||||
file_tests=[
|
||||
test_guards.Def(d.path, d.name, d.body) for d in definitions
|
||||
if d.kind == "file" and d.body and test_guards.is_test_path(d.path)
|
||||
],
|
||||
)
|
||||
await test_guards.sync_repo_guards(project_id, key, links)
|
||||
except Exception:
|
||||
@@ -932,7 +944,7 @@ async def compute_coverage(
|
||||
# repo that was unreachable today still has live rows, and they count.
|
||||
rows = await shape_ledger.live_rows(project_id)
|
||||
counts = {"canonical": 0, "instance": 0, "variant": 0, "exempt": 0,
|
||||
"redundant": 0, "unused": 0, "scoped": 0, "unclassified": 0}
|
||||
"redundant": 0, "unused": 0, "scoped": 0, "test": 0, "unclassified": 0}
|
||||
for row in rows:
|
||||
counts[row.status] = counts.get(row.status, 0) + 1
|
||||
by_repo: dict[str, dict[str, int]] = {}
|
||||
@@ -976,9 +988,10 @@ async def compute_coverage(
|
||||
from grimoire.services import test_guards
|
||||
|
||||
test_groups = (await test_guards.guard_groups(project_id, top=0))["count"]
|
||||
tests = await test_guards.test_summary(project_id)
|
||||
except Exception:
|
||||
logger.warning("test guard groups read failed", exc_info=True)
|
||||
test_groups = 0
|
||||
test_groups, tests = 0, None
|
||||
# The write-time figure: how often the end-of-turn
|
||||
# question was put on this project, and how often it was walked past.
|
||||
# An audit reads the ledger; this reads whether the reflex held.
|
||||
@@ -1008,6 +1021,8 @@ async def compute_coverage(
|
||||
"unused_css": unused_css,
|
||||
# Same-guard test groups awaiting a verdict (test_guard_groups).
|
||||
"test_groups": test_groups,
|
||||
# The suite by what it protects: {linked, unlinked, redundant}.
|
||||
"tests": tests,
|
||||
"proposer": proposer_stats,
|
||||
# The divergence readout: new shapes where a different canon
|
||||
# dominates, and judged shapes whose bodies moved since they were
|
||||
@@ -1152,7 +1167,8 @@ def coverage_line(coverage: dict) -> str:
|
||||
counts = coverage.get("counts") or {}
|
||||
breakdown = " · ".join(
|
||||
f"{counts[k]} {k}"
|
||||
for k in ("canonical", "instance", "variant", "exempt", "redundant", "unused", "scoped")
|
||||
for k in ("canonical", "instance", "variant", "exempt", "redundant", "unused",
|
||||
"scoped", "test")
|
||||
if counts.get(k)
|
||||
)
|
||||
line = (
|
||||
@@ -1217,6 +1233,12 @@ def coverage_line(coverage: dict) -> str:
|
||||
line += ", largest: " + ", ".join(gaps)
|
||||
elif standing:
|
||||
line += f"; standing: {', '.join(standing)}"
|
||||
tests = coverage.get("tests") or {}
|
||||
if any(tests.values()):
|
||||
line += (
|
||||
f"; tests: {tests.get('linked', 0)} linked · {tests.get('unlinked', 0)} "
|
||||
f"guarding nothing found · {tests.get('redundant', 0)} redundant"
|
||||
)
|
||||
if coverage.get("recheck"):
|
||||
line += f"; {coverage['recheck']} judged shape{'s' if coverage['recheck'] != 1 else ''} changed since judged — recheck"
|
||||
# Rows the hook asserted on evidence below the ledger's floor. They do
|
||||
|
||||
@@ -3035,8 +3035,15 @@ async def unjudged_shapes(
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(query)).scalars().all()
|
||||
by_key = {(r.path, r.kind, r.symbol): r for r in rows}
|
||||
from grimoire.services.test_guards import is_test_case
|
||||
|
||||
out: list[dict] = []
|
||||
for path, kind, name in wanted:
|
||||
# A test case is accounted for by what it guards: the refresh links
|
||||
# it and stamps it `test`, so the writer is not asked to call it a
|
||||
# one-off.
|
||||
if is_test_case(path, name, kind):
|
||||
continue
|
||||
row = by_key.get((path, kind, name))
|
||||
if row is not None and _is_judged(row):
|
||||
continue
|
||||
|
||||
@@ -39,6 +39,7 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
import re
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timezone
|
||||
from typing import Iterable, NamedTuple
|
||||
|
||||
# Directory names that hold tests, in the conventions the ledger meets.
|
||||
@@ -89,6 +90,28 @@ def is_test_name(name: str) -> bool:
|
||||
return bool(_TEST_NAME_RE.match(name))
|
||||
|
||||
|
||||
# A spec written as calls — `it("…", …)`, `test("…", …)` — defines no
|
||||
# test-named function, so the file is the unit: one ledger row per spec.
|
||||
_TEST_CALL_RE = re.compile(r"^\s*(?:it|test)(?:\.\w+)?\s*\(", re.MULTILINE)
|
||||
|
||||
|
||||
def is_call_style_spec(path: str, text: str, names: Iterable[str]) -> bool:
|
||||
"""A test file whose cases are calls, not definitions."""
|
||||
return (
|
||||
is_test_path(path)
|
||||
and not any(is_test_name(n) for n in names)
|
||||
and _TEST_CALL_RE.search(text) is not None
|
||||
)
|
||||
|
||||
|
||||
def is_test_case(path: str, symbol: str, kind: str) -> bool:
|
||||
"""Is this ledger row a test case: a test-named definition in a test
|
||||
file, or a call-style spec file's own row?"""
|
||||
if not is_test_path(path):
|
||||
return False
|
||||
return kind == "file" or (kind == "sym" and is_test_name(symbol))
|
||||
|
||||
|
||||
def test_signals(body: str) -> list[str]:
|
||||
"""The weak-test signals a test's body shows, sorted."""
|
||||
out = [name for name, rx in SIGNALS.items() if rx.search(body)]
|
||||
@@ -210,13 +233,15 @@ def link_tests(
|
||||
files: dict[str, TestFile],
|
||||
repo_paths: Iterable[str] = (),
|
||||
*,
|
||||
file_tests: Iterable[Def] = (),
|
||||
blank=None,
|
||||
) -> Links:
|
||||
"""Link each test in a repo to what it guards. Pure: `defs` are the
|
||||
repo's symbol definitions with their bodies, `files` each test file read
|
||||
by `read_test_file`, `repo_paths` every file in the tree. `blank` masks
|
||||
strings and comments out of a body; it defaults to the coverage
|
||||
extractor's own pass so the two read code the same way.
|
||||
extractor's own pass so the two read code the same way. `file_tests`
|
||||
are call-style spec files, each a test whose body is the whole file.
|
||||
|
||||
A qualified reference `q.name` counts only when `q` is the defining
|
||||
module, by name or through an alias the file binds (`pc` for
|
||||
@@ -238,6 +263,9 @@ def link_tests(
|
||||
tests.append(d)
|
||||
else:
|
||||
product[d.name].append(d.path)
|
||||
for d in file_tests:
|
||||
helpers[d.name].append(d)
|
||||
tests.append(d)
|
||||
|
||||
own_names: dict[str, set[str]] = defaultdict(set) # test file → names it defines
|
||||
for name, ds in helpers.items():
|
||||
@@ -372,6 +400,10 @@ def same_guard_groups(
|
||||
|
||||
# Statuses whose test has had its verdict: it leaves every group.
|
||||
_SETTLED = ("redundant", "unused")
|
||||
_TEST_REASON = (
|
||||
"a test case linked to what it guards (stamped by the coverage sync); "
|
||||
"test_guard_groups lists the ones guarding the same thing"
|
||||
)
|
||||
# How many groups a readout carries; the count says how many there are.
|
||||
GROUPS_SHOWN = 25
|
||||
|
||||
@@ -393,7 +425,8 @@ async def sync_repo_guards(project_id: int, repo_key: str, links: Links) -> int:
|
||||
CodeShape.vanished_at.is_(None),
|
||||
)
|
||||
)).scalars().all()
|
||||
ids = {(r.path, r.symbol): r.id for r in rows if r.kind == "sym"}
|
||||
ids = {(r.path, r.symbol): r.id for r in rows if r.kind in ("sym", "file")}
|
||||
by_key = {(r.path, r.symbol): r for r in rows if r.kind in ("sym", "file")}
|
||||
all_ids = [r.id for r in rows]
|
||||
if all_ids:
|
||||
await session.execute(delete(CodeShapeGuard).where(CodeShapeGuard.test_id.in_(all_ids)))
|
||||
@@ -411,13 +444,57 @@ async def sync_repo_guards(project_id: int, repo_key: str, links: Links) -> int:
|
||||
session.add(CodeShapeGuard(test_id=tid, path=path, basis="static"))
|
||||
edges += 1
|
||||
for r in rows:
|
||||
sig = ",".join(links.signals.get((r.path, r.symbol), ())) if r.kind == "sym" else ""
|
||||
sig = ",".join(links.signals.get((r.path, r.symbol), ())) if r.kind in ("sym", "file") else ""
|
||||
if (r.test_signals or "") != sig:
|
||||
r.test_signals = sig
|
||||
# The `test` stamp follows the links: on while a test case guards
|
||||
# something, withdrawn when it guards nothing, never over a judgment.
|
||||
from grimoire.services.shape_ledger import _judge
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
for key, guarded in links.shapes.items():
|
||||
row = by_key.get(key)
|
||||
if row is None:
|
||||
continue
|
||||
linked = bool(guarded) or bool(links.paths.get(key))
|
||||
if linked and row.status == "unclassified":
|
||||
await _judge(session, row, status="test", snippet_id=None,
|
||||
by="mechanical", reason=_TEST_REASON, at=now)
|
||||
elif not linked and row.status == "test":
|
||||
await _judge(session, row, status="unclassified", snippet_id=None,
|
||||
by=None, reason=None, at=now)
|
||||
await session.commit()
|
||||
return edges
|
||||
|
||||
|
||||
async def test_summary(project_id: int) -> dict:
|
||||
"""{linked, unlinked, redundant} over a project's live test cases: linked
|
||||
to something they guard, linked to nothing, judged redundant."""
|
||||
from sqlalchemy import select
|
||||
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.code_shape import CodeShape, CodeShapeGuard
|
||||
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(CodeShape.id, CodeShape.path, CodeShape.symbol, CodeShape.kind, CodeShape.status)
|
||||
.where(CodeShape.project_id == project_id, CodeShape.vanished_at.is_(None))
|
||||
)).all()
|
||||
cases = {r[0]: r for r in rows if is_test_case(r[1], r[2], r[3])}
|
||||
guarded = set((await session.execute(
|
||||
select(CodeShapeGuard.test_id).where(CodeShapeGuard.test_id.in_(list(cases)))
|
||||
)).scalars().all()) if cases else set()
|
||||
out = {"linked": 0, "unlinked": 0, "redundant": 0}
|
||||
for tid, r in cases.items():
|
||||
if r[4] == "redundant":
|
||||
out["redundant"] += 1
|
||||
elif tid in guarded:
|
||||
out["linked"] += 1
|
||||
else:
|
||||
out["unlinked"] += 1
|
||||
return out
|
||||
|
||||
|
||||
def _shape_ref(row) -> dict:
|
||||
return {"id": row.id, "path": row.path, "symbol": row.symbol}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user