xtask: test-lint scopes bindings, spans ignore reasons and names its failing rules

- The module docs and docs/development.md name the four rules that fail
  the check, and describe `only-weak` and `self-compare` by what they
  match (`len() > 0`, `assert_ne!`).
- The changed-lines diff passes `--inter-hunk-context=0`, so a clone's
  `diff.interHunkContext` cannot mark unchanged lines between two edits.
- Single-letter workflow variables count as set.
- Test names with non-ASCII letters are read whole.
- An allow in a block comment needs a reason before `*/`.
- `all-unguarded` uses only a binding still in scope at the assertion,
  treats a `const` declared with different values as unknown, and drops
  a counted local once its collection may shrink or be replaced.
- `only-weak` ignores `unwrap_err`, `expect_err` and `panic!` in failure
  messages.
- `self-compare` leaves out operands that call a method returning the
  next value each time (`next`, `pop_front`, `recv` and others).
- An `ignore-without-reason` span reaches the attribute's `]`, so a
  change to a reason on the next line counts.
This commit is contained in:
dotCooCoo committed 2026-11-30 05:20:08 -08:00
1 parent 747593d0dd
commit 28f33ca04c
2 files changed
+149 -27

No files matched your search

+1 -1
View File
@@ -351,7 +351,7 @@ The app decides which cursors exist; whoever draws them works from the list. For
## Test lint
`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on a test whose only checks are `is_ok`, `is_some` or `!is_empty` (`only-weak`), `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base <rev>` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow <rule> <reason>` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail.
`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. The base is `--base <rev>` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow <rule> <reason>` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail.
## Tests
+148 -26
View File
@@ -21,7 +21,8 @@
//! * `only-weak`: every assertion is `is_ok()`, `is_some()`, `!is_empty()` or `len() > 0`, and the
//! test calls no asserting helper;
//! * `self-compare`: `assert_eq!(x, x)` or `assert_ne!(x, x)` on the same expression, when that
//! expression calls nothing with arguments (two calls with arguments check determinism);
//! expression calls nothing with arguments (two calls with arguments check determinism) and no
//! method that returns the next value each time ([`ADVANCING`], such as `next`);
//! * `exit-status-only`: a test that runs a process and checks only its exit status, reading no
//! output, with a status check in any condition or compared operand of a standard assertion;
//! * `no-assertion`: no assertion macro, `panic!`, `unwrap_err`, `expect_err` or asserting helper,
@@ -50,8 +51,9 @@
//! rules about a whole test it can be on any line from the line above the test attribute to the
//! `fn` line. An allow without a reason exempts nothing.
//!
//! `cargo xtask test-lint` fails on the hits in the lines and tests changed since a base: `--base
//! <rev>` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's
//! `cargo xtask test-lint` fails on hits of `only-weak`, `self-compare`, `ignore-without-reason`
//! and `sleep` in the lines and tests changed since a base, and lists the other rules' hits there
//! without failing. The base is `--base <rev>` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's
//! merge commit is checked out, and a shallow checkout fetches that parent); elsewhere the merge
//! base of `HEAD` and `upstream/main` or `origin/main`. Uncommitted and untracked files count as
//! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the
@@ -186,7 +188,8 @@ pub struct Hit {
pub note: String,
/// The first and last line of what the hit covers: the test, from its attribute to its closing
/// brace, for a rule about a whole test or `all-unguarded`, through the second operand for
/// `self-compare`, through the variable's name for `env-gate-unset`, else `line`. This span
/// `self-compare`, through the variable's name for `env-gate-unset`, through the attribute's
/// `]` for `ignore-without-reason`, else `line`. This span
/// controls changed-line detection; `all-unguarded` and `self-compare` exemptions still apply
/// only near `line`.
pub first: usize,
@@ -384,7 +387,20 @@ fn resolve_base(root: &Path, explicit: Option<String>) -> Result<String, String>
fn changed_lines(root: &Path, base: &str) -> Result<BTreeMap<String, Option<BTreeSet<usize>>>, String> {
let diff = git(
root,
&["-c", "core.quotepath=off", "diff", "-U0", "--no-color", "--no-ext-diff", "--src-prefix=a/", "--dst-prefix=b/", base, "--", "*.rs"],
&[
"-c",
"core.quotepath=off",
"diff",
"-U0",
"--inter-hunk-context=0",
"--no-color",
"--no-ext-diff",
"--src-prefix=a/",
"--dst-prefix=b/",
base,
"--",
"*.rs",
],
)?;
let mut out = parse_diff(&diff);
for path in git(root, &["ls-files", "-z", "--others", "--exclude-standard", "--", "*.rs"])?.split('\0').filter(|p| !p.is_empty()) {
@@ -511,9 +527,7 @@ fn printed(line: &str, from: usize) -> bool {
}
fn env_assignment_name(name: &str) -> bool {
name.len() > 1
&& name.starts_with(|c: char| c.is_ascii_uppercase())
&& name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')
name.starts_with(|c: char| c.is_ascii_uppercase()) && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')
}
/// Removes comment text outside quotes from a workflow line.
@@ -820,7 +834,8 @@ fn fn_after(m: &[u8], attr: usize, from: usize) -> Option<TestFn> {
return None;
}
let name_start = skip_ws(m, fn_at + 2);
let name_end = name_start + m[name_start..].iter().take_while(|&&c| is_ident(c)).count();
// Identifiers may hold non-ASCII letters (`échec`); their UTF-8 bytes are all 0x80 or above.
let name_end = name_start + m[name_start..].iter().take_while(|&&c| is_ident(c) || c >= 0x80).count();
if name_end == name_start {
return None;
}
@@ -1124,7 +1139,8 @@ fn allows(src: &str, m: &[u8]) -> Vec<(usize, Rule)> {
src.match_indices(ALLOW)
.filter(|&(p, _)| m[p] == b' ' && literals[p] == b't')
.filter_map(|(p, _)| {
let rest = src[p + ALLOW.len()..].lines().next()?;
// The reason ends with the line, or with the block comment that holds the marker.
let rest = src[p + ALLOW.len()..].lines().next()?.split("*/").next()?;
let mut words = rest.split_whitespace();
let rule = Rule::from_id(words.next()?)?;
words.next().map(|_| (lines.of(p), rule))
@@ -1622,7 +1638,7 @@ fn array_receiver(receiver: &str) -> &str {
receiver.strip_suffix(".iter()").or_else(|| receiver.strip_suffix(".into_iter()")).unwrap_or(receiver)
}
/// The fewest items a plain local receiver has after its latest preceding binding: from the
/// The fewest items a plain local receiver has after its latest preceding binding still in scope: from the
/// binding ([`array_binding`]) or a loop that fills it ([`loop_fill_len`]), and 0 when a later
/// statement may shrink or replace it ([`may_shrink`]).
fn bound_len(receiver: &str, body: &[u8], sizes: &Sizes) -> usize {
@@ -1631,7 +1647,8 @@ fn bound_len(receiver: &str, body: &[u8], sizes: &Sizes) -> usize {
return 0;
}
let name = name.as_bytes();
let Some((len, end)) = words(body, b"let", 0, body.len()).into_iter().rev().find_map(|at| array_binding(body, at, name, sizes)) else {
let mut in_scope = words(body, b"let", 0, body.len()).into_iter().rev().filter(|&at| open_at_end(body, at));
let Some((len, end)) = in_scope.find_map(|at| array_binding(body, at, name, sizes)) else {
return 0;
};
if may_shrink(body, name, end) {
@@ -1640,6 +1657,21 @@ fn bound_len(receiver: &str, body: &[u8], sizes: &Sizes) -> usize {
len.max(loop_fill_len(body, name, end, sizes))
}
/// Whether the block holding offset `at` of `body` is still open at the end of `body`: a binding
/// there is still in scope.
fn open_at_end(body: &[u8], at: usize) -> bool {
let mut depth = 0usize;
for &c in &body[at..] {
match c {
b'{' => depth += 1,
b'}' if depth == 0 => return false,
b'}' => depth -= 1,
_ => {}
}
}
true
}
/// For a `let` at `at` that binds `name` (allowing `mut`): the fewest items its array type
/// annotation gives (which decides when there is one), else its initializer gives ([`expr_len`]),
/// and where the statement ends. `None` for a binding of another name.
@@ -2012,10 +2044,11 @@ fn int_literal(text: &str) -> Option<usize> {
text[..digits].replace('_', "").parse().ok()
}
/// `const NAME: T = <integer literal>;` in a masked file; a name declared more than once keeps
/// its smallest value, and 0 when one of its values is not a literal.
/// `const NAME: T = <integer literal>;` in a masked file. A name declared more than once with
/// different values, or with a value that is not a literal, is left out (its value is unknown).
fn file_consts(file: &[u8]) -> HashMap<String, usize> {
let mut out: HashMap<String, usize> = HashMap::new();
// `None` for a name declared with a value that is not a literal or with different values.
let mut out: HashMap<String, Option<usize>> = HashMap::new();
for at in words(file, b"const", 0, file.len()) {
let start = skip_ws(file, at + 5);
let end = start + file[start..].iter().copied().take_while(|&c| is_ident(c)).count();
@@ -2025,12 +2058,14 @@ fn file_consts(file: &[u8]) -> HashMap<String, usize> {
let stop = statement_end(file, end);
let stmt = norm(&file[end..stop]);
let Some((_, value)) = stmt.split_once('=') else { continue };
let value = int_literal(value).unwrap_or(0);
let value = int_literal(value);
let name = String::from_utf8_lossy(&file[start..end]).into_owned();
let slot = out.entry(name).or_insert(value);
*slot = (*slot).min(value);
if *slot != value {
*slot = None;
}
}
out
out.into_iter().filter_map(|(name, value)| Some((name, value?))).collect()
}
/// A `let` of a plain name: the name, where the statement ends, and whether it binds an expression
@@ -2039,6 +2074,8 @@ struct Binding {
name: Vec<u8>,
end: usize,
counts: bool,
/// The local whose method the initializer calls (`xs` in `let n = xs.len()`).
source: Option<Vec<u8>>,
}
/// Every `let` of a plain name in `body`, in order.
@@ -2056,19 +2093,24 @@ fn bindings(body: &[u8]) -> Vec<Binding> {
}
let stop = statement_end(body, end);
let stmt = norm(&body[end..stop]);
let counts = stmt.split_once('=').is_some_and(|(_, init)| SIZE_CHECKS.iter().any(|g| init.contains(g)));
Some(Binding { name: body[start..end].to_vec(), end: stop, counts })
let init = stmt.split_once('=').map_or("", |(_, init)| init);
let counts = SIZE_CHECKS.iter().any(|g| init.contains(g));
let ident = init.bytes().take_while(|&c| is_ident(c)).count();
let source = (ident > 0 && init[ident..].starts_with('.')).then(|| init.as_bytes()[..ident].to_vec());
Some(Binding { name: body[start..end].to_vec(), end: stop, counts, source })
})
.collect()
}
/// Whether `body[from..to]` (an assertion operand) reads a local whose binding reaching that
/// point checks a size and was not assigned since.
/// point checks a size and was not assigned since, of a collection that no later code may shrink
/// or replace.
fn reads_counted_local(body: &[u8], all: &[Binding], from: usize, to: usize) -> bool {
all.iter().filter(|b| b.counts && b.name != b"_").any(|b| {
words(body, &b.name, from, to).into_iter().any(|p| {
let reaching = all.iter().rfind(|o| o.name == b.name && o.end <= p);
reaching.is_some_and(|r| r.counts && !may_shrink(&body[..p], &r.name, r.end))
reaching
.is_some_and(|r| r.counts && !may_shrink(&body[..p], &r.name, r.end) && r.source.as_ref().is_none_or(|s| !may_shrink(body, s, r.end)))
})
})
}
@@ -2089,13 +2131,20 @@ fn is_weak(cond: &str) -> bool {
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)));
let other = contains(v.body(), b"panic!") || contains(v.body(), b".unwrap_err()") || contains(v.body(), b".expect_err(");
// 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(");
if v.asserts.is_empty() || !all_weak || other || v.delegates || v.should_panic {
return None;
}
Some(v.whole(Rule::OnlyWeak, format!("its {} assertion(s) only check is_ok/is_some/non-empty", v.asserts.len())))
}
/// Methods that return the next value of something each time (`assert_ne!(it.next(), it.next())`
/// compares two items).
const ADVANCING: &[&str] =
&["next", "next_back", "pop", "pop_front", "pop_back", "recv", "try_recv", "read_line", "take", "tick", "step", "advance", "now", "elapsed"];
fn self_compare(v: &View) -> Vec<Hit> {
v.asserts
.iter()
@@ -2105,7 +2154,8 @@ fn self_compare(v: &View) -> Vec<Hit> {
let (l, r) = (v.file.src_norm(*a.args.first()?), v.file.src_norm(right));
let (l, r) = (l.trim_start_matches('&'), r.trim_start_matches('&'));
let calls_with_args = l.replace("()", "").contains(['(', '!']);
(l == r && !l.is_empty() && !calls_with_args).then(|| {
let advances = ADVANCING.iter().any(|m| l.contains(&format!(".{m}()")));
(l == r && !l.is_empty() && !calls_with_args && !advances).then(|| {
let mut h = v.hit(a.at, Rule::SelfCompare, format!("{}! compares `{l}` with itself", a.name));
let end = right.0 + v.file.m[right.0..right.1].trim_ascii_end().len();
h.last = v.file.lines.of(end.saturating_sub(1));
@@ -2373,7 +2423,10 @@ fn ignore_hits(file: &File) -> Vec<Hit> {
};
if !reason {
let test = file.tests.iter().find(|t| t.fn_at > at).map_or("", |t| t.name.as_str());
out.push(file.hit(at - 2, Rule::IgnoreWithoutReason, test, "#[ignore] gives no reason".into()));
// The hit sits on `#[ignore`; its span reaches the attribute's `]`, past a reason on a later line.
let mut hit = file.hit(at - 2, Rule::IgnoreWithoutReason, test, "#[ignore] gives no reason".into());
hit.last = matching(m, at - 1).map_or(hit.line, |close| file.lines.of(close));
out.push(hit);
}
}
out
@@ -3579,7 +3632,7 @@ mod tests {
#[test]
fn workflow_variables_count_as_set() {
let names: Vec<String> = upper_words("env:\n AFFINITY_CORPUS_REQUIRED: 1\n run: X=1 cargo test # A\n").collect();
assert_eq!(names, ["AFFINITY_CORPUS_REQUIRED"]);
assert_eq!(names, ["AFFINITY_CORPUS_REQUIRED", "X"]);
assert!(set_by_system("CARGO_MANIFEST_DIR") && set_by_system("HOME") && !set_by_system("MY_SAMPLES"));
}
@@ -3729,4 +3782,73 @@ mod tests {
let walk = "#[test]\nfn t() {\n let n = files().filter(|p| p.ends_with(r#\".rs\"#)).count();\n assert_eq!(n, 4);\n}\n";
assert_eq!(hits(walk), [(3, "reads-source")]);
}
#[test]
fn single_letter_variables_set_in_ci_count() {
let src = "#[test]\nfn t() {\n let dir = std::env::var(\"X\");\n assert_eq!(f(dir), 3);\n}\n";
assert_eq!(hits(src), [(3, "env-gate-unset")]);
let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words("env:\n X: 1\n").collect() };
assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), []);
}
#[test]
fn tests_with_non_ascii_names_are_checked() {
let src = "#[test]\nfn échec() {\n assert!(f().is_ok());\n}\n";
assert_eq!(lint_file("crates/x/src/tests.rs", src, &ctx()).iter().map(|h| (h.line, h.test.as_str())).collect::<Vec<_>>(), [(2, "échec")]);
}
#[test]
fn block_comment_allows_need_a_reason_before_the_closing_delimiter() {
let bare = "#[test]\nfn t() {\n thread::sleep(D); /* test-lint: allow sleep */\n assert_eq!(f(), 1);\n}\n";
assert_eq!(hits(bare), [(3, "sleep")]);
assert_eq!(hits(&bare.replace("sleep */", "sleep the clock has a 2 ms step */")), []);
}
#[test]
fn bindings_out_of_scope_do_not_guard_all() {
let src = "#[test]\nfn t() {\n let xs: Vec<u8> = vec![];\n {\n let xs = vec![1];\n use_it(&xs);\n }\n assert!(xs.iter().all(|x| *x > 0));\n}\n";
assert_eq!(hits(src), [(8, "all-unguarded")]);
let inside = "#[test]\nfn t() {\n let xs: Vec<u8> = vec![];\n {\n let xs = vec![1];\n assert!(xs.iter().all(|x| *x > 0));\n }\n use_it(&xs);\n}\n";
assert_eq!(hits(inside), []);
}
#[test]
fn constants_with_several_values_are_unknown() {
let src = "mod a { const START: usize = 0; }\nmod b {\nconst START: usize = 2;\nconst END: usize = 2;\n#[test]\nfn t() {\n let xs: Vec<usize> = (START..END).collect();\n assert!(xs.iter().all(|x| *x > 0));\n}\n}\n";
assert_eq!(hits(src), [(8, "all-unguarded")]);
assert_eq!(hits(&src.replace("mod a { const START: usize = 0; }\n", "").replace("END: usize = 2", "END: usize = 4")), []);
}
#[test]
fn a_count_stops_guarding_when_its_collection_changes() {
let src =
"#[test]\nfn t() {\n let mut xs = f();\n let n = xs.len();\n assert_eq!(n, 1);\n assert!(xs.iter().all(|x| *x > 0));\n}\n";
assert_eq!(hits(src), []);
let cleared = src.replace(" assert_eq!(n, 1);", " xs.clear();\n assert_eq!(n, 1);");
assert_eq!(hits(&cleared), [(7, "all-unguarded")]);
}
#[test]
fn checks_in_failure_messages_do_not_end_only_weak() {
let src = "#[test]\nfn t() {\n assert!(parse(input).is_ok(), \"{:?}\", probe().unwrap_err());\n}\n";
assert_eq!(hits(src), [(2, "only-weak")]);
assert_eq!(hits(&src.replace(" assert!", " let _ = probe().unwrap_err();\n assert!")), []);
}
#[test]
fn advancing_calls_are_not_self_comparisons() {
for operand in ["it.next()", "q.pop_front()", "rx.recv()"] {
let src = format!("#[test]\nfn t() {{\n assert_ne!({operand}, {operand});\n}}\n");
assert_eq!(hits(&src), [], "{operand}");
}
assert_eq!(hits("#[test]\nfn t() {\n assert_eq!(x.len(), x.len());\n}\n"), [(3, "self-compare")]);
}
#[test]
fn ignore_spans_reach_a_reason_on_the_next_line() {
let src = "#[test]\n#[ignore =\n \"\"]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
let found = lint_file("crates/x/src/tests.rs", src, &ctx());
assert_eq!(found.iter().map(|h| (h.rule, h.line, h.first, h.last)).collect::<Vec<_>>(), [(Rule::IgnoreWithoutReason, 2, 2, 3)]);
assert!(touches(&found[0], Some(&[3].into_iter().collect())), "a change to the reason alone");
}
}