Files

49 lines
2.1 KiB
Python

#!/usr/bin/env python3
"""How many tests a test file declares: the `def test_` written in it, and those of the shared classes of tests/ that its classes
build on (vector_lanes.py's), once for each class that inherits them.
run_suite.py and run_single.py compare that number with what unittest ran, so that a file which stops early, or a test that never
runs, fails the CI. Counted on the file's text alone, a file built on shared tests read as running more than it declares:
test_embed_lane.py ran 40 of its 14, test_clipstral_lane.py 35 of its 9 (found in the review of v1.61.0, 2026-12-02)."""
import ast
import pathlib
# spelled in two parts: the CI counts that string to know how many tests a file declares
TEST_DEF = "def " + "test_"
def inherited(module, name, seen=None):
"""The tests the class `name` of a shared module of tests/ declares, its bases in that module included. A test module's
classes are its own file's: 0 for them, and for anything that is not a class of such a module."""
module = pathlib.Path(module)
if not module.is_file() or module.name.startswith("test_"):
return 0
try:
classes = {c.name: c for c in ast.parse(module.read_text()).body if isinstance(c, ast.ClassDef)}
except SyntaxError:
return 0
seen = set() if seen is None else seen
if name not in classes or name in seen:
return 0
seen.add(name)
cls = classes[name]
n = sum(isinstance(f, (ast.FunctionDef, ast.AsyncFunctionDef)) and f.name.startswith("test_") for f in cls.body)
return n + sum(inherited(module, b.id, seen) for b in cls.bases if isinstance(b, ast.Name))
def declared(path):
"""The tests the file at `path` declares (see the module's docstring)."""
path = pathlib.Path(path)
text = path.read_text()
n = text.count(TEST_DEF)
try:
tree = ast.parse(text)
except SyntaxError:
return n
for node in tree.body:
if isinstance(node, ast.ClassDef):
for base in node.bases:
if isinstance(base, ast.Attribute) and isinstance(base.value, ast.Name):
n += inherited(path.parent / f"{base.value.id}.py", base.attr)
return n