Files
leleka/scripts/check_limits_test.py
T
Pavlo Ratushnyi 056ab3d689 Retire the oracles, generators and scripts that only worked against the vendored Strata tree (STRA-406)
The vendored Strata tree engine/strata is removed for good (owner decision 2026-11-23): Leleka never builds or runs it, the vanilla
benchmark builds from its own checkout, the comparison measurements are finished and the CUDA ports are frozen. Everything below
compiled or read that tree, so it cannot run without it and is retired (the tree stays in git history, see third_party/strata/UPSTREAM.md).
Checked-in fixtures, golden JSON, sealed PTX, seal plans and MANIFEST hashes are untouched and keep being replayed by the cargo tests.

Drift guard
- crates/experimental-ref/tests/literal_port.rs: include_str! of the Original .cu files compared with the checked-in experimental ports.

Oracle generators and builders (they compile or extract from the Strata C++/Python sources; their outputs are the checked-in goldens)
- crates/experimental-ref/oracle/gen_{cvec,kv,remote,stream}_golden.{cpp,sh}, gen_seal_additions.py and the cuda_runtime stub they used
- crates/sampler-ref/oracle/build_oracle.sh, gen_fixtures.cpp, gen_sampling_keys.py, stub/ (run_port_host_tests.sh and the fixtures stay)
- crates/serving-policy/oracle/ (build_oracle.sh, gen_{host,cvec,vision}_fixtures.cpp)
- crates/context/tests/rope_plan_golden/gen_* (plan, rope, kv pool)
- crates/engine-core/src/conversation/golden/gen*.{sh,cpp} and stub/
- crates/cuda-driver/oracle/gen_prefill_ring_trace.py and drivers/prefill_ring_trace.cpp (extracted prefill.cpp), check_cu_syntax.sh
- crates/engine-qwen35-cuda/tests/stra161_reference/reference.py (fixtures.json and the Rust constants stay)
- control-plane/tests/golden/gen_goldens.py, scripts/offline/ (Python differentials and golden generators against the Strata Python tools)

Source-compiling CUDA oracles and builders
- scripts/build-cuda-{projection-family,q5,q6,qsa}-oracle.sh with scripts/cuda-{projection-family,q5,q6,qsa}-oracle/ (include the Original .cu; sha256 pins of them)
- scripts/build-original-verify-ptx.sh, scripts/q8/rebuild_quantizer_ptx.sh, scripts/decode-sm120/make_iq_prefix.py (needs engine/strata/include)
- scripts/cuda-stubs/ (check-cu.py and literal_diff.py need the strata headers and the Original sources; the stub headers served only them)
- tools/chain-probe/build.sh, tools/kernel-ab/{cpp,aa.sh,smoke.sh,time_smoke.sh} (the C++ comparator is built from the Strata CPU kernels; verify_manifest.py stays)
- scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/ (compiles the upstream kernel from the tree)

Engine builds and Python smokes that need the tree
- scripts/build-cpu.sh, scripts/build-static-cuda.sh, scripts/check-keyless-gpu.sh, scripts/test-static-cuda-profile.py (CMake of engine/strata)
- scripts/compare-real-tokenizer.py, scripts/smoke-mtp-pack.py (reads src/core/mtp.cpp and a bench manifest), scripts/prepare-keyless-routing.py and its test
- scripts/smoke-native-pack.py became scripts/native-pack-fixture.py: the synthetic GGUF fixtures the four other smokes import stay, the iq_pack.py oracle comparison goes

Gates and CI
- scripts/check-local.sh: no live Python oracle differentials, no literal_port note, no check-cu, no build-cpu, no retired test scripts
- .github/workflows/linux.yml: the keyless-cuda, static-cuda-package and hosted-cuda-package jobs (they built the engine from the tree) and their dispatch
  inputs, and the two oracle smoke steps; .github/workflows/port.yml: the Python oracle environment and the llama.cpp fetch of port-oracles
  (the sampler host shim still runs)
- limits.json and scripts/check_limits_test.py exclude third_party/strata/ instead of engine/strata/

Documentation and comments: README.md names third_party/strata and the pin; deploy/README.md marks the retired build and smoke commands; comments
in Rust, Python and Markdown that named engine/strata/... now name "Strata 41cf05a0, ..."; the gpu-bringup scratch-copy test no longer copies the
removed include directories. Stale engine/strata paths in sealed .cu, .ptx, seal-plan and MANIFEST files are left as they are (hashes may depend on the bytes).
2026-11-23 21:19:11 +01:00

499 lines
22 KiB
Python
Executable File

#!/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, "params": 5}, 4,
("third_party/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<u8>) -> Option<u8> {{\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<T: Clone> Wrapper<T> { fn get(&self) {} }
impl From<A> for Wrapper<u8> { 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<A> for X { fn from() {} }\nimpl From<B> 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<Item = u8> { 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": ["third_party/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("third_party/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, "third_party/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 Parameters(unittest.TestCase):
"""Lawbook 301: at most 5 parameters, `self` counted; FFI and test functions count like the rest."""
def count(self, signature):
return one(signature + " {}").params
def test_counts_every_parameter_and_self(self):
self.assertEqual(self.count("fn a()"), 0)
self.assertEqual(self.count("fn a(&self)"), 1)
self.assertEqual(self.count("fn a(&mut self, x: u8, y: u8)"), 3)
self.assertEqual(self.count("fn a(self: Box<Self>, x: u8)"), 2)
def test_a_trailing_comma_and_multiline_lists_are_free(self):
self.assertEqual(self.count("fn a(\n x: u8,\n y: u8,\n)"), 2)
def test_commas_inside_types_patterns_and_closures_do_not_count(self):
self.assertEqual(self.count("fn a(m: HashMap<K, V>, t: (u8, u8), s: [u8; 4])"), 3)
self.assertEqual(self.count("fn a(f: impl Fn(u8, u8) -> Result<u8, E>, g: &dyn Fn(A, B))"), 2)
self.assertEqual(self.count("fn a(Foo { x, y }: Foo, (p, q): (u8, u8))"), 2)
def test_generics_before_the_list_are_skipped(self):
self.assertEqual(self.count("fn a<T: Into<u8>, U>(x: T, y: U) -> Option<(u8, u8)>"), 2)
def test_ffi_and_test_functions_count_like_any_other(self):
ffi = 'pub unsafe extern "C" fn a(a: *mut u8, b: i32, c: i32, d: i32, e: i32, f: i32)'
self.assertEqual(self.count(ffi), 6)
text = "#[cfg(test)]\nmod t {\n fn a(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) {}\n}\n"
(fn,) = rscan.scan(text, set())
self.assertEqual((fn.params, fn.test), (6, True))
def test_python_counts_self_keyword_only_and_star_arguments(self):
(fn,) = pyscan.scan("def f(self, a, /, b, *args, c, **kw):\n pass\n", set())
self.assertEqual(fn.params, 6)
def test_the_diff_gate_rejects_a_changed_function_with_six_parameters(self):
six = "fn a(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) {}\n"
errors = gate.check_changed([state("a.rs", six, added=[1])], {}, LIMITS, 4).errors
self.assertEqual(errors, ["a.rs:1: a: parameters 6 > 5"])
five = "fn a(a: u8, b: u8, c: u8, d: u8, e: u8) {}\n"
self.assertEqual(gate.check_changed([state("a.rs", five, added=[1])], {}, LIMITS, 4).errors, [])
def test_the_census_counts_functions_over_the_limit(self):
(fn,) = rscan.scan("fn a(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) {}\n", set())
self.assertEqual(census.tally("src/a.rs", [fn], set(), LIMITS), [("prod", "params", 1)])
class PolicyFile(unittest.TestCase):
def test_the_committed_policy_matches_lawbook_301(self):
root = pathlib.Path(__file__).resolve().parent.parent
want = {"fn_lines": 30, "complexity": 10, "nesting": 4, "width": 120, "params": 5}
self.assertEqual(policy.load(root).limits, want)
if __name__ == "__main__":
unittest.main()