From ded4e473a29f73fe134197df041b26d95a5f0dfc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:04:59 -0800 Subject: [PATCH] xtask: test-lint follows comments, inline and shared modules, and changed mod cfgs - never-run reads cfg predicates with comments removed, finds a module declared inside an inline module of its parent's parent, stops when several files declare a module with different attributes, and counts a change to a cfg on a mod declaration in another file against the tests it turns off. The lines between a module's cfg and the test no longer count as changes to the test. - reads-source ignores paths in comments. - census bounds weak_predicate at 64 levels and does not take a lookup with an operator before it as a round trip. - fixture-only treats a for-loop binding that shadows a fixture as unknown. - exact-pixel skips ratios and scaled values. - docs/development.md lists reads-source and never-run as failing rules. --- docs/development.md | 2 +- xtask/src/test_lint.rs | 284 +++++++++++++++++++++++++++++++++++------ 2 files changed, 243 insertions(+), 43 deletions(-) diff --git a/docs/development.md b/docs/development.md index a1ceccaf59..7a6b8e04cf 100644 --- a/docs/development.md +++ b/docs/development.md @@ -353,7 +353,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 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: 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`), `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 ` 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 ` 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 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`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that no CI target builds because of a `cfg` on it or on a `mod` above it (`never-run`). It lists the hits of the other rules without failing: 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`), `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 the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base ` 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 ` 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 diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index a5fc3e4bbc..bd00b6e833 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -240,6 +240,9 @@ pub struct Hit { /// only near `line`. pub first: usize, pub last: usize, + /// Other lines whose change counts as a change to the hit, by file: the `cfg` attributes that + /// turn a `never-run` test off, on its module or on a `mod` declaration in another file. + pub also: Vec<(String, usize, usize)>, } impl Hit { @@ -256,6 +259,18 @@ pub struct Ctx { pub helpers: HashMap>, pub ci_env: HashSet, pub module_cfgs: HashMap>, + /// Where the attributes of [`Ctx::module_cfgs`] are. + pub module_sites: HashMap>, +} + +/// [`Ctx::module_cfgs`] and [`Ctx::module_sites`] for `paths`. +fn module_ctx(paths: &[String], read: &dyn Fn(&str) -> Option) -> (HashMap>, HashMap>) { + let (mut cfgs, mut sites) = (HashMap::new(), HashMap::new()); + for (path, (preds, at)) in module_walk(paths, read) { + cfgs.insert(path.clone(), preds); + sites.insert(path, at); + } + (cfgs, sites) } /// A source file read from the work tree, or `None` when it is missing or larger than [`MAX_FILE`]. @@ -271,8 +286,8 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let files: Vec = repo.into_iter().filter(|p| is_scanned(p)).collect(); if opts.all { let sources = read_all(root, &files)?; - let module_cfgs = module_cfgs(&files, &|p| read_small(root, p)); - let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs }; + let (module_cfgs, module_sites) = module_ctx(&files, &|p| read_small(root, p)); + let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs, module_sites }; let hits: Vec = sources.iter().flat_map(|(p, s)| lint_file(p, s, &ctx)).collect(); print!("{}", report(&hits, sources.len())); return Ok(()); @@ -283,18 +298,30 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let crates: BTreeSet = changed.keys().map(|p| crate_of(p)).chain([TESTKIT.to_owned()]).collect(); let helper_files: Vec = files.iter().filter(|p| crates.contains(&crate_of(p))).cloned().collect(); let present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); - let module_cfgs = module_cfgs(&present, &|p| read_small(root, p)); - let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs }; + // Every file whose module a changed `mod` declaration governs is linted too, so a `cfg` added to + // `mod child;` counts against the tests in `child.rs`. + let cache: std::cell::RefCell>> = Default::default(); + let read = |p: &str| cache.borrow_mut().entry(p.to_owned()).or_insert_with(|| read_small(root, p)).clone(); + let (module_cfgs, module_sites) = module_ctx(&files, &read); + let governed: Vec = module_sites + .iter() + .filter(|(p, sites)| !changed.contains_key(*p) && sites.iter().any(|(decl, _, _)| changed.contains_key(decl))) + .map(|(p, _)| p.clone()) + .collect(); + let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs, module_sites }; let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { for hit in lint_file(&path, &src, &ctx) { - if touches(&hit, changed.get(&path).and_then(Option::as_ref)) { + if touches_in(&hit, &changed) { counted.push(hit); } else { older += 1; } } } + for (path, src) in read_all(root, &governed)? { + counted.extend(lint_file(&path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && touches_in(h, &changed))); + } finish(&counted, older, present.len(), &base) } @@ -544,7 +571,14 @@ fn hunk_range(hunk: &str) -> Option<(usize, usize)> { /// Whether `hit` covers a changed line (`None`: the whole file is new). fn touches(hit: &Hit, changed: Option<&BTreeSet>) -> bool { - changed.is_none_or(|lines| lines.range(hit.first..=hit.last).next().is_some()) + let within = |lines: &BTreeSet, a: usize, b: usize| lines.range(a..=b).next().is_some(); + changed.is_none_or(|lines| within(lines, hit.first, hit.last) || hit.also.iter().any(|(p, a, b)| *p == hit.path && within(lines, *a, *b))) +} + +/// [`touches`] across files: the hit's own lines, or its [`Hit::also`] lines in any changed file. +fn touches_in(hit: &Hit, changed: &BTreeMap>>) -> bool { + let in_file = |p: &str, a: usize, b: usize| changed.get(p).is_some_and(|c| c.as_ref().is_none_or(|l| l.range(a..=b).next().is_some())); + changed.get(&hit.path).is_some_and(|c| touches(hit, c.as_ref())) || hit.also.iter().any(|(p, a, b)| in_file(p, *a, *b)) } // ---- What CI sets ---- @@ -1183,7 +1217,7 @@ struct File<'a> { impl File<'_> { fn hit(&self, at: usize, rule: Rule, test: &str, note: String) -> Hit { let line = self.lines.of(at); - Hit { path: self.path.to_owned(), line, rule, test: test.to_owned(), note, first: line, last: line } + Hit { path: self.path.to_owned(), line, rule, test: test.to_owned(), note, first: line, last: line, also: vec![] } } fn test_at(&self, pos: usize) -> &str { @@ -1586,12 +1620,21 @@ const ROUND_TRIP: &[&str] = &["parse", "from_str", "from_id", "from_name", "from /// Whether every operand of a (whitespace-free) condition or closure is a presence check alone. fn weak_predicate(pred: &str) -> bool { + weak_predicate_within(pred, 0) +} + +/// [`weak_predicate`] for at most 64 levels of nesting; deeper conditions are not judged, as in +/// [`census_condition`]. +fn weak_predicate_within(pred: &str, depth: usize) -> bool { + if depth > 64 { + return false; + } 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]); + return weak_predicate_within(&pred[1..pred.len() - 1], depth + 1); } if let Some(at) = boolean_split(pred) { - return weak_predicate(&pred[..at]) && weak_predicate(&pred[at + 2..]); + return weak_predicate_within(&pred[..at], depth + 1) && weak_predicate_within(&pred[at + 2..], depth + 1); } let pred = pred.trim_start_matches('!'); if let Some(list) = pred.strip_suffix(".len()>0") { @@ -1636,6 +1679,8 @@ fn round_trip_call(op: &str) -> bool { op.match_indices(&format!("{r}(")).any(|(at, _)| { let open = at + r.len(); !op.as_bytes()[..at].last().copied().is_some_and(is_ident) + // Only a path or receiver before the call: `offset + lookup(n)` is a derived value. + && !op[..at].contains(['+', '-', '*', '/', '%', '^', '|', '=', '!', ',', '&']) && matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..])) }) }) @@ -2924,7 +2969,8 @@ fn reads_source_hits(file: &File) -> Vec { for at in words(m, word, 0, m.len()).into_iter().filter(|&at| in_regions(&file.regions, at)) { let open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!'))); let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; - let arg = norm(&file.src[open + 1..close]); + // Comments dropped, so `/* "src/lib.rs" */` beside a JSON path is not a hit. + let arg = file.src_norm((open + 1, close)); // An ordinary or raw string literal: `".rs"`, `r".rs"`, `r#"…/lib.rs"#`. let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); let literal = raw.unwrap_or(&arg); @@ -3111,6 +3157,26 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option in` binding of the name, whose block holds `before`, shadows the + // `let`: its value is unknown. + let found_at = match &found { + Some(Some((_, at))) => Some(*at), + _ => None, + }; + let shadows = |kw: &[u8], sep: &[u8]| { + words(body, kw, 0, before).into_iter().any(|at| { + let head = at + kw.len(); + let Some(open) = body[head..before].iter().position(|&c| c == b'{').map(|p| p + head) else { return false }; + let Some(split) = find(&body[..open], sep, head) else { return false }; + let pattern = &body[head..split]; + !words(pattern, name.as_bytes(), 0, pattern.len()).is_empty() + && matching(body, open).is_some_and(|close| open < before && before < close) + && found_at.is_none_or(|l| at > l) + }) + }; + if shadows(b"for", b" in ") { + return Some(None); + } found } @@ -3224,9 +3290,19 @@ fn cfg_value(p: &str, t: &Target) -> Option { } } +/// The text of a `cfg(…)` predicate without whitespace and comments; string literals keep their text. +fn cfg_text(src: &[u8]) -> String { + norm(&mask_parts(&String::from_utf8_lossy(src), true, false)) +} + +/// The 1-based line of a byte offset. +fn line_at(b: &[u8], at: usize) -> usize { + b[..at.min(b.len())].iter().filter(|&&c| c == b'\n').count() + 1 +} + /// The predicates of the `#[cfg(…)]` and `#![cfg(…)]` attributes whose item holds `pos`, each with -/// the offset of its attribute. `m` is the masked text of `src`. -fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { +/// the offsets of its attribute's `cfg` and closing `]`. `m` is the masked text of `src`. +fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> { let mut out = vec![]; for at in words(m, b"cfg", 0, m.len()) { let before = m[..at].trim_ascii_end(); @@ -3255,76 +3331,133 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { }; if span.0 <= pos && pos <= span.1 { // The source text: masking blanks the string literals `target_os = "macos"` needs. - out.push((norm(&src[open + 1..close]), at)); + out.push((cfg_text(&src[open + 1..close]), at, end)); } } out } +/// A file that may declare a module, and the inline module it must be declared in, if any. +type Candidate = (String, Option); +/// The predicates on a `mod` declaration and the first and last line of each attribute. +type Declared = (Vec, Vec<(usize, usize)>); +/// A file that declares a module, whether it does so in an inline module, and what it declares. +type Owner = (String, bool, Declared); + /// The module name a file declares and the files that may declare it with `mod ;`, or `None` /// for a crate root (`lib.rs`, `main.rs`, `build.rs`, a file directly in `tests`, `benches` or -/// `examples`). -fn module_parent(path: &str) -> Option<(&str, Vec)> { +/// `examples`). A candidate that comes with a module name declares it inside that inline module +/// (`mod platform { mod child; }` in `src/lib.rs` for `src/platform/child.rs`); those come last. +fn module_parent(path: &str) -> Option<(&str, Vec)> { let (dir, file) = path.rsplit_once('/')?; let root_dir = ["/tests", "/benches", "/examples"].iter().any(|d| dir.ends_with(d)); if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") { return None; } let (name, parent) = if file == "mod.rs" { dir.rsplit_once('/').map(|(p, n)| (n, p))? } else { (file.strip_suffix(".rs")?, dir) }; - let mut candidates: Vec = ["mod.rs", "lib.rs", "main.rs"].iter().map(|f| format!("{parent}/{f}")).collect(); - candidates.push(format!("{parent}.rs")); + let files_of = |dir: &str| -> Vec { + let mut c: Vec = ["mod.rs", "lib.rs", "main.rs"].iter().map(|f| format!("{dir}/{f}")).collect(); + c.push(format!("{dir}.rs")); + c + }; + let mut candidates: Vec = files_of(parent).into_iter().map(|c| (c, None)).collect(); + if let Some((grand, inline)) = parent.rsplit_once('/') { + candidates.extend(files_of(grand).into_iter().map(|c| (c, Some(inline.to_owned())))); + } Some((name, candidates)) } /// The predicates of the `#[cfg(…)]` attributes on a `mod ;` declaration in `src` and on the /// items and file around it, or `None` when `src` declares no such module. +#[cfg(test)] fn declared_cfgs(src: &str, name: &str) -> Option> { + declared_cfg_spans(src, name, None).map(|(preds, _)| preds) +} + +/// [`declared_cfgs`] with the first and last line of each attribute. With `within`, only a +/// declaration inside the inline module of that name counts. +fn declared_cfg_spans(src: &str, name: &str, within: Option<&str>) -> Option { let m = mask(src); - let decl = words(&m, b"mod", 0, m.len()).into_iter().find(|&at| { + let named = |at: usize, word: &str, next: u8| { let start = skip_ws(&m, at + 3); let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); - &m[start..end] == name.as_bytes() && m.get(skip_ws(&m, end)) == Some(&b';') - })?; + (&m[start..end] == word.as_bytes() && m.get(skip_ws(&m, end)) == Some(&next)).then(|| skip_ws(&m, end)) + }; + let blocks: Option> = within.map(|w| { + words(&m, b"mod", 0, m.len()).into_iter().filter_map(|at| named(at, w, b'{').and_then(|o| matching(&m, o).map(|c| (o, c)))).collect() + }); + let decl = words(&m, b"mod", 0, m.len()) + .into_iter() + .find(|&at| named(at, name, b';').is_some() && blocks.as_ref().is_none_or(|bs| bs.iter().any(|&(o, c)| o < at && at < c)))?; let item = m[..decl].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); - let mut out = vec![]; + let (mut preds, mut lines) = (vec![], vec![]); for at in words(&m, b"cfg", item, decl) { let open = skip_ws(&m, at + 3); let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); if let Some(close) = (attr && m.get(open) == Some(&b'(')).then(|| matching(&m, open)).flatten() { - out.push(norm(&src.as_bytes()[open + 1..close])); + preds.push(cfg_text(&src.as_bytes()[open + 1..close])); + lines.push((line_at(&m, at), line_at(&m, close))); } } - out.extend(cfgs_over(&m, src.as_bytes(), decl).into_iter().map(|(p, _)| p)); - Some(out) + for (p, at, end) in cfgs_over(&m, src.as_bytes(), decl) { + preds.push(p); + lines.push((line_at(&m, at), line_at(&m, end))); + } + Some((preds, lines)) } +/// Where a module's `cfg` attributes are: the declaring file and the attribute's first and last line. +pub type CfgSite = (String, usize, usize); + /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the -/// modules above it, read through `read`. -fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { +/// modules above it, read through `read`, with where those attributes are. When several files +/// declare a module (`lib.rs` and `main.rs`) with different attributes, the walk stops there and +/// the module's ownership is unknown. +fn module_walk(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap, Vec)> { let mut out = HashMap::new(); for path in paths { - let (mut preds, mut at) = (vec![], path.clone()); + let (mut preds, mut sites, mut at) = (vec![], vec![], path.clone()); for _ in 0..16 { let Some((name, candidates)) = module_parent(&at) else { break }; - let Some((parent, found)) = candidates.into_iter().find_map(|c| read(&c).and_then(|s| declared_cfgs(&s, name)).map(|f| (c, f))) else { - break; + let found: Vec = candidates + .into_iter() + .filter_map(|(c, within)| read(&c).and_then(|s| declared_cfg_spans(&s, name, within.as_deref())).map(|f| (c, within.is_some(), f))) + .collect(); + let direct = found.iter().any(|(_, inline, _)| !inline); + let owners: Vec<&Owner> = found.iter().filter(|(_, inline, _)| !inline || !direct).collect(); + let Some(first) = owners.first() else { break }; + let sorted = |p: &[String]| { + let mut p = p.to_vec(); + p.sort(); + p }; - preds.extend(found); - at = parent; + let base = sorted(&first.2.0); + if !owners.iter().all(|o| sorted(&o.2.0) == base) { + break; + } + preds.extend(first.2.0.iter().cloned()); + for o in &owners { + sites.extend(o.2.1.iter().map(|&(a, b)| (o.0.clone(), a, b))); + } + at = first.0.clone(); } if !preds.is_empty() { - out.insert(path.clone(), preds); + out.insert(path.clone(), (preds, sites)); } } out } +/// The predicates of [`module_walk`] alone. +#[cfg(test)] +fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { + module_walk(paths, read).into_iter().map(|(p, (preds, _))| (p, preds)).collect() +} + /// A test that a `cfg` compiles out on every target CI runs tests on. fn never_run(v: &View, ctx: &Ctx) -> Option { let local = cfgs_over(&v.file.m, v.file.src, v.t.fn_at); - // A change to an attribute that turns the test off counts as a change to the test. - let first_attr = local.iter().map(|&(_, at)| at).min(); - let mut preds: Vec = local.into_iter().map(|(p, _)| p).collect(); + let mut preds: Vec = local.iter().map(|(p, _, _)| p.clone()).collect(); preds.extend(ctx.module_cfgs.get(v.file.path).into_iter().flatten().cloned()); if preds.is_empty() { return None; @@ -3334,9 +3467,11 @@ fn never_run(v: &View, ctx: &Ctx) -> Option { if CI_TARGETS.iter().chain(windows).all(off) { let shown: Vec = preds.iter().filter(|p| p.as_str() != "test").map(|p| format!("cfg({p})")).collect(); let mut hit = v.whole(Rule::NeverRun, format!("{} leaves it out of every target CI tests on", shown.join(", "))); - if let Some(at) = first_attr { - hit.first = hit.first.min(v.file.lines.of(at)); - } + // A change to an attribute that turns the test off counts as a change to the test; the + // lines between that attribute and the test do not. + let lines = &v.file.lines; + hit.also.extend(local.iter().map(|&(_, at, end)| (v.file.path.to_owned(), lines.of(at), lines.of(end)))); + hit.also.extend(ctx.module_sites.get(v.file.path).into_iter().flatten().cloned()); return Some(hit); } None @@ -3366,6 +3501,10 @@ fn names_rect(op: &str) -> bool { if ["artboard", "doc", ".x0", ".y0", ".x1", ".y1", "obox"].iter().any(|w| op.contains(w)) { return false; } + // A ratio or a scaled value (`a.width() / b.width()`) is not a pixel size. + if op.trim_start_matches(['&', '*']).contains(['/', '*']) { + return false; + } let b = op.as_bytes(); let mut i = 0; while i < b.len() { @@ -3381,7 +3520,13 @@ fn names_rect(op: &str) -> bool { after = matching(b, after).map_or(b.len(), |c| c + 1); } let rest = &op[after..]; - if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.starts_with(p)) { + // The access must end the operand or a tuple or array item: `rect.width() / panel.width()` + // is a ratio, not a pixel size. + let ends = |r: &str| { + let r = r.strip_prefix(".x").or_else(|| r.strip_prefix(".y")).unwrap_or(r); + r.is_empty() || r.starts_with([',', ')', ']']) + }; + if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.strip_prefix(p).is_some_and(ends)) { return true; } } @@ -3525,6 +3670,18 @@ mod tests { assert_eq!(census(subsets), [], "subset adapters pick a few entries"); } + #[test] + fn census_skips_derived_lookups_and_deep_nesting() { + let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); + let offset = "#[test]\nfn t() {\n for n in COUNTS {\n assert_eq!(offset + lookup(n).unwrap(), n);\n }\n}\n"; + assert_eq!(census(offset), [], "an operator before the lookup derives a value"); + let qualified = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::parse(k.name()).unwrap(), k);\n }\n}\n"; + assert_eq!(census(qualified), [(2, "census")]); + let deep = + format!("#[test]\nfn t() {{\n for c in COLORS {{\n assert!({}c.is_some(){});\n }}\n}}\n", "(".repeat(66), ")".repeat(66)); + assert_eq!(census(&deep), [], "nesting deeper than the limit is not judged"); + } + #[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::>(); @@ -4954,7 +5111,7 @@ mod tests { let ne = "#[test]\nfn t() {\n assert_ne!(hash(a), hash(b));\n}\n"; assert_eq!(only("mirror", ne), [], "two inputs that must differ"); let allowed = - "#[test]\nfn t() {\n // test-lint: allow mirror both spellings parse to one value\n assert_eq!(parse(\"a\"), parse(\"A\"));\n}\n"; + "#[test]\nfn t() {\n // test-lint: allow mirror doubling is linear here\n assert_eq!(scale(p, 2.0), scale(p, 1.0) * 2.0);\n}\n"; assert_eq!(only("mirror", allowed), []); } @@ -4967,6 +5124,8 @@ mod tests { assert_eq!(only("fixture-only", fixture), [(2, "fixture-only")]); let result = "#[test]\nfn t() {\n let input = vec![1, 2, 3];\n let out = process(&input);\n assert_eq!(out.len(), 3);\n}\n"; assert_eq!(only("fixture-only", result), [], "the result of the code under test"); + let shadowed = "#[test]\nfn t() {\n let n = 1;\n for n in results() {\n assert_eq!(n, 2);\n }\n}\n"; + assert_eq!(only("fixture-only", shadowed), [], "a loop binding that shadows the fixture"); let changed = "#[test]\nfn t() {\n let mut input = vec![1, 2, 3];\n process(&mut input);\n assert_eq!(input.len(), 3);\n}\n"; assert_eq!(only("fixture-only", changed), [], "a mutable local the code changes"); let borrowed = "#[test]\nfn t() {\n let input = &mut [3, 1];\n sort(input);\n assert_eq!(*input, [1, 3]);\n}\n"; @@ -5050,8 +5209,46 @@ mod tests { let src = "#[cfg(target_os = \"macos\")]\nmod mac {\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; let found = lint_file("crates/x/src/tests.rs", src, &ctx()); let hit = found.iter().find(|h| h.rule == Rule::NeverRun).map(|h| (h.first, h.line)); - assert_eq!(hit, Some((1, 4))); - assert!(touches(found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(), Some(&[1].into_iter().collect())), "a change to the cfg alone"); + assert_eq!(hit, Some((3, 4))); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(touches(hit, Some(&[1].into_iter().collect())), "a change to the cfg alone"); + let helper = + "#[cfg(target_os = \"macos\")]\nmod mac {\n fn helper() {}\n\n #[test]\n fn t() {\n assert_eq!(f(), 1);\n }\n}\n"; + let found = lint_file("crates/x/src/tests.rs", helper, &ctx()); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + assert!(!touches(hit, Some(&[3].into_iter().collect())), "a helper between the cfg and the test"); + let commented = "#[cfg(target_os = /* supported */ \"linux\")]\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", commented), [], "a comment inside the predicate"); + } + + #[test] + fn never_run_counts_a_changed_mod_declaration_in_another_file() { + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod child;\n"), ("crates/x/src/child.rs", "")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let (module_cfgs, module_sites) = module_ctx(&["crates/x/src/child.rs".to_owned()], &read); + let ctx = Ctx { module_cfgs, module_sites, ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let found = lint_file("crates/x/src/child.rs", test, &ctx); + let hit = found.iter().find(|h| h.rule == Rule::NeverRun).unwrap(); + let changed = |lines: &[usize]| BTreeMap::from([("crates/x/src/lib.rs".to_owned(), Some(lines.iter().copied().collect()))]); + assert!(touches_in(hit, &changed(&[1])), "the cfg on the declaration changed"); + assert!(!touches_in(hit, &changed(&[2])), "only the declaration line changed"); + } + + #[test] + fn never_run_resolves_inline_parents_and_several_owners() { + let files: HashMap<&str, &str> = [ + ("crates/x/src/lib.rs", "#[cfg(windows)]\nmod platform {\n mod child;\n}\n#[cfg(target_os = \"macos\")]\nmod shared;\n"), + ("crates/x/src/main.rs", "mod shared;\n"), + ] + .into_iter() + .collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let paths: Vec = ["crates/x/src/platform/child.rs", "crates/x/src/shared.rs"].into_iter().map(String::from).collect(); + let cfgs = module_cfgs(&paths, &read); + assert_eq!(cfgs.get("crates/x/src/platform/child.rs").map(Vec::as_slice), Some(&["windows".to_owned()][..])); + assert!(!cfgs.contains_key("crates/x/src/shared.rs"), "main.rs compiles it on every target"); } #[test] @@ -5063,6 +5260,7 @@ mod tests { assert_eq!(px("assert!(rect.width() == 120.0);"), [(4, "exact-pixel")]); assert_eq!(px("assert!(panel_rect.contains_rect(button_rect));"), [], "a relationship"); assert_eq!(px("assert!(rect.width() >= SPACING);"), []); + assert_eq!(px("assert_eq!(button_rect.width() / panel_rect.width(), 0.5);"), [], "a ratio"); assert_eq!(px("assert_eq!(rects.len(), 3);"), [], "a count"); assert_eq!(px("assert_eq!(correct, 3);"), [], "a word that only contains rect"); assert_eq!(px("assert_eq!(tabs_rect(&app).min.y, 0.0);"), [(4, "exact-pixel")], "a call that returns a rect"); @@ -5079,5 +5277,7 @@ mod tests { assert_eq!(only("reads-source", read), [(3, "reads-source")]); let data = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", data), []); + let commented = "#[test]\nfn t() {\n let s = fs::read_to_string(/* formerly \"src/lib.rs\" */ \"fixture.json\").unwrap();\n assert!(s.contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", commented), [], "a path in a comment"); } }