返回 CodeWhale
test_check_dead_code_budget.py
根目录 / scripts / test_check_dead_code_budget.py
1 #!/usr/bin/env python3
2 """Hermetic tests for scripts/check-dead-code-budget.py.
3
4 The property under test is the one #6241 reported missing: the gate must
5 ratchet on dead-code *suppression*, not on one spelling of it. Rewriting
6 `#[allow(dead_code)]` as `#[expect(dead_code)]` removes no dead code, so it
7 must not lower the headline number.
8 """
9
10 from __future__ import annotations
11
12 import importlib.util
13 import io
14 import json
15 import sys
16 import tempfile
17 import unittest
18 from contextlib import redirect_stderr, redirect_stdout
19 from pathlib import Path
20
21 ROOT = Path(__file__).resolve().parents[1]
22 SCRIPT = ROOT / "scripts" / "check-dead-code-budget.py"
23
24 SPEC = importlib.util.spec_from_file_location("check_dead_code_budget", SCRIPT)
25 assert SPEC and SPEC.loader
26 mod = importlib.util.module_from_spec(SPEC)
27 sys.modules[SPEC.name] = mod
28 SPEC.loader.exec_module(mod)
29
30
31 class DeadCodeBudgetTest(unittest.TestCase):
32 def setUp(self) -> None:
33 self._tmp = tempfile.TemporaryDirectory()
34 root = Path(self._tmp.name)
35 self.crates = root / "crates"
36 (self.crates / "demo" / "src").mkdir(parents=True)
37 self.budget = root / "scripts" / "dead-code-budget.json"
38 self.budget.parent.mkdir(parents=True)
39 self._saved = (mod.REPO_ROOT, mod.CRATES_DIR, mod.BUDGET_PATH)
40 mod.REPO_ROOT, mod.CRATES_DIR, mod.BUDGET_PATH = root, self.crates, self.budget
41
42 def tearDown(self) -> None:
43 mod.REPO_ROOT, mod.CRATES_DIR, mod.BUDGET_PATH = self._saved
44 self._tmp.cleanup()
45
46 def write_source(self, body: str) -> None:
47 (self.crates / "demo" / "src" / "lib.rs").write_text(body, encoding="utf-8")
48
49 def write_budget(self, total: int) -> None:
50 self.budget.write_text(json.dumps({"total": total}) + "\n", encoding="utf-8")
51
52 def run_main(self, *argv: str) -> tuple[int, str, str]:
53 out, err = io.StringIO(), io.StringIO()
54 saved = sys.argv
55 sys.argv = ["check-dead-code-budget.py", *argv]
56 try:
57 with redirect_stdout(out), redirect_stderr(err):
58 code = mod.main()
59 finally:
60 sys.argv = saved
61 return code, out.getvalue(), err.getvalue()
62
63 def test_expect_spelling_is_counted(self) -> None:
64 """The blind spot itself: `expect(dead_code)` is a suppression too."""
65 self.write_source("#[expect(dead_code)]\nfn a() {}\n")
66 allow_total, expect_total, _ = mod.measure()
67 self.assertEqual(allow_total, 0)
68 self.assertEqual(expect_total, 1)
69
70 def test_dead_code_in_any_lint_list_position_is_counted(self) -> None:
71 self.write_source(
72 "#[allow(async_fn_in_trait, dead_code)]\nfn a() {}\n"
73 "#[allow(\n unused_imports,\n dead_code,\n)]\nfn b() {}\n"
74 "#[expect(clippy::too_many_arguments, dead_code)]\nfn c() {}\n"
75 )
76 allow_total, expect_total, _ = mod.measure()
77 self.assertEqual((allow_total, expect_total), (2, 1))
78
79 def test_comment_prose_is_not_counted(self) -> None:
80 self.write_source(
81 "// the old #[allow(dead_code)] was replaced by expect(dead_code)\n"
82 " /// see allow(dead_code) here\n"
83 "//! and expect(dead_code)\nfn a() {}\n"
84 )
85 self.assertEqual(mod.measure()[:2], (0, 0))
86
87 def test_rewriting_allow_as_expect_does_not_lower_the_total(self) -> None:
88 """#6241's exact regression: a spelling change is not progress."""
89 self.write_source("#[allow(dead_code)]\nfn a() {}\n#[allow(dead_code)]\nfn b() {}\n")
90 before = sum(mod.measure()[:2])
91 self.write_source("#[expect(dead_code)]\nfn a() {}\n#[expect(dead_code)]\nfn b() {}\n")
92 after = sum(mod.measure()[:2])
93 self.assertEqual(
94 before,
95 after,
96 "converting allow->expect removes no dead code and must not move the ratchet",
97 )
98
99 def test_gate_fails_when_expect_pushes_past_the_ceiling(self) -> None:
100 self.write_source("#[allow(dead_code)]\nfn a() {}\n#[expect(dead_code)]\nfn b() {}\n")
101 self.write_budget(1)
102 code, _, err = self.run_main()
103 self.assertEqual(code, 1)
104 self.assertIn("allow=1", err)
105 self.assertIn("expect=1", err)
106
107 def test_gate_passes_at_the_combined_ceiling(self) -> None:
108 self.write_source("#[allow(dead_code)]\nfn a() {}\n#[expect(dead_code)]\nfn b() {}\n")
109 self.write_budget(2)
110 code, out, _ = self.run_main()
111 self.assertEqual(code, 0)
112 self.assertIn("PASS", out)
113
114 def test_update_records_both_spellings_separately(self) -> None:
115 self.write_source("#[allow(dead_code)]\nfn a() {}\n#[expect(dead_code)]\nfn b() {}\n")
116 self.write_budget(0)
117 code, _, _ = self.run_main("--update")
118 self.assertEqual(code, 0)
119 payload = json.loads(self.budget.read_text(encoding="utf-8"))
120 self.assertEqual(payload["total"], 2)
121 self.assertEqual(payload["allow_total"], 1)
122 self.assertEqual(payload["expect_total"], 1)
123 self.assertEqual(payload["per_crate"]["demo"], {"allow": 1, "expect": 1})
124
125 def test_legacy_per_crate_shape_still_renders(self) -> None:
126 """A budget written before #6241 mapped each crate to a bare int."""
127 self.write_source("#[allow(dead_code)]\nfn a() {}\n#[expect(dead_code)]\nfn b() {}\n")
128 self.budget.write_text(
129 json.dumps({"total": 1, "per_crate": {"demo": 1}}) + "\n", encoding="utf-8"
130 )
131 code, _, err = self.run_main()
132 self.assertEqual(code, 1)
133 self.assertIn("budget 1", err)
134
135
136 if __name__ == "__main__":
137 unittest.main()
138
138 lines PYTHON