diff options
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/architecture.rs | 184 | ||||
| -rw-r--r-- | tests/common/mod.rs | 10 | ||||
| -rw-r--r-- | tests/dispatch.rs | 5 |
3 files changed, 183 insertions, 16 deletions
diff --git a/tests/architecture.rs b/tests/architecture.rs index 6f68f2b..696bac1 100644 --- a/tests/architecture.rs +++ b/tests/architecture.rs @@ -143,13 +143,19 @@ fn pub_decl(line: &str) -> Option<String> { } fn is_pub_crate_decl(line: &str) -> bool { + pub_crate_decl(line).is_some() +} + +/// The name a `pub(crate)` declaration introduces. A narrowed item is still a +/// member of its module, which is what the allowlist is checked against. +fn pub_crate_decl(line: &str) -> Option<String> { if is_comment(line) { - return false; + return None; } - let Some(rest) = line.trim_start().strip_prefix("pub(crate) ") else { - return false; - }; - DECL_KEYWORDS.into_iter().any(|kw| rest.starts_with(&format!("{kw} "))) + let rest = line.trim_start().strip_prefix("pub(crate) ")?; + let keyword = DECL_KEYWORDS.into_iter().find(|kw| rest.starts_with(&format!("{kw} "))) ?; + let name = word_tail(&rest[keyword.len() + 1..]); + (!name.is_empty()).then_some(name) } fn is_glob_reexport(line: &str) -> bool { @@ -798,3 +804,171 @@ fn the_release_build_exports_nothing_that_only_tests_reach() { "the probe did not report success:\n{text}" ); } + +/// 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. +#[test] +fn the_dead_code_allowlist_names_real_items() { + let path = root().join("tests/architecture-budget.json"); + let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {}", path.display(), e)); + let value: serde_json::Value = serde_json::from_str(&text).expect("budget file is json"); + let allow = value + .get("dead_code") + .and_then(|d| d.get("allowlist")) + .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. + let mut declared: BTreeMap<String, BTreeSet<String>> = BTreeMap::new(); + for path in src_files() { + let module = module_of(&path); + for line in std::fs::read_to_string(&path).expect("read source").lines() { + let name = match pub_decl(line) { + Some(name) => name, + None => match pub_crate_decl(line) { + Some(name) => name, + None => continue, + }, + }; + if !name.is_empty() { + declared.entry(module.clone()).or_default().insert(name); + } + } + } + + let mut stale = Vec::new(); + let mut blank = Vec::new(); + for (key, reason) in allow { + let Some((module, name)) = key.split_once('.') else { + stale.push(format!("{key}: a key is `module.item`")); + continue; + }; + if reason.as_str().map(|r| r.trim().len() < 20).unwrap_or(true) { + blank.push(key.clone()); + } + if !declared.get(module).is_some_and(|names| names.contains(name)) { + stale.push(format!("{key} at {reason}")); + } + } + stale.sort(); + blank.sort(); + assert!( + stale.is_empty(), + "these allowlist entries name something the module no longer declares.\n\ + A permission nobody can point at is how a dead item returns unnoticed:\n{}", + stale.join("\n") + ); + assert!( + blank.is_empty(), + "these allowlist entries have no reason (or one too short to be a reason):\n{}\n\ + an item is kept by an argument, not by a blank line.", + blank.join("\n") + ); +} + +/// `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. +#[test] +fn the_test_helpers_are_used() { + let common = root().join("tests/common/mod.rs"); + let text = std::fs::read_to_string(&common).expect("read tests/common/mod.rs"); + let mut others = String::new(); + for path in test_files() { + others.push_str(&std::fs::read_to_string(&path).expect("read test")); + } + + let lines: Vec<&str> = text.lines().collect(); + let mut unused = Vec::new(); + for (i, line) in lines.iter().enumerate() { + let t = line.trim_start(); + let Some(rest) = t.strip_prefix("pub ") else { continue }; + let rest = rest.trim_start(); + let Some(kind) = ["fn ", "struct ", "enum ", "const ", "static ", "type ", "trait "] + .into_iter() + .find(|k| rest.starts_with(k)) + else { + continue; + }; + let name = word_tail(&rest[kind.len()..]); + if name.is_empty() { + continue; + } + // Everything this declaration introduces, minus the declaration itself. + let mut corpus = others.replace(&format!("pub {kind}{name}"), ""); + if kind != "fn " { + // Members of a struct or enum count as uses of the type. + let mut depth = 0; + for follow in lines[i..].iter() { + depth += follow.matches('{').count() as i32 - follow.matches('}').count() as i32; + if depth > 1 { + let member = follow + .trim_start() + .trim_start_matches("pub ") + .split([':', '(']) + .next() + .unwrap_or("") + .split_whitespace() + .last() + .unwrap_or(""); + if !member.is_empty() && member != name { + corpus.push('\n'); + corpus.push_str(member); + } + } + if depth <= 0 && follow != line { + break; + } + } + } + if !mentions(&corpus, &name) { + unused.push(format!("{name} ({})", &t[..t.len().min(60)])); + } + } + unused.sort(); + assert!( + unused.is_empty(), + "these test helpers are named by no test:\n{}\n\ + delete them; `allow(dead_code)` in `tests/common` excuses per-binary \ + noise, not dead weight.", + unused.join("\n") + ); +} + +/// 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. +#[test] +fn every_fixture_is_referenced() { + let corpus = root().join("testcorpus"); + let mut names = String::new(); + for path in test_files() { + names.push_str(&std::fs::read_to_string(&path).expect("read test")); + } + let unreferenced: Vec<String> = std::fs::read_dir(&corpus) + .expect("read testcorpus") + .filter_map(|e| e.ok()) + .filter(|e| e.file_type().is_ok_and(|t| t.is_dir())) + .map(|e| e.file_name().to_string_lossy().to_string()) + .filter(|name| !mentions(&names, name)) + .collect(); + assert!( + unreferenced.is_empty(), + "these fixtures in testcorpus/ are named by no test: {unreferenced:?}\n\ + either drive one or delete the directory.", + ); +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 5c48923..0b46aeb 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -1,3 +1,7 @@ +// Every test binary compiles this file, so a helper that one of them uses is +// dead code in the other twenty and the lint would fire everywhere and mean +// nothing. `the_test_helpers_are_used` in tests/architecture.rs is the check +// that does matter: a helper no test names is deleted, not excused. #![allow(dead_code)] use std::collections::HashMap; @@ -507,12 +511,6 @@ impl Fixture { git(&up, &["rev-parse", "HEAD"]) } - pub fn upstream2_commit(&self, body: &str) -> String { - let up = self.upstream2.clone().expect("fixture has no second upstream repo"); - git_add_commit(&up, &[(("README"), body)], body); - git(&up, &["rev-parse", "HEAD"]) - } - pub fn upstream_head(&self) -> String { let up = self.upstream.clone().expect("fixture has no upstream repo"); git(&up, &["rev-parse", "HEAD"]) diff --git a/tests/dispatch.rs b/tests/dispatch.rs index 9381a17..a2aaeed 100644 --- a/tests/dispatch.rs +++ b/tests/dispatch.rs @@ -1,9 +1,7 @@ mod common; -use std::sync::atomic::AtomicBool; use std::sync::Arc; -use aur_build::config::Config; use aur_build::db::{self, builds, model::*}; use aur_build::pipeline::{self, dispatch}; use aur_build::review::{candidates, diff}; @@ -254,6 +252,3 @@ fn wait_for(env: &Env, id: &str, want: &[BuildState]) -> BuildState { } panic!("build {id} never reached {want:?}"); } - -#[allow(dead_code)] -fn unused(_: AtomicBool, _: Config) {} |
