Merge pull request #10367 from dotCooCoo/chore/test-lint-census

xtask: test-lint reports census tests
This commit is contained in:
.CooCoo authored and GitHub committed 2026-12-01 06:43:03 -08:00
commit 730e891dd0
1 file changed
+468 -7
+468 -7
View File
@@ -38,7 +38,13 @@
//! reads do not;
//! * `sleep`: `thread::sleep` in test code, or a bare `sleep(…)` in a file that imports it;
//! * `reads-source`: test code that reads Rust source (`include_str!` of a `.rs` file, or a walk
//! that keeps files ending in `.rs`), outside the source audits in [`SOURCE_AUDITS`].
//! that keeps files ending in `.rs`), outside the source audits in [`SOURCE_AUDITS`];
//! * `census`: a test that loops over a whole table (a `SCREAMING_CASE` constant, `Type::ALL`,
//! `Type::iter()`, or a call named `all`, `catalog`, `registry`, `presets`, `swatches`,
//! `entries`, `variants`, `commands`, `builtins` or `palette`, or ending or starting with one of
//! those after `_`) where every assertion in the loop only checks presence (`is_some`, `is_ok`,
//! `is_empty`, `contains`, `starts_with`, `is_finite`, `len() > 0`) or compares with a lookup or
//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table.
//!
//! Test code is a test file (`tests.rs`, `tests_*.rs`, `*_tests.rs`, a file in a `tests` or
//! `benches` folder, `crates/testkit`), an item under `#[cfg(test)]` or `#[cfg(all(test, …))]`,
@@ -120,10 +126,11 @@ pub enum Rule {
EnvGateUnset,
Sleep,
ReadsSource,
Census,
}
impl Rule {
pub const ALL: [Rule; 10] = [
pub const ALL: [Rule; 11] = [
Rule::AllUnguarded,
Rule::OnlyWeak,
Rule::SelfCompare,
@@ -134,6 +141,7 @@ impl Rule {
Rule::EnvGateUnset,
Rule::Sleep,
Rule::ReadsSource,
Rule::Census,
];
pub fn id(self) -> &'static str {
@@ -148,6 +156,7 @@ impl Rule {
Rule::EnvGateUnset => "env-gate-unset",
Rule::Sleep => "sleep",
Rule::ReadsSource => "reads-source",
Rule::Census => "census",
}
}
@@ -163,6 +172,7 @@ impl Rule {
Rule::EnvGateUnset => "set the variable in a CI leg, or make the test run without it",
Rule::Sleep => "wait on a handshake (channel, barrier) or a controllable clock",
Rule::ReadsSource => "test the behavior, or add the file to SOURCE_AUDITS in xtask/src/test_lint.rs if it audits the source tree",
Rule::Census => "test one or a few representative entries and the edge cases (or generate inputs), not every entry of the table",
}
}
@@ -955,10 +965,7 @@ fn is_helper_call(name: &str, method: bool, helpers: &HashSet<String>) -> bool {
/// `expect_err`.
fn checks_itself(m: &[u8], from: usize, to: usize) -> bool {
let body = &m[from..to];
contains(body, b"panic!")
|| contains(body, b".unwrap_err()")
|| contains(body, b".expect_err(")
|| macro_calls(m, from, to).iter().any(|c| is_assert_macro(&c.name))
contains(body, b"panic!") || rejects(body) || macro_calls(m, from, to).iter().any(|c| is_assert_macro(&c.name))
}
/// `tests.rs`, `tests_*.rs`, `*_tests.rs`, files in a `tests` or `benches` folder, and
@@ -1230,6 +1237,7 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec<Hit> {
hits.extend(self_compare(&v));
hits.extend(early_returns(&v));
hits.extend(env_gates(&v, ctx));
hits.extend(census(&v, helpers));
hits.extend([only_weak(&v), exit_status_only(&v), no_assertion(&v)].into_iter().flatten());
hits
}
@@ -1320,6 +1328,322 @@ fn all_unguarded(v: &View) -> Vec<Hit> {
.collect()
}
/// A loop over a whole table (`for x in TABLE`, `for c in Color::ALL`, `assert!(presets().iter().all(…))`)
/// whose assertions only check presence, non-emptiness or a round trip.
fn census(v: &View, helpers: &HashSet<String>) -> Vec<Hit> {
let m = &v.file.exec;
// Failure messages run only after an assertion has failed, so a check there does not count.
let unmessaged = v.body_without_messages();
let helpers_in = |from: usize, to: usize| -> Vec<String> {
calls(&unmessaged, from - v.t.open, to - v.t.open)
.into_iter()
.filter(|(n, method)| !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers))
.map(|(n, _)| n)
.collect()
};
let weak_in = |from: usize, to: usize, var: &str| {
let inside: Vec<&MacroCall> = v.asserts.iter().filter(|a| a.at > from && a.at < to).collect();
let body = &unmessaged[from - v.t.open..to - v.t.open];
helpers_in(from, to).is_empty()
&& !rejects(body)
&& !inside.is_empty()
&& inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm(&m[f..t])).collect::<Vec<_>>(), var))
};
for at in words(m, b"for", v.t.open, v.t.close) {
let Some(&kw) = words(m, b"in", at, v.t.close).first() else { continue };
let Some(open) = loop_open(m, kw + 2, v.t.close) else { continue };
let Some(close) = matching(m, open) else { continue };
let pattern = String::from_utf8_lossy(&m[at + 3..kw]);
let var = pattern.split_whitespace().last().unwrap_or("").trim_start_matches('&');
// A `break` in the body can end the loop before it reaches every entry.
// An asserting helper in the loop source runs for every entry, like one in the body.
if whole_table(&norm(&m[kw + 2..open]))
&& helpers_in(kw + 2, open).is_empty()
&& words(m, b"break", open, close).is_empty()
&& weak_in(open, close, var)
{
return vec![v.whole(Rule::Census, "loops over every entry of a table and checks only presence or a round trip".into())];
}
}
for a in v.asserts.iter().filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())) {
let called = a.args.first().map(|&(f, t)| helpers_in(f, t)).unwrap_or_default();
if census_condition(&v.first_arg(a), 0, &called) == (true, true) {
return vec![v.whole(Rule::Census, "checks .all(…) over every entry of a table for presence only".into())];
}
}
vec![]
}
/// For a (whitespace-free) assertion condition: whether it holds on presence checks alone, and
/// whether one of those is a [`weak_table_all`]. Operands joined by `&&` all have to be weak, while
/// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions
/// nested deeper than 64 operators are not judged. An operand that calls one of `helpers` (asserting
/// helpers called in the condition) is not a presence check, and a weak right side of an `||` does
/// not count when the left side calls one, since the left side always runs.
fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool) {
let or = top_level_at(cond, "||").first().copied();
if depth > 64 || !cond.contains(".all(") {
(false, false)
} else if cond.starts_with('(') && matching(cond.as_bytes(), 0) == Some(cond.len() - 1) {
census_condition(&cond[1..cond.len() - 1], depth + 1, helpers)
} else if let Some(at) = or.or_else(|| top_level_at(cond, "&&").first().copied()) {
let side = |s: &str| {
if s.contains(".all(") {
census_condition(s, depth + 1, helpers)
} else {
(weak_predicate(s) && !calls_any(s, helpers) && !rejects(s.as_bytes()), false)
}
};
let (l, r) = (side(&cond[..at]), side(&cond[at + 2..]));
let r = if or.is_some() && (calls_any(&cond[..at], helpers) || rejects(&cond.as_bytes()[..at])) { (false, false) } else { r };
if or.is_none() {
(l.0 && r.0, l.1 || r.1)
} else if l == (true, true) || r == (true, true) {
(true, true)
} else {
(l.0 || r.0, false)
}
} else {
let table = weak_table_all(cond, helpers);
(table || weak_predicate(cond) && !calls_any(cond, helpers), table)
}
}
/// Whether `s` calls a function or method named in `names`, with or without a turbofish.
fn calls_any(s: &str, names: &[String]) -> bool {
names.iter().any(|n| {
[format!("{n}("), format!("{n}::<")]
.iter()
.any(|call| s.match_indices(call.as_str()).any(|(at, _)| at == 0 || !is_ident(s.as_bytes()[at - 1])))
})
}
/// Whether a (whitespace-free) `.all(…)` predicate checks only presence. A predicate that calls one
/// of `helpers` is weak only when a presence check can pass without the helper running: a weak left
/// side of an `||`, a weak right side after a left side that calls no helper, or weak operands on
/// both sides of an `&&`.
fn presence_only(pred: &str, helpers: &[String], depth: usize) -> bool {
let body = pred.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(pred, |(_, body)| body);
let (or, and) = (top_level_at(body, "||").first().copied(), top_level_at(body, "&&").first().copied());
if !calls_any(pred, helpers) {
weak_predicate(pred)
} else if depth > 64 {
false
} else if body.starts_with('(') && matching(body.as_bytes(), 0) == Some(body.len() - 1) {
presence_only(&body[1..body.len() - 1], helpers, depth + 1)
} else if let Some(at) = or {
let left = &body[..at];
presence_only(left, helpers, depth + 1) || !calls_any(left, helpers) && presence_only(&body[at + 2..], helpers, depth + 1)
} else if let Some(at) = and {
presence_only(&body[..at], helpers, depth + 1) && presence_only(&body[at + 2..], helpers, depth + 1)
} else {
false
}
}
/// Whether a (whitespace-free) operand is exactly `TABLE.iter().all(…)` with a presence-only predicate.
fn weak_table_all(op: &str, helpers: &[String]) -> bool {
let Some(&i) = top_level_at(op, ".all(").last() else { return false };
let receiver = op[..i].trim_end_matches(".iter()").trim_end_matches(".into_iter()");
let rest = &op[i + ".all(".len()..];
let end = arg_end(rest);
// A rejection call checks something only on the branches that run it, like an asserting helper.
let checks: Vec<String> = helpers.iter().cloned().chain(["unwrap_err".into(), "expect_err".into()]).collect();
rest[end..] == *")" && whole_table(receiver) && !calls_any(&op[..i], helpers) && presence_only(&rest[..end], &checks, 0)
}
/// Whether `body` calls `.unwrap_err()` or `.expect_err(`, with any whitespace inside the call.
fn rejects(body: &[u8]) -> bool {
let tight: Vec<u8> = body.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect();
contains(&tight, b".unwrap_err()") || contains(&tight, b".expect_err(")
}
/// The `{` that opens a `for` loop's body: the first one outside brackets after `from`.
fn loop_open(m: &[u8], from: usize, to: usize) -> Option<usize> {
let mut i = from;
while i < to {
match m[i] {
b'{' => return Some(i),
b'(' | b'[' => i = matching(m, i)? + 1,
b';' => return None,
_ => i += 1,
}
}
None
}
/// Calls whose name says they return a whole table.
const TABLE_CALLS: &[&str] = &["all", "catalog", "registry", "presets", "swatches", "entries", "variants", "commands", "builtins", "palette"];
/// Whether a (whitespace-free) loop source names a whole table: a `SCREAMING_CASE` constant, an
/// `ALL`, `all()`, `iter()` or `variants()` on a type, or a call named like a catalog.
fn whole_table(src: &str) -> bool {
let src = src.trim_start_matches('&');
let head: &str = src.split(['.', '(', '[']).next().unwrap_or("");
let restricted = [
".take(",
".skip(",
".filter(",
".filter_map(",
".take_while(",
".skip_while(",
".map_while(",
".step_by(",
".nth(",
".first(",
".last(",
".rev().take(",
"[",
];
let chain = &src[head.len()..];
// A `zip` stops at its shorter side and a `flat_map` yields what its closure's iterator yields,
// so a restricted iterator inside either bounds the loop too, as does a range zipped in.
let bounded_inside = [".zip(", ".flat_map("].iter().any(|adapter| {
top_level_at(chain, adapter).into_iter().any(|at| {
let open = at + adapter.len() - 1;
matching(chain.as_bytes(), open).is_none_or(|close| {
let inner = &chain[open + 1..close];
let range = unparenthesized(inner.trim_end_matches(','));
restricted.iter().any(|r| inner.contains(r))
|| *adapter == ".zip(" && top_level_at(range, "..").first().is_some_and(|&at| !range[at + 2..].trim_start_matches('=').is_empty())
})
})
});
if bounded_inside || restricted.iter().any(|r| top_level_contains(chain, r)) {
return false;
}
let last = head.rsplit("::").next().unwrap_or("");
let screaming = last.len() > 1
&& last.bytes().any(|c| c.is_ascii_uppercase())
&& last.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_');
let segments: Vec<&str> = head.split("::").collect();
let on_type = segments.len() > 1 && segments[segments.len() - 2].starts_with(|c: char| c.is_ascii_uppercase());
let type_table = on_type && matches!(last, "ALL" | "all" | "iter" | "variants" | "VARIANTS" | "value_variants");
let named = src[head.len()..].starts_with("()")
&& TABLE_CALLS.iter().any(|n| last == *n || last.ends_with(&format!("_{n}")) || last.starts_with(&format!("{n}_")));
screaming || type_table || named
}
/// Whether `pat` starts at a position of `s` outside every bracket, so an adapter inside a closure
/// does not count as one on the outer iterator chain.
fn top_level_contains(s: &str, pat: &str) -> bool {
!top_level_at(s, pat).is_empty()
}
/// The byte offsets where `pat` starts in `s` outside every bracket.
fn top_level_at(s: &str, pat: &str) -> Vec<usize> {
let (s, pat) = (s.as_bytes(), pat.as_bytes());
let mut depth = 0i32;
let mut found = vec![];
for (i, c) in s.iter().enumerate() {
if depth == 0 && s[i..].starts_with(pat) {
found.push(i);
}
depth += match c {
b'(' | b'[' | b'{' => 1,
b')' | b']' | b'}' => -1,
_ => 0,
};
}
found
}
/// Predicates and comparisons that every entry passes by construction.
const PRESENCE: &[&str] = &[".is_some()", ".is_ok()", ".is_empty()", ".contains(", ".contains_key(", ".len()>0", ".starts_with(", ".is_finite()"];
/// Calls on one side of an equality that turn an entry back into itself.
const ROUND_TRIP: &[&str] = &["parse", "from_str", "from_id", "from_name", "from_key", "by_id", "by_name", "lookup", "find"];
/// Whether every operand of a (whitespace-free) condition or closure is a presence check alone.
fn weak_predicate(pred: &str) -> bool {
let pred = pred.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(pred, |(_, body)| body);
if pred.starts_with('(') && matching(pred.as_bytes(), 0) == Some(pred.len() - 1) {
return weak_predicate(&pred[1..pred.len() - 1]);
}
if let Some(at) = boolean_split(pred) {
return weak_predicate(&pred[..at]) && weak_predicate(&pred[at + 2..]);
}
let negated = (pred.len() - pred.trim_start_matches('!').len()) % 2 == 1;
let pred = pred.trim_start_matches('!');
// A negated check is a presence check only for `!….is_empty()`; `!….is_ok()` checks a rejection.
if negated && !pred.ends_with(".is_empty()") {
return false;
}
if let Some(list) = pred.strip_suffix(".len()>0") {
return !list.contains(['=', '<', '>']);
}
let compares = pred.contains("==") || pred.contains("!=") || pred.contains(['<', '>']) && !pred.contains("::<");
!compares
&& PRESENCE.iter().any(|p| match p.strip_suffix('(') {
Some(call) => pred.rfind(p).is_some_and(|at| matching(pred.as_bytes(), at + call.len()) == Some(pred.len() - 1)),
None => pred.ends_with(p),
})
}
/// Whether an assertion in a loop over entries bound to `var` checks only presence, or compares
/// a lookup or parse with the entry itself.
fn weak_census_check(name: &str, args: &[String], var: &str) -> bool {
match guard_arg_count(name) {
1 => args.first().is_some_and(|a| weak_predicate(a)),
2 if name.ends_with("_ne") => false,
2 => match args {
[a, b, ..] => (round_trip_call(a) && is_entry(b, var)) || (round_trip_call(b) && is_entry(a, var)),
_ => false,
},
_ => false,
}
}
/// Whether a (whitespace-free) operand is the result of one of [`ROUND_TRIP`], called by its whole
/// name and followed only by unwrapping (`.unwrap()`, `.ok()`, `.expect(…)`, `?` and the like), so
/// the operand is the parsed or looked-up entry itself and not a value derived from it.
fn round_trip_call(op: &str) -> bool {
let mut op = op.trim_start_matches(['&', '*']);
loop {
let wraps = |w: &&str| op.starts_with(*w) && matching(op.as_bytes(), w.len() - 1) == Some(op.len() - 1);
let inner = ["Some(", "Ok(", "("].iter().find(|w| wraps(w)).map(|w| &op[w.len()..op.len() - 1]);
match inner {
Some(inner) => op = inner.trim_start_matches(['&', '*']),
None => break,
}
}
ROUND_TRIP.iter().any(|r| {
op.match_indices(&format!("{r}(")).any(|(at, _)| {
let open = at + r.len();
!op.as_bytes()[..at].last().copied().is_some_and(is_ident)
&& matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..]))
})
})
}
/// Whether a (whitespace-free) call suffix only unwraps or copies the call's result.
fn only_unwraps(mut rest: &str) -> bool {
const UNWRAPS: &[&str] = &[".unwrap()", ".ok()", ".copied()", ".cloned()", ".clone()", ".as_ref()", ".as_deref()", "?"];
loop {
let next = match UNWRAPS.iter().find_map(|s| rest.strip_prefix(s)) {
Some(r) => Some(r),
None if rest.starts_with(".expect(") => matching(rest.as_bytes(), ".expect".len()).map(|close| &rest[close + 1..]),
None => None,
};
match next {
_ if rest.is_empty() => break true,
Some(r) => rest = r,
None => break false,
}
}
}
/// Whether an operand is the loop entry itself: `x`, `*x`, `&x`, `Some(x)`, `Ok(x)` or `x.clone()`.
fn is_entry(op: &str, var: &str) -> bool {
let mut op = op.trim_start_matches(['&', '*']);
for wrap in ["Some(", "Ok("] {
if let Some(inner) = op.strip_prefix(wrap).and_then(|r| r.strip_suffix(')')) {
op = inner.trim_start_matches(['&', '*']);
}
}
!var.is_empty() && op.trim_end_matches(".clone()") == var
}
/// The number of condition or compared operands in a standard assertion macro.
fn guard_arg_count(name: &str) -> usize {
match name {
@@ -2220,7 +2544,7 @@ fn only_weak(v: &View) -> Option<Hit> {
let all_weak = v.asserts.iter().all(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && is_weak(&v.first_arg(a)));
// Failure messages run only after an assertion has failed, so a check there does not count.
let body = v.body_without_messages();
let other = contains(&body, b"panic!") || contains(&body, b".unwrap_err()") || contains(&body, b".expect_err(");
let other = contains(&body, b"panic!") || rejects(&body);
if v.asserts.is_empty() || !all_weak || other || v.delegates || v.should_panic {
return None;
}
@@ -2618,6 +2942,143 @@ mod tests {
assert_eq!(hits(mixed), [(3, "all-unguarded")]);
}
#[test]
fn census_loops_over_whole_tables_are_reported() {
let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
let consts = "#[test]\nfn t() {\n for c in COLORS.iter() {\n assert!(!c.name.is_empty());\n }\n}\n";
assert_eq!(census(consts), [(2, "census")]);
let round = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id()), Some(k));\n }\n}\n";
assert_eq!(census(round), [(2, "census")]);
let call = "#[test]\nfn t() {\n for p in builtin_presets() {\n assert!(lookup(&p.name).is_some());\n }\n}\n";
assert_eq!(census(call), [(2, "census")]);
let all = "#[test]\nfn t() {\n assert!(Swatch::iter().all(|s| s.rgb().is_some()));\n}\n";
assert_eq!(census(all), [(2, "census")]);
let behavior = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(apply(k, 2), 4);\n }\n}\n";
assert_eq!(census(behavior), [], "a computed result for each entry is a real check");
let mixed = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some());\n assert_eq!(blend(c), WHITE);\n }\n}\n";
assert_eq!(census(mixed), [], "one real assertion in the loop keeps it");
let joined = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some() && blend(c) == WHITE);\n }\n assert!(Swatch::iter().all(|s| s.rgb().is_some() && s.rgb() != BLACK));\n}\n";
assert_eq!(census(joined), [], "a presence guard joined to a real check");
let both = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some() && !c.name.is_empty());\n }\n}\n";
assert_eq!(census(both), [(2, "census")]);
let few = "#[test]\nfn t() {\n for c in COLORS.iter().take(2) {\n assert!(c.is_some());\n }\n for c in &COLORS[..2] {\n assert!(c.is_some());\n }\n}\n";
assert_eq!(census(few), [], "a few representative entries");
let expected = "#[test]\nfn t() {\n for case in CASES {\n assert_eq!(parse(case.input), case.expected);\n assert_eq!(sparse(case), case);\n }\n}\n";
assert_eq!(census(expected), [], "an expected value written in the table, and a name that only ends in parse");
let helper = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some());\n check_render(c);\n }\n}\n";
assert_eq!(census(helper), [], "an asserting helper in the loop");
let local = "#[test]\nfn t() {\n for x in xs.iter() {\n assert!(x.is_some());\n }\n}\n";
assert_eq!(census(local), [], "a local collection is not a table");
let allowed = "// test-lint: allow census every command needs a menu path\n#[test]\nfn t() {\n for c in COMMANDS {\n assert!(menu(c).is_some());\n }\n}\n";
assert_eq!(census(allowed), []);
for ne in ["assert_ne!(Kind::from_id(k.id()), Some(k))", "debug_assert_ne!(lookup(k), k)", "prop_assert_ne!(Kind::parse(k.name()), Ok(k))"] {
let rejects = format!("#[test]\nfn t() {{\n for k in Kind::ALL {{\n {ne};\n }}\n}}\n");
assert_eq!(census(&rejects), [], "an inequality is not a round trip: {ne}");
}
let borrowed = "#[test]\nfn t() {\n for k in &Kind::ALL {\n assert_eq!(Kind::from_id(k.id()).as_ref(), Some(k));\n }\n}\n";
assert_eq!(census(borrowed), [(2, "census")]);
let both_all = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some()) && LABELS.iter().all(|s| !s.is_empty()));\n}\n";
assert_eq!(census(both_all), [(2, "census")]);
let either = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some()) || actual == expected);\n}\n";
assert_eq!(census(either), [(2, "census")], "an || lets the presence branch pass alone");
let long = format!(
"#[test]\nfn t() {{\n assert!(COLORS.iter().all(|c| c.is_some()){});\n}}\n",
"&&COLORS.iter().all(|c|c.is_some())".repeat(200)
);
assert_eq!(census(&long), [], "a chain deeper than the limit is not judged");
let inner = "#[test]\nfn t() {\n for a in COLORS.iter().map(|c| c.aliases.iter().filter_map(|a| a.id()).next()) {\n assert!(a.is_some());\n }\n}\n";
assert_eq!(census(inner), [(2, "census")]);
let accented = "#[test]\nfn t() {\n for c in COLORS.iter().clonés() {\n assert!(c.is_some());\n }\n}\n";
assert_eq!(census(accented), [(2, "census")], "a non-ASCII method name is read without panicking");
let nested = "#[test]\nfn t() {\n assert!(COLORS.iter().map(|c| c.parts.iter().all(|p| p.ok)).all(|c| c.is_some()));\n}\n";
assert_eq!(census(nested), [(2, "census")]);
let wrapped = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Some(Kind::parse(k.name()).unwrap()), Some(k));\n }\n}\n";
assert_eq!(census(wrapped), [(2, "census")]);
let derived = "#[test]\nfn t() {\n for n in COUNTS {\n assert_eq!(parse(&src(n)).unwrap().children.len(), n);\n }\n}\n";
assert_eq!(census(derived), [], "a value derived from the parsed entry is a real check");
let unwrapped = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::parse(k.name()).unwrap(), k);\n }\n}\n";
assert_eq!(census(unwrapped), [(2, "census")]);
let all_joined = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some()) && actual == expected);\n}\n";
assert_eq!(census(all_joined), [], "an .all(…) presence check joined to a real check");
let subsets = "#[test]\nfn t() {\n for c in COLORS.iter().filter_map(|c| c.alt) {\n assert!(c.is_some());\n }\n for c in COLORS.iter().take_while(|c| c.light) {\n assert!(c.is_some());\n }\n for c in COLORS.iter().skip_while(|c| c.light) {\n assert!(c.is_some());\n }\n for c in COLORS.iter().map_while(|c| c.alt) {\n assert!(c.is_some());\n }\n}\n";
assert_eq!(census(subsets), [], "subset adapters pick a few entries");
}
#[test]
fn census_skips_loops_bounded_by_zip_or_flat_map() {
let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
let zipped = "#[test]\nfn t() {\n for (c, l) in COLORS.iter().zip(labels.iter().take(2)) {\n assert!(c.is_some());\n }\n}\n";
assert_eq!(census(zipped), [], "a bounded iterator zipped in bounds the loop");
let ranged = "#[test]\nfn t() {\n for (c, i) in COLORS.iter().zip(0..2) {\n assert!(c.is_some());\n }\n}\n";
assert_eq!(census(ranged), [], "a range zipped in bounds the loop");
for range in ["0..", "0..,", "(0..)", "((0..)),", "std::iter::repeat(0..2)"] {
let open = format!("#[test]\nfn t() {{\n for (c, i) in COLORS.iter().zip({range}) {{\n assert!(c.is_some());\n }}\n}}\n");
assert_eq!(census(&open), [(2, "census")], "an open-ended range zipped in visits every entry: {range}");
}
let flat = "#[test]\nfn t() {\n for e in GROUPS.iter().flat_map(|g| g.es.iter().take(1)) {\n assert!(e.is_some());\n }\n}\n";
assert_eq!(census(flat), [], "a bounded iterator returned by flat_map bounds the loop");
}
#[test]
fn census_counts_rejections_and_helpers_as_checks() {
let census_in = |src: &str, ctx: &Ctx| hits_in("crates/x/src/tests.rs", src, ctx).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
let rejected = "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).unwrap_err();\n }\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).expect_err(\"rejects\");\n }\n}\n";
assert_eq!(census_in(rejected, &ctx()), [], "an unwrap_err or expect_err in the loop checks a rejection");
let spaced = "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).unwrap_err ();\n }\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).expect_err (\"rejects\");\n }\n}\n";
assert_eq!(census_in(spaced, &ctx()), [], "whitespace inside the rejection call");
let all_rejects = "#[test]\nfn t() {\n assert!(CASES.iter().all(|c| parse(c.bad).unwrap_err().contains(\"bad\")));\n assert!(CASES.iter().all(|c| parse(c.bad).expect_err(\"rejects\").contains(\"bad\")));\n}\n";
assert_eq!(census_in(all_rejects, &ctx()), [], "an unwrap_err or expect_err in the .all(…) predicate checks a rejection");
let skips = "#[test]\nfn t() {\n assert!(CASES.iter().all(|c| c.is_some() || parse(c.bad).unwrap_err().contains(\"bad\")));\n}\n";
assert_eq!(census_in(skips, &ctx()), [(2, "census")], "a rejection after a presence check on an || can be skipped");
let first = "#[test]\nfn t() {\n assert!(parse(invalid).unwrap_err().contains(\"bad\") || CASES.iter().all(|c| c.is_some()));\n}\n";
assert_eq!(census_in(first, &ctx()), [], "a rejection on the left of an || always runs");
let and_rejects = "#[test]\nfn t() {\n assert!(CASES.iter().all(|c| c.is_some()) && parse(invalid).unwrap_err().is_empty());\n}\n";
assert_eq!(census_in(and_rejects, &ctx()), [], "a rejection on the other side of an && always runs");
let broken = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some());\n break;\n }\n}\n";
assert_eq!(census_in(broken, &ctx()), [], "a break can end the loop before the last entry");
assert_eq!(census_in(&broken.replace(" break;\n", ""), &ctx()), [(2, "census")]);
let only_ok = "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n }\n}\n";
assert_eq!(census_in(only_ok, &ctx()), [(2, "census")]);
let all_helper = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| exercise(c).is_some()));\n}\nfn exercise(c: &Color) -> Option<()> {\n assert_eq!(blend(c), WHITE);\n Some(())\n}\n";
let files = [("crates/x/src/tests.rs".to_owned(), all_helper.to_owned())];
let with_helpers = Ctx { helpers: asserting_helpers(&files), ..ctx() };
assert_eq!(census_in(all_helper, &with_helpers), [], "an asserting helper in the .all(…) predicate");
assert_eq!(census_in(all_helper, &ctx()), [(2, "census")], "a predicate whose call does not assert");
let message =
"#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok(),\"{:?}\", probe().unwrap_err());\n }\n}\n";
assert_eq!(census_in(message, &ctx()), [(2, "census")], "an unwrap_err in a failure message runs only after a failure");
let skipped = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some()) || verify_fallback());\n}\n";
assert_eq!(census_in(skipped, &ctx()), [(2, "census")], "a helper on the other side of an || can be skipped");
let inner = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some() || verify_fallback(c).is_some()));\n}\n";
assert_eq!(census_in(inner, &ctx()), [(2, "census")], "a helper inside the predicate behind an || can be skipped");
let outer = "#[test]\nfn t() {\n assert!(verify_entry() || COLORS.iter().all(|c| c.is_some()));\n}\n";
assert_eq!(census_in(outer, &ctx()), [], "a helper on the left of an outer || always runs");
let in_message = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some(), \"{:?}\", verify_entry(c));\n }\n}\n";
assert_eq!(census_in(in_message, &ctx()), [(2, "census")], "a helper in a failure message runs only after a failure");
let first = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| verify_entry(c) || c.is_some()));\n}\n";
assert_eq!(census_in(first, &ctx()), [], "a helper on the left of an || always runs");
let generic = all_helper.replace("exercise(c)", "exercise::<Color>(c)");
assert_eq!(census_in(&generic, &with_helpers), [], "a helper called with a turbofish");
let enforced = "#[test]\nfn t() {\n for case in CASES {\n assert!(!case.is_empty());\n let Ok(_) = parse(case) else { panic!(\"parse failed\") };\n }\n}\n";
assert_eq!(census_in(enforced, &ctx()), [(2, "census")], "a panic that only enforces success");
let mapped = "#[test]\nfn t() {\n assert!(COLORS.iter().map(|c| { verify_entry(c); c }).all(|c| c.is_some()));\n}\n";
assert_eq!(census_in(mapped, &ctx()), [], "a helper in the .all(…) receiver runs for every entry");
assert_eq!(census_in(&mapped.replace("verify_entry(c); ", ""), &ctx()), [(2, "census")]);
let sourced = "#[test]\nfn t() {\n for c in COLORS.iter().map(|c| { verify_entry(c); c }) {\n assert!(c.is_some());\n }\n}\n";
assert_eq!(census_in(sourced, &ctx()), [], "a helper in the loop source runs for every entry");
assert_eq!(census_in(&sourced.replace("verify_entry(c); ", ""), &ctx()), [(2, "census")]);
let refused = "#[test]\nfn t() {\n for case in CASES {\n assert!(!parse(case.invalid).is_ok());\n }\n for case in CASES {\n assert!(!lookup(case.missing).is_some());\n }\n}\n";
assert_eq!(census_in(refused, &ctx()), [], "a negated is_ok or is_some checks a rejection");
let filled = "#[test]\nfn t() {\n for c in COLORS {\n assert!(!c.name.is_empty());\n }\n}\n";
assert_eq!(census_in(filled, &ctx()), [(2, "census")]);
}
#[test]
fn census_is_report_only() {
assert!(!Rule::Census.fails());
assert_eq!(Rule::from_id("census"), Some(Rule::Census));
}
#[test]
fn all_equality_guards_match_each_receiver() {
for assertion in ["assert_eq", "debug_assert_eq", "prop_assert_eq"] {