Files
leleka/scripts/check_architecture_test.py
T
Pavlo Ratushnyi 82d31e68da STRA-338 S13: the source ratchets also skip an inline module under a test cfg
An inline `#[cfg(all(test, ...))] mod x {` proof module in a production file (gdn_chain, gdn_verification,
mtp_expert_workspace, kar_ple_cache) was counted. production_lines now skips it up to its closing brace
and still counts the code after it. Accounting only: env-read leleka-runtime 101 to 93, leleka-cuda-driver
77 to 76, instant-now strata-control 37 to 35; nothing rose.
2026-11-05 21:44:34 +01:00

178 lines
8.5 KiB
Python

#!/usr/bin/env python3
"""Negative and positive proofs for the architecture gate: each rule must fail on a synthetic violation.
Usage: python3 scripts/check_architecture_test.py (no cargo, no network)
"""
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from archcheck import baseline as bl # noqa: E402
from archcheck import measure, rules # noqa: E402
CONFIG = {
"max_lines": 400,
"adapter_layer": "L3",
"pure_layers": ["L0", "L1"],
"forbidden_in_pure": ["tokio"],
"layers": {"L0": ["api"], "L1": ["lib"], "L2": ["core"], "L3": ["adapter-a", "adapter-b"], "L4": ["host"]},
"adapter_edges": [["adapter-b", "adapter-a"]],
}
EMPTY = {"violations": [], "oversize": {}, "source": {}}
def pkg(name, normal=(), external=()):
return {"name": name, "dir": pathlib.Path(name), "normal": list(normal), "external": list(external)}
def packages(**overrides):
base = {
"api": pkg("api"), "lib": pkg("lib", ["api"]), "core": pkg("core", ["lib"]),
"adapter-a": pkg("adapter-a", ["core"]), "adapter-b": pkg("adapter-b", ["core", "adapter-a"]),
"host": pkg("host", ["adapter-a", "adapter-b", "core"]),
}
base.update(overrides)
return list(base.values())
def run(pkgs, baseline=None, sizes=None, counts=None):
return rules.evaluate(pkgs, CONFIG, baseline or EMPTY, sizes or {}, counts or {})
def base(violations=(), oversize=None, source=None):
return {"violations": list(violations), "oversize": oversize or {}, "source": source or {}}
class GraphRules(unittest.TestCase):
def test_clean_graph_passes(self):
found = run(packages())
self.assertEqual((found.errors, found.debt, found.stale), ([], [], []))
def test_upward_edge_fails(self):
found = run(packages(core=pkg("core", ["host"])))
self.assertIn("layer-up core -> host", found.violations)
self.assertEqual(len(found.errors), 1)
def test_core_may_not_depend_on_an_adapter(self):
found = run(packages(core=pkg("core", ["adapter-a"])))
self.assertTrue(any("core (L2) depends on adapter-a (L3)" in e for e in found.errors))
def test_sideways_adapter_edge_fails_unless_listed(self):
found = run(packages(**{"adapter-a": pkg("adapter-a", ["adapter-b"])}))
self.assertIn("adapter-sideways adapter-a -> adapter-b", found.violations)
self.assertEqual(run(packages()).errors, [])
def test_unassigned_package_fails(self):
found = run(packages(extra=pkg("extra")))
self.assertTrue(any("extra has no layer" in e for e in found.errors))
def test_pure_crate_with_forbidden_dependency_fails_but_an_adapter_may_use_it(self):
found = run(packages(lib=pkg("lib", ["api"], ["tokio"])))
self.assertIn("forbidden-dep lib tokio", found.violations)
self.assertEqual(run(packages(**{"adapter-a": pkg("adapter-a", ["core"], ["tokio"])})).errors, [])
def test_baselined_violation_is_debt_and_a_fixed_one_is_stale(self):
known = base(violations=["layer-up core -> host"])
found = run(packages(core=pkg("core", ["host"])), known)
self.assertEqual((found.errors, found.debt), ([], ["layer-up core -> host"]))
self.assertEqual(len(run(packages(), known).stale), 1)
class SizeAndRatchetRules(unittest.TestCase):
def test_new_large_file_fails_and_a_file_at_the_limit_passes(self):
self.assertEqual(len(run(packages(), sizes={"big.rs": 401}).errors), 1)
self.assertEqual(run(packages(), sizes={"ok.rs": 400}).errors, [])
def test_baselined_large_file_may_not_grow_and_shrinking_is_stale(self):
known = base(oversize={"big.rs": 900})
self.assertEqual(run(packages(), known, {"big.rs": 900}).errors, [])
self.assertEqual(len(run(packages(), known, {"big.rs": 901}).errors), 1)
self.assertEqual(len(run(packages(), known, {"big.rs": 700}).stale), 1)
def test_ratchet_may_only_fall(self):
known = base(source={"env-read:host": 10})
self.assertEqual(run(packages(), known, counts={"env-read:host": 10}).errors, [])
self.assertEqual(len(run(packages(), known, counts={"env-read:host": 11}).errors), 1)
self.assertEqual(len(run(packages(), known, counts={"env-read:host": 9}).stale), 1)
def test_new_ratchet_key_starts_at_zero(self):
self.assertEqual(len(run(packages(), counts={"env-read:host": 1}).errors), 1)
class BaselineRewrite(unittest.TestCase):
def test_refuses_increase_and_accepts_decrease(self):
old = base(oversize={"a.rs": 500}, source={"env-read:host": 3})
higher = base(["layer-up a -> b"], {"a.rs": 501}, {"env-read:host": 4})
self.assertEqual(len(bl.raised(old, higher)), 3)
self.assertEqual(bl.raised(old, base(oversize={"a.rs": 450}, source={"env-read:host": 2})), [])
def test_code_that_moved_between_crates_keeps_its_total(self):
old = base(source={"env-read:host": 3})
self.assertEqual(bl.raised(old, base(source={"env-read:other": 3})), [])
def test_a_moved_file_is_accepted_but_a_new_large_one_is_not(self):
old = base(oversize={"src/a.rs": 500})
self.assertEqual(bl.raised(old, base(oversize={"src/sub/a.rs": 500})), [])
self.assertEqual(len(bl.raised(old, base(oversize={"src/sub/a.rs": 501}))), 1)
self.assertEqual(len(bl.raised(old, base(oversize={"src/a.rs": 500, "src/b.rs": 450}))), 1)
def test_a_split_may_add_only_its_module_declaration(self):
old = base(oversize={"src/big.rs": 1000})
self.assertEqual(bl.raised(old, base(oversize={"src/big.rs": 503, "src/big/tests.rs": 500})), [])
def test_a_split_into_a_same_stem_directory_may_not_gain_lines(self):
old = base(oversize={"src/big.rs": 1000})
self.assertEqual(bl.raised(old, base(oversize={"src/big.rs": 500, "src/big/part.rs": 480})), [])
self.assertEqual(len(bl.raised(old, base(oversize={"src/big.rs": 600, "src/big/part.rs": 480}))), 1)
class Measurement(unittest.TestCase):
def test_counter_stops_at_a_test_module_and_skips_comments(self):
text = 'let a = std::env::var("A");\n// env::var("B")\n#[cfg(test)]\nmod t {}\nlet c = env::var("C");\n'
self.assertEqual(measure.production_lines(text), ['let a = std::env::var("A");'])
def test_a_single_cfg_test_function_does_not_hide_the_code_after_it(self):
text = '#[cfg(test)]\nfn only_tests() {}\nlet a = env::var("A");\n'
self.assertEqual(len(measure.production_lines(text)), 3)
def test_an_inline_module_under_another_test_cfg_is_skipped_but_the_code_after_it_counts(self):
text = ('let a = env::var("A");\n#[cfg(all(test, unix))]\nmod proof {\n let b = env::var("B");\n}\n'
'#[cfg(not(test))]\nmod live {\n let c = env::var("C");\n}\nlet d = env::var("D");\n')
rows = measure.production_lines(text)
self.assertEqual([r for r in rows if "env::var" in r], [
'let a = env::var("A");', ' let c = env::var("C");', 'let d = env::var("D");'])
def test_counts_are_per_crate_and_skip_test_files(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
src.mkdir()
(src / "lib.rs").write_text('let a = env::var("A");\n')
(src / "tests.rs").write_text('let b = env::var("B");\n')
package = dict(pkg("p"), dir=pathlib.Path(tmp))
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}])
self.assertEqual(counts, {"e:p": 1})
def test_modules_declared_under_a_test_cfg_are_not_production(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
(src / "a" / "proofs").mkdir(parents=True)
(src / "lib.rs").write_text('mod a;\nmod b;\nlet a = env::var("A");\n')
(src / "b.rs").write_text('let b = env::var("B");\n')
(src / "a.rs").write_text(
'let c = env::var("C");\n#[cfg(not(test))]\nmod live;\n'
'#[cfg(all(\n test,\n target_os = "linux"\n))]\n#[path = "a/proofs/x.rs"]\nmod proof;\n'
'#[cfg(test)]\nmod helper;\n')
(src / "a" / "proofs" / "x.rs").write_text('let d = env::var("D");\n')
(src / "a" / "helper.rs").write_text('let e = env::var("E");\n')
(src / "a" / "live.rs").write_text('let f = env::var("F");\n')
package = dict(pkg("p"), dir=pathlib.Path(tmp))
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}])
self.assertEqual(counts, {"e:p": 4})
if __name__ == "__main__":
unittest.main()