|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Refuse duplicate methods, test functions, and class bindings. |
| 3 | +
|
| 4 | +Parses the Python test/driver inventory with ``ast``, never importing targets. |
| 5 | +Control-flow suites share their enclosing module or class namespace. Exits 1 |
| 6 | +with ``file:line`` diagnostics for duplicates, absent inventory directories, |
| 7 | +or an inspection with no files or no ``test_*`` names; exits 0 otherwise. |
| 8 | +""" |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import argparse |
| 12 | +import ast |
| 13 | +from pathlib import Path |
| 14 | +import sys |
| 15 | +from typing import Iterable, Sequence |
| 16 | +import warnings |
| 17 | + |
| 18 | +ROOT = Path(__file__).resolve().parent.parent |
| 19 | +TEST_GLOBS = ( |
| 20 | + # CMake registers test_*, *_self_test, --self-test drivers and source |
| 21 | + # guards in scripts; tests also has e2e/receipt/equivalence driver names. |
| 22 | + # Scan the whole directories so those naming variants cannot evade this. |
| 23 | + ('scripts', '*.py'), |
| 24 | + ('docker', '*_test.py'), |
| 25 | + ('tests', '*.py'), |
| 26 | + ('tests/ownership', 'test_*.py'), |
| 27 | + ('benchmarks', '*.py'), |
| 28 | + ('benchmarks/tests', 'test_*.py'), |
| 29 | +) |
| 30 | + |
| 31 | + |
| 32 | +def default_test_files(root: Path = ROOT) -> list[Path]: |
| 33 | + if not root.is_dir(): |
| 34 | + raise ValueError(f'missing repository root: {root}') |
| 35 | + files: list[Path] = [] |
| 36 | + for subdir, pattern in TEST_GLOBS: |
| 37 | + directory = root / subdir |
| 38 | + if not directory.is_dir(): |
| 39 | + raise ValueError(f'missing expected test directory: {directory}') |
| 40 | + files.extend(sorted(directory.glob(pattern))) |
| 41 | + return files |
| 42 | + |
| 43 | + |
| 44 | +def _scope_statements(nodes: Iterable[ast.AST]) -> Iterable[ast.stmt]: |
| 45 | + """Walk all control-flow suites, stopping at namespace boundaries.""" |
| 46 | + for node in nodes: |
| 47 | + if isinstance(node, ast.stmt): |
| 48 | + yield node |
| 49 | + if not isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)): |
| 50 | + yield from _scope_statements(ast.iter_child_nodes(node)) |
| 51 | + |
| 52 | + |
| 53 | +def _check_scope( |
| 54 | + path: Path, |
| 55 | + nodes: Iterable[ast.stmt], |
| 56 | + findings: list[tuple[Path, int, str]], |
| 57 | + class_name: str | None = None, |
| 58 | +) -> int: |
| 59 | + seen_functions: dict[str, int] = {} |
| 60 | + seen_classes: dict[str, int] = {} |
| 61 | + test_names = 0 |
| 62 | + for stmt in _scope_statements(nodes): |
| 63 | + if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)): |
| 64 | + is_test = stmt.name.startswith('test_') |
| 65 | + test_names += int(is_test) |
| 66 | + if class_name is None and not is_test: |
| 67 | + continue |
| 68 | + kind = f'method {class_name}.{stmt.name}' if class_name else f'top-level test function {stmt.name}' |
| 69 | + if stmt.name in seen_functions: |
| 70 | + findings.append(( |
| 71 | + path, |
| 72 | + stmt.lineno, |
| 73 | + f'duplicate {kind} ' |
| 74 | + f'(first defined at line {seen_functions[stmt.name]})', |
| 75 | + )) |
| 76 | + else: |
| 77 | + seen_functions[stmt.name] = stmt.lineno |
| 78 | + elif isinstance(stmt, ast.ClassDef): |
| 79 | + qualified = f'{class_name}.{stmt.name}' if class_name else stmt.name |
| 80 | + test_names += _check_scope(path, stmt.body, findings, qualified) |
| 81 | + # An empty body can inherit tests; refuse the rebinding without |
| 82 | + # trying to execute imports or resolve the class's ancestry. |
| 83 | + if stmt.name in seen_classes: |
| 84 | + findings.append(( |
| 85 | + path, |
| 86 | + stmt.lineno, |
| 87 | + f'duplicate test class {qualified} ' |
| 88 | + f'(first defined at line {seen_classes[stmt.name]})', |
| 89 | + )) |
| 90 | + else: |
| 91 | + seen_classes[stmt.name] = stmt.lineno |
| 92 | + return test_names |
| 93 | + |
| 94 | + |
| 95 | +def _inspect_file(path: Path) -> tuple[list[tuple[Path, int, str]], int]: |
| 96 | + with warnings.catch_warnings(): |
| 97 | + # Scanned source warnings must not leak or become parse failures under |
| 98 | + # a caller's warning-as-error policy. Actual syntax errors still fail. |
| 99 | + warnings.simplefilter('ignore') |
| 100 | + tree = ast.parse(path.read_text(encoding='utf-8'), filename=str(path)) |
| 101 | + findings: list[tuple[Path, int, str]] = [] |
| 102 | + test_names = _check_scope(path, tree.body, findings) |
| 103 | + return findings, test_names |
| 104 | + |
| 105 | + |
| 106 | +def check_file(path: Path) -> list[tuple[Path, int, str]]: |
| 107 | + return _inspect_file(path)[0] |
| 108 | + |
| 109 | + |
| 110 | +def collect_files(root: Path, paths: Sequence[Path]) -> list[Path]: |
| 111 | + if not paths: |
| 112 | + return default_test_files(root) |
| 113 | + collected: list[Path] = [] |
| 114 | + for item in paths: |
| 115 | + if item.is_dir(): |
| 116 | + if any((item / subdir).exists() for subdir, _ in TEST_GLOBS): |
| 117 | + collected.extend(default_test_files(item)) |
| 118 | + else: |
| 119 | + collected.extend(sorted(item.glob('*.py'))) |
| 120 | + else: |
| 121 | + collected.append(item) |
| 122 | + return list(dict.fromkeys(collected)) |
| 123 | + |
| 124 | + |
| 125 | +def check_paths(paths: Sequence[Path]) -> list[tuple[Path, int, str]]: |
| 126 | + findings: list[tuple[Path, int, str]] = [] |
| 127 | + test_names = 0 |
| 128 | + for path in paths: |
| 129 | + file_findings, file_test_names = _inspect_file(path) |
| 130 | + findings.extend(file_findings) |
| 131 | + test_names += file_test_names |
| 132 | + if paths and test_names == 0: |
| 133 | + findings.append((paths[0], 1, 'no test names inspected')) |
| 134 | + return findings |
| 135 | + |
| 136 | + |
| 137 | +def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: |
| 138 | + parser = argparse.ArgumentParser(description=__doc__) |
| 139 | + parser.add_argument( |
| 140 | + '--root', |
| 141 | + type=Path, |
| 142 | + default=ROOT, |
| 143 | + help='Repository root to scan when no explicit paths are given.', |
| 144 | + ) |
| 145 | + parser.add_argument( |
| 146 | + 'paths', |
| 147 | + nargs='*', |
| 148 | + type=Path, |
| 149 | + help='Optional explicit test files or directories to check.', |
| 150 | + ) |
| 151 | + return parser.parse_args(argv) |
| 152 | + |
| 153 | + |
| 154 | +def main(argv: Sequence[str] | None = None) -> int: |
| 155 | + args = parse_args(argv) |
| 156 | + try: |
| 157 | + files = collect_files(args.root, args.paths) |
| 158 | + if not files: |
| 159 | + print('no test files inspected', file=sys.stderr) |
| 160 | + return 1 |
| 161 | + findings = check_paths(files) |
| 162 | + except (OSError, SyntaxError, ValueError) as error: |
| 163 | + print(error, file=sys.stderr) |
| 164 | + return 1 |
| 165 | + if findings: |
| 166 | + for path, lineno, detail in findings: |
| 167 | + print(f'{path}:{lineno}: {detail}', file=sys.stderr) |
| 168 | + return 1 |
| 169 | + return 0 |
| 170 | + |
| 171 | + |
| 172 | +if __name__ == '__main__': |
| 173 | + raise SystemExit(main()) |
0 commit comments