diff options
Diffstat (limited to 'tests/architecture.rs')
| -rw-r--r-- | tests/architecture.rs | 220 |
1 files changed, 66 insertions, 154 deletions
diff --git a/tests/architecture.rs b/tests/architecture.rs index b32ea54..7159b32 100644 --- a/tests/architecture.rs +++ b/tests/architecture.rs @@ -106,10 +106,7 @@ fn test_files() -> Vec<PathBuf> { /// any of them. 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(); + let parts: Vec<String> = rel.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect(); match parts.as_slice() { [only] => only.trim_end_matches(".rs").to_string(), [head, rest @ ..] if head == "bin" => { @@ -125,9 +122,7 @@ fn is_comment(line: &str) -> bool { } fn word_tail(rest: &str) -> String { - rest.chars() - .take_while(|c| c.is_alphanumeric() || *c == '_') - .collect() + rest.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect() } /// The name a `pub` declaration introduces, if this line declares one. `pub @@ -153,7 +148,7 @@ fn pub_crate_decl(line: &str) -> Option<String> { return None; } let rest = line.trim_start().strip_prefix("pub(crate) ")?; - let keyword = DECL_KEYWORDS.into_iter().find(|kw| rest.starts_with(&format!("{kw} "))) ?; + 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) } @@ -163,13 +158,7 @@ fn is_glob_reexport(line: &str) -> bool { return false; } let t = line.trim_start(); - let after = match t - .strip_prefix("pub(crate) use ") - .or_else(|| t.strip_prefix("pub use ")) - { - Some(after) => after, - None => return false, - }; + let Some(after) = t.strip_prefix("pub(crate) use ").or_else(|| t.strip_prefix("pub use ")) else { return false }; after.contains("::*") } @@ -238,14 +227,10 @@ struct Census { impl Census { fn take() -> Census { let files = src_files(); - let texts: Vec<(PathBuf, String)> = files - .iter() - .map(|f| (f.clone(), std::fs::read_to_string(f).expect("read source"))) - .collect(); - let test_texts: Vec<String> = test_files() - .iter() - .map(|f| std::fs::read_to_string(f).expect("read test")) - .collect(); + let texts: Vec<(PathBuf, String)> = + files.iter().map(|f| (f.clone(), std::fs::read_to_string(f).expect("read source"))).collect(); + let test_texts: Vec<String> = + test_files().iter().map(|f| std::fs::read_to_string(f).expect("read test")).collect(); let mut modules: BTreeMap<String, Module> = BTreeMap::new(); let allowlist = allowed_pub_items(); @@ -278,9 +263,8 @@ impl Census { for module in declaring { modules.get_mut(module).unwrap().pub_items += 1; } - let read_outside = texts - .iter() - .any(|(path, text)| !declaring.contains(&module_of(path)) && mentions(text, name)); + let read_outside = + texts.iter().any(|(path, text)| !declaring.contains(&module_of(path)) && mentions(text, name)); if read_outside { continue; } @@ -319,9 +303,7 @@ impl Census { } let over_allow = allowed_overwide_items(); for (name, files) in &pc_declared { - let read_outside = texts - .iter() - .any(|(path, text)| !files.contains(path) && mentions(text, name)); + let read_outside = texts.iter().any(|(path, text)| !files.contains(path) && mentions(text, name)); if read_outside { continue; } @@ -360,19 +342,10 @@ impl Census { /// The budget file, as `module -> key -> allowed`. fn budget() -> BTreeMap<String, BTreeMap<String, usize>> { 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 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 mut out = BTreeMap::new(); - let modules = value - .get("modules") - .and_then(|m| m.as_object()) - .expect("budget file has a modules object"); + let modules = value.get("modules").and_then(|m| m.as_object()).expect("budget file has a modules object"); for (module, row) in modules { let mut keys = BTreeMap::new(); if let Some(row) = row.as_object() { @@ -394,19 +367,14 @@ fn allowed_pub_items() -> BTreeSet<String> { 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"); - value - .get("dead_code") - .and_then(|d| d.get("allowlist")) - .and_then(|a| a.as_object()) - .map(|a| { - a.keys() - .map(|k| { - assert!(!k.trim().is_empty(), "an allowlist key cannot be blank"); - k.clone() - }) - .collect() - }) - .unwrap_or_default() + value.get("dead_code").and_then(|d| d.get("allowlist")).and_then(|a| a.as_object()).map_or_default(|a| { + a.keys() + .map(|k| { + assert!(!k.trim().is_empty(), "an allowlist key cannot be blank"); + k.clone() + }) + .collect() + }) } /// The `over_visibility.allowlist` keys — `module.item` for every `pub(crate)` @@ -415,19 +383,14 @@ fn allowed_overwide_items() -> BTreeSet<String> { 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"); - value - .get("over_visibility") - .and_then(|d| d.get("allowlist")) - .and_then(|a| a.as_object()) - .map(|a| { - a.keys() - .map(|k| { - assert!(!k.trim().is_empty(), "an over-wide permission key cannot be blank"); - k.clone() - }) - .collect() - }) - .unwrap_or_default() + value.get("over_visibility").and_then(|d| d.get("allowlist")).and_then(|a| a.as_object()).map_or_default(|a| { + a.keys() + .map(|k| { + assert!(!k.trim().is_empty(), "an over-wide permission key cannot be blank"); + k.clone() + }) + .collect() + }) } /// A top-level section of the budget file, as `key -> allowed`. @@ -450,20 +413,13 @@ fn budget_section(section: &str) -> BTreeMap<String, usize> { } fn rank_of(module: &str) -> Option<u8> { - RANKS - .iter() - .find(|(name, _, _)| *name == module) - .map(|(_, rank, _)| *rank) + RANKS.iter().find(|(name, _, _)| *name == module).map(|(_, rank, _)| *rank) } #[test] fn every_module_is_on_the_map() { let census = Census::take(); - let unmapped: Vec<&String> = census - .modules - .keys() - .filter(|m| rank_of(m).is_none()) - .collect(); + let unmapped: Vec<&String> = census.modules.keys().filter(|m| rank_of(m).is_none()).collect(); assert!( unmapped.is_empty(), "these modules have no rank, so nothing says what they may depend on: {unmapped:#?}\n\ @@ -474,11 +430,7 @@ fn every_module_is_on_the_map() { #[test] fn the_map_names_no_module_twice() { let mut seen = BTreeSet::new(); - let dupes: Vec<&str> = RANKS - .iter() - .filter(|(name, _, _)| !seen.insert(*name)) - .map(|(name, _, _)| *name) - .collect(); + let dupes: Vec<&str> = RANKS.iter().filter(|(name, _, _)| !seen.insert(*name)).map(|(name, _, _)| *name).collect(); assert!(dupes.is_empty(), "RANKS lists {dupes:?} twice; the second entry is dead weight"); for (_, _, reason) in RANKS { assert!(reason.len() > 12, "a rank needs a reason, not a shrug: {reason:?}"); @@ -552,11 +504,7 @@ fn glob_reexports_stay_on_the_allowlist() { let census = Census::take(); let mut offenders = Vec::new(); for (module, row) in &census.modules { - let allowed = GLOB_ALLOWLIST - .iter() - .find(|(m, _)| m == module) - .map(|(_, n)| *n) - .unwrap_or(0); + let allowed = GLOB_ALLOWLIST.iter().find(|(m, _)| m == module).map_or(0, |(_, n)| *n); if row.globs > allowed { offenders.push(format!("{module}: {} glob re-exports, {allowed} allowed", row.globs)); } @@ -642,10 +590,7 @@ 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. - let available = std::process::Command::new("python3") - .arg("--version") - .output() - .is_ok(); + 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"); return; @@ -676,7 +621,7 @@ fn the_census_tool_and_this_test_agree() { ("overwide", mine.over_wide), ("glob", mine.globs), ] { - let got = row.get(key).and_then(|v| v.as_u64()).unwrap_or(u64::MAX) as usize; + let got = row.get(key).and_then(serde_json::Value::as_u64).unwrap_or(u64::MAX) as usize; if got != theirs { disagreements.push(format!("{module}.{key}: tool {got}, test {theirs}")); } @@ -713,11 +658,7 @@ fn the_census_tool_and_this_test_agree() { /// while it is worked down by changing tests rather than visibilities. #[test] fn the_test_surface_is_disposed_of() { - if !std::process::Command::new("python3") - .arg("--version") - .output() - .is_ok() - { + if !std::process::Command::new("python3").arg("--version").output().is_ok() { println!("python3 is not on PATH — skipping the test-surface check"); return; } @@ -727,11 +668,7 @@ fn the_test_surface_is_disposed_of() { .current_dir(root()) .output() .expect("run tools/test-surface.py"); - assert!( - out.status.success(), - "tools/test-surface.py failed: {}", - String::from_utf8_lossy(&out.stderr) - ); + assert!(out.status.success(), "tools/test-surface.py failed: {}", String::from_utf8_lossy(&out.stderr)); let report: serde_json::Value = serde_json::from_slice(&out.stdout).expect("test-surface json"); let rows = report.get("rows").and_then(|r| r.as_array()).expect("rows"); @@ -741,7 +678,7 @@ fn the_test_surface_is_disposed_of() { let name = row.get("name").and_then(|v| v.as_str()).unwrap_or("?"); let module = row.get("module").and_then(|v| v.as_str()).unwrap_or("?"); let disp = row.get("disp").and_then(|v| v.as_str()).unwrap_or("?"); - if !row.get("hand_written").and_then(|v| v.as_bool()).unwrap_or(false) { + 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 @@ -749,11 +686,12 @@ fn the_test_surface_is_disposed_of() { // 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. - if row.get("dotted_only").and_then(|v| v.as_bool()).unwrap_or(false) + if row.get("dotted_only").and_then(serde_json::Value::as_bool).unwrap_or(false) && disp != "already-gated" - && !row.get("confirmed").and_then(|v| v.as_bool()).unwrap_or(false) + && !row.get("confirmed").and_then(serde_json::Value::as_bool).unwrap_or(false) { - unconfirmed.push(format!("{module}.{name} at {}", row.get("where").and_then(|v| v.as_str()).unwrap_or("?"))); + unconfirmed + .push(format!("{module}.{name} at {}", row.get("where").and_then(|v| v.as_str()).unwrap_or("?"))); } } assert!( @@ -781,8 +719,8 @@ fn the_test_surface_is_disposed_of() { // so a human has to say which item the mention meant and record the verdict. let mut unadjudicated = Vec::new(); for row in rows { - if row.get("ambiguous").and_then(|v| v.as_bool()).unwrap_or(false) - && !row.get("adjudicated").and_then(|v| v.as_bool()).unwrap_or(false) + if row.get("ambiguous").and_then(serde_json::Value::as_bool).unwrap_or(false) + && !row.get("adjudicated").and_then(serde_json::Value::as_bool).unwrap_or(false) { unadjudicated.push(format!( "{}:{} at {}", @@ -808,7 +746,7 @@ fn the_test_surface_is_disposed_of() { let mut looser = Vec::new(); let mut tighter = Vec::new(); for (key, ceiling) in surface { - let actual = counts.get(key).and_then(|v| v.as_u64()).unwrap_or(0) as usize; + let actual = counts.get(key).and_then(serde_json::Value::as_u64).unwrap_or(0) as usize; if actual > *ceiling { looser.push(format!("{key}: budget {ceiling}, actual {actual}")); } else if actual < *ceiling { @@ -857,10 +795,7 @@ fn the_release_build_exports_nothing_that_only_tests_reach() { "a release build still exports something only the test tier needs:\n{text}{}", String::from_utf8_lossy(&out.stderr) ); - assert!( - text.contains("nothing leaked"), - "the probe did not report success:\n{text}" - ); + assert!(text.contains("nothing leaked"), "the probe did not report success:\n{text}"); } /// The `dead_code.allowlist` is a set of decisions, so it has to stay in step @@ -908,7 +843,7 @@ fn the_dead_code_allowlist_names_real_items() { stale.push(format!("{key}: a key is `module.item`")); continue; }; - if reason.as_str().map(|r| r.trim().len() < 20).unwrap_or(true) { + if reason.as_str().is_none_or(|r| r.trim().len() < 20) { blank.push(key.clone()); } if !declared.get(module).is_some_and(|names| names.contains(name)) { @@ -968,13 +903,10 @@ fn the_over_visibility_allowlist_names_real_items() { stale.push(format!("{key}: a key is `module.item`")); continue; }; - if reason.as_str().map(|r| r.trim().len() < 20).unwrap_or(true) { + if reason.as_str().is_none_or(|r| r.trim().len() < 20) { blank.push(key.clone()); } - if !pub_crate_declared - .get(module) - .is_some_and(|names| names.contains(name)) - { + if !pub_crate_declared.get(module).is_some_and(|names| names.contains(name)) { stale.push(format!("{key} at {reason}")); } } @@ -1041,13 +973,11 @@ fn the_test_helpers_are_used() { continue; } // Everything this declaration introduces, minus the declaration itself. - let mut corpus = others - .replace(&format!("pub {kind}{name}"), "") - .replace(&format!("{kind}{name}"), ""); + let mut corpus = others.replace(&format!("pub {kind}{name}"), "").replace(&format!("{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() { + for follow in &lines[i..] { depth += follow.matches('{').count() as i32 - follow.matches('}').count() as i32; if depth > 1 { let member = follow @@ -1095,7 +1025,7 @@ fn every_fixture_is_referenced() { } let unreferenced: Vec<String> = std::fs::read_dir(&corpus) .expect("read testcorpus") - .filter_map(|e| e.ok()) + .filter_map(std::result::Result::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)) @@ -1122,27 +1052,18 @@ fn the_dead_code_budget_matches_the_code() { let value: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&path).expect("read budget")).expect("budget is json"); let modules = value.get("modules").and_then(|m| m.as_object()).expect("modules"); - let dead_code = value - .get("dead_code") - .and_then(|d| d.get("deadonly")) - .and_then(|d| d.as_object()) - .expect("dead_code.deadonly"); + let dead_code = + value.get("dead_code").and_then(|d| d.get("deadonly")).and_then(|d| d.as_object()).expect("dead_code.deadonly"); let census = Census::take(); let mut mismatch = Vec::new(); for (module, row) in modules { - let interface = row.get("deadonly").and_then(|v| v.as_u64()).unwrap_or(u64::MAX); - let dead = dead_code.get(module).and_then(|v| v.as_u64()); - let actual = census - .modules - .get(module) - .map(|m| m.dead_only as u64) - .unwrap_or(u64::MAX); + let interface = row.get("deadonly").and_then(serde_json::Value::as_u64).unwrap_or(u64::MAX); + let dead = dead_code.get(module).and_then(serde_json::Value::as_u64); + let actual = census.modules.get(module).map_or(u64::MAX, |m| m.dead_only as u64); if dead != Some(interface) || interface != actual { - mismatch.push(format!( - "{module}: dead_code.deadonly {:?}, modules.deadonly {interface}, actual {actual}", - dead - )); + mismatch + .push(format!("{module}: dead_code.deadonly {dead:?}, modules.deadonly {interface}, actual {actual}")); } } for module in dead_code.keys() { @@ -1177,17 +1098,12 @@ fn the_over_visibility_budget_matches_the_code() { let mut mismatch = Vec::new(); for (module, row) in modules { - let stated = row.get("overwide").and_then(|v| v.as_u64()).unwrap_or(u64::MAX); - let accepted = over.get(module).and_then(|v| v.as_u64()); - let actual = census - .modules - .get(module) - .map(|m| m.over_wide as u64) - .unwrap_or(u64::MAX); + let stated = row.get("overwide").and_then(serde_json::Value::as_u64).unwrap_or(u64::MAX); + let accepted = over.get(module).and_then(serde_json::Value::as_u64); + let actual = census.modules.get(module).map_or(u64::MAX, |m| m.over_wide as u64); if accepted != Some(stated) || stated != actual { mismatch.push(format!( - "{module}: over_visibility.overwide {:?}, modules.overwide {stated}, actual {actual}", - accepted + "{module}: over_visibility.overwide {accepted:?}, modules.overwide {stated}, actual {actual}" )); } } @@ -1228,14 +1144,10 @@ fn the_budget_writers_preserve_each_other() { .output() .unwrap_or_else(|e| panic!("run {tool}: {e}")); assert!(out.status.success(), "{tool} failed: {}", String::from_utf8_lossy(&out.stderr)); - let after: serde_json::Value = - serde_json::from_str(&std::fs::read_to_string(&tmp).expect("read temp budget")) - .expect("written budget is json"); + let after: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&tmp).expect("read temp budget")) + .expect("written budget is json"); for section in ["test_surface", "dead_code", "over_visibility"] { - assert!( - after.get(section).is_some(), - "{tool} erased the `{section}` section it does not own" - ); + assert!(after.get(section).is_some(), "{tool} erased the `{section}` section it does not own"); } assert_eq!( after["dead_code"]["allowlist"], before["dead_code"]["allowlist"], |
