Skip to content

Commit 7729c18

Browse files
MaxFreedomPollardteknium1
authored andcommitted
test: restore four silently shadowed definitions and guard against more
Python keeps only the last definition of a name in a scope, so a duplicate silently deletes the first. Four had accumulated, and two cost real coverage. tests/agent/test_auxiliary_client.py grew a second _clean_env autouse fixture alongside an NVIDIA feature. Being module-level with the same name, it replaced the original for all 158 tests in the file: the ANTHROPIC_API_KEY, ANTHROPIC_TOKEN, CLAUDE_CODE_OAUTH_TOKEN, OPENAI_MODEL, LLM_MODEL and NOUS_INFERENCE_BASE_URL stripping went away, and so did the _aux_unhealthy_* cache reset between tests. Two tests had already started clearing that cache by hand to work around the leak, one of them with a comment describing the pollution. The NVIDIA keys are folded into the original fixture and the duplicate removed. tests/gateway/test_mattermost.py had two copies of test_progress_send_with_invalid_thread_root_never_falls_back_flat. The surviving copy omitted the recorded 400 "invalid root_id" state, so the case the name describes never ran. Both now run under distinct names. The other two were harmless but hid the pattern: an exact duplicate in test_tts_media_routing.py, and a dead _codex_auth_store in test_credential_pool.py that nothing calls. tests/test_no_shadowed_test_definitions.py walks every test module and fails on any repeated definition in one scope, exempting the property/setter/ register family and throwaway _ callbacks. It fails on main listing exactly these four.
1 parent 3dee063 commit 7729c18

5 files changed

Lines changed: 127 additions & 52 deletions

File tree

‎tests/agent/test_auxiliary_client.py‎

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ def _clean_env(monkeypatch):
6767
"OPENROUTER_API_KEY", "OPENAI_BASE_URL", "OPENAI_API_KEY",
6868
"OPENAI_MODEL", "LLM_MODEL", "NOUS_INFERENCE_BASE_URL",
6969
"ANTHROPIC_API_KEY", "ANTHROPIC_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN",
70+
"NVIDIA_API_KEY", "NVIDIA_BASE_URL",
7071
):
7172
monkeypatch.delenv(key, raising=False)
7273
# Module-level unhealthy cache (10-min TTL) leaks between tests;
@@ -3493,16 +3494,6 @@ def test_empty_tools_unchanged(self):
34933494

34943495

34953496

3496-
@pytest.fixture(autouse=True)
3497-
def _clean_env(monkeypatch):
3498-
"""Strip provider env vars so each test starts clean."""
3499-
for key in (
3500-
"OPENROUTER_API_KEY", "OPENAI_BASE_URL", "OPENAI_API_KEY",
3501-
"NVIDIA_API_KEY", "NVIDIA_BASE_URL",
3502-
):
3503-
monkeypatch.delenv(key, raising=False)
3504-
3505-
35063497
class TestNvidiaBillingHeaders:
35073498
"""NVIDIA NIM billing-origin headers are scoped to NVIDIA cloud."""
35083499

‎tests/agent/test_credential_pool.py‎

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1509,23 +1509,6 @@ def test_request_count_increments(self):
15091509

15101510
# ── OpenAI Codex OAuth cross-process sync tests ────────────────────────────
15111511

1512-
def _codex_auth_store(access: str, refresh: str) -> dict:
1513-
return {
1514-
"version": 1,
1515-
"active_provider": "openai-codex",
1516-
"providers": {
1517-
"openai-codex": {
1518-
"auth_mode": "chatgpt",
1519-
"tokens": {
1520-
"access_token": access,
1521-
"refresh_token": refresh,
1522-
"id_token": "id-" + access,
1523-
},
1524-
"last_refresh": "2026-04-28T00:00:00Z",
1525-
}
1526-
},
1527-
}
1528-
15291512

15301513

15311514

‎tests/gateway/test_mattermost.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -244,8 +244,8 @@ async def test_notify_send_with_invalid_thread_root_falls_back_flat_with_warning
244244

245245

246246
@pytest.mark.asyncio
247-
async def test_progress_send_with_invalid_thread_root_never_falls_back_flat(self):
248-
"""Tool/status/progress bubbles must stay quiet when the thread is broken."""
247+
async def test_progress_send_with_broken_thread_and_no_recorded_error_stays_quiet(self):
248+
"""Same rule when no post error was recorded: still no flat fallback."""
249249
self.adapter._reply_mode = "thread"
250250
self.adapter._api_get = AsyncMock(return_value={"id": "bad_root", "root_id": ""})
251251
self.adapter._api_post = AsyncMock(return_value={})

‎tests/gateway/test_tts_media_routing.py‎

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -196,26 +196,3 @@ async def send(self, chat_id, content=None, **kwargs):
196196

197197
async def get_chat_info(self, chat_id):
198198
return {"id": chat_id, "type": "dm"}
199-
200-
201-
@pytest.mark.asyncio
202-
async def test_non_streaming_media_failure_notifies_user(tmp_path, monkeypatch):
203-
"""Attachmentless send_video results must surface a user-visible notice (#66797)."""
204-
adapter = _DiscordMediaFailureAdapter()
205-
event = _event()
206-
media_file = _allowed_media_path(tmp_path, monkeypatch, "clip.mp4")
207-
adapter._message_handler = AsyncMock(return_value=f"MEDIA:{media_file}")
208-
adapter.send_video = AsyncMock(
209-
return_value=SendResult(
210-
success=False,
211-
error="Discord accepted the message but attached no files (clip.mp4)",
212-
)
213-
)
214-
adapter.send_document = AsyncMock(return_value=SendResult(success=True, message_id="doc"))
215-
adapter.send_voice = AsyncMock(return_value=SendResult(success=True, message_id="voice"))
216-
adapter.send_multiple_images = AsyncMock()
217-
218-
await adapter._process_message_background(event, build_session_key(event.source))
219-
220-
adapter.send_video.assert_awaited_once()
221-
assert adapter.notices == ["⚠️ Couldn't deliver the video attachment."]
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
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

Comments
 (0)