"""Tests for tools/typing_audit.py — the zero-tolerance typing enforcer. Covers every check the audit makes, the self-auditing invariant (the script passes its own rules), string-literal masking, CLI flags, and the ratchet. All tests are pure-unit — no file-system access beyond tmp_path fixtures, no network, no subprocess (we import the module directly). """ from __future__ import annotations import json import sys from pathlib import Path import pytest # ── Import the tool under test ────────────────────────────────────────────── # tools/ is not on sys.path by default; add it so we can import directly. _TOOLS_DIR = Path(__file__).parent.parent / "tools" if str(_TOOLS_DIR) not in sys.path: sys.path.insert(0, str(_TOOLS_DIR)) from typing_audit import ( # noqa: E402 FileResult, Offender, Report, ReportSummary, UntypedDef, _classify_type_ignore, _find_untyped_defs, _imports_any, _mask_string_literals, generate_report, print_human_summary, scan_file, scan_directory, ) type _PatternsMap = dict[str, int] # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def _write(tmp_path: Path, name: str, content: str) -> Path: """Write *content* to ``tmp_path/name`` and return the path.""" p = tmp_path / name p.write_text(content, encoding="utf-8") return p def _scan(content: str, tmp_path: Path) -> FileResult: """Write *content* to a temp file, scan it, and return the result.""" p = _write(tmp_path, "subject.py", content) result = scan_file(p) assert result is not None, "scan_file returned None for a valid file" return result def _total(result: FileResult) -> int: """Return total violation count for *result*.""" return sum(result["patterns"].values()) # --------------------------------------------------------------------------- # Self-auditing invariant # --------------------------------------------------------------------------- class TestSelfAudit: """The audit script itself must pass its own zero-violation ratchet.""" def test_tool_has_zero_violations(self) -> None: """tools/typing_audit.py passes --max-any 0 on itself.""" tool_path = _TOOLS_DIR / "typing_audit.py" result = scan_file(tool_path) assert result is not None total = sum(result["patterns"].values()) assert total == 0, ( f"typing_audit.py has {total} violation(s): " f"{result['patterns']}" ) def test_tool_has_zero_untyped_defs(self) -> None: """Every function in the tool has full type annotations.""" tool_path = _TOOLS_DIR / "typing_audit.py" result = scan_file(tool_path) assert result is not None assert result["untyped_defs"] == [], ( f"Untyped defs found in typing_audit.py: {result['untyped_defs']}" ) # --------------------------------------------------------------------------- # String-literal masking # --------------------------------------------------------------------------- class TestMaskStringLiterals: """_mask_string_literals removes string content without altering structure.""" def test_single_quoted_string_is_blanked(self) -> None: src = 'x = "hello: Any world"' masked = _mask_string_literals(src) assert "Any" not in masked def test_raw_string_is_blanked(self) -> None: src = r'pat = re.compile(r":\s*Any\b")' masked = _mask_string_literals(src) assert "Any" not in masked def test_newlines_are_preserved_in_multiline_string(self) -> None: src = '"""line one\nline two\nline three"""\nx = 1' masked = _mask_string_literals(src) assert masked.count("\n") == src.count("\n") def test_code_outside_strings_is_preserved(self) -> None: src = 'x: dict[str, int] = {}' masked = _mask_string_literals(src) assert "dict[str, int]" in masked def test_comment_not_masked(self) -> None: """Comments are not string literals — they survive masking.""" src = 'x = 1 # type: ignore' masked = _mask_string_literals(src) assert "type: ignore" in masked def test_docstring_content_masked(self) -> None: src = '"""This function uses dict[str, Any] for convenience."""\ndef f(): ...' masked = _mask_string_literals(src) assert "Any" not in masked def test_pattern_in_string_does_not_trigger_violation( self, tmp_path: Path ) -> None: """A string literal containing 'Any' must not count as a violation.""" result = _scan('x = "param: Any"\n', tmp_path) assert _total(result) == 0 def test_raw_regex_pattern_does_not_trigger_violation( self, tmp_path: Path ) -> None: """Raw regex strings like r':\\s*Any\\b' must not count as violations.""" result = _scan('import re\npat = re.compile(r":\\s*Any\\b")\n', tmp_path) assert _total(result) == 0 # --------------------------------------------------------------------------- # _imports_any # --------------------------------------------------------------------------- class TestImportsAny: def test_detects_direct_any_import(self) -> None: assert _imports_any("from typing import Any\n") def test_detects_any_among_other_imports(self) -> None: assert _imports_any("from typing import List, Any, Dict\n") def test_does_not_flag_non_any_import(self) -> None: assert not _imports_any("from typing import Optional\n") def test_does_not_flag_any_in_comment(self) -> None: assert not _imports_any("# from typing import Any\n") # --------------------------------------------------------------------------- # _classify_type_ignore # --------------------------------------------------------------------------- class TestClassifyTypeIgnore: def test_blanket_ignore(self) -> None: assert _classify_type_ignore("x = 1 # type: ignore") == "type_ignore[blanket]" def test_specific_ignore(self) -> None: assert _classify_type_ignore("x = 1 # type: ignore[attr-defined]") == "type_ignore[attr-defined]" def test_multiple_codes_returned_as_is(self) -> None: label = _classify_type_ignore("x = 1 # type: ignore[union-attr, arg-type]") assert "union-attr" in label # --------------------------------------------------------------------------- # Any-as-type patterns # --------------------------------------------------------------------------- class TestAnyPatterns: def test_dict_str_any(self, tmp_path: Path) -> None: result = _scan("def f() -> dict[str, Any]: ...\n", tmp_path) assert result["patterns"].get("dict_str_any", 0) >= 1 def test_list_any(self, tmp_path: Path) -> None: result = _scan("def f() -> list[Any]: ...\n", tmp_path) assert result["patterns"].get("list_any", 0) >= 1 def test_return_any(self, tmp_path: Path) -> None: result = _scan("def f() -> Any: ...\n", tmp_path) assert result["patterns"].get("return_any", 0) >= 1 def test_param_any(self, tmp_path: Path) -> None: result = _scan("def f(x: Any) -> None: ...\n", tmp_path) assert result["patterns"].get("param_any", 0) >= 1 def test_mapping_any(self, tmp_path: Path) -> None: result = _scan("def f(x: Mapping[str, Any]) -> None: ...\n", tmp_path) assert result["patterns"].get("mapping_any", 0) >= 1 def test_tuple_any(self, tmp_path: Path) -> None: result = _scan("x: tuple[int, Any] = (1, 2)\n", tmp_path) assert result["patterns"].get("tuple_any", 0) >= 1 def test_any_in_docstring_not_flagged(self, tmp_path: Path) -> None: """Any inside docstrings must not be counted.""" src = '"""Accepts dict[str, Any] for flexibility."""\ndef f() -> None: ...\n' result = _scan(src, tmp_path) assert result["patterns"].get("dict_str_any", 0) == 0 # --------------------------------------------------------------------------- # object-as-type patterns # --------------------------------------------------------------------------- class TestObjectPatterns: def test_param_object(self, tmp_path: Path) -> None: result = _scan("def f(x: object) -> None: ...\n", tmp_path) assert result["patterns"].get("param_object", 0) >= 1 def test_return_object(self, tmp_path: Path) -> None: result = _scan("def f() -> object: ...\n", tmp_path) assert result["patterns"].get("return_object", 0) >= 1 def test_collection_object(self, tmp_path: Path) -> None: result = _scan("x: list[object] = []\n", tmp_path) assert result["patterns"].get("collection_object", 0) >= 1 # --------------------------------------------------------------------------- # cast() — banned # --------------------------------------------------------------------------- class TestCastUsage: def test_cast_flagged(self, tmp_path: Path) -> None: result = _scan("from typing import cast\ny = cast(int, x)\n", tmp_path) assert result["patterns"].get("cast_usage", 0) >= 1 # --------------------------------------------------------------------------- # type: ignore # --------------------------------------------------------------------------- class TestTypeIgnore: def test_bare_type_ignore_flagged(self, tmp_path: Path) -> None: result = _scan("x: int = y # type: ignore\n", tmp_path) assert result["patterns"].get("type_ignore", 0) >= 1 def test_specific_type_ignore_not_flagged(self, tmp_path: Path) -> None: """Code-specific ignores like type: ignore[assignment] are acceptable — not flagged.""" result = _scan("x: int = y # type: ignore[assignment]\n", tmp_path) assert result["patterns"].get("type_ignore", 0) == 0 def test_type_ignore_in_string_not_flagged(self, tmp_path: Path) -> None: """The text '# type: ignore' inside a print string is not a comment.""" result = _scan('print("use # type: ignore sparingly")\n', tmp_path) assert result["patterns"].get("type_ignore", 0) == 0 def test_type_ignore_variant_classified(self, tmp_path: Path) -> None: result = _scan("x = 1 # type: ignore\n", tmp_path) assert result["type_ignore_variants"].get("type_ignore[blanket]", 0) >= 1 def test_specific_variant_not_classified(self, tmp_path: Path) -> None: """Code-specific ignores don't match the blanket pattern — variants dict stays empty.""" result = _scan("x = 1 # type: ignore[attr-defined]\n", tmp_path) assert result["type_ignore_variants"].get("type_ignore[attr-defined]", 0) == 0 # --------------------------------------------------------------------------- # Bare collections # --------------------------------------------------------------------------- class TestBareCollections: def test_bare_list_in_annotation(self, tmp_path: Path) -> None: result = _scan("def f() -> list: ...\n", tmp_path) assert result["patterns"].get("bare_list", 0) >= 1 def test_bare_dict_in_annotation(self, tmp_path: Path) -> None: result = _scan("def f() -> dict: ...\n", tmp_path) assert result["patterns"].get("bare_dict", 0) >= 1 def test_bare_set_in_annotation(self, tmp_path: Path) -> None: result = _scan("x: set = set()\n", tmp_path) assert result["patterns"].get("bare_set", 0) >= 1 def test_bare_tuple_in_annotation(self, tmp_path: Path) -> None: result = _scan("x: tuple = (1, 2)\n", tmp_path) assert result["patterns"].get("bare_tuple", 0) >= 1 def test_parameterised_list_not_flagged(self, tmp_path: Path) -> None: result = _scan("def f() -> list[int]: ...\n", tmp_path) assert result["patterns"].get("bare_list", 0) == 0 def test_parameterised_dict_not_flagged(self, tmp_path: Path) -> None: result = _scan("x: dict[str, int] = {}\n", tmp_path) assert result["patterns"].get("bare_dict", 0) == 0 # --------------------------------------------------------------------------- # Optional / Union (legacy) # --------------------------------------------------------------------------- class TestOptionalUnion: def test_optional_usage_flagged(self, tmp_path: Path) -> None: result = _scan("def f(x: Optional[int]) -> None: ...\n", tmp_path) assert result["patterns"].get("optional_usage", 0) >= 1 def test_union_usage_flagged(self, tmp_path: Path) -> None: result = _scan("def f(x: Union[int, str]) -> None: ...\n", tmp_path) assert result["patterns"].get("union_usage", 0) >= 1 def test_pipe_union_not_flagged(self, tmp_path: Path) -> None: result = _scan("def f(x: int | str) -> None: ...\n", tmp_path) assert _total(result) == 0 def test_x_or_none_not_flagged(self, tmp_path: Path) -> None: result = _scan("def f(x: int | None) -> None: ...\n", tmp_path) assert _total(result) == 0 # --------------------------------------------------------------------------- # Legacy typing imports # --------------------------------------------------------------------------- class TestLegacyImports: def test_legacy_List_flagged(self, tmp_path: Path) -> None: result = _scan("from typing import List\nx: List[int] = []\n", tmp_path) assert result["patterns"].get("legacy_List", 0) >= 1 def test_legacy_Dict_flagged(self, tmp_path: Path) -> None: result = _scan("from typing import Dict\nx: Dict[str, int] = {}\n", tmp_path) assert result["patterns"].get("legacy_Dict", 0) >= 1 def test_legacy_Set_flagged(self, tmp_path: Path) -> None: result = _scan("from typing import Set\nx: Set[int] = set()\n", tmp_path) assert result["patterns"].get("legacy_Set", 0) >= 1 def test_legacy_Tuple_flagged(self, tmp_path: Path) -> None: result = _scan("from typing import Tuple\nx: Tuple[int, str] = (1, 'a')\n", tmp_path) assert result["patterns"].get("legacy_Tuple", 0) >= 1 # --------------------------------------------------------------------------- # Callable patterns (new in rewrite) # --------------------------------------------------------------------------- class TestCallablePatterns: def test_bare_callable_in_annotation_flagged(self, tmp_path: Path) -> None: result = _scan("def f(cb: Callable) -> None: ...\n", tmp_path) assert result["patterns"].get("bare_callable", 0) >= 1 def test_bare_callable_as_return_flagged(self, tmp_path: Path) -> None: result = _scan("def f() -> Callable: ...\n", tmp_path) assert result["patterns"].get("bare_callable", 0) >= 1 def test_callable_returning_any_flagged(self, tmp_path: Path) -> None: result = _scan("def f(cb: Callable[[int], Any]) -> None: ...\n", tmp_path) assert result["patterns"].get("callable_any", 0) >= 1 def test_callable_with_full_signature_not_flagged(self, tmp_path: Path) -> None: result = _scan("def f(cb: Callable[[int], str]) -> None: ...\n", tmp_path) assert result["patterns"].get("bare_callable", 0) == 0 assert result["patterns"].get("callable_any", 0) == 0 # --------------------------------------------------------------------------- # Untyped varargs (new in rewrite) # --------------------------------------------------------------------------- class TestVarargsPatterns: def test_args_any_flagged(self, tmp_path: Path) -> None: result = _scan("def f(*args: Any) -> None: ...\n", tmp_path) assert result["patterns"].get("varargs_any", 0) >= 1 def test_kwargs_any_flagged(self, tmp_path: Path) -> None: result = _scan("def f(**kwargs: Any) -> None: ...\n", tmp_path) assert result["patterns"].get("varargs_any", 0) >= 1 def test_typed_args_not_flagged(self, tmp_path: Path) -> None: result = _scan("def f(*args: int) -> None: ...\n", tmp_path) assert result["patterns"].get("varargs_any", 0) == 0 def test_typed_kwargs_not_flagged(self, tmp_path: Path) -> None: result = _scan("def f(**kwargs: str) -> None: ...\n", tmp_path) assert result["patterns"].get("varargs_any", 0) == 0 def test_varargs_any_in_string_not_flagged(self, tmp_path: Path) -> None: result = _scan('x = "*args: Any is bad"\n', tmp_path) assert result["patterns"].get("varargs_any", 0) == 0 # --------------------------------------------------------------------------- # _find_untyped_defs (AST-based) # --------------------------------------------------------------------------- class TestFindUntypedDefs: def test_missing_return_type(self) -> None: src = "def f():\n pass\n" defs = _find_untyped_defs(src, "x.py") assert any(d["issue"] == "missing_return_type" for d in defs) def test_missing_param_type(self) -> None: src = "def f(x) -> None:\n pass\n" defs = _find_untyped_defs(src, "x.py") assert any(d["issue"] == "missing_param_type" and "x" in d["name"] for d in defs) def test_self_excluded(self) -> None: src = "class C:\n def f(self) -> None:\n pass\n" defs = _find_untyped_defs(src, "x.py") assert not any("self" in d["name"] for d in defs) def test_cls_excluded(self) -> None: src = "class C:\n @classmethod\n def f(cls) -> None:\n pass\n" defs = _find_untyped_defs(src, "x.py") assert not any("cls" in d["name"] for d in defs) def test_fully_typed_function_has_no_violations(self) -> None: src = "def f(x: int, y: str) -> bool:\n return True\n" defs = _find_untyped_defs(src, "x.py") assert defs == [] def test_args_any_detected(self) -> None: src = "def f(*args: Any) -> None:\n pass\n" defs = _find_untyped_defs(src, "x.py") issues = [d["issue"] for d in defs] assert "untyped_args" in issues def test_kwargs_any_detected(self) -> None: src = "def f(**kwargs: Any) -> None:\n pass\n" defs = _find_untyped_defs(src, "x.py") issues = [d["issue"] for d in defs] assert "untyped_kwargs" in issues def test_syntax_error_returns_empty(self) -> None: assert _find_untyped_defs("def f(: pass", "x.py") == [] def test_posonly_arg_without_annotation_flagged(self) -> None: src = "def f(x, /, y: int) -> None:\n pass\n" defs = _find_untyped_defs(src, "x.py") assert any("x" in d["name"] for d in defs) def test_kwonly_arg_without_annotation_flagged(self) -> None: src = "def f(*, x) -> None:\n pass\n" defs = _find_untyped_defs(src, "x.py") assert any("x" in d["name"] for d in defs) # --------------------------------------------------------------------------- # scan_file edge cases # --------------------------------------------------------------------------- class TestScanFile: def test_returns_none_for_missing_file(self, tmp_path: Path) -> None: assert scan_file(tmp_path / "nonexistent.py") is None def test_clean_file_has_zero_violations(self, tmp_path: Path) -> None: result = _scan("def f(x: int) -> str:\n return str(x)\n", tmp_path) assert _total(result) == 0 def test_file_path_in_result(self, tmp_path: Path) -> None: p = _write(tmp_path, "check.py", "x = 1\n") result = scan_file(p) assert result is not None assert result["file"] == str(p) def test_imports_any_detected(self, tmp_path: Path) -> None: result = _scan("from typing import Any\nx: Any = 1\n", tmp_path) assert result["imports_any"] is True def test_imports_any_false_for_no_any(self, tmp_path: Path) -> None: result = _scan("x: int = 1\n", tmp_path) assert result["imports_any"] is False def test_multiple_violations_in_same_line(self, tmp_path: Path) -> None: result = _scan("def f(x: Any) -> Any: ...\n", tmp_path) assert _total(result) >= 2 def test_blank_and_comment_lines_skipped(self, tmp_path: Path) -> None: """Blank lines and pure comments must not contribute to any violation.""" src = "\n# This has Any in a comment: Any\n\nx: int = 1\n" result = _scan(src, tmp_path) assert _total(result) == 0 # --------------------------------------------------------------------------- # scan_directory # --------------------------------------------------------------------------- class TestScanDirectory: def test_scans_all_py_files(self, tmp_path: Path) -> None: _write(tmp_path, "a.py", "x: int = 1\n") _write(tmp_path, "b.py", "def f() -> None: ...\n") results = scan_directory(tmp_path) assert len(results) == 2 def test_skips_venv(self, tmp_path: Path) -> None: venv = tmp_path / "venv" venv.mkdir() _write(venv, "bad.py", "x: Any = 1\n") _write(tmp_path, "good.py", "x: int = 1\n") results = scan_directory(tmp_path) assert len(results) == 1 def test_skips_pycache(self, tmp_path: Path) -> None: cache = tmp_path / "__pycache__" cache.mkdir() _write(cache, "cached.py", "x: Any = 1\n") _write(tmp_path, "real.py", "x: int = 1\n") results = scan_directory(tmp_path) assert len(results) == 1 def test_empty_directory(self, tmp_path: Path) -> None: results = scan_directory(tmp_path) assert results == [] # --------------------------------------------------------------------------- # generate_report # --------------------------------------------------------------------------- class TestGenerateReport: def _make_result( self, file: str = "x.py", patterns: _PatternsMap | None = None, imports_any: bool = False, ) -> FileResult: return FileResult( file=file, imports_any=imports_any, patterns=patterns or {}, pattern_lines={}, type_ignore_variants={}, untyped_defs=[], ) def test_empty_results_produce_zero_totals(self) -> None: report = generate_report([]) assert report["summary"]["total_any_patterns"] == 0 assert report["summary"]["total_files_scanned"] == 0 def test_total_counts_aggregated(self) -> None: r1 = self._make_result("a.py", {"param_any": 2}) r2 = self._make_result("b.py", {"return_any": 3}) report = generate_report([r1, r2]) assert report["summary"]["total_any_patterns"] == 5 def test_top_offenders_sorted_descending(self) -> None: r1 = self._make_result("low.py", {"param_any": 1}) r2 = self._make_result("high.py", {"param_any": 10}) report = generate_report([r1, r2]) assert report["top_offenders"][0]["file"] == "high.py" def test_files_importing_any_counted(self) -> None: r1 = self._make_result("a.py", imports_any=True) r2 = self._make_result("b.py", imports_any=False) report = generate_report([r1, r2]) assert report["summary"]["files_importing_any"] == 1 def test_per_file_only_includes_violating_files(self) -> None: r1 = self._make_result("clean.py", {}) r2 = self._make_result("dirty.py", {"param_any": 1}) report = generate_report([r1, r2]) assert "clean.py" not in report["per_file"] assert "dirty.py" in report["per_file"] def test_report_is_serialisable_to_json(self) -> None: r = self._make_result("x.py", {"param_any": 1}) report = generate_report([r]) serialised = json.dumps(report) loaded = json.loads(serialised) assert loaded["summary"]["total_any_patterns"] == 1 def test_type_ignore_variants_aggregated(self) -> None: r = FileResult( file="x.py", imports_any=False, patterns={}, pattern_lines={}, type_ignore_variants={"type_ignore[blanket]": 3}, untyped_defs=[], ) report = generate_report([r]) assert report["type_ignore_variants"]["type_ignore[blanket]"] == 3 def test_untyped_defs_aggregated(self) -> None: ud = UntypedDef(file="x.py", line=1, name="f", issue="missing_return_type") r = FileResult( file="x.py", imports_any=False, patterns={}, pattern_lines={}, type_ignore_variants={}, untyped_defs=[ud], ) report = generate_report([r]) assert report["summary"]["untyped_defs"] == 1 assert len(report["untyped_defs"]) == 1 # --------------------------------------------------------------------------- # print_human_summary (smoke test) # --------------------------------------------------------------------------- class TestPrintHumanSummary: def test_outputs_to_stdout(self, capsys: pytest.CaptureFixture[str]) -> None: r = FileResult( file="x.py", imports_any=True, patterns={"param_any": 2}, pattern_lines={"param_any": [10, 20]}, type_ignore_variants={}, untyped_defs=[], ) report = generate_report([r]) print_human_summary(report) out = capsys.readouterr().out assert "TYPING AUDIT" in out assert "param_any" in out def test_no_violations_shows_none_label( self, capsys: pytest.CaptureFixture[str] ) -> None: report = generate_report([]) print_human_summary(report) out = capsys.readouterr().out assert "(none)" in out def test_type_ignore_variants_shown( self, capsys: pytest.CaptureFixture[str] ) -> None: r = FileResult( file="x.py", imports_any=False, patterns={"type_ignore": 1}, pattern_lines={"type_ignore": [5]}, type_ignore_variants={"type_ignore[blanket]": 1}, untyped_defs=[], ) report = generate_report([r]) print_human_summary(report) out = capsys.readouterr().out assert "type_ignore[blanket]" in out # --------------------------------------------------------------------------- # CLI (via main() directly, capturing SystemExit) # --------------------------------------------------------------------------- class TestCLI: def test_ratchet_passes_at_zero(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: _write(tmp_path, "clean.py", "def f(x: int) -> str:\n return str(x)\n") monkeypatch.setattr( sys, "argv", ["typing_audit.py", "--dirs", str(tmp_path), "--max-any", "0"], ) from typing_audit import main main() # must not raise SystemExit def test_ratchet_fails_above_threshold( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: _write(tmp_path, "dirty.py", "def f(x: Any) -> None: ...\n") monkeypatch.setattr( sys, "argv", ["typing_audit.py", "--dirs", str(tmp_path), "--max-any", "0"], ) from typing_audit import main with pytest.raises(SystemExit) as exc: main() assert exc.value.code == 1 def test_json_output_written(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: _write(tmp_path, "src.py", "def f(x: int) -> str:\n return str(x)\n") out_json = tmp_path / "report.json" monkeypatch.setattr( sys, "argv", ["typing_audit.py", "--dirs", str(tmp_path), "--json", str(out_json)], ) from typing_audit import main main() assert out_json.exists() data = json.loads(out_json.read_text()) assert "summary" in data def test_missing_dir_warns_but_does_not_crash( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: monkeypatch.setattr( sys, "argv", ["typing_audit.py", "--dirs", str(tmp_path / "nonexistent")], ) from typing_audit import main main() # must not raise err = capsys.readouterr().err assert "WARNING" in err def test_single_file_arg_accepted( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: p = _write(tmp_path, "single.py", "def f(x: int) -> None: ...\n") monkeypatch.setattr( sys, "argv", ["typing_audit.py", "--dirs", str(p), "--max-any", "0"], ) from typing_audit import main main() # single file path accepted and scanned # --------------------------------------------------------------------------- # TypedDict shape invariants # --------------------------------------------------------------------------- class TestTypedDictShapes: """Confirm that the TypedDicts have the exact keys callers depend on.""" def test_file_result_has_required_keys(self, tmp_path: Path) -> None: result = _scan("x: int = 1\n", tmp_path) for key in ("file", "imports_any", "patterns", "pattern_lines", "type_ignore_variants", "untyped_defs"): assert key in result, f"FileResult missing key: {key!r}" def test_report_has_required_keys(self) -> None: report = generate_report([]) for key in ("summary", "pattern_totals", "type_ignore_variants", "top_offenders", "per_file", "untyped_defs"): assert key in report, f"Report missing key: {key!r}" def test_summary_has_required_keys(self) -> None: report = generate_report([]) for key in ("total_files_scanned", "files_importing_any", "total_any_patterns", "untyped_defs"): assert key in report["summary"], f"ReportSummary missing key: {key!r}"