summaryrefslogtreecommitdiffstats
path: root/tests/architecture.rs
diff options
context:
space:
mode:
authoraur-build <aur-build@localhost>2026-11-21 14:01:34 +0000
committeraur-build <aur-build@localhost>2026-11-21 14:01:34 +0000
commit47f6c6db7faedc292fb55b6637a5f6e292ffcaec (patch)
tree3baf3934f00d7280e649d48de3a6cf19d88a09ec /tests/architecture.rs
parent7afffd1a0ca798dd5826c2e1881b09fe135dbcbd (diff)
downloadaur-build-47f6c6db7faedc292fb55b6637a5f6e292ffcaec.tar.gz
aur-build-47f6c6db7faedc292fb55b6637a5f6e292ffcaec.zip
tests: make the blanket `allow(dead_code)` in the test tier worth keeping
`tests/common/mod.rs` opened with `#![allow(dead_code)]` and nothing else, which means it could have been hiding helpers no test called. It was not hiding many — `upstream2_commit` and nothing else at file scope — but "not many" is not a check, and the file cannot simply drop the allowance: it is compiled into every test binary, so a helper one binary uses is dead code in the other twenty and the lint fires everywhere and means nothing. So the allowance stays and the check moves up a level. `the_test_helpers_are_used` reads the file and fails on any `pub` item no test writes, counting a type as used when a field or method of it is — `Web::raw_request` hands back a `Raw` no test ever names. `every_fixture_is_referenced` does the same for `testcorpus/`, which had one entry, `git-submodules`, that no test had ever driven; it is gone. Both were checked by planting a dead helper and a dead fixture and watching the suite refuse them. `tests/dispatch.rs` also carried a function whose entire body was an `#[allow(dead_code)]` on `fn unused(_: AtomicBool, _: Config) {}` — the deadest code in the repository, with its two imports behind it.
Diffstat (limited to 'tests/architecture.rs')
-rw-r--r--tests/architecture.rs184
1 files changed, 179 insertions, 5 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.",
+ );
+}