#!/usr/bin/env python3 """Negative and positive proofs for the limits gate (STRA-367): every measure and rule fails on a synthetic violation. Usage: python3 scripts/check_limits_test.py (needs git for the temp-repository tests; no cargo, no network) """ import contextlib import io import json import pathlib import subprocess import sys import tempfile import textwrap import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from limits import allow, baseline, census, cli, clippy_ratchet, diffs, files, gate # noqa: E402 from limits import model, policy, pyscan, rscan # noqa: E402 POLICY = policy.Policy({"fn_lines": 30, "complexity": 10, "nesting": 4, "width": 120}, 4, ("engine/strata/",), ("scripts/limits/",), ("claude/hexagonal-integ", "main")) LIMITS = POLICY.limits def rs(source): """{key: Fn} of a Rust source.""" return {fn.key: fn for fn in rscan.scan(textwrap.dedent(source), set())} def one(source): (fn,) = rscan.scan(textwrap.dedent(source), set()) return fn def body(lines, indent=" "): return "\n".join(f"{indent}let a{n} = {n};" for n in range(lines)) class RustLines(unittest.TestCase): def test_a_function_runs_from_fn_to_the_closing_brace(self): fn = one(""" // comment pub fn f(a: u8, b: u8) -> u8 { a + b } """) self.assertEqual((fn.start, fn.end, fn.fn_lines), (3, 6, 4)) def test_declarations_and_fn_pointers_are_not_functions(self): found = rs(""" trait T { fn decl(&self); fn with_body(&self) {} } struct S { f: fn(u8) -> u8 } extern "C" { fn ffi(x: u8); } """) self.assertEqual(list(found), ["T::with_body"]) def test_braces_in_strings_and_chars_do_not_count(self): fn = one(""" fn f() -> char { let s = "}}} {"; let r = r#"} "{"#; let _ = (s, r, '{'); '}' } """) self.assertEqual((fn.fn_lines, fn.nesting), (6, 0)) class RustComplexity(unittest.TestCase): def cx(self, code): inner = textwrap.indent(textwrap.dedent(code), " ") return one(f"fn f(x: Option) -> Option {{\n{inner}\n}}").complexity def test_a_straight_line_is_one(self): self.assertEqual(self.cx("let a = 1;\nSome(a)"), 1) def test_branches_and_loops_add_one_each(self): self.assertEqual(self.cx("if x.is_some() {}\nwhile false {}\nfor _ in 0..1 {}\nloop { break; }"), 5) def test_else_if_and_if_let_count_once(self): self.assertEqual(self.cx("if a() {} else if b() {} else {}\nif let Some(_) = x {}"), 4) def test_boolean_operators_and_question_mark(self): self.assertEqual(self.cx("let c = a() && b() || c();\nlet d = g()?;\nx"), 4) def test_match_arms_after_the_first_count(self): self.assertEqual(self.cx("match x { Some(1) => 1, Some(_) if a() => 2, _ => 3 }\nx"), 4) def test_references_and_closures_are_not_boolean_operators(self): self.assertEqual(self.cx("let r = &&x;\nlet f = || 1;\nlet g = (a(), || 2);\nx"), 1) def test_nested_function_is_measured_on_its_own(self): found = rs("fn outer() { fn inner(a: bool) { if a {} if a {} } }") self.assertEqual((found["outer"].complexity, found["outer::inner"].complexity), (1, 3)) class RustNesting(unittest.TestCase): def test_control_blocks_nest(self): fn = one("fn f() { if a() { for _ in b() { loop { match c() { _ => { if d() {} } } } } } }") self.assertEqual(fn.nesting, 5) def test_sibling_blocks_do_not_add(self): self.assertEqual(one("fn f() { if a() {} if b() {} for _ in c() {} }").nesting, 1) def test_struct_literals_patterns_and_macros_do_not_nest(self): fn = one("fn f() { let p = Point { x: 1, y: 2 }; let Point { x, .. } = p; m! { 1 }; }") self.assertEqual(fn.nesting, 0) def test_closure_block_and_else_block_nest(self): fn = one("fn f() { let g = |v| { if v { 1 } else { 2 } }; }") self.assertEqual(fn.nesting, 2) def test_condition_struct_pattern_does_not_hide_the_block(self): fn = one("fn f() { if let Point { x, .. } = p() { if x > 0 {} } }") self.assertEqual(fn.nesting, 2) class RustKeys(unittest.TestCase): def test_methods_carry_the_impl_type_and_trait(self): found = rs(""" impl Wrapper { fn get(&self) {} } impl From for Wrapper { fn from(a: A) -> Self { todo!() } } mod inner { pub fn helper() {} } """) self.assertEqual(sorted(found), ["From for Wrapper::from", "Wrapper::get", "inner::helper"]) def test_repeated_keys_are_numbered_in_order(self): found = rs("impl From for X { fn from() {} }\nimpl From for X { fn from() {} }") self.assertEqual(sorted(found), ["From for X::from", "From for X::from#2"]) def test_impl_trait_in_a_signature_is_not_an_impl_block(self): found = rs("fn make(x: impl Fn(u8) -> u8) -> impl Iterator { fn inner() {} std::iter::empty() }") self.assertEqual(sorted(found), ["make", "make::inner"]) def test_cfg_test_modules_mark_their_functions(self): found = rs("fn prod() {}\n#[cfg(test)]\nmod tests {\n #[test]\n fn case() {}\n}") self.assertEqual((found["prod"].test, found["tests::case"].test), (False, True)) class PythonScan(unittest.TestCase): SOURCE = textwrap.dedent(''' class Box: def method(self, items): total = 0 for item in items: if item and item.ok or item.forced: total += 1 elif item.skip: continue return [x for x in items if x] def free(a): return a ''') def test_keys_lines_and_measures(self): found = {fn.key: fn for fn in pyscan.scan(self.SOURCE, set())} method = found["Box.method"] self.assertEqual((method.fn_lines, method.complexity, method.nesting), (8, 8, 2)) self.assertEqual(found["free"].complexity, 1) def test_nested_functions_are_separate(self): found = {fn.key: fn for fn in pyscan.scan("def a():\n def b(x):\n if x:\n pass\n", set())} self.assertEqual((found["a"].complexity, found["a.b"].complexity), (1, 2)) class Width(unittest.TestCase): def test_tabs_count_four_and_the_limit_is_inclusive(self): self.assertEqual(model.line_width("\tx\r\n", 4), 5) self.assertEqual(model.wide_lines("a" * 120 + "\n" + "a" * 121 + "\n\t" + "a" * 117, 120, 4), {2, 3}) def test_wide_lines_are_counted_per_function(self): text = "fn f() {\n let s = \"" + "x" * 130 + "\";\n}\n" (fn,) = files.scan_text(POLICY, "a.rs", text)[0] self.assertEqual(fn.width, 1) def state(rel, source, added=(), gaps=()): text = textwrap.dedent(source) fns, wide = files.scan_text(POLICY, rel, text) return gate.State(rel, text, fns, wide, diffs.Changes(list(added), list(gaps))) LONG = "fn long() {\n" + body(35) + "\n}\n" class DiffGate(unittest.TestCase): def check(self, states, entries=None): return gate.check_changed(states, entries or {}, LIMITS, 4) def test_a_changed_line_makes_an_overlong_function_an_error(self): result = self.check([state("a.rs", LONG, added=[5])]) self.assertEqual(result.errors, ["a.rs:1: long: lines 37 > 30"]) self.assertEqual(list(result.needs), [("a.rs", "long")]) def test_an_untouched_function_is_not_checked(self): self.assertEqual(self.check([state("a.rs", LONG + "fn other() {}\n", added=[39])]).errors, []) def test_deleted_lines_inside_a_function_touch_it(self): self.assertEqual(len(self.check([state("a.rs", LONG, gaps=[4])]).errors), 1) self.assertEqual(self.check([state("a.rs", LONG, gaps=[37])]).errors, []) def test_every_limit_fails_on_its_own(self): deep = "fn n() { if a() { if b() { if c() { if d() { if e() {} } } } } }\n" branchy = "fn c(x: u8) { " + "if x {} " * 10 + "}\n" errors = self.check([state("a.rs", deep + branchy, added=[1, 2])]).errors self.assertEqual(errors, ["a.rs:1: n: nesting 5 > 4", "a.rs:2: c: complexity 11 > 10"]) def test_wide_changed_lines_fail_but_unchanged_ones_do_not(self): wide = "const A: &str = \"" + "x" * 120 + "\";\nconst B: &str = \"" + "y" * 120 + "\";\n" errors = self.check([state("a.rs", wide, added=[2])]).errors self.assertEqual(errors, ["a.rs:2: width 139 > 120"]) def test_allowlisted_function_and_its_wide_lines_are_exempt(self): entries = {("a.rs", "long"): {"reason": "moved", "owner": "STRA-367"}} self.assertEqual(self.check([state("a.rs", LONG, added=range(1, 38))], entries).errors, []) def test_file_entry_covers_wide_lines_outside_functions(self): wide = "const B: &str = \"" + "y" * 120 + "\";\n" entries = {("a.rs", allow.FILE): {"width": 1}} self.assertEqual(self.check([state("a.rs", wide, added=[1])], entries).errors, []) empty = {("a.rs", allow.FILE): {"width": 0}} self.assertEqual(len(self.check([state("a.rs", wide, added=[1])], empty).errors), 1) def entry(**measures): return {"reason": "moved verbatim", "owner": "STRA-367", **measures} class AllowlistRatchet(unittest.TestCase): def run_check(self, entries, source=LONG): return gate.check_allowlist(entries, {"a.rs": state("a.rs", source)}, LIMITS) def test_an_unchanged_entry_is_clean(self): self.assertEqual(self.run_check({("a.rs", "long"): entry(fn_lines=37)}), ([], [])) def test_growth_is_an_error(self): errors, _ = self.run_check({("a.rs", "long"): entry(fn_lines=36)}) self.assertEqual(len(errors), 1) self.assertIn("fn_lines grew from 36 to 37", errors[0]) def test_shrinking_asks_for_a_tighter_entry(self): errors, stale = self.run_check({("a.rs", "long"): entry(fn_lines=50)}) self.assertEqual((errors, len(stale)), ([], 1)) def test_a_function_within_the_limits_is_stale(self): _, stale = self.run_check({("a.rs", "long"): entry(fn_lines=37)}, "fn long() {}\n") self.assertIn("within the limits", stale[0]) def test_a_missing_function_is_stale_and_a_missing_reason_is_an_error(self): errors, stale = self.run_check({("a.rs", "gone"): {"reason": " ", "owner": "STRA-367"}}) self.assertEqual((len(errors), len(stale)), (1, 1)) def test_tightening_lowers_and_drops_but_never_raises(self): entries = {("a.rs", "long"): entry(fn_lines=50, complexity=7), ("a.rs", "gone"): entry(fn_lines=40)} kept = gate.tightened(entries, {"a.rs": state("a.rs", LONG)}, LIMITS) self.assertEqual({key: row["fn_lines"] for key, row in kept.items()}, {("a.rs", "long"): 37}) self.assertEqual(kept[("a.rs", "long")]["complexity"], 1) class Diffs(unittest.TestCase): DIFF = textwrap.dedent("""\ diff --git a/a.rs b/a.rs --- a/a.rs +++ b/a.rs @@ -3,0 +4,2 @@ fn x +++ not a header +second @@ -10,2 +12 @@ -old one -old two +new @@ -20,2 +21,0 @@ -gone -gone diff --git a/b.rs b/c.rs --- a/b.rs +++ /dev/null """) def test_hunks_become_added_lines_and_gaps(self): changes = diffs.parse(self.DIFF) self.assertEqual(list(changes), ["a.rs"]) self.assertEqual((changes["a.rs"].added, changes["a.rs"].gaps), ([4, 5, 12], [21])) def git(root, *args): identity = ["-c", "user.name=t", "-c", "user.email=t@t"] subprocess.run(["git", *identity, *args], cwd=root, check=True, capture_output=True) class TempRepo(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.root = pathlib.Path(self.tmp.name) git(self.root, "init", "-q", "-b", "main") (self.root / "limits.json").write_text(json.dumps({ "limits": LIMITS, "tab_width": 4, "exclude": ["engine/strata/"], "python_include": [], "base_candidates": ["claude/hexagonal-integ", "main"]}), encoding="utf-8") self.write("old.rs", LONG) git(self.root, "add", "-A") git(self.root, "commit", "-q", "-m", "base") git(self.root, "checkout", "-q", "-b", "work") def tearDown(self): self.tmp.cleanup() def write(self, rel, text): (self.root / rel).parent.mkdir(parents=True, exist_ok=True) with open(self.root / rel, "w", encoding="utf-8", newline="\n") as handle: handle.write(text) def run_gate(self, *extra): with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): return cli.main(["--root", str(self.root), "--skip-census", *extra], self.root) class GateOnARepository(TempRepo): def test_untouched_legacy_passes(self): self.assertEqual(self.run_gate(), 0) def test_a_new_file_with_a_long_function_fails(self): self.write("new.rs", LONG) self.assertEqual(self.run_gate(), 1) def test_touching_a_legacy_function_fails_and_a_commit_does_not_hide_it(self): self.write("old.rs", LONG.replace("a3 = 3", "a3 = 33")) git(self.root, "commit", "-qam", "touch") self.assertEqual(self.run_gate(), 1) def test_a_moved_file_without_edits_passes(self): git(self.root, "mv", "old.rs", "moved.rs") self.assertEqual(self.run_gate(), 0) def test_allowlist_add_then_pass_then_growth_fails(self): self.write("new.rs", LONG) self.assertEqual(self.run_gate("--allowlist-add"), 1) self.assertEqual(self.run_gate("--allowlist-add", "--reason", "moved", "--owner", "STRA-367"), 0) self.assertEqual(self.run_gate(), 0) self.write("new.rs", LONG.replace("}\n", " let extra = 1;\n}\n")) self.assertEqual(self.run_gate(), 1) def test_excluded_paths_are_ignored(self): self.write("engine/strata/x.rs", LONG) self.assertEqual(self.run_gate(), 0) def test_base_resolution(self): head = diffs.git(self.root, "rev-parse", "main").strip() self.assertEqual(diffs.resolve_base(self.root, None, ["claude/hexagonal-integ", "main"])[0], head) self.assertEqual(diffs.resolve_base(self.root, "main", [])[0], head) with self.assertRaises(diffs.GitError): diffs.resolve_base(self.root, "nope", []) self.assertEqual(self.run_gate("--base", "nope"), 2) class Census(unittest.TestCase): def test_counts_per_scope_and_kind(self): text = LONG + "#[cfg(test)]\nmod tests {\n" + LONG.replace("long", "long_test") + "}\n" fns, wide = files.scan_text(POLICY, "src/a.rs", text) rows = census.tally("src/a.rs", fns, wide, LIMITS) self.assertEqual(sorted(rows), [("prod", "fn_lines", 1), ("test", "fn_lines", 1)]) def test_a_tests_directory_is_test_scope(self): fns, wide = files.scan_text(POLICY, "crates/x/tests/t.rs", LONG) self.assertEqual(census.tally("crates/x/tests/t.rs", fns, wide, LIMITS), [("test", "fn_lines", 1)]) def counts(prod=None, test=None): return {"prod": prod or {}, "test": test or {}} class BaselineRatchet(unittest.TestCase): OLD = {"census": counts({"a": {"fn_lines": 5, "width": 2}, "b": {"fn_lines": 3}})} def test_a_higher_total_is_an_error_and_a_lower_one_is_stale(self): errors, stale = baseline.findings(counts({"a": {"fn_lines": 6}, "b": {"fn_lines": 3}}), self.OLD) self.assertEqual((len(errors), len(stale)), (1, 1)) self.assertIn("prod fn_lines rose to 9", errors[0]) def test_code_moving_between_crates_keeps_its_total(self): moved = counts({"a": {"fn_lines": 2, "width": 2}, "c": {"fn_lines": 6}}) self.assertEqual(baseline.findings(moved, self.OLD), ([], [])) def test_a_rewrite_never_raises_a_total(self): new = {"census": counts({"a": {"fn_lines": 9, "width": 2}})} self.assertEqual(baseline.raised(self.OLD, new), ["prod fn_lines: total 8 -> 9"]) self.assertEqual(baseline.raised(self.OLD, {"census": counts({"a": {"fn_lines": 1}})}), []) class Policy(unittest.TestCase): def test_scope_of_files(self): self.assertEqual(policy.language(POLICY, "crates/x/src/a.rs"), "rust") self.assertIsNone(policy.language(POLICY, "engine/strata/src/a.rs")) self.assertIsNone(policy.language(POLICY, "crates/x/target/debug/build.rs")) self.assertEqual(policy.language(POLICY, "scripts/limits/cli.py"), "python") self.assertIsNone(policy.language(POLICY, "scripts/other.py")) def test_test_paths(self): for rel in ("crates/x/tests/a.rs", "crates/x/src/tests.rs", "crates/x/src/a_tests.rs", "a/benches/b.rs"): self.assertTrue(policy.is_test_path(rel), rel) self.assertFalse(policy.is_test_path("crates/x/src/lib.rs")) class ClippyRatchet(unittest.TestCase): @staticmethod def message(code, line, package="path+file:///w/crates/a#leleka-a@0.1.0"): return json.dumps({"reason": "compiler-message", "package_id": package, "message": {"code": {"code": code}, "spans": [{"is_primary": True, "file_name": "f.rs", "line_start": line, "column_start": 1}]}}) def test_counts_per_crate_once_per_site(self): lines = [self.message("clippy::too_many_lines", 1), self.message("clippy::too_many_lines", 1), self.message("clippy::too_many_arguments", 2), self.message("clippy::needless_return", 3), "not json"] expected = {"leleka-a": {"clippy::too_many_lines": 1, "clippy::too_many_arguments": 1}} self.assertEqual(clippy_ratchet.count(lines), expected) def test_package_id_forms(self): self.assertEqual(clippy_ratchet.crate_of("path+file:///w/crates/a#0.1.0"), "a") self.assertEqual(clippy_ratchet.crate_of("leleka-a 0.1.0 (path+file:///w/crates/a)"), "leleka-a") def test_totals_may_only_fall(self): base = {"a": {"clippy::too_many_lines": 2}} self.assertEqual(len(clippy_ratchet.compare({"a": {"clippy::too_many_lines": 3}}, base)[0]), 1) self.assertEqual(len(clippy_ratchet.compare({"b": {"clippy::too_many_lines": 1}}, base)[1]), 1) class ClippyConfig(unittest.TestCase): @staticmethod def keys(path): rows = [line.split("=", 1) for line in path.read_text(encoding="utf-8").splitlines() if "=" in line] return {key.strip(): value.strip() for key, value in rows if not key.startswith("#")} def test_the_root_thresholds_repeat_the_opt_in_ones_without_the_default_on_lint(self): root = pathlib.Path(__file__).resolve().parent.parent shared = self.keys(root / "clippy.toml") opt_in = self.keys(root / "scripts" / "limits" / "clippy" / "clippy.toml") self.assertEqual(shared, {key: opt_in[key] for key in shared}) self.assertNotIn("too-many-arguments-threshold", shared) self.assertEqual(opt_in["too-many-arguments-threshold"], "5") class PolicyFile(unittest.TestCase): def test_the_committed_policy_matches_lawbook_301(self): root = pathlib.Path(__file__).resolve().parent.parent self.assertEqual(policy.load(root).limits, {"fn_lines": 30, "complexity": 10, "nesting": 4, "width": 120}) if __name__ == "__main__": unittest.main()