stocks / scripts /validate_tests.py
user
python version
ee446e8
Raw History Blame Contribute Delete
21.2 kB
#!/usr/bin/env python3
"""
validate_tests.py β€” validates that tests are actually meaningful.
Pipeline:
1. Static scan (50ms) β€” finds tests with no/trivial assertions
Mutation testing is no longer part of this script: it was migrated to
mutmut (see [tool.mutmut] in pyproject.toml and the `mutation` Makefile
target), which is the standard Python mutation-testing tool and replaces
the old text/regex-based mutant injector this script used to run.
Usage:
uv run python scripts/validate_tests.py
uv run python scripts/validate_tests.py --quick # same as default now
uv run python scripts/validate_tests.py --target core/dsl/security.py
"""
import ast
import os
import sys
from dataclasses import dataclass
from pathlib import Path
# ── Config ──
DEFAULT_TARGET = "core/infra/data_manager.py"
TEST_MAP = {
"core/infra/data_manager.py": [
"tests/test_filters_core.py",
"tests/test_data_manager_extended.py",
"tests/test_data_providers.py",
],
"core/dsl/grammar.py": [
"tests/test_filters_core.py",
"tests/test_dsl_advanced_features.py",
],
}
ISSUE_LABELS: dict[str, str] = {
"NO_ASSERT": "no assert",
"TRIVIAL_ASSERT": "trivial assert",
"WEAK_ASSERT": "weak assert",
"FRAGMENT_ONLY": "only fragment asserts",
"PARSE_ERROR": "parse error",
"SHARED_DB": "shared app_state.db",
}
# ═══════════════════════════════════════════════════════════════
# Static analysis
# ═══════════════════════════════════════════════════════════════
@dataclass
class TestIssue:
test_file: str
test_name: str
lineno: int
issue_type: str # NO_ASSERT, TRIVIAL_ASSERT
detail: str = ""
def _assertion_kind(node: ast.Assert) -> str:
"""Classify one assertion as ``fragment``, ``exact`` or ``other``.
A *fragment* assertion only checks that a piece of text appears in, or is
a prefix/suffix of, a value the test never pins. `assert "date >= 'x'" in
expr` passes for ``expr`` = the wrong window, so it cannot fail on the bug
it looks like it covers -- the shape that let a broken date filter ship
with a green suite.
An *exact* assertion compares a whole value: ``==``/``!=`` between
non-constants, or a membership that tests a container rather than text
(``x in {..}``/``x in [..]``, where the literal is on the right).
"""
test = node.test
if not isinstance(test, ast.Compare) or len(test.ops) != 1:
return "other"
op = test.ops[0]
if isinstance(op, (ast.Eq, ast.NotEq)):
# `assert x == 1` still pins the value; only constant-vs-constant is
# meaningless, and TRIVIAL_ASSERT already catches that.
return "exact"
if isinstance(op, (ast.In, ast.NotIn)):
container = test.comparators[0]
# `"text" in composed_string` is a substring check against a value the
# test never compares; `"k" in SOME_SET` pins a container lookup.
if isinstance(test.left, ast.Constant) and isinstance(test.left.value, str):
return "fragment"
if isinstance(container, ast.Constant) and isinstance(container.value, str):
return "fragment"
return "exact"
return "other"
def _is_fragment_call(node: ast.Assert) -> bool:
"""True for `assert <value>.startswith(...)` / `.endswith(...)`."""
test = node.test
return (
isinstance(test, ast.Call)
and isinstance(test.func, ast.Attribute)
and test.func.attr in ("startswith", "endswith")
)
def analyze_test_quality(test_files: list[str]) -> list[TestIssue]:
"""Find tests with quality issues via AST analysis (no test execution)."""
issues = []
for tf in test_files:
if not os.path.exists(tf):
continue
with open(tf) as f:
try:
source = f.read()
tree = ast.parse(source)
except SyntaxError as e:
issues.append(TestIssue(tf, "<file>", 0, "PARSE_ERROR", str(e)))
continue
for node in ast.walk(tree):
if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
continue
# Only flag functions that start with test_ (methods inside Test*
# classes that don't start with test_ are run by pytest but are
# unusual β€” skip them).
if not (node.name.startswith("test_") or node.name.startswith("async_test_")):
continue
# Check for pytest.raises/pytest.warns context managers (valid assertions)
has_pytest_raises = False
for w in ast.walk(node):
if isinstance(w, ast.With):
for item in w.items:
ctx = item.context_expr
if (
isinstance(ctx, ast.Call)
and isinstance(ctx.func, ast.Attribute)
and isinstance(ctx.func.value, ast.Name)
and ctx.func.value.id == "pytest"
and ctx.func.attr in ("raises", "warns")
):
has_pytest_raises = True
# Count assert statements
assert_nodes = [n for n in ast.walk(node) if isinstance(n, ast.Assert)]
if len(assert_nodes) == 0 and not has_pytest_raises:
issues.append(TestIssue(tf, node.name, node.lineno, "NO_ASSERT"))
continue
# Check for trivial assertions (assert True/False/None)
for n in assert_nodes:
if isinstance(n.test, ast.Constant) and n.test.value in (True, False, None):
issues.append(
TestIssue(tf, node.name, node.lineno, "TRIVIAL_ASSERT", f"L{n.lineno}: assert {n.test.value}")
)
break # one flag per test is enough
# Check for single assert that is just "assert X is not None" (weak)
if len(assert_nodes) == 1:
only = assert_nodes[0]
if isinstance(only.test, ast.IsNot):
issues.append(
TestIssue(
tf, node.name, node.lineno, "WEAK_ASSERT", f"L{only.lineno}: assert X is not None only"
)
)
elif isinstance(only.test, ast.Is):
issues.append(
TestIssue(tf, node.name, node.lineno, "WEAK_ASSERT", f"L{only.lineno}: assert X is None only")
)
# A test whose every assertion only inspects a fragment of a
# composed value cannot fail when the whole value is wrong. That is
# exactly how the calendar's date filter shipped broken: its test
# checked `"date >= '2026-09-01'" in plan.full_expr`, which passes
# for any window containing that string.
kinds = [_assertion_kind(n) for n in assert_nodes]
if assert_nodes and "exact" not in kinds:
only_fragments = "fragment" in kinds or any(_is_fragment_call(n) for n in assert_nodes)
if only_fragments:
issues.append(
TestIssue(
tf,
node.name,
node.lineno,
"FRAGMENT_ONLY",
f"{len(assert_nodes)} assertion(s), none compares a whole value",
)
)
return issues
def _is_fixture(node: ast.FunctionDef | ast.AsyncFunctionDef) -> bool:
"""True when the function carries a @pytest.fixture decorator."""
for decorator in node.decorator_list:
target = decorator.func if isinstance(decorator, ast.Call) else decorator
if isinstance(target, ast.Attribute) and target.attr == "fixture":
return True
if isinstance(target, ast.Name) and target.id == "fixture":
return True
return False
def _patches_db_path(node: ast.AST) -> bool:
"""True when the subtree monkeypatches the DB_PATH attribute."""
for child in ast.walk(node):
if not isinstance(child, ast.Call) or not isinstance(child.func, ast.Attribute):
continue
if child.func.attr != "setattr":
continue
values = list(child.args) + [kw.value for kw in child.keywords]
if any(isinstance(v, ast.Constant) and v.value == "DB_PATH" for v in values):
return True
return False
def _fixture_deps(node: ast.FunctionDef | ast.AsyncFunctionDef) -> set[str]:
args = node.args
names = {a.arg for a in [*args.posonlyargs, *args.args, *args.kwonlyargs]}
return names - {"self", "cls"}
def _scan_fixtures(tree: ast.AST) -> tuple[dict[str, set[str]], set[str]]:
"""Return (fixture -> fixtures it requests, fixtures that patch DB_PATH)."""
graph: dict[str, set[str]] = {}
patching: set[str] = set()
for node in ast.walk(tree):
if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) or not _is_fixture(node):
continue
graph[node.name] = _fixture_deps(node)
if _patches_db_path(node):
patching.add(node.name)
return graph, patching
def _parse(path: str) -> ast.Module | None:
if not os.path.exists(path):
return None
with open(path) as f:
try:
return ast.parse(f.read())
except SyntaxError:
return None
def _conftest_fixture_graph() -> tuple[dict[str, set[str]], set[str]]:
"""The fixture graph and DB_PATH-patching fixtures declared in conftest."""
graph: dict[str, set[str]] = {}
patching: set[str] = set()
for conftest in ("tests/conftest.py", "conftest.py"):
tree = _parse(conftest)
if tree is None:
continue
sub_graph, sub_patching = _scan_fixtures(tree)
graph.update(sub_graph)
patching |= sub_patching
return graph, patching
def _close_isolation(graph: dict[str, set[str]], patching: set[str]) -> set[str]:
"""Grow the DB_PATH-patching fixture set over fixture-to-fixture deps."""
isolating = set(patching)
changed = True
while changed:
changed = False
for name, deps in graph.items():
if name not in isolating and deps & isolating:
isolating.add(name)
changed = True
return isolating
def _calls_handle(tree: ast.AST, aliases: set[str]) -> bool:
"""True when the module actually calls into the db handle.
Only an attribute access on the imported module can open a connection, so
a suite that merely imports it (say, to assert the handle is importable)
is not a leak and is not worth flagging.
"""
if not aliases:
return False
return any(
isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id in aliases
for node in ast.walk(tree)
)
def analyze_shared_db(test_files: list[str]) -> list[TestIssue]:
"""Flag tests that could touch the real app_state.db (parallel/xdist unsafe)."""
issues: list[TestIssue] = []
conftest_graph, conftest_patching = _conftest_fixture_graph()
for tf in test_files:
if not os.path.exists(tf):
continue
with open(tf) as f:
try:
source = f.read()
tree = ast.parse(source)
except SyntaxError as e:
issues.append(TestIssue(tf, "<file>", 0, "PARSE_ERROR", str(e)))
continue
import_lineno: int | None = None
db_aliases: set[str] = set()
patches_db_path = False
hardcoded_lineno: int | None = None
local_graph, local_patching = _scan_fixtures(tree)
for node in ast.walk(tree):
imports_db = False
if isinstance(node, ast.Import) and any(
a.name == "core.shared.db" or a.name.startswith("core.shared.db.") for a in node.names
):
imports_db = True
db_aliases.update(a.asname or a.name for a in node.names)
elif isinstance(node, ast.ImportFrom) and (
node.module == "core.shared.db"
or (node.module == "core.shared" and any(a.name == "db" for a in node.names))
):
imports_db = True
db_aliases.update(
a.asname or a.name for a in node.names if a.name != "db" or node.module == "core.shared.db"
)
if imports_db and import_lineno is None:
import_lineno = node.lineno
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "setattr":
arg_values = list(node.args) + [kw.value for kw in node.keywords]
if any(isinstance(a, ast.Constant) and a.value == "DB_PATH" for a in arg_values):
patches_db_path = True
if (
hardcoded_lineno is None
and isinstance(node, ast.Constant)
and isinstance(node.value, str)
and node.value.endswith("data/app_state.db")
):
hardcoded_lineno = node.lineno
merged_graph = {**conftest_graph, **local_graph}
isolating = _close_isolation(merged_graph, conftest_patching | local_patching)
requests_isolated = any(
isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
and node.name.startswith("test")
and _fixture_deps(node) & isolating
for node in ast.walk(tree)
)
calls_db = _calls_handle(tree, db_aliases)
if import_lineno is not None and calls_db and not patches_db_path and not requests_isolated:
issues.append(
TestIssue(
tf, "<file>", import_lineno, "SHARED_DB", "imports core.shared.db without monkeypatching DB_PATH"
)
)
if hardcoded_lineno is not None:
issues.append(
TestIssue(tf, "<file>", hardcoded_lineno, "SHARED_DB", "hardcoded path to the real app_state.db")
)
return issues
# ═══════════════════════════════════════════════════════════════
# CLI
# ═══════════════════════════════════════════════════════════════
def find_all_test_files() -> list[str]:
"""Every test file under tests/, skipping __pycache__."""
return sorted(str(p) for p in Path("tests").rglob("*.py") if "__pycache__" not in p.parts)
def _audit(test_files: list[str]) -> int:
"""Report the files where assertions only inspect fragments of a value.
Advisory only: a structural test ("this class name appears in the rendered
HTML") is legitimately fragment-shaped, so a global threshold would be a
gate that can never be satisfied. The report exists to point a reviewer at
the files where fragment-only assertions dominate, which is where a whole
value can be wrong while every test stays green.
"""
issues = [i for i in analyze_test_quality(test_files) if i.issue_type == "FRAGMENT_ONLY"]
if not issues:
print(" βœ… No fragment-only test functions found")
return 0
from collections import Counter
per_file = Counter(i.test_file for i in issues)
print(f"\n {len(issues)} test function(s) assert only on fragments, across {len(per_file)} file(s)\n")
print(" Files where fragment-only assertions dominate:")
for path, count in per_file.most_common(20):
print(f" {count:4d} {path}")
print("\n Advisory: structural tests are legitimately fragment-shaped. Audit a")
print(" file above when it also owns composition or formatting logic.")
return 0
def find_test_files(source_path: str) -> list[str]:
"""Find test files for a given source module."""
rel = os.path.normpath(source_path)
for key, tests in TEST_MAP.items():
if key == rel:
return tests
# Fallback: glob for test files
basename = os.path.basename(source_path).replace(".py", "")
test_files = list(Path("tests").glob(f"test_*{basename}*.py"))
return [str(f) for f in test_files] if test_files else []
def main():
import argparse
parser = argparse.ArgumentParser(description="Validate that tests are meaningful")
parser.add_argument(
"--target", default=DEFAULT_TARGET, help="Source module to check (default: core/infra/data_manager.py)"
)
parser.add_argument(
"--quick",
action="store_true",
help="Kept for backwards compatibility; static analysis is the only stage now",
)
parser.add_argument("--tests", nargs="*", help="Test files (default: auto-detect)")
parser.add_argument(
"--audit",
action="store_true",
help="Scan the whole tests/ tree for fragment-only assertions and report the worst files",
)
args = parser.parse_args()
if args.audit:
return _audit(args.tests or find_all_test_files())
source_path = args.target
if not os.path.exists(source_path):
print(f"❌ File not found: {source_path}")
return 1
test_files = args.tests if args.tests else find_test_files(source_path)
if not test_files:
print(f"❌ No test files found for {source_path}")
return 1
print(f"\n Source: {source_path}")
print(f" Tests: {', '.join(test_files)}")
# ── Static analysis ──
print()
print(" ── Static analysis (mutation testing moved to mutmut) ──")
static_issues = analyze_test_quality(test_files)
if static_issues:
print(f" Found {len(static_issues)} issue(s)")
for i in static_issues:
label = ISSUE_LABELS.get(i.issue_type, i.issue_type)
print(f" ⚠️ {Path(i.test_file).name}::{i.test_name} β€” {label}")
else:
print(" βœ… All tests have assertions")
no_assert = [i for i in static_issues if i.issue_type == "NO_ASSERT"]
trivial = [i for i in static_issues if i.issue_type == "TRIVIAL_ASSERT"]
weak = [i for i in static_issues if i.issue_type == "WEAK_ASSERT"]
if no_assert:
print(f"\n ❌ {len(no_assert)} test(s) with NO assertions:")
for i in no_assert:
print(f" - {Path(i.test_file).name}::{i.test_name} (L{i.lineno})")
if trivial:
print(f"\n ⚠️ {len(trivial)} test(s) with TRIVIAL assertions (assert True/False/None):")
for i in trivial:
print(f" - {Path(i.test_file).name}::{i.test_name} (L{i.lineno}) β€” {i.detail}")
if weak:
print(f"\n ⚠️ {len(weak)} test(s) with WEAK assertions (single is/is-not check):")
for i in weak:
print(f" - {Path(i.test_file).name}::{i.test_name} (L{i.lineno}) β€” {i.detail}")
fragment = [i for i in static_issues if i.issue_type == "FRAGMENT_ONLY"]
if fragment:
print(f"\n ⚠️ {len(fragment)} test(s) that only inspect a FRAGMENT of a value:")
print(" Every assertion checks a substring/prefix/suffix, so none of")
print(" them fails when the whole value is wrong. Pin the full value")
print(" with ==, or compare the container the fragment came from.")
for i in fragment:
print(f" - {Path(i.test_file).name}::{i.test_name} (L{i.lineno}) β€” {i.detail}")
# ── Shared-database check ──
print()
print(" ── Shared-database check (parallel-safe) ──")
db_issues = analyze_shared_db(find_all_test_files())
if db_issues:
print(f" Found {len(db_issues)} issue(s)")
for i in db_issues:
label = ISSUE_LABELS.get(i.issue_type, i.issue_type)
print(f" ⚠️ {Path(i.test_file).name}::{i.test_name} (L{i.lineno}) β€” {label}: {i.detail}")
else:
print(" βœ… No tests touch the real app_state.db")
quality_issues = len(no_assert) + len(trivial)
shared_db_issues = [i for i in db_issues if i.issue_type == "SHARED_DB"]
if quality_issues > 0:
print(f"\n ❌ {quality_issues} test(s) with static quality issues (NO_ASSERT or TRIVIAL_ASSERT)")
return 1
if shared_db_issues:
print(f"\n ❌ {len(shared_db_issues)} test(s) sharing the real app_state.db:")
for i in shared_db_issues:
print(f" - {Path(i.test_file).name} (L{i.lineno}) β€” {i.detail}")
return 1
print("\n βœ… Static analysis passed")
return 0
if __name__ == "__main__":
sys.exit(main())