Skip to content

Commit ff4db9b

Browse files
Add guard tests for display helper usage
Co-authored-by: Shri Sukhani <shrisukhani@users.noreply.github.com>
1 parent 9e08783 commit ff4db9b

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

tests/test_display_helper_usage.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import ast
2+
from pathlib import Path
3+
4+
5+
HYPERBROWSER_ROOT = Path(__file__).resolve().parents[1] / "hyperbrowser"
6+
ALLOWED_NORMALIZE_DISPLAY_CALL_FILES = {
7+
Path("display_utils.py"),
8+
Path("client/managers/response_utils.py"),
9+
Path("transport/base.py"),
10+
}
11+
12+
13+
def _python_files() -> list[Path]:
14+
return sorted(HYPERBROWSER_ROOT.rglob("*.py"))
15+
16+
17+
def _collect_normalize_display_calls(module: ast.AST) -> list[int]:
18+
matches: list[int] = []
19+
for node in ast.walk(module):
20+
if not isinstance(node, ast.Call):
21+
continue
22+
if not isinstance(node.func, ast.Name):
23+
continue
24+
if node.func.id != "normalize_display_text":
25+
continue
26+
matches.append(node.lineno)
27+
return matches
28+
29+
30+
def _collect_format_key_calls(module: ast.AST) -> list[int]:
31+
matches: list[int] = []
32+
for node in ast.walk(module):
33+
if not isinstance(node, ast.Call):
34+
continue
35+
if not isinstance(node.func, ast.Name):
36+
continue
37+
if node.func.id != "format_string_key_for_error":
38+
continue
39+
matches.append(node.lineno)
40+
return matches
41+
42+
43+
def test_normalize_display_text_usage_is_centralized():
44+
violations: list[str] = []
45+
46+
for path in _python_files():
47+
relative_path = path.relative_to(HYPERBROWSER_ROOT)
48+
source = path.read_text(encoding="utf-8")
49+
module = ast.parse(source, filename=str(relative_path))
50+
normalize_calls = _collect_normalize_display_calls(module)
51+
if not normalize_calls:
52+
continue
53+
if relative_path in ALLOWED_NORMALIZE_DISPLAY_CALL_FILES:
54+
continue
55+
for line in normalize_calls:
56+
violations.append(f"{relative_path}:{line}")
57+
58+
assert violations == []
59+
60+
61+
def test_key_formatting_helper_is_used_outside_display_module():
62+
helper_usage_files: set[Path] = set()
63+
64+
for path in _python_files():
65+
relative_path = path.relative_to(HYPERBROWSER_ROOT)
66+
if relative_path == Path("display_utils.py"):
67+
continue
68+
source = path.read_text(encoding="utf-8")
69+
module = ast.parse(source, filename=str(relative_path))
70+
if _collect_format_key_calls(module):
71+
helper_usage_files.add(relative_path)
72+
73+
assert helper_usage_files != set()

0 commit comments

Comments
 (0)