|
| 1 | +"""No test module may define the same name twice in one scope. |
| 2 | +
|
| 3 | +Python keeps only the last definition, so a duplicate silently deletes the |
| 4 | +first one. When the shadowed name is a test, its coverage disappears with no |
| 5 | +error and no skip; when it is an ``autouse`` fixture, the whole module quietly |
| 6 | +switches to the newer one's isolation rules. |
| 7 | +
|
| 8 | +Both had already happened here: |
| 9 | +
|
| 10 | +* ``tests/agent/test_auxiliary_client.py`` grew a second ``_clean_env`` |
| 11 | + ``autouse`` fixture alongside an NVIDIA feature. It replaced the original for |
| 12 | + all 158 tests in the file, dropping the ``ANTHROPIC_API_KEY`` / |
| 13 | + ``ANTHROPIC_TOKEN`` / ``CLAUDE_CODE_OAUTH_TOKEN`` env stripping and the |
| 14 | + ``_aux_unhealthy_*`` cache reset between tests. Individual tests had started |
| 15 | + clearing that cache by hand to work around it. |
| 16 | +* ``tests/gateway/test_mattermost.py`` had two copies of |
| 17 | + ``test_progress_send_with_invalid_thread_root_never_falls_back_flat``; the |
| 18 | + surviving one omitted the recorded 400 ``invalid root_id`` state, so the |
| 19 | + case the name describes was never exercised. |
| 20 | +
|
| 21 | +This guard is cheap and catches the whole class at collection time. |
| 22 | +""" |
| 23 | + |
| 24 | +from __future__ import annotations |
| 25 | + |
| 26 | +import ast |
| 27 | +from pathlib import Path |
| 28 | + |
| 29 | +import pytest |
| 30 | + |
| 31 | +REPO_ROOT = Path(__file__).resolve().parent.parent |
| 32 | +TESTS_ROOT = REPO_ROOT / "tests" |
| 33 | + |
| 34 | +# Decorators that legitimately repeat a name in one scope. |
| 35 | +_REDEFINING_DECORATORS = ("overload", "setter", "getter", "deleter", "register") |
| 36 | + |
| 37 | +# Throwaway callbacks conventionally named `_` are not shadowing bugs. |
| 38 | +_ALLOWED_REPEATS = {"_"} |
| 39 | + |
| 40 | + |
| 41 | +def _decorator_names(node: ast.AST) -> list[str]: |
| 42 | + out = [] |
| 43 | + for dec in getattr(node, "decorator_list", []): |
| 44 | + try: |
| 45 | + out.append(ast.unparse(dec)) |
| 46 | + except Exception: # pragma: no cover - defensive |
| 47 | + pass |
| 48 | + return out |
| 49 | + |
| 50 | + |
| 51 | +def _duplicates_in(body, scope: str, rel: str) -> list[str]: |
| 52 | + seen: dict[str, int] = {} |
| 53 | + problems: list[str] = [] |
| 54 | + for node in body: |
| 55 | + if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): |
| 56 | + continue |
| 57 | + if node.name in _ALLOWED_REPEATS: |
| 58 | + continue |
| 59 | + if any( |
| 60 | + marker in dec |
| 61 | + for dec in _decorator_names(node) |
| 62 | + for marker in _REDEFINING_DECORATORS |
| 63 | + ): |
| 64 | + seen[node.name] = node.lineno |
| 65 | + continue |
| 66 | + if node.name in seen: |
| 67 | + problems.append( |
| 68 | + f"{rel}:{node.lineno} {scope}.{node.name}() shadows the " |
| 69 | + f"definition at line {seen[node.name]}" |
| 70 | + ) |
| 71 | + seen[node.name] = node.lineno |
| 72 | + return problems |
| 73 | + |
| 74 | + |
| 75 | +def _test_modules() -> list[Path]: |
| 76 | + return sorted(TESTS_ROOT.rglob("test_*.py")) |
| 77 | + |
| 78 | + |
| 79 | +def test_no_shadowed_definitions_in_test_modules(): |
| 80 | + problems: list[str] = [] |
| 81 | + for path in _test_modules(): |
| 82 | + try: |
| 83 | + tree = ast.parse(path.read_text(encoding="utf-8")) |
| 84 | + except (SyntaxError, UnicodeDecodeError): # pragma: no cover |
| 85 | + continue |
| 86 | + rel = path.relative_to(REPO_ROOT).as_posix() |
| 87 | + problems += _duplicates_in(tree.body, "<module>", rel) |
| 88 | + for node in ast.walk(tree): |
| 89 | + if isinstance(node, ast.ClassDef): |
| 90 | + problems += _duplicates_in(node.body, node.name, rel) |
| 91 | + |
| 92 | + assert not problems, ( |
| 93 | + "A duplicate definition silently deletes the earlier one. Rename or " |
| 94 | + "remove:\n " + "\n ".join(problems) |
| 95 | + ) |
| 96 | + |
| 97 | + |
| 98 | +def test_guard_detects_a_known_duplicate_shape(): |
| 99 | + """The guard must actually fire, not vacuously pass.""" |
| 100 | + src = ( |
| 101 | + "def test_a():\n pass\n\n" |
| 102 | + "def test_a():\n pass\n" |
| 103 | + ) |
| 104 | + tree = ast.parse(src) |
| 105 | + assert _duplicates_in(tree.body, "<module>", "fake.py") |
| 106 | + |
| 107 | + |
| 108 | +@pytest.mark.parametrize("decorator", ["@property", "@x.setter", "@functools.singledispatch"]) |
| 109 | +def test_guard_allows_legitimate_redefinition(decorator): |
| 110 | + src = ( |
| 111 | + "class C:\n" |
| 112 | + " def f(self):\n pass\n" |
| 113 | + f" {decorator}\n" |
| 114 | + " def f(self):\n pass\n" |
| 115 | + ) |
| 116 | + tree = ast.parse(src) |
| 117 | + cls = tree.body[0] |
| 118 | + problems = _duplicates_in(cls.body, "C", "fake.py") |
| 119 | + # Only the setter/getter/register family is exempt; a bare @property |
| 120 | + # repeat is still a real shadow. |
| 121 | + if any(m in decorator for m in _REDEFINING_DECORATORS): |
| 122 | + assert not problems |
| 123 | + else: |
| 124 | + assert problems |
0 commit comments