diff options
Diffstat (limited to 'tests/architecture.rs')
| -rw-r--r-- | tests/architecture.rs | 216 |
1 files changed, 66 insertions, 150 deletions
diff --git a/tests/architecture.rs b/tests/architecture.rs index 7159b32..55d80a5 100644 --- a/tests/architecture.rs +++ b/tests/architecture.rs @@ -1,31 +1,16 @@ -//! The layer map, in one place, checked on every test run. +//! The layer map and the interface budgets, checked on every test run. //! -//! `tests/layers.rs` grew four greps for four mistakes. Four greps cannot say -//! what the architecture *is*, cannot tell you where a new module belongs, and -//! say nothing at all about the modules nobody has tripped over yet. This -//! declares the whole map instead: every module in `src/` gets a rank, and a -//! module may name only modules ranked strictly below it. One rule, every -//! module, and the direction of dependence is written down rather than -//! remembered. -//! -//! The same file holds the interface budgets. An interface is only as narrow as -//! the items a module hands out, so each module is budgeted on how many `pub` -//! items it declares and how many of them nothing outside the module ever -//! names. Budgets live in `architecture-budget.json` and may only shrink: a -//! number that grows fails the suite, and a number that has quietly got smaller -//! has to be written back at the lower value, which is what stops a widening -//! being mistaken for progress. -//! -//! `tools/arch-census.py` computes the same numbers for a human to read. -//! `the_census_tool_and_this_test_agree` is the seam between them. +//! Every module in `src/` gets a rank and may name only modules ranked strictly +//! below it. Each module is budgeted on how many `pub` items it declares and how +//! many of them nothing outside the module names; budgets live in +//! `architecture-budget.json` and may only shrink. `tools/arch-census.py` computes +//! the same numbers for a human to read. use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; -/// A module may name only modules ranked strictly below it. The order is the -/// dependency graph itself, so each rank is written with the reason it sits -/// there — a bare number invites someone to slot a module in wherever it is -/// convenient. +/// A module may name only modules ranked strictly below it; each rank is written +/// with the reason it sits there. const RANKS: &[(&str, u8, &str)] = &[ ("error", 0, "the crate's error type: nothing in the crate is beneath it"), ("hash", 1, "sha256 and canonical json: pure"), @@ -58,10 +43,6 @@ const RANKS: &[(&str, u8, &str)] = &[ ]; /// `pub use … ::*` a module is still allowed to keep, as `module -> count`. -/// This is the allowlist, and the ratchet is what empties it: a glob re-export -/// flattens a namespace so a reader cannot see a module's width from its -/// exports, which is the whole point of the budgets. `db` used to need two; it -/// now names every export, so the slot is closed rather than left at zero. const GLOB_ALLOWLIST: &[(&str, usize)] = &[("http", 2)]; const DECL_KEYWORDS: [&str; 7] = ["fn", "struct", "enum", "trait", "const", "static", "type"]; @@ -101,9 +82,7 @@ fn test_files() -> Vec<PathBuf> { } /// The module a file belongs to: a directory is one module, a top-level file is -/// a module of its own, and a binary keeps its own name. A map that lumped -/// eleven unrelated top-level files into one box could not say anything about -/// any of them. +/// a module of its own, and a binary keeps its own name. fn module_of(path: &Path) -> String { let rel = path.strip_prefix(src_root()).unwrap(); let parts: Vec<String> = rel.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect(); @@ -270,9 +249,8 @@ impl Census { } let used_by_tests = test_texts.iter().any(|t| mentions(t, name)); for module in declaring { - // An item the budget file argues for is a decision, not a hole, - // so it leaves the dead columns entirely. `deadonly` then means - // *dead and unargued* — the one number that can stay at zero. + // An item the budget file argues for leaves the dead columns, + // so `deadonly` means dead *and unargued*. if allowlist.contains(&format!("{module}.{name}")) { continue; } @@ -287,12 +265,8 @@ impl Census { } // A `pub(crate)` item is over-wide when no file except the one that - // declares it writes its name: it offers the crate a thing nothing - // outside its own file reaches, and plain private is what it should be. - // `tests/` is not consulted — a separate crate cannot name a `pub(crate)` - // item, so a mention there says nothing. As with `dead`, a name declared - // in several files is flagged only when no file outside all of them says - // it, and the compiler, not this count, gives the verdict. + // declares it names it. `tests/` is not consulted: a separate crate + // cannot name a `pub(crate)` item. let mut pc_declared: BTreeMap<String, BTreeSet<PathBuf>> = BTreeMap::new(); for (path, text) in &texts { for line in text.lines() { @@ -309,8 +283,7 @@ impl Census { } for path in files { let module = module_of(path); - // Argued, so not counted: the reason it stays `pub(crate)` is in - // the budget file next to its name, exactly as on the `pub` side. + // Argued in the budget file, so not counted. if over_allow.contains(&format!("{module}.{name}")) { continue; } @@ -477,9 +450,8 @@ fn dependence_only_points_downward() { #[test] fn the_map_admits_no_cycle() { - // Strictly downward edges make a cycle impossible by construction, which is - // the whole trick — so this asserts the property the map is trusted for, - // over the edges that actually exist, rather than trusting the ranks. + // Strictly downward edges make a cycle impossible; this checks the edges + // that exist rather than trusting the ranks. let census = Census::take(); let mut offenders = Vec::new(); for (source, targets) in &census.edges { @@ -529,11 +501,8 @@ fn budgeted(row: &Module) -> [(&'static str, usize); 5] { #[test] fn interfaces_stay_within_budget() { - // A `pub` item with no reader outside its module is not an interface, it is - // a hole: a thing a caller may depend on and a thing a later refactor cannot - // change without a grep across the crate. Zero holes is the destination, not - // the starting point, so the rule is the ratchet — `deadonly` is how many - // holes a module still has, and the only direction it may move is down. + // A `pub` item nobody outside its module reads is a hole, not an interface; + // `deadonly` counts them and may only move down. let census = Census::take(); let budget = Census::budget(); let mut over = Vec::new(); @@ -562,8 +531,7 @@ fn interfaces_stay_within_budget() { #[test] fn a_shrunk_interface_is_written_back() { - // The ratchet cuts both ways. A stale, generous budget is how a later - // widening slips through unnoticed, so the file has to say what is true. + // A stale, generous budget is how a widening slips through unnoticed. let census = Census::take(); let budget = Census::budget(); let mut stale = Vec::new(); @@ -587,9 +555,9 @@ fn a_shrunk_interface_is_written_back() { #[test] fn the_census_tool_and_this_test_agree() { - // Two implementations of one definition will drift, and a drift means the - // ratchet is measuring the wrong thing. Gated the way the vercmp oracle is: - // without python3 the note prints and the suite moves on. + // Two implementations of one definition drift, and a drift means the ratchet + // measures the wrong thing. Without python3 the note prints and the suite + // moves on. let available = std::process::Command::new("python3").arg("--version").output().is_ok(); if !available { println!("python3 is not on PATH — skipping the census cross-check"); @@ -639,23 +607,15 @@ fn the_census_tool_and_this_test_agree() { /// Every `pub` item that exists only because a test names it has a recorded /// disposition, and the counts may only shrink. /// -/// `tools/test-surface.py` asks two questions the census cannot: whether a test -/// actually *calls* the item or merely mentions it inside a string, and whether -/// production code inside the declaring module calls it. The answers yield four -/// dispositions — `gate`, `move-test`, `narrow`, `residue` — and this test holds -/// the crate to them in three ways: -/// -/// - every row must carry a hand-written reason from -/// `tools/test-surface-reasons.json`, so no item is disposed of by a heuristic -/// nobody read; -/// - the per-disposition counts, and `gate_pending` — items decided to be gated -/// but not yet gated — may only shrink against the budget. +/// `tools/test-surface.py` decides whether a test calls the item or merely +/// mentions it in a string, and whether production inside the module calls it; +/// the answers are the four dispositions `gate`, `move-test`, `narrow` and +/// `residue`. Every row carries a hand-written reason from +/// `tools/test-surface-reasons.json`. /// -/// `residue` is the honest column: items production needs inside their own module -/// *and* a fixture-bound integration test needs from outside. Rust has no -/// test-conditional visibility, so those cannot be narrowed without breaking one -/// side or the other; ratcheting the count is what keeps the column from growing -/// while it is worked down by changing tests rather than visibilities. +/// `residue` is the honest column: production needs the item inside its module +/// and a fixture-bound test needs it from outside, and Rust has no +/// test-conditional visibility. #[test] fn the_test_surface_is_disposed_of() { if !std::process::Command::new("python3").arg("--version").output().is_ok() { @@ -681,11 +641,8 @@ fn the_test_surface_is_disposed_of() { if !row.get("hand_written").and_then(serde_json::Value::as_bool).unwrap_or(false) { unreasoned.push(format!("{module}.{name} ({disp})")); } - // Every piece of in-module evidence for this item is a call in method - // position on some receiver. A name match cannot tell `self.store_dir()` - // from `listener.local_addr()` — the latter is std's, on a different - // type, and it once made a function with no callers look production-used. - // So these rows are named for a human and stay failing until confirmed. + // A name match cannot tell `self.store_dir()` from std's + // `listener.local_addr()`; ambiguous rows are named for a human. if row.get("dotted_only").and_then(serde_json::Value::as_bool).unwrap_or(false) && disp != "already-gated" && !row.get("confirmed").and_then(serde_json::Value::as_bool).unwrap_or(false) @@ -712,11 +669,8 @@ fn the_test_surface_is_disposed_of() { unconfirmed.join("\n") ); - // A row is `ambiguous` when the only evidence that production uses the item - // is a bare mention of a name the detector cannot resolve — `new`, `open` - // and `record` are declared in many modules, and a line saying `Foo::new()` - // in http says nothing about `db::open`. The tool genuinely does not know, - // so a human has to say which item the mention meant and record the verdict. + // A row is `ambiguous` when the only evidence is a bare mention of a + // name the detector cannot resolve, so a human records the verdict. let mut unadjudicated = Vec::new(); for row in rows { if row.get("ambiguous").and_then(serde_json::Value::as_bool).unwrap_or(false) @@ -767,20 +721,14 @@ fn the_test_surface_is_disposed_of() { ); } -/// The definitive check, and the slow one: compile a throwaway crate against -/// `aur-build` twice, once without `test-support` and once with it, and try to -/// name every dispositioned item from outside. +/// The definitive check: compile a throwaway crate against `aur-build` twice, +/// once without `test-support` and once with it, and try to name every +/// dispositioned item from outside. It asks the compiler what a release build +/// actually lets an outside crate reach, rather than inferring it from source. /// -/// `tools/test-surface.py` infers the test surface by reading source, and -/// inference has been wrong before — a name matched inside a string literal -/// made `review::approve::withdraw` look production-used, and keying rows by -/// bare name merged `pipeline::dispatch::Pool::shutdown` into the gated -/// `db::Writer::shutdown` row. This test does not read source. It asks the -/// compiler what a release build actually lets an outside crate reach. -/// -/// `#[ignore]`d because it builds the library twice from scratch, roughly -/// doubling the suite. Run it with `cargo test --test architecture -- --ignored` -/// or `AUR_PROBE_RELEASE_SURFACE=1 cargo test --test architecture`. +/// `#[ignore]`d because it builds the library twice. Run it with +/// `cargo test --test architecture -- --ignored` or +/// `AUR_PROBE_RELEASE_SURFACE=1 cargo test --test architecture`. #[test] #[ignore = "builds the library twice; run with --ignored or AUR_PROBE_RELEASE_SURFACE=1"] fn the_release_build_exports_nothing_that_only_tests_reach() { @@ -799,12 +747,8 @@ fn the_release_build_exports_nothing_that_only_tests_reach() { } /// The `dead_code.allowlist` is a set of decisions, so it has to stay in step -/// with the code in both directions. -/// -/// An entry that names nothing is the dangerous direction: it is an excuse that -/// outlived the item it excused, and the next item to appear under that name -/// inherits a permission nobody granted. The other direction — a blank reason — -/// is an entry nobody read, which is the same thing as no entry. +/// with the code in both directions: an entry naming nothing is an excuse that +/// outlived its item, and a blank reason is an entry nobody read. #[test] fn the_dead_code_allowlist_names_real_items() { let path = root().join("tests/architecture-budget.json"); @@ -816,9 +760,8 @@ fn the_dead_code_allowlist_names_real_items() { .and_then(|a| a.as_object()) .expect("budget file has a dead_code.allowlist object"); - // Every name a module declares, `pub` or `pub(crate)`: a narrowed item keeps - // its entry (the reason it is not named from outside still holds), an item - // that no longer exists does not. + // Every name a module declares, `pub` or `pub(crate)`: a narrowed item + // keeps its entry, a vanished item does not. let mut declared: BTreeMap<String, BTreeSet<String>> = BTreeMap::new(); for path in src_files() { let module = module_of(&path); @@ -866,15 +809,10 @@ fn the_dead_code_allowlist_names_real_items() { ); } -/// The `over_visibility.allowlist` is a set of decisions too, and it is checked -/// the same two ways: an entry must name something that is still `pub(crate)` in -/// the module it names, and it must carry a reason worth reading. -/// -/// The first direction matters more here than on the `pub` side. A `pub(crate)` -/// item that has since gone private still matches a `module.item` key written -/// against the module's declared names, so the check has to look at the -/// `pub(crate)` declarations specifically — otherwise the permission quietly -/// re-widens the item it was left behind by. +/// The `over_visibility.allowlist` is checked the same two ways. The direction +/// that matters here: a `pub(crate)` item that has since gone private still +/// matches a `module.item` key written against declared names, so the check +/// looks at `pub(crate)` declarations specifically. #[test] fn the_over_visibility_allowlist_names_real_items() { let path = root().join("tests/architecture-budget.json"); @@ -927,20 +865,9 @@ fn the_over_visibility_allowlist_names_real_items() { } /// `tests/common/mod.rs` is compiled into every test binary, so the suite keeps -/// a crate-level `allow(dead_code)` there — a helper used by one binary is dead -/// code in the other twenty, and the lint would fire everywhere and mean -/// nothing. That allowance is only honest if nothing is unused by *all* of them, -/// which is what this checks. -/// -/// A name is used if anything under `tests/` writes it besides its own -/// declaration. A type whose name nobody writes is still used if a field or -/// method of it is: `Web::raw_request` hands back a `Raw` no test names, and -/// reading `.status` off it is a use of the type. -/// -/// Private items are checked too. The blanket allowance in `tests/common` -/// excuses a private helper exactly as thoroughly as a public one, and a -/// private helper called by nothing is the harder case to notice, not the -/// easier one. +/// a crate-level `allow(dead_code)` there. That allowance is only honest if +/// nothing is unused by *all* of them, which is what this checks — private +/// helpers included, and a type whose members are read counts as used. #[test] fn the_test_helpers_are_used() { let common = root().join("tests/common/mod.rs"); @@ -953,9 +880,8 @@ fn the_test_helpers_are_used() { let lines: Vec<&str> = text.lines().collect(); let mut unused = Vec::new(); for (i, line) in lines.iter().enumerate() { - // `pub` and private alike: the blanket `allow(dead_code)` at the top of - // the file excuses both, so a private helper nobody calls is exactly as - // dead as a public one, and just as invisible to the compiler here. + // The blanket allowance excuses `pub` and private alike, so a private + // helper nobody calls is just as dead and just as invisible. let t = line.trim_start(); let indent = line.len() - t.len(); if indent > 4 { @@ -1013,9 +939,8 @@ fn the_test_helpers_are_used() { ); } -/// A fixture no test names is a corpus entry nobody maintains: it still costs -/// the copy every `env_with_fixture` performs on its way to failing, and it -/// drifts silently because nothing notices it drifting. +/// A fixture no test names still costs the copy every `env_with_fixture` +/// performs, and drifts silently because nothing reads it. #[test] fn every_fixture_is_referenced() { let corpus = root().join("testcorpus"); @@ -1038,14 +963,10 @@ fn every_fixture_is_referenced() { } /// The two places the budget states how many unargued dead items a module may -/// have must say the same thing. -/// -/// `modules.<m>.deadonly` is the ratchet `interfaces_stay_within_budget` reads; -/// `dead_code.deadonly.<m>` is the one `tools/arch-census.py --budget` reads. -/// They are written by the same invocation and disagree only if someone edited -/// one by hand, which is exactly the moment a ratchet stops meaning anything. -/// Both are zero, and zero is the point: an item that is dead, exported and -/// unargued is not a budget question, it is a failure. +/// have must say the same thing: `modules.<m>.deadonly` is what the ratchet +/// reads, `dead_code.deadonly.<m>` is what `tools/arch-census.py --budget` +/// reads. Both are zero: dead, exported and unargued is a failure, not a +/// budget question. #[test] fn the_dead_code_budget_matches_the_code() { let path = root().join("tests/architecture-budget.json"); @@ -1081,10 +1002,8 @@ fn the_dead_code_budget_matches_the_code() { #[test] fn the_over_visibility_budget_matches_the_code() { - // The same self-consistency the dead-code budget is held to: the accepted - // count, the number in the `modules` section, and the number the census - // actually measures have to be one number, or the ratchet is checking a - // figure nothing reads. + // The accepted count, the `modules` section and the measured number have to + // be one number, or the ratchet checks a figure nothing reads. let path = root().join("tests/architecture-budget.json"); let value: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&path).expect("read budget")).expect("budget is json"); @@ -1121,13 +1040,10 @@ fn the_over_visibility_budget_matches_the_code() { ); } -/// Two tools write one file, so neither may erase what the other owns. -/// -/// `tools/arch-census.py` writes the module numbers and the accepted dead-code -/// counts; `tools/test-surface.py` writes the test-surface counts; a human owns -/// the allowlist. A rewrite that drops a section does not fail anything until -/// the ratchet quietly stops checking that axis, so this runs both writers -/// against a copy and fails if either section disappears. +/// Two tools write one file, so neither may erase what the other owns: a +/// dropped section fails nothing until the ratchet quietly stops checking that +/// axis, so this runs both writers against a copy and fails if either section +/// disappears. #[test] fn the_budget_writers_preserve_each_other() { let source = std::fs::read_to_string(root().join("tests/architecture-budget.json")).expect("read budget"); |
