diff --git a/docs/development.md b/docs/development.md index 5a1b6efd95..26058129e7 100644 --- a/docs/development.md +++ b/docs/development.md @@ -349,6 +349,10 @@ The app decides which cursors exist; whoever draws them works from the list. For `cargo xtask brands` (part of `cargo xtask ci`) fails when user-visible text names another vendor's products or company: string literals in Rust sources (command labels and params docs, menus, panels, MCP tool definitions), `Cargo.toml` descriptions and packaging files. Comments, test files and `#[cfg(test)]` modules are not checked. Say "the reference app" or name the feature itself. A line that must keep an old name, such as an alias that files or preferences from earlier versions still use, or a name another project defines, such as a shared MIME type, carries a `brand-ok` comment. In the Linux desktop entry, whose comments take whole lines, the comment goes on the `#` line just above it; `MARK_ABOVE` in `xtask/src/brands.rs` lists the files that accept a mark there. +## Test lint + +`cargo xtask test-lint` (part of `cargo xtask ci`) fails on tests that a wrong result can pass, in the lines and tests changed since a base: `assert!(….all(…))` with no length or emptiness check, a test whose only checks are `is_ok`, `is_some` or `!is_empty`, `assert_eq!(x, x)`, 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, `#[ignore]` without a reason, an environment variable that no CI leg sets, `thread::sleep` in test code, 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. + ## Tests - `cargo xtask test` runs the workspace's unit and integration tests with diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 08a55df09a..f48f088aa8 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -18,6 +18,7 @@ mod sha256; mod shards; mod stats; mod test262; +mod test_lint; mod ui_commands; mod version; mod web_fonts; @@ -32,6 +33,10 @@ commands: assets check that every icon/image/font/asset is attributed in ASSETS.md brands check that user-visible text (labels, params docs, MCP, docs, packaging) names no other vendor's products cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails) + test-lint [--base ] [--all] + fail on weak tests (unguarded .all(), only is_ok/is_some checks, no assertion, early + returns, unset env gates, sleeps...) in the lines changed since the base + (xtask/src/test_lint.rs); --all lists every hit by crate and never fails i18n-report list the strings each language's catalog lacks, shown in English (fails only on a broken scan; ci runs it too) ui-commands regenerate crates/mcp/src/ui_catalog.rs from desktop UI_COMMANDS; --check fails on drift @@ -39,7 +44,7 @@ commands: layers enforce the crate dependency layering (plan/architecture.md §3) wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates, the web app and its plug-in worker test the workspace tests (cargo nextest when installed, else cargo test), then the doctests - ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, cursors (warnings only), ui-commands --check, layers, wasm (stops at first failure) + ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, cursors (warnings only), test-lint, ui-commands --check, layers, wasm (stops at first failure) ci shard shard $GATE_SHARD of $GATE_SHARDS of ci (xtask/src/shards.rs): a test shard runs the tests and doctests of its crates, the last shard the other steps ci warm build what every shard builds, without running it (fills the gate's cache); with @@ -74,6 +79,7 @@ fn main() -> ExitCode { Some("assets") => assets::run(&root()), Some("brands") => brands::run(&root()), Some("cursors") => cursors::run(&root()), + Some("test-lint") => test_lint::run(&root(), &rest), Some("i18n-report") => cmd_i18n_report(), Some("ui-commands") => ui_commands::run(&root(), rest.contains(&"--check")), Some("layers") => cmd_layers(), @@ -515,6 +521,7 @@ fn ci_steps() -> Vec { ("assets", Box::new(|| assets::run(&root()))), ("brands", Box::new(|| brands::run(&root()))), ("cursors", Box::new(|| cursors::run(&root()))), + ("test-lint", Box::new(|| test_lint::run(&root(), &[]))), ("i18n-report", Box::new(cmd_ci_i18n_report)), ("ui-commands", Box::new(|| ui_commands::run(&root(), true))), ("layers", Box::new(cmd_layers)), diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs new file mode 100644 index 0000000000..8664403997 --- /dev/null +++ b/xtask/src/test_lint.rs @@ -0,0 +1,2574 @@ +//! `cargo xtask test-lint`: tests that a wrong result can pass, in the tests a change touches. +//! +//! Rules, checked in `#[test]` functions (and `#[tokio::test]`, `#[test_case]`, +//! `#[wasm_bindgen_test]`, and `#[test]` inside `proptest!`): +//! * `all-unguarded`: `assert!(….all(…))` in a test that neither checks a length, emptiness, +//! count, first item or `any` in an assertion's condition or compared operands, nor takes a +//! first item by indexing, unwrapping or a panicking `let … else`: `.all()` is true for an empty +//! collection (negated `.all(…)`, including `== false`, and predicates saying that no item +//! matches, with whole negations or `!=` comparisons joined only by `&&`, are left out). An earlier +//! `assert_eq!`, `debug_assert_eq!` or `prop_assert_eq!` comparing a plain local receiver +//! (optionally borrowed or viewed through `.as_slice()` or `[..]`) with a non-empty array +//! literal or `vec![…]` guards only that receiver. Non-empty array literals and plain local +//! names bound to them in the test, optionally through `.map(…)`, are also left out. Empty arrays +//! still count. A change anywhere in the test counts as a change to the hit; +//! * `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); +//! * `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, +//! and no `#[should_panic]`; +//! * `early-return`: a silent bare `return` before the end of the test whose guard tests a value +//! from the code under test. Left out: a return after an assertion in its block, one whose +//! statement or line has a comment or a printed note saying why, and guards on files, fonts, +//! corpora, environment variables, the platform or a child process; +//! * `ignore-without-reason`: `#[ignore]` with no `= "reason"`; +//! * `env-gate-unset`: `env::var("NAME")` in a test where no CI workflow, the shared gate or the +//! file itself sets `NAME`; workflow mapping keys and `NAME=` assignments count, but comments +//! and variable reads do not; +//! * `sleep`: `thread::sleep` in test code; +//! * `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`]. +//! +//! 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 a test function. +//! +//! An asserting helper is a function or macro in the crate's test code (or in `crates/testkit`) +//! that asserts, panics or calls one that does, or a call whose name starts with `assert`, +//! `check`, `verify`, `ensure` or `expect_`. +//! +//! `// test-lint: allow ` exempts the line it is on and the line below it; for the +//! 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 +//! ` 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 +//! workspace by crate and rule, and does not fail. + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::path::Path; +use std::process::Command; + +/// Test files that read Rust source on purpose: they audit the source tree. +pub const SOURCE_AUDITS: &[&str] = &[ + "crates/plugins/tests/grant_sites.rs", + "crates/ui-egui/src/i18n/tests.rs", + "crates/ui-egui/src/icons.rs", + "crates/eps/src/import/tests_generators.rs", +]; + +/// Variables the shared gate workflow and its setup action set on every leg, besides those named +/// in `.github/workflows/*.yml`. +const SHARED_GATE_ENV: &[&str] = + &["CRAFT_FONTS_DIR", "CRAFT_FONTS_REQUIRED", "GATE_SHARD", "GATE_SHARDS", "NEXTEST_PARTITION", "NEXTEST_ARCHIVE_FILE"]; + +/// Variables the runner, the operating system or cargo set. +const SYSTEM_ENV: &[&str] = &[ + "HOME", + "PATH", + "USER", + "USERNAME", + "LOGNAME", + "TMPDIR", + "TEMP", + "TMP", + "APPDATA", + "LOCALAPPDATA", + "USERPROFILE", + "PROGRAMDATA", + "PROGRAMFILES", + "WINDIR", + "SYSTEMROOT", + "CI", + "LANG", + "SHELL", + "PWD", + "OUT_DIR", +]; +const SYSTEM_ENV_PREFIXES: &[&str] = &["CARGO_", "NEXTEST", "RUST", "GITHUB_", "RUNNER_", "XDG_"]; + +/// Larger source files are refused rather than read. +const MAX_FILE: u64 = 16 << 20; + +/// The marker of an exemption comment. +const ALLOW: &str = "test-lint: allow "; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Rule { + AllUnguarded, + OnlyWeak, + SelfCompare, + ExitStatusOnly, + NoAssertion, + EarlyReturn, + IgnoreWithoutReason, + EnvGateUnset, + Sleep, + ReadsSource, +} + +impl Rule { + pub const ALL: [Rule; 10] = [ + Rule::AllUnguarded, + Rule::OnlyWeak, + Rule::SelfCompare, + Rule::ExitStatusOnly, + Rule::NoAssertion, + Rule::EarlyReturn, + Rule::IgnoreWithoutReason, + Rule::EnvGateUnset, + Rule::Sleep, + Rule::ReadsSource, + ]; + + pub fn id(self) -> &'static str { + match self { + Rule::AllUnguarded => "all-unguarded", + Rule::OnlyWeak => "only-weak", + Rule::SelfCompare => "self-compare", + Rule::ExitStatusOnly => "exit-status-only", + Rule::NoAssertion => "no-assertion", + Rule::EarlyReturn => "early-return", + Rule::IgnoreWithoutReason => "ignore-without-reason", + Rule::EnvGateUnset => "env-gate-unset", + Rule::Sleep => "sleep", + Rule::ReadsSource => "reads-source", + } + } + + fn advice(self) -> &'static str { + match self { + Rule::AllUnguarded => "also assert the expected length (or that the collection is not empty)", + Rule::OnlyWeak => "assert the value itself (assert_eq! on the result), not only that there is one", + Rule::SelfCompare => "compare with an expected value written out, or with a second, independent computation", + Rule::ExitStatusOnly => "also check the output (stdout, stderr or the files written)", + Rule::NoAssertion => "assert what the code returns or changes", + Rule::EarlyReturn => "assert the condition instead of returning, so a wrong value fails the test", + Rule::IgnoreWithoutReason => "write #[ignore = \"why\"]", + 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", + } + } + + fn from_id(id: &str) -> Option { + Rule::ALL.into_iter().find(|r| r.id() == id) + } +} + +/// A rule broken in a file. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Hit { + pub path: String, + /// 1-based: the line of the finding, or of `fn` for a rule about a whole test. + pub line: usize, + pub rule: Rule, + /// The test it is in; empty for test code outside a test function. + pub test: String, + 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`, else `line`. This span controls changed-line detection; `all-unguarded` + /// and `self-compare` exemptions still apply only near `line`. + pub first: usize, + pub last: usize, +} + +impl Hit { + fn show(&self) -> String { + let test = if self.test.is_empty() { String::new() } else { format!(" `{}`", self.test) }; + format!("{}:{}: [{}]{test}: {}", self.path, self.line, self.rule.id(), self.note) + } +} + +/// What the rules need beyond the file: asserting helper names by crate and the variables CI sets. +pub struct Ctx { + pub helpers: HashMap>, + pub ci_env: HashSet, +} + +pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { + let opts = Options::parse(args)?; + let repo = crate::repo_files(root)?; + let ci_env = ci_env(root, &repo)?; + let files: Vec = repo.into_iter().filter(|p| is_scanned(p)).collect(); + if opts.all { + let sources = read_all(root, &files)?; + let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env }; + let hits: Vec = sources.iter().flat_map(|(p, s)| lint_file(p, s, &ctx)).collect(); + print!("{}", report(&hits, sources.len())); + return Ok(()); + } + let base = resolve_base(root, opts.base)?; + let changed = changed_lines(root, &base)?; + let changed: BTreeMap>> = changed.into_iter().filter(|(p, _)| is_scanned(p)).collect(); + 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 ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env }; + let present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); + 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)) { + counted.push(hit); + } else { + older += 1; + } + } + } + finish(&counted, older, present.len(), &base) +} + +/// The command line: `--all`, `--base `. +#[derive(Debug, Default, PartialEq)] +struct Options { + all: bool, + base: Option, +} + +impl Options { + fn parse(args: &[&str]) -> Result { + let mut opts = Options::default(); + let mut it = args.iter(); + while let Some(&arg) = it.next() { + match arg { + "--all" if !opts.all => opts.all = true, + "--base" if opts.base.is_none() => match it.next() { + Some(rev) if !rev.is_empty() && !rev.starts_with('-') => opts.base = Some((*rev).to_owned()), + _ => return Err("test-lint: --base takes a revision".into()), + }, + _ => return Err(format!("test-lint: unexpected argument `{arg}` (usage: cargo xtask test-lint [--all] [--base ])")), + } + } + if opts.all && opts.base.is_some() { + return Err("test-lint: --all checks every file and takes no --base".into()); + } + Ok(opts) + } +} + +fn finish(counted: &[Hit], older: usize, files: usize, base: &str) -> Result<(), String> { + let older = if older == 0 { String::new() } else { format!("; {older} hit(s) on unchanged lines of those files are not counted") }; + if counted.is_empty() { + println!("test-lint: no hits in the changed lines of {files} Rust file(s) since {base}{older}"); + return Ok(()); + } + let mut out: Vec = counted.iter().map(Hit::show).collect(); + let rules: BTreeSet = counted.iter().map(|h| h.rule).collect(); + out.extend(rules.iter().map(|r| format!("{}: {}", r.id(), r.advice()))); + Err(format!( + "{} test-lint hit(s) in the lines changed since {base}{older} (exempt a line with `// {ALLOW} `):\n {}", + counted.len(), + out.join("\n ") + )) +} + +/// `--all`: counts by crate and rule, then every hit. +fn report(hits: &[Hit], files: usize) -> String { + let mut by_crate: BTreeMap> = BTreeMap::new(); + for h in hits { + *by_crate.entry(crate_of(&h.path)).or_default().entry(h.rule).or_default() += 1; + } + let mut out = format!("test-lint --all: {} hit(s) in {files} Rust file(s)\n\nby rule:\n", hits.len()); + for rule in Rule::ALL { + out += &format!(" {:<22} {}\n", rule.id(), hits.iter().filter(|h| h.rule == rule).count()); + } + out += "\nby crate:\n"; + for (krate, rules) in &by_crate { + let list: Vec = rules.iter().map(|(r, n)| format!("{} {n}", r.id())).collect(); + out += &format!(" {krate}: {}\n", list.join(", ")); + } + out += "\nhits:\n"; + for h in hits { + out += &format!(" {}\n", h.show()); + } + out +} + +/// Rust files the lint reads. +fn is_scanned(path: &str) -> bool { + path.ends_with(".rs") && ["crates/", "apps/", "xtask/"].iter().any(|d| path.starts_with(d)) +} + +/// `crates/` or `apps/` for a file in one, else its first path component. +fn crate_of(path: &str) -> String { + let parts: Vec<&str> = path.split('/').collect(); + match parts.as_slice() { + [top @ ("crates" | "apps"), name, _, ..] => format!("{top}/{name}"), + [first, ..] => (*first).to_owned(), + [] => String::new(), + } +} + +fn read_all(root: &Path, paths: &[String]) -> Result, String> { + paths + .iter() + .map(|p| { + let full = root.join(p); + let len = std::fs::metadata(&full).map_err(|e| format!("{p}: {e}"))?.len(); + if len > MAX_FILE { + return Err(format!("{p}: {len} bytes, over test-lint's limit of {MAX_FILE}")); + } + Ok((p.clone(), std::fs::read_to_string(&full).map_err(|e| format!("{p}: {e}"))?)) + }) + .collect() +} + +// ---- Git: the base and the changed lines ---- + +fn git(root: &Path, args: &[&str]) -> Result { + let out = Command::new("git").current_dir(root).args(args).output().map_err(|e| format!("git {}: {e}", args.join(" ")))?; + if !out.status.success() { + return Err(format!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim())); + } + Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned()) +} + +fn resolve_base(root: &Path, explicit: Option) -> Result { + if let Some(rev) = explicit.or_else(|| std::env::var("TEST_LINT_BASE").ok().filter(|v| !v.is_empty())) { + return git(root, &["rev-parse", "--verify", "--quiet", &format!("{rev}^{{commit}}")]) + .map_err(|_| format!("test-lint: base `{rev}` is not a commit")); + } + if std::env::var_os("GITHUB_ACTIONS").is_some() { + if let Ok(parent) = git(root, &["rev-parse", "--verify", "--quiet", "HEAD^1^{commit}"]) { + return Ok(parent); + } + let head = git(root, &["rev-parse", "HEAD"])?; + git(root, &["fetch", "--no-tags", "--quiet", "--depth=2", "origin", &head])?; + return git(root, &["rev-parse", "--verify", "--quiet", "HEAD^1^{commit}"]) + .map_err(|_| "test-lint: HEAD has no parent to compare with (set TEST_LINT_BASE)".into()); + } + for main in ["upstream/main", "origin/main"] { + if let Ok(base) = git(root, &["merge-base", "HEAD", main]) { + return Ok(base); + } + } + Err("test-lint: no upstream/main or origin/main to compare with; pass --base or set TEST_LINT_BASE".into()) +} + +/// The changed files since `base` with their changed lines (new numbering); `None` for a file that +/// is new or untracked. A pure deletion marks the lines before and after it, or line 1 at the top +/// of the file. +fn changed_lines(root: &Path, base: &str) -> Result>>, String> { + let diff = git( + root, + &["-c", "core.quotepath=off", "diff", "-U0", "--no-color", "--no-ext-diff", "--src-prefix=a/", "--dst-prefix=b/", base, "--", "*.rs"], + )?; + let mut out = parse_diff(&diff); + for path in git(root, &["-c", "core.quotepath=off", "ls-files", "--others", "--exclude-standard", "--", "*.rs"])?.lines() { + out.insert(path.to_owned(), None); + } + Ok(out) +} + +/// The changed new-side lines in each file. A pure deletion includes its anchor and the following +/// line, or just line 1 when the anchor is 0. +fn parse_diff(diff: &str) -> BTreeMap>> { + let mut out: BTreeMap>> = BTreeMap::new(); + let mut current: Option = None; + // Inside a file's header (from `diff --git` to its first hunk), where `+++ ` names the file. + let (mut header, mut new_file) = (false, false); + for line in diff.lines() { + if line.starts_with("diff --git ") { + (header, new_file) = (true, false); + } else if header && line.starts_with("new file mode") { + new_file = true; + } else if let Some(path) = line.strip_prefix("+++ ").filter(|_| header) { + current = path.strip_prefix("b/").map(str::to_owned); + if let Some(p) = ¤t { + out.insert(p.clone(), if new_file { None } else { Some(BTreeSet::new()) }); + } + } else if let (Some(hunk), Some(path)) = (line.strip_prefix("@@ "), ¤t) { + header = false; + if let (Some((start, count)), Some(Some(lines))) = (hunk_range(hunk), out.get_mut(path)) { + if count == 0 { + lines.extend(start.max(1)..=start.saturating_add(1)); + } else { + lines.extend(start..start + count); + } + } + } + } + out +} + +/// `(start, count)` of the new side of a hunk header's `-a,b +c,d @@`. A pure deletion has count 0 +/// and sits between lines c and c + 1; c = 0 places it before line 1. +fn hunk_range(hunk: &str) -> Option<(usize, usize)> { + let new = hunk.split_whitespace().find(|w| w.starts_with('+'))?.trim_start_matches('+'); + match new.split_once(',') { + Some((s, c)) => Some((s.parse().ok()?, c.parse().ok()?)), + None => Some((new.parse().ok()?, 1)), + } +} + +/// 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()) +} + +// ---- What CI sets ---- + +fn ci_env(root: &Path, files: &[String]) -> Result, String> { + let mut names: HashSet = SHARED_GATE_ENV.iter().map(|s| (*s).to_owned()).collect(); + for path in files.iter().filter(|p| p.starts_with(".github/workflows/") && (p.ends_with(".yml") || p.ends_with(".yaml"))) { + let text = std::fs::read_to_string(root.join(path)).map_err(|e| format!("{path}: {e}"))?; + names.extend(upper_words(&text)); + } + Ok(names) +} + +/// Workflow mapping keys and assignments with capitalized environment variable names. +fn upper_words(text: &str) -> impl Iterator + '_ { + text.lines().flat_map(|line| { + let line = workflow_code(line); + let start = line.trim_start().strip_prefix("- ").unwrap_or(line.trim_start()).trim_start(); + let mapping = + start.split_once(':').filter(|(name, rest)| env_assignment_name(name) && (rest.is_empty() || rest.starts_with(char::is_whitespace))); + let assignments = line.match_indices('=').filter_map(move |(at, _)| { + let name = line[..at].rsplit(|c: char| !(c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')).next().unwrap_or_default(); + let from = at - name.len(); + let boundary = from == 0 || line.as_bytes().get(from - 1).is_some_and(|c| c.is_ascii_whitespace() || matches!(c, b'\'' | b'"' | b';')); + (boundary && env_assignment_name(name) && !line[at + 1..].starts_with(['=', '>'])).then(|| name.to_owned()) + }); + mapping.map(|(name, _)| name.to_owned()).into_iter().chain(assignments) + }) +} + +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'_') +} + +/// Removes comment text outside quotes from a workflow line. +fn workflow_code(line: &str) -> &str { + let (mut quote, mut escaped) = (None, false); + for (at, c) in line.char_indices() { + if escaped { + escaped = false; + } else if c == '\\' && quote != Some('\'') { + escaped = true; + } else if quote == Some(c) { + quote = None; + } else if quote.is_none() { + match c { + '\'' | '"' => quote = Some(c), + '#' => return &line[..at], + _ => {} + } + } + } + line +} + +fn set_by_system(name: &str) -> bool { + SYSTEM_ENV.contains(&name) || SYSTEM_ENV_PREFIXES.iter().any(|p| name.starts_with(p)) +} + +// ---- Lexing ---- + +fn is_ident(c: u8) -> bool { + c.is_ascii_alphanumeric() || c == b'_' +} + +/// `src` with the text of comments and of string and character literals replaced by spaces (line +/// breaks and quotes kept), at the same byte offsets. +fn mask(src: &str) -> Vec { + mask_with(src, true) +} + +/// [`mask`], keeping comments when `comments` is false. +fn mask_with(src: &str, comments: bool) -> Vec { + mask_parts(src, comments, true) +} + +/// Blanks comments while keeping code and literal contents at the same byte offsets. +fn mask_comments(src: &str) -> Vec { + mask_parts(src, true, false) +} + +/// Blanks the selected comments and literal contents, preserving line breaks and literal quotes. +fn mask_parts(src: &str, comments: bool, literals: bool) -> Vec { + let b = src.as_bytes(); + let mut out = b.to_vec(); + let mut i = 0; + while i < b.len() { + let next = match b[i] { + b'/' if b.get(i + 1) == Some(&b'/') => { + let end = find(b, b"\n", i).unwrap_or(b.len()); + if comments { + blank(&mut out, i, end); + } + end + } + b'/' if b.get(i + 1) == Some(&b'*') => { + let end = block_comment_end(b, i); + if comments { + blank(&mut out, i, end); + } + end + } + b'"' => { + let end = string_end(b, i + 1); + if literals { + blank(&mut out, i + 1, end.saturating_sub(1)); + } + end + } + b'\'' => { + let end = after_char_or_lifetime(src, i); + if literals { + blank(&mut out, i + 1, end.saturating_sub(1).max(i + 1)); + } + end + } + c if c.is_ascii_alphabetic() || c == b'_' => after_ident(b, &mut out, i, literals), + _ => i + 1, + }; + i = next.max(i + 1); + } + out +} + +fn blank(out: &mut [u8], from: usize, to: usize) { + for c in out.iter_mut().take(to).skip(from) { + if *c != b'\n' { + *c = b' '; + } + } +} + +fn block_comment_end(b: &[u8], mut i: usize) -> usize { + let mut nest = 0usize; + while i < b.len() { + if b[i..].starts_with(b"/*") { + nest += 1; + i += 2; + } else if b[i..].starts_with(b"*/") { + nest = nest.saturating_sub(1); + i += 2; + if nest == 0 { + return i; + } + } else { + i += 1; + } + } + b.len() +} + +/// The index after the closing quote of a `"…"` literal whose body starts at `i`. +fn string_end(b: &[u8], mut i: usize) -> usize { + while i < b.len() && b[i] != b'"' { + i += if b[i] == b'\\' { 2 } else { 1 }; + } + (i + 1).min(b.len()) +} + +/// The index after a char literal (`'x'`, `'\n'`, `'\u{…}'`) at `i`, or after the quote of a +/// lifetime or label. +fn after_char_or_lifetime(src: &str, i: usize) -> usize { + let b = src.as_bytes(); + if b.get(i + 1) == Some(&b'\\') { + let close = (i + 3..b.len()).find(|&j| b[j] == b'\'').unwrap_or(b.len()); + return (close + 1).min(b.len()); + } + match src.get(i + 1..).and_then(|s| s.chars().next()) { + Some(c) if b.get(i + 1 + c.len_utf8()) == Some(&b'\'') => i + 2 + c.len_utf8(), + _ => i + 1, + } +} + +/// Skips the identifier at `start`; a raw string prefix (`r`, `br`, `cr`) also skips the raw +/// string after it and blanks its contents when `literals` is true. +fn after_ident(b: &[u8], out: &mut [u8], start: usize, literals: bool) -> usize { + let mut i = start; + while i < b.len() && is_ident(b[i]) { + i += 1; + } + if start > 0 && is_ident(b[start - 1]) { + return i; + } + let hashes = b[i..].iter().take_while(|&&h| h == b'#').count(); + if !matches!(&b[start..i], b"r" | b"br" | b"cr") || b.get(i + hashes) != Some(&b'"') { + return i; + } + let body = i + hashes + 1; + let close: Vec = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); + let end = find(b, &close, body).unwrap_or(b.len()); + if literals { + blank(out, body, end); + } + (end + close.len()).min(b.len()) +} + +fn find(hay: &[u8], needle: &[u8], from: usize) -> Option { + if needle.is_empty() || from >= hay.len() { + return None; + } + hay[from..].windows(needle.len()).position(|w| w == needle).map(|p| p + from) +} + +fn contains(hay: &[u8], needle: &[u8]) -> bool { + find(hay, needle, 0).is_some() +} + +fn skip_ws(b: &[u8], mut i: usize) -> usize { + while i < b.len() && b[i].is_ascii_whitespace() { + i += 1; + } + i +} + +/// Every start of `word` in `b[from..to]` with no identifier character on either side. +fn words(b: &[u8], word: &[u8], from: usize, to: usize) -> Vec { + let mut out = vec![]; + let mut i = from; + while let Some(at) = find(&b[..to.min(b.len())], word, i) { + let before = at.checked_sub(1).and_then(|j| b.get(j)).copied().is_some_and(is_ident); + let after = b.get(at + word.len()).copied().is_some_and(is_ident); + if !before && !after { + out.push(at); + } + i = at + 1; + } + out +} + +/// The index of the bracket closing the one at `open`. +fn matching(m: &[u8], open: usize) -> Option { + let (o, c) = match m.get(open)? { + b'(' => (b'(', b')'), + b'[' => (b'[', b']'), + b'{' => (b'{', b'}'), + _ => return None, + }; + let mut depth = 0usize; + for (j, &ch) in m.iter().enumerate().skip(open) { + if ch == o { + depth += 1; + } else if ch == c { + depth = depth.saturating_sub(1); + if depth == 0 { + return Some(j); + } + } + } + None +} + +/// The ranges of the top-level comma-separated parts of `m[from..to]`. +fn split_args(m: &[u8], from: usize, to: usize) -> Vec<(usize, usize)> { + let (mut out, mut depth, mut start) = (vec![], 0i32, from); + let mut angles = 0usize; + for (j, &ch) in m.iter().enumerate().take(to).skip(from) { + match ch { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth -= 1, + b'<' if angles > 0 || m[from..j].trim_ascii_end().ends_with(b"::") => angles += 1, + b'>' if angles > 0 => angles -= 1, + b',' if depth == 0 && angles == 0 => { + out.push((start, j)); + start = j + 1; + } + _ => {} + } + } + if m[start..to].iter().any(|c| !c.is_ascii_whitespace()) { + out.push((start, to)); + } + out +} + +/// `b` without whitespace. +fn norm(b: &[u8]) -> String { + String::from_utf8_lossy(&b.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect::>()).into_owned() +} + +/// Line starts, to turn byte offsets into 1-based lines. +struct Lines(Vec); + +impl Lines { + fn new(src: &str) -> Lines { + Lines(std::iter::once(0).chain(src.match_indices('\n').map(|(i, _)| i + 1)).collect()) + } + + fn of(&self, pos: usize) -> usize { + self.0.partition_point(|&s| s <= pos) + } +} + +// ---- Tests and calls ---- + +/// A test function: its name, the offsets of its first attribute and `fn`, and its body's braces. +#[derive(Debug)] +struct TestFn { + name: String, + /// The first attribute of the function (`#[should_panic]` can come before `#[test]`). + attr: usize, + fn_at: usize, + open: usize, + close: usize, +} + +fn is_test_attr(path: &[u8]) -> bool { + matches!(path, b"test" | b"wasm_bindgen_test" | b"test_case") || path.ends_with(b"::test") || path.ends_with(b"::test_case") +} + +/// The test functions of masked source `m`. +fn tests_in(m: &[u8]) -> Vec { + let mut out: Vec = vec![]; + let mut i = 0; + while let Some(at) = find(m, b"#[", i) { + i = at + 2; + let start = skip_ws(m, at + 2); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c) || c == b':').count(); + if !is_test_attr(&m[start..end]) || !matches!(m.get(skip_ws(m, end)), Some(b']' | b'(')) { + continue; + } + let Some(t) = fn_after(m, at, end) else { continue }; + if out.iter().any(|o| o.fn_at == t.fn_at) { + continue; + } + i = t.open; + out.push(t); + } + out +} + +/// The function an attribute at `attr` (ending at `from`) belongs to. +fn fn_after(m: &[u8], attr: usize, from: usize) -> Option { + let limit = (from + 800).min(m.len()); + let fn_at = *words(m, b"fn", from, limit).first()?; + if m[from..fn_at].iter().any(|&c| c == b'{' || c == b';') { + 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(); + if name_end == name_start { + return None; + } + let open = name_end + m[name_end..].iter().position(|&c| c == b'{' || c == b';')?; + if m[open] != b'{' { + return None; + } + let close = matching(m, open)?; + // The item starts after the previous item or block opening; comments before it are masked. + let item = m[..attr].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let attr = skip_ws(m, item).min(attr); + Some(TestFn { name: String::from_utf8_lossy(&m[name_start..name_end]).into_owned(), attr, fn_at, open, close }) +} + +/// A macro call in a test: its name, offset and argument ranges. +struct MacroCall { + name: String, + at: usize, + args: Vec<(usize, usize)>, +} + +/// The macro calls (`name!(…)`, `name![…]`, `name!{…}`) in `m[from..to]`. +fn macro_calls(m: &[u8], from: usize, to: usize) -> Vec { + let mut out = vec![]; + let mut i = from; + while let Some(bang) = find(&m[..to], b"!", i) { + i = bang + 1; + let start = (from..bang).rev().take_while(|&j| is_ident(m[j])).last().unwrap_or(bang); + let open = skip_ws(m, bang + 1); + if start == bang || start.checked_sub(1).is_some_and(|j| is_ident(m[j])) || !matches!(m.get(open), Some(b'(' | b'[' | b'{')) { + continue; + } + let Some(close) = matching(m, open).filter(|&c| c < to) else { continue }; + out.push(MacroCall { name: String::from_utf8_lossy(&m[start..bang]).into_owned(), at: start, args: split_args(m, open + 1, close) }); + } + out +} + +fn is_assert_macro(name: &str) -> bool { + ["assert", "debug_assert", "prop_assert"].iter().any(|p| name.starts_with(p)) +} + +const KEYWORDS: &[&str] = &["if", "while", "match", "for", "loop", "return", "fn", "in", "as", "let", "else", "move", "Some", "Ok", "Err"]; + +/// Names that helper detection ignores: too common to tell a helper from the code under test. +const COMMON: &[&str] = &[ + "new", "default", "from", "into", "get", "set", "run", "apply", "build", "make", "open", "load", "save", "parse", "read", "write", "draw", + "render", "len", "clone", "push", "vec", "format", "json", "Box", "Arc", "Vec", "String", "main", +]; + +/// The names called in `m[from..to]`: functions (`name(`, also through a path), methods +/// (`.name(`), including calls with turbofish arguments, and macros (`name!`). +fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> { + let m = &m[..to]; + let mut out = vec![]; + let mut i = from; + while i < to { + if !(m[i].is_ascii_alphabetic() || m[i] == b'_') || (i > 0 && is_ident(m[i - 1])) { + i += 1; + continue; + } + let end = i + m[i..to].iter().take_while(|&&c| is_ident(c)).count(); + let bang = m.get(end) == Some(&b'!'); + let after = skip_ws(m, end + usize::from(bang)); + let after = if bang { after } else { skip_turbofish(m, after) }; + if matches!(m.get(after), Some(b'(' | b'[' | b'{')) && (bang || m[after] == b'(') { + let name = String::from_utf8_lossy(&m[i..end]).into_owned(); + let method = i > 0 && m[i - 1] == b'.'; + if !KEYWORDS.contains(&name.as_str()) { + out.push((if bang { format!("{name}!") } else { name }, method)); + } + } + i = end; + } + out +} + +/// Skips optional `::<…>` arguments and the whitespace after them. +fn skip_turbofish(m: &[u8], at: usize) -> usize { + if !m[at..].starts_with(b"::") { + return at; + } + let open = skip_ws(m, at + 2); + if m.get(open) != Some(&b'<') { + return at; + } + let (mut i, mut depth) = (open + 1, 1usize); + while i < m.len() { + match m[i] { + b'<' => depth += 1, + b'>' if m[i - 1] != b'-' => { + depth -= 1; + if depth == 0 { + return skip_ws(m, i + 1); + } + } + b'(' | b'[' | b'{' => i = matching(m, i).unwrap_or(m.len()), + _ => {} + } + i += 1; + } + m.len() +} + +/// Whether `name` (a call in a test) is an asserting helper. +fn is_helper_call(name: &str, method: bool, helpers: &HashSet) -> bool { + let base = name.trim_end_matches('!'); + let named = ["assert", "check", "verify", "ensure", "expect_"].iter().any(|p| base.starts_with(p)); + named || (!method && !COMMON.contains(&base) && helpers.contains(name)) +} + +/// Whether the masked text checks something itself: an assertion, `panic!`, `unwrap_err` or +/// `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)) +} + +/// `tests.rs`, `tests_*.rs`, `*_tests.rs`, files in a `tests` or `benches` folder, and +/// `crates/testkit`. +fn is_test_file(path: &str) -> bool { + let mut parts = path.split('/').rev(); + let file = parts.next().unwrap_or_default(); + file == "tests.rs" + || file.starts_with("tests_") + || file.ends_with("_tests.rs") + || parts.any(|d| d == "tests" || d == "benches") + || path.starts_with("crates/testkit/") +} + +/// The byte ranges of test code in a file: all of a test file, else each item under +/// `#[cfg(test)]` that has a body in the file, and each test function. +fn test_regions(path: &str, m: &[u8], tests: &[TestFn]) -> Vec<(usize, usize)> { + if is_test_file(path) { + return vec![(0, m.len())]; + } + let mut out: Vec<(usize, usize)> = tests.iter().map(|t| (t.attr, t.close)).collect(); + for at in words(m, b"cfg", 0, m.len()) { + let attr = skip_ws(m, at + "cfg".len()); + if !m[..at].ends_with(b"#[") || !m[attr..].starts_with(b"(test)]") { + continue; + } + // The item's body: the first `{` before any `;` (`mod tests;` has none here). + let after = attr + "(test)]".len(); + let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; + if let (b'{', Some(close)) = (m[open], matching(m, open)) { + out.push((at, close)); + } + } + out +} + +fn in_regions(regions: &[(usize, usize)], pos: usize) -> bool { + regions.iter().any(|&(from, to)| from <= pos && pos <= to) +} + +/// A function or macro in test code: its name (`name!` for a macro), whether it checks something +/// itself, and the names it calls. +type Def = (String, bool, Vec); + +/// For each crate of `files` ([`crate_of`]), the names of the functions and macros in its test +/// code, or in `crates/testkit`'s, that assert, panic or call one that does. +pub fn asserting_helpers(files: &[(String, String)]) -> HashMap> { + let mut defs: HashMap> = HashMap::new(); + for (path, src) in files { + let m = mask(src); + let regions = test_regions(path, &m, &tests_in(&m)); + let crate_defs = defs.entry(crate_of(path)).or_default(); + for at in words(&m, b"fn", 0, m.len()).into_iter().chain(words(&m, b"macro_rules", 0, m.len())) { + if in_regions(®ions, at) { + crate_defs.extend(definition(&m, at)); + } + } + } + let testkit = defs.get(TESTKIT).cloned().unwrap_or_default(); + defs.iter().map(|(krate, own)| (krate.clone(), checking(own.iter().chain(if krate == TESTKIT { &[][..] } else { &testkit[..] })))).collect() +} + +/// The crate whose test helpers every crate can call. +const TESTKIT: &str = "crates/testkit"; + +/// The names among `defs` that check something, directly or through another of `defs`. +fn checking<'a>(defs: impl Iterator + Clone) -> HashSet { + let mut known: HashSet = defs.clone().filter(|d| d.1).map(|d| d.0.clone()).collect(); + loop { + let more: Vec = + defs.clone().filter(|d| !known.contains(&d.0) && d.2.iter().any(|c| known.contains(c))).map(|d| d.0.clone()).collect(); + if more.is_empty() { + return known; + } + known.extend(more); + } +} + +/// The `fn` or `macro_rules!` at `at`. +fn definition(m: &[u8], at: usize) -> Option { + let is_macro = m[at..].starts_with(b"macro_rules"); + let mut start = skip_ws(m, at + if is_macro { "macro_rules".len() } else { 2 }); + if is_macro { + start = skip_ws(m, start + usize::from(m.get(start) == Some(&b'!'))); + } + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + if end == start { + return None; + } + let open = end + m[end..].iter().position(|&c| c == b'{' || c == b';')?; + if m[open] != b'{' { + return None; + } + let close = matching(m, open)?; + let name = String::from_utf8_lossy(&m[start..end]).into_owned(); + let called = calls(m, open, close).into_iter().filter(|(_, method)| !method).map(|(n, _)| n).collect(); + Some((if is_macro { format!("{name}!") } else { name }, checks_itself(m, open, close), called)) +} + +// ---- The rules ---- + +/// The source, its masked copy and its tests. +struct File<'a> { + path: &'a str, + src: &'a [u8], + m: Vec, + lines: Lines, + tests: Vec, + /// The test code ([`test_regions`]). + regions: Vec<(usize, usize)>, +} + +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 } + } + + fn test_at(&self, pos: usize) -> &str { + self.tests.iter().find(|t| t.open <= pos && pos <= t.close).map_or("", |t| t.name.as_str()) + } + + /// The source of `from..to` without whitespace and comments between tokens; string and + /// character literals keep their text. + fn src_norm(&self, (from, to): (usize, usize)) -> String { + let mut out = Vec::with_capacity(to - from); + let mut in_literal = false; + for i in from..to { + let (s, m) = (self.src[i], self.m[i]); + if m == b'"' || (m == b'\'' && !in_literal && self.m.get(i + 1) == Some(&b' ')) { + in_literal = !in_literal; + } else if m == b'\'' && in_literal { + in_literal = false; + } + if in_literal || (m == s && !s.is_ascii_whitespace()) { + out.push(s); + } + } + String::from_utf8_lossy(&out).into_owned() + } +} + +/// Every hit in one file, exemptions applied. +pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { + let m = mask(src); + let tests = tests_in(&m); + let regions = test_regions(path, &m, &tests); + let file = File { path, src: src.as_bytes(), m, lines: Lines::new(src), tests, regions }; + let mut hits: Vec = file.tests.iter().flat_map(|t| test_hits(&file, t, ctx)).collect(); + hits.extend(ignore_hits(&file)); + hits.extend(sleep_hits(&file)); + hits.extend(reads_source_hits(&file)); + let allows = allows(src, &file.m); + hits.retain(|h| { + let first = if h.rule == Rule::AllUnguarded { h.line } else { h.first }; + !allows.iter().any(|&(line, rule)| rule == h.rule && line + 1 >= first && line <= h.line) + }); + hits.sort(); + hits +} + +/// `(line, rule)` of each exemption comment that names a rule and a reason. +/// A marker counts only inside a comment: masked (`m`) there, and kept when only literals are +/// masked. +fn allows(src: &str, m: &[u8]) -> Vec<(usize, Rule)> { + let literals = mask_with(src, false); + let lines = Lines::new(src); + src.match_indices(ALLOW) + .filter(|&(p, _)| m[p] == b' ' && literals[p] == b't') + .filter_map(|(p, _)| { + let rest = src[p + ALLOW.len()..].lines().next()?; + let mut words = rest.split_whitespace(); + let rule = Rule::from_id(words.next()?)?; + words.next().map(|_| (lines.of(p), rule)) + }) + .collect() +} + +/// What the rules read of one test. +struct View<'a> { + file: &'a File<'a>, + t: &'a TestFn, + asserts: Vec, + delegates: bool, + checks: bool, + should_panic: bool, +} + +fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { + let m = &file.m; + let asserts: Vec = macro_calls(m, t.open, t.close).into_iter().filter(|c| is_assert_macro(&c.name)).collect(); + let none = HashSet::new(); + let helpers = ctx.helpers.get(&crate_of(file.path)).unwrap_or(&none); + let delegates = calls(m, t.open, t.close) + .iter() + .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)); + let checks = checks_itself(m, t.open, t.close); + let should_panic = contains(&m[t.attr..t.fn_at], b"should_panic"); + let v = View { file, t, asserts, delegates, checks, should_panic }; + let mut hits = all_unguarded(&v); + hits.extend(self_compare(&v)); + hits.extend(early_returns(&v)); + hits.extend(env_gates(&v, ctx)); + hits.extend([only_weak(&v), exit_status_only(&v), no_assertion(&v)].into_iter().flatten()); + hits +} + +impl View<'_> { + fn hit(&self, at: usize, rule: Rule, note: String) -> Hit { + self.file.hit(at, rule, &self.t.name, note) + } + + /// A hit for the whole test, on its `fn` line. + fn whole(&self, rule: Rule, note: String) -> Hit { + let mut h = self.hit(self.t.fn_at, rule, note); + h.first = self.file.lines.of(self.t.attr); + h.last = self.file.lines.of(self.t.close); + h + } + + fn body(&self) -> &[u8] { + &self.file.m[self.t.open..self.t.close] + } + + /// The masked body with assertion failure-message arguments replaced by spaces. + fn body_without_messages(&self) -> Vec { + let mut body = self.body().to_vec(); + for a in &self.asserts { + for &(from, to) in a.args.iter().skip(guard_arg_count(&a.name)) { + blank(&mut body, from - self.t.open, to - self.t.open); + } + } + body + } + + /// The first argument of an assertion, masked, without whitespace. + fn first_arg(&self, a: &MacroCall) -> String { + a.args.first().map(|&(f, t)| norm(&self.file.m[f..t])).unwrap_or_default() + } +} + +const PLAIN_ASSERTS: &[&str] = &["assert", "debug_assert", "prop_assert"]; + +fn all_unguarded(v: &View) -> Vec { + let mut body = v.body_without_messages(); + strip_all_predicates(&mut body); + let checked = v.asserts.iter().any(|a| { + a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { + let arg = norm(&body[from - v.t.open..to - v.t.open]); + [".len()", ".is_empty()", ".count()", ".first()", ".any(", ".next()", ".last()"].iter().any(|g| arg.contains(g)) + }) + }); + if checked || first_item_guard(&body) { + return vec![]; + } + v.asserts + .iter() + .filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && unguarded_all(&v.first_arg(a), &v.file.m[v.t.open..a.at])) + .map(|a| { + let mut h = v.hit(a.at, Rule::AllUnguarded, format!("{}!(…all(…)) with no length or emptiness check in the test", a.name)); + h.first = v.file.lines.of(v.t.attr); + h.last = v.file.lines.of(v.t.close); + h + }) + .collect() +} + +/// The number of condition or compared operands in a standard assertion macro. +fn guard_arg_count(name: &str) -> usize { + match name { + "assert" | "debug_assert" | "prop_assert" => 1, + "assert_eq" | "assert_ne" | "debug_assert_eq" | "debug_assert_ne" | "prop_assert_eq" | "prop_assert_ne" => 2, + _ => 0, + } +} + +/// Blanks `.all(…)` predicates so their checks do not guard the collection. +fn strip_all_predicates(body: &mut [u8]) { + for at in words(body, b"all", 0, body.len()) { + let method = body[..at].trim_ascii_end().ends_with(b"."); + let open = skip_ws(body, at + 3); + let Some(close) = (method && body.get(open) == Some(&b'(')).then(|| matching(body, open)).flatten() else { continue }; + blank(body, at, close + 1); + } +} + +/// Whether test code accesses a first item in a way that fails on an empty collection. +fn first_item_guard(body: &[u8]) -> bool { + let compact = norm(body); + let unwrapped = [".first().unwrap()", ".first().expect(", ".next().unwrap()", ".next().expect("]; + let indexed = compact.match_indices("[0]").any(|(at, _)| !on_array_literal(&compact[..at + 3])); + indexed || unwrapped.iter().any(|g| compact.contains(g)) || panicking_first_binding(body) +} + +/// Whether a `let Some(…) = ….first() else { panic!(…) }` binding checks for an item. +fn panicking_first_binding(body: &[u8]) -> bool { + words(body, b"let", 0, body.len()).into_iter().any(|at| { + let rest = &body[at + 3..]; + let Some(otherwise) = words(rest, b"else", 0, rest.len()).first().copied() else { return false }; + let binding = norm(&rest[..otherwise]); + let Some(close) = binding.strip_prefix("Some(").and_then(|_| matching(binding.as_bytes(), 4)) else { return false }; + let Some(value) = binding[close + 1..].strip_prefix('=') else { return false }; + let first = value.ends_with(".first()") || value.ends_with(".next()"); + first && !value.contains([';', '{', '}']) && norm(&rest[otherwise + 4..]).starts_with("{panic!(") + }) +} + +/// Whether a (masked, whitespace-free) condition holds an `.all(…)` that an empty collection would +/// pass by mistake. Left out: a negated result, a closure that says no item matches (whole +/// negations or `!=` comparisons joined only by `&&`), and a non-empty array literal or a local +/// name bound to or previously compared equal to one. +fn unguarded_all(cond: &str, body: &[u8]) -> bool { + all_with_polarity(cond, true, body) +} + +/// Tracks negation through boolean operands and comparisons with `false`. +fn all_with_polarity(cond: &str, positive: bool, body: &[u8]) -> bool { + if cond.starts_with('(') && matching(cond.as_bytes(), 0) == Some(cond.len() - 1) { + return all_with_polarity(&cond[1..cond.len() - 1], positive, body); + } + if let Some(at) = boolean_split(cond) { + return all_with_polarity(&cond[..at], positive, body) || all_with_polarity(&cond[at + 2..], positive, body); + } + if let Some(expr) = cond.strip_suffix("==false").or_else(|| cond.strip_prefix("false==")) { + return all_with_polarity(expr, !positive, body); + } + if let Some(expr) = cond.strip_prefix('!') { + return all_with_polarity(expr, !positive, body); + } + positive && positive_all(cond, body) +} + +/// Finds a boolean operator outside parentheses, brackets and braces. +fn boolean_split(cond: &str) -> Option { + let b = cond.as_bytes(); + let mut at = 0; + while at < b.len() { + if b[at..].starts_with(b"&&") || b[at..].starts_with(b"||") { + return Some(at); + } + at = if matches!(b[at], b'(' | b'[' | b'{') { matching(b, at)? + 1 } else { at + 1 }; + } + None +} + +fn positive_all(cond: &str, test_body: &[u8]) -> bool { + cond.match_indices(".all(").any(|(i, _)| { + let rest = &cond[i + ".all(".len()..]; + let arg = &rest[..arg_end(rest)]; + let body = arg.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(arg, |(_, body)| body); + let none_match = not_equal_conjunction(body); + !none_match && !on_array_literal(&cond[..i]) && !on_bound_array(&cond[..i], test_body) && !on_equal_array(&cond[..i], test_body) + }) +} + +/// Whether every boolean operand is a whole negation or `!=` comparison joined only by `&&`. +fn not_equal_conjunction(body: &str) -> bool { + if body.starts_with('(') && matching(body.as_bytes(), 0) == Some(body.len() - 1) { + return not_equal_conjunction(&body[1..body.len() - 1]); + } + if let Some(at) = boolean_split(body) { + return body[at..].starts_with("&&") && not_equal_conjunction(&body[..at]) && not_equal_conjunction(&body[at + 2..]); + } + if whole_negation(body) { + return true; + } + let (mut at, mut comparisons) = (0, 0); + let b = body.as_bytes(); + while at < b.len() { + if b[at..].starts_with(b"!=") { + comparisons += 1; + at += 2; + } else if matches!(b[at], b'=' | b'<' | b'>' | b'&' | b'|') { + return false; + } else if matches!(b[at], b'(' | b'[' | b'{') { + let Some(close) = matching(b, at) else { return false }; + at = close + 1; + } else { + at += 1; + } + } + comparisons == 1 +} + +/// Whether `!` negates the whole operand rather than one side of a binary expression. +fn whole_negation(body: &str) -> bool { + let Some(rest) = body.strip_prefix('!') else { return false }; + let rest = rest.trim_start_matches(['!', '*', '&']); + let b = rest.as_bytes(); + let mut at = 0; + while at < b.len() { + if matches!(b[at], b'=' | b'<' | b'>' | b'&' | b'|' | b'+' | b'-' | b'*' | b'/' | b'%' | b'^') { + return false; + } + at = if matches!(b[at], b'(' | b'[' | b'{') { + let Some(close) = matching(b, at) else { return false }; + close + 1 + } else { + at + 1 + }; + } + !rest.is_empty() +} + +/// Whether an earlier equality assertion compares this plain local receiver with a non-empty literal. +fn on_equal_array(receiver: &str, body: &[u8]) -> bool { + let name = array_receiver(receiver); + if name.is_empty() || name.as_bytes()[0].is_ascii_digit() || !name.bytes().all(is_ident) { + return false; + } + macro_calls(body, 0, body.len()).iter().any(|a| { + if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) { + return false; + } + let Some(&(lf, lt)) = a.args.first() else { return false }; + let Some(&(rf, rt)) = a.args.get(1) else { return false }; + let (left, right) = (norm(&body[lf..lt]), norm(&body[rf..rt])); + (collection_operand(&left) == name && non_empty_literal(&right)) || (collection_operand(&right) == name && non_empty_literal(&left)) + }) +} + +/// Removes one borrow and a slice view from a compared operand. +fn collection_operand(operand: &str) -> &str { + let operand = operand.strip_prefix('&').unwrap_or(operand); + operand.strip_suffix(".as_slice()").or_else(|| operand.strip_suffix("[..]")).unwrap_or(operand) +} + +/// Whether the whole operand is a non-empty array literal or `vec![…]`. +fn non_empty_literal(operand: &str) -> bool { + let b = operand.strip_prefix("vec!").unwrap_or(operand).as_bytes(); + b.first() == Some(&b'[') && matching(b, 0) == Some(b.len() - 1) && non_empty_array(&b[1..b.len() - 1]) +} + +/// The length of a call's arguments in `rest`, the text after its `(`: up to its closing bracket. +fn arg_end(rest: &str) -> usize { + let mut depth = 0i32; + rest.bytes() + .position(|c| { + depth += match c { + b'(' | b'[' | b'{' => 1, + b')' | b']' | b'}' => -1, + _ => 0, + }; + depth < 0 + }) + .unwrap_or(rest.len()) +} + +/// Whether `receiver` (the text before `.all(`) ends with a non-empty array literal, through `.iter()` or +/// `.into_iter()`. +fn on_array_literal(receiver: &str) -> bool { + let r = array_receiver(receiver); + let b = r.as_bytes(); + if b.last() != Some(&b']') { + return false; + } + let mut depth = 0usize; + for (j, &c) in b.iter().enumerate().rev() { + match c { + b']' => depth += 1, + b'[' => { + depth = depth.saturating_sub(1); + if depth == 0 { + let literal = !j.checked_sub(1).and_then(|k| b.get(k)).is_some_and(|&p| is_ident(p) || matches!(p, b')' | b']' | b'.')); + return literal && non_empty_array(&b[j + 1..b.len() - 1]); + } + } + _ => {} + } + } + false +} + +/// Removes the iterator method from an array receiver. +fn array_receiver(receiver: &str) -> &str { + receiver.strip_suffix(".iter()").or_else(|| receiver.strip_suffix(".into_iter()")).unwrap_or(receiver) +} + +/// Whether a plain local receiver's latest preceding binding initializes a non-empty array. +fn on_bound_array(receiver: &str, body: &[u8]) -> bool { + let name = array_receiver(receiver).as_bytes(); + if name.is_empty() || name[0].is_ascii_digit() || !name.iter().copied().all(is_ident) { + return false; + } + words(body, b"let", 0, body.len()).into_iter().rev().find_map(|at| array_binding(&body[at + 3..], name)).unwrap_or(false) +} + +/// Checks a named binding, allowing `mut` and an array type annotation. +fn array_binding(mut rest: &[u8], name: &[u8]) -> Option { + rest = rest.trim_ascii_start(); + if rest.starts_with(b"mut") && rest.get(3).is_some_and(u8::is_ascii_whitespace) { + rest = rest[3..].trim_ascii_start(); + } + let end = rest.iter().copied().take_while(|&c| is_ident(c)).count(); + if &rest[..end] != name { + return None; + } + rest = rest[end..].trim_ascii_start(); + if let Some(annotation) = rest.strip_prefix(b":") { + let annotation = annotation.trim_ascii_start(); + let close = (annotation.first() == Some(&b'[')).then(|| matching(annotation, 0)).flatten(); + let Some(close) = close else { return Some(false) }; + rest = annotation[close + 1..].trim_ascii_start(); + } + Some(rest.strip_prefix(b"=").is_some_and(array_initializer)) +} + +/// Whether an initializer is a non-empty array literal, optionally followed by one `.map(…)`. +fn array_initializer(rest: &[u8]) -> bool { + let rest = rest.trim_ascii_start(); + let Some(close) = (rest.first() == Some(&b'[')).then(|| matching(rest, 0)).flatten() else { return false }; + if !non_empty_array(&rest[1..close]) { + return false; + } + let tail = rest[close + 1..].trim_ascii_start(); + if tail.starts_with(b";") { + return true; + } + let compact = norm(tail); + if !compact.starts_with(".map(") { + return false; + } + let Some(close) = matching(compact.as_bytes(), 4) else { return false }; + compact[close + 1..].starts_with(';') +} + +/// Whether an array's masked contents have an element and, for repetition, a positive literal count. +fn non_empty_array(contents: &[u8]) -> bool { + let mut at = 0; + while at < contents.len() { + match contents[at] { + b';' => return norm(&contents[at + 1..]).parse::().is_ok_and(|count| count > 0), + b'(' | b'[' | b'{' => { + let Some(close) = matching(contents, at) else { return false }; + at = close + 1; + } + _ => at += 1, + } + } + !contents.trim_ascii().is_empty() +} + +/// Whether an assertion's (masked, whitespace-free) condition only says that there is a value. +fn is_weak(cond: &str) -> bool { + let (negated, expr) = match cond.strip_prefix('!') { + Some(rest) => (true, rest), + None => (false, cond), + }; + let plain = |rest: &str| !["&&", "||", "==", "!=", "<", ">"].iter().any(|op| rest.contains(op)); + let suffix = |s: &str| expr.strip_suffix(s).is_some_and(plain); + if negated { + return suffix(".is_empty()"); + } + suffix(".is_ok()") || suffix(".is_some()") || suffix(".len()>0") || suffix(".len()!=0") || suffix(".len()>=1") +} + +fn only_weak(v: &View) -> Option { + 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("); + 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()))) +} + +fn self_compare(v: &View) -> Vec { + v.asserts + .iter() + .filter(|a| a.name.ends_with("_eq") || a.name.ends_with("_ne")) + .filter_map(|a| { + let right = *a.args.get(1)?; + 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 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)); + h + }) + }) + .collect() +} + +fn exit_status_only(v: &View) -> Option { + let mut body = norm(&v.body_without_messages()).into_bytes(); + let runs = contains(&body, b"Command::new") || contains(&body, b".output()") || contains(&body, b".status()"); + strip_stream_configuration(&mut body); + let reads = + ["stdout", "stderr", "fs::read", "read_to_string", "from_slice", "from_str", "contains("].iter().any(|w| contains(&body, w.as_bytes())); + let status_only = |a: &MacroCall| { + a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { + let c = norm(&v.file.m[from..to]); + c.contains(".success()") || c.contains(".code()") + }) + }; + if !runs || reads || v.asserts.is_empty() || !v.asserts.iter().all(status_only) || v.delegates { + return None; + } + Some(v.whole(Rule::ExitStatusOnly, "runs a process and checks only its exit status".into())) +} + +/// Blanks stream method names that configure a process with `Stdio` in whitespace-free text. +fn strip_stream_configuration(body: &mut [u8]) { + for stream in ["stdout", "stderr", "stdin"] { + for at in words(body, stream.as_bytes(), 0, body.len()) { + let rest = &body[at + stream.len()..]; + let config = rest.starts_with(b"(Stdio::") || rest.starts_with(b"(std::process::Stdio::"); + if body[..at].ends_with(b".") && config { + blank(body, at, at + stream.len()); + } + } + } +} + +fn no_assertion(v: &View) -> Option { + if v.checks || v.delegates || v.should_panic { + return None; + } + Some(v.whole(Rule::NoAssertion, "no assertion and no asserting helper".into())) +} + +/// Guards that mark a skip for a missing resource or another platform, or a test that runs itself +/// in a child process, matched case-sensitively on the guard without whitespace. +const SKIP_GUARDS: &[&str] = &[ + "in_own_process", + "OWN_PROCESS", + "_TEST_CHILD", + "current_exe()", + "skip_without_craft_fonts", + "CRAFT_FONTS", + "japanese_fonts", + "craft_fonts", + "env::var", + "cfg!(", + "target_os", + "geteuid", + "Command::new", + "File::open", + "fs::read", + "read_dir(", + ".exists()", + "which(", +]; + +/// The same, matched without regard to case. +const SKIP_GUARDS_ANY_CASE: &[&str] = &[ + "installed_family", + "kufi", + "library/fonts", + "default_font(", + "arabic_face", + "arabic_test_face", + "devanagari_test_face", + "joiner_test_faces", + "mark_text(", + "arabic_style", + "has_family", + "variable_font", + "fontdb", + ".face(", + "covers(", + "thai", + "cjk", + "corpus", + "suite_dir", + "json2_file", + "read_fixture", + "samples(", + "pinned(", + "platform()", + "is_mac", + "/system/library", +]; + +fn early_returns(v: &View) -> Vec { + let (m, t) = (&v.file.m, v.t); + words(m, b"return", t.open, t.close) + .into_iter() + .filter_map(|at| { + let end = bare_return_end(m, at + "return".len())?; + let rest_empty = m[end..t.close].iter().all(|c| c.is_ascii_whitespace() || matches!(c, b';' | b'}')); + if rest_empty || nested(m, t.open, at) || skip_guard(v.file, t.open, at, end) { + return None; + } + Some(v.hit(at, Rule::EarlyReturn, "returns early on a value from the code under test".into())) + }) + .collect() +} + +/// The end of a bare `return` (`return;`, `return }`, `return Ok(());`) whose keyword ends at `i`. +fn bare_return_end(m: &[u8], i: usize) -> Option { + let mut j = skip_ws(m, i); + if m[j..].starts_with(b"Ok") { + j += 2; + for c in *b"(())" { + j = skip_ws(m, j); + if m.get(j) != Some(&c) { + return None; + } + j += 1; + } + j = skip_ws(m, j); + } + match m.get(j)? { + b';' => Some(j + 1), + b'}' | b',' => Some(j), + _ => None, + } +} + +/// Whether `pos` is inside a closure or a nested function in the body opened at `open`. +fn nested(m: &[u8], open: usize, pos: usize) -> bool { + let mut stack: Vec = vec![]; + for i in open..pos { + match m[i] { + b'{' => stack.push(i > open && opens_closure_or_fn(m, open, i)), + b'}' => { + stack.pop(); + } + _ => {} + } + } + stack.contains(&true) +} + +fn opens_closure_or_fn(m: &[u8], open: usize, brace: usize) -> bool { + let from = brace.saturating_sub(160).max(open + 1); + let head = &m[from..brace]; + let start = head.iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let head = String::from_utf8_lossy(&head[start..]).into_owned(); + let head = head.trim_end(); + let closure = head.ends_with('|') || head.rfind("->").is_some_and(|p| head[..p].trim_end().ends_with('|')); + closure || !words(head.as_bytes(), b"fn", 0, head.len()).is_empty() +} + +/// Whether the return at `at..end` is not a silent skip on a value: the block it ends asserts +/// first; a comment or a printed note from the start of its statement to the end of its line says +/// why it returns; or its guard skips for a resource, a platform or a child process. +fn skip_guard(file: &File, open: usize, at: usize, end: usize) -> bool { + let m = &file.m; + let block = m[open..at].iter().rposition(|&c| c == b'{').map_or(open, |p| p + open); + let stmt = m[open..block].iter().rposition(|&c| c == b';' || c == b'}').map_or(open, |p| p + open); + let line_end = find(m, b"\n", end).unwrap_or(m.len()); + let asserted = macro_calls(m, block, at).iter().any(|c| is_assert_macro(&c.name)); + let printed = macro_calls(m, stmt, at).iter().any(|c| c.name.ends_with("print") || c.name.ends_with("println")); + let commented = (stmt..line_end).any(|i| file.src[i..].starts_with(b"//") && m[i] == b' '); + if asserted || printed || commented { + return true; + } + let guard = norm(&file.src[stmt..end]); + let lower = guard.to_ascii_lowercase(); + let wide = &file.src[stmt.saturating_sub(250).max(open)..end]; + SKIP_GUARDS.iter().any(|g| guard.contains(g)) + || SKIP_GUARDS_ANY_CASE.iter().any(|g| lower.contains(g)) + || (lower.contains("fs::write(") && lower.contains(".is_err()")) + || ["in_own_process", "OWN_PROCESS", "_TEST_CHILD", "current_exe()"].iter().any(|g| contains(wide, g.as_bytes())) + || !words(wide, b"CHILD", 0, wide.len()).is_empty() +} + +fn env_gates(v: &View, ctx: &Ctx) -> Vec { + let (m, src, t) = (&v.file.m, v.file.src, v.t); + let mut out = vec![]; + for at in words(m, b"var", t.open, t.close).into_iter().chain(words(m, b"var_os", t.open, t.close)) { + if !m[..at].ends_with(b"env::") { + continue; + } + let Some(name) = env_name(m, src, at) else { continue }; + if ctx.ci_env.contains(&name) || set_by_system(&name) { + continue; + } + // The whole file is masked and searched only for a name that CI and the system leave unset. + let file = norm(&mask_comments(&String::from_utf8_lossy(src))); + let set_here = file.contains(&format!(".env(\"{name}\"")) + || file.contains(&format!("=\"{name}\";")) + || file.match_indices(&format!("set_var(\"{name}\"")).any(|(at, _)| at == 0 || !is_ident(file.as_bytes()[at - 1])); + if !set_here { + out.push(v.hit(at, Rule::EnvGateUnset, format!("reads {name}, which no CI leg sets"))); + } + } + out +} + +/// The literal name in `env::var("NAME")` whose `var` is at `at`. +fn env_name(m: &[u8], src: &[u8], at: usize) -> Option { + let open = skip_ws(m, at + m[at..].iter().take_while(|&&c| is_ident(c)).count()); + if m.get(open) != Some(&b'(') { + return None; + } + let quote = skip_ws(m, open + 1); + if m.get(quote) != Some(&b'"') { + return None; + } + let end = string_end(src, quote + 1).saturating_sub(1); + let name = std::str::from_utf8(&src[quote + 1..end]).ok()?; + (!name.is_empty() && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')).then(|| name.to_owned()) +} + +fn ignore_hits(file: &File) -> Vec { + let m = &file.m; + let mut out = vec![]; + for at in words(m, b"ignore", 0, m.len()) { + if !m[..at].ends_with(b"#[") { + continue; + } + let j = skip_ws(m, at + "ignore".len()); + let reason = match m.get(j) { + Some(b'=') => { + let q = skip_ws(m, j + 1); + ignore_reason(&file.src[q..]).is_some_and(|body| body.iter().any(|c| !c.is_ascii_whitespace())) + } + _ => false, + }; + 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())); + } + } + out +} + +/// The body of an ordinary or raw string literal used as an ignore reason. +fn ignore_reason(src: &[u8]) -> Option<&[u8]> { + if src.first() == Some(&b'"') { + return src.get(1..string_end(src, 1).saturating_sub(1)); + } + let raw = src.strip_prefix(b"r")?; + let hashes = raw.iter().take_while(|&&c| c == b'#').count(); + if raw.get(hashes) != Some(&b'"') { + return None; + } + let body = hashes + 2; + let close: Vec = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); + let end = find(src, &close, body)?; + src.get(body..end) +} + +fn sleep_hits(file: &File) -> Vec { + let m = &file.m; + words(m, b"sleep", 0, m.len()) + .into_iter() + .filter(|&at| { + if !in_regions(&file.regions, at) { + return false; + } + let before = m[..at].iter().rposition(|c| !c.is_ascii_whitespace()); + let method = before.is_some_and(|b| m[b] == b'.'); + let definition = m[..at].trim_ascii_end().ends_with(b"fn"); + !method && !definition && m.get(skip_ws(m, at + "sleep".len())) == Some(&b'(') + }) + .map(|at| file.hit(at, Rule::Sleep, file.test_at(at), "sleeps in test code".into())) + .collect() +} + +fn reads_source_hits(file: &File) -> Vec { + if SOURCE_AUDITS.contains(&file.path) { + return vec![]; + } + let m = &file.m; + let mut out = vec![]; + for (word, note) in [(&b"include_str"[..], "includes a .rs file as text"), (&b"ends_with"[..], "keeps files ending in .rs")] { + 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]); + let rs = if word == b"ends_with" { arg == "\".rs\"" } else { arg.ends_with(".rs\"") }; + if rs { + out.push(file.hit(at, Rule::ReadsSource, file.test_at(at), note.into())); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ctx() -> Ctx { + Ctx { helpers: HashMap::new(), ci_env: ["SET_IN_CI".to_owned()].into_iter().collect() } + } + + /// The rule ids of `src`'s hits, as `(line, rule)`. + fn hits(src: &str) -> Vec<(usize, &'static str)> { + hits_in("crates/x/src/tests.rs", src, &ctx()) + } + + fn hits_in(path: &str, src: &str, ctx: &Ctx) -> Vec<(usize, &'static str)> { + lint_file(path, src, ctx).into_iter().map(|h| (h.line, h.rule.id())).collect() + } + + #[test] + fn all_needs_a_non_empty_guard() { + let bad = "#[test]\nfn t() {\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(bad), [(4, "all-unguarded")]); + let good = "#[test]\nfn t() {\n let xs = f();\n assert_eq!(xs.len(), 3);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(good), []); + let inner = "#[test]\nfn t() {\n assert!(rows().iter().all(|r| r.len() == 3));\n}\n"; + assert_eq!(hits(inner), [(3, "all-unguarded")], "a length inside the predicate is about each item"); + let none = "#[test]\nfn t() {\n assert!(warnings().iter().all(|w| !w.contains(\"lost\")), \"no warning\");\n}\n"; + assert_eq!(hits(none), [], "all(|w| !…) says that no item matches"); + let other = "#[test]\nfn t() {\n assert!(listed().iter().all(|e| e[\"id\"] != id));\n assert!([0, 4, 20].iter().all(|&i| glow[i].a() == 0));\n}\n"; + assert_eq!(hits(other), [], "one != comparison, and an array literal"); + let indexed = "#[test]\nfn t() {\n assert!(rows()[2].iter().all(|r| r.ok && r.n != 0));\n assert!(f().iter().all(|x| x.0 != 1 && x.1 != 2));\n}\n"; + assert_eq!(hits(indexed), [(3, "all-unguarded")]); + let mixed = "#[test]\nfn t() {\n assert!(f().iter().all(|x| x.0 != 1 && x.1 > 2));\n}\n"; + assert_eq!(hits(mixed), [(3, "all-unguarded")]); + } + + #[test] + fn all_equality_guards_match_each_receiver() { + for assertion in ["assert_eq", "debug_assert_eq", "prop_assert_eq"] { + for operand in ["xs", "&xs", "xs.as_slice()", "&xs.as_slice()", "xs[..]", "&xs[..]"] { + for literal in ["[1]", "[1, 2,]", "[1; 2]", "vec![1, 2]", "vec![1; 2]", "[\"[;]\", name]"] { + for (left, right) in [(operand, literal), (literal, operand)] { + let src = format!( + "#[test]\nfn t() {{\n {assertion}!({left}, {right}, \"items\");\n assert!(xs.iter().all(|x| valid(x)));\n assert!(ys.iter().all(|x| valid(x)));\n}}\n" + ); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{assertion}!({left}, {right})"); + let combined = src.replace("valid(x)));\n assert!(ys", "valid(x)) && ys"); + assert_eq!(hits(&combined), [(4, "all-unguarded")], "another receiver in the same condition"); + } + } + } + } + } + + #[test] + fn all_equality_guards_require_non_empty_literals() { + for expected in ["[]", "[1; 0]", "vec![]", "vec![1; 0]", "expected", "items()", "[1].map(f)", "vec![1].clone()"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!(xs, {expected});\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{expected}"); + } + for operand in ["ys", "xs_other", "other.xs", "other::xs", "xs()", "xs.clone()", "xs[1..]", "&&xs"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({operand}, [1]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{operand}"); + } + } + + #[test] + fn all_equality_guards_require_earlier_compared_operands_in_the_test() { + for assertion in ["assert_ne", "debug_assert_ne", "prop_assert_ne"] { + let src = format!("#[test]\nfn t() {{\n {assertion}!(xs, [1]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{assertion}"); + } + let later = "#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n assert_eq!(xs, [1]);\n}\n"; + assert_eq!(hits(later), [(3, "all-unguarded")]); + let outside = "fn helper() { assert_eq!(xs, [1]); }\n#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(outside), [(4, "all-unguarded")]); + let message = "#[test]\nfn t() {\n assert_eq!(a, b, \"items {:?} {:?}\", xs, [1]);\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(message), [(4, "all-unguarded")]); + } + + #[test] + fn all_skips_conjunctions_of_not_equal_comparisons() { + for predicate in [ + "|(id, _)| id != \"action.batch\" && id != \"flattener.preview\"", + "|x| x.0 != 1 && x.1 != 2", + "|x| x != 1 && x != 2 && x != 3", + "|x| (x != 1) && ((x != 2) && x != 3)", + "|x| value(x) != expected(1, 2) && *x != 3", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(names.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [], "{predicate}"); + let mixed = src.replace("));\n", ") && ys.iter().all(|y| valid(y)));\n"); + assert_eq!(hits(&mixed), [(3, "all-unguarded")], "another positive predicate beside {predicate}"); + } + } + + #[test] + fn all_reports_conjunctions_with_other_predicates() { + for predicate in [ + "|x| x != 1 && x == 2", + "|x| x != 1 && x < 2", + "|x| x.0 != 1 && x.1 > 2", + "|x| x != 1 && valid(x)", + "|x| valid(x) && x != 1", + "|x| x != 1 || x != 2", + "|x| x != 1 && x != 2 || x != 3", + "|x| x != 1 && (x != 2 || x != 3)", + "|x| (x != 1 && x > 2) && x != 3", + "|x| valid(x != 1) && x != 2", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(names.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [(3, "all-unguarded")], "{predicate}"); + } + } + + #[test] + fn all_skips_only_whole_negations_and_not_equal_conjunctions() { + for predicate in [ + "|x| !x.contains(\"lost\")", + "|x| !blocked!(x)", + "|x| !(blocked(x) && invalid(x))", + "|x| !a(x) && !b(x)", + "|x| !a(x) && x != 1", + "|x| x != 1 && (!a(x) && !(b(x)))", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(xs.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [], "{predicate}"); + } + for predicate in [ + "|x| !blocked(x) && valid(x)", + "|x| valid(x) && !blocked(x)", + "|x| !a(x) || b(x)", + "|x| !a(x) == b(x)", + "|x| (!a(x) == b(x)) && x != 1", + "|x| !a(x) && (!b(x) || c(x))", + "|x| !a(x) ^ b(x)", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(xs.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [(3, "all-unguarded")], "{predicate}"); + } + } + + #[test] + fn all_skips_locally_bound_non_empty_arrays() { + for binding in [ + "let xs = [1, 2];", + "let mut xs = [1, 2];", + "let xs: [u8; 2] = [1, 2];", + "let mut xs: [u8; 2] = [1, 2];", + "let xs = [1; 2];", + "let xs = [[1, 2], [3, 4]];", + "let xs = [\"[\", \";\", \"bad ] brackets [\"].map(|s| s.trim());", + "let xs = [1, 2].map(|x| { let pair = [x, x]; pair });", + "let xs /* items */ : [u8; 2] = [1, 2] . map (|x| x + 1);", + ] { + for method in ["iter", "into_iter"] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.{method}().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding} through {method}"); + let mixed = src.replace("valid(x)))", "valid(x)) && ys.iter().all(|y| valid(y)))"); + assert_eq!(hits(&mixed), [(4, "all-unguarded")], "another collection beside {binding}"); + } + } + } + + #[test] + fn all_reports_empty_arrays_and_other_initializers() { + for value in [ + "[]", + "[1; 0]", + "[1; 0].map(|x| x + 1)", + "vec![1, 2]", + "items()", + "items().collect()", + "[1, 2].into_iter().collect()", + "[1, 2].map(|x| x + 1).into_iter().collect()", + "[1, 2].map(|x| x + 1).map(|x| x + 1)", + ] { + for binding in [format!("let xs = {value};"), format!("let mut xs = {value};"), format!("let xs: [u8; 0] = {value};")] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{binding}"); + } + } + } + + #[test] + fn all_array_bindings_match_only_plain_preceding_local_names() { + for (binding, receiver) in [ + ("let xs_other = [1, 2];", "xs"), + ("let other_xs = [1, 2];", "xs"), + ("let (xs, ys) = ([1, 2], items());", "xs"), + ("let xs = [1, 2]; let xs = items();", "xs"), + ("let xs = [1, 2];", "other.xs"), + ("let xs = [1, 2];", "other::xs"), + ("let xs = [1, 2];", "xs()"), + ] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!({receiver}.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{binding} with {receiver}"); + } + let later = "#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n let xs = [1, 2];\n}\n"; + assert_eq!(hits(later), [(3, "all-unguarded")], "a later binding does not initialize the receiver"); + let outside = "fn helper() { let xs = [1, 2]; }\n#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(outside), [(4, "all-unguarded")], "a binding outside the test does not count"); + } + + #[test] + fn all_direct_array_literals_must_be_non_empty() { + for method in ["iter", "into_iter"] { + for array in ["[]", "[1; 0]", "[items(); 0]", "[1; 0usize]"] { + let src = format!("#[test]\nfn t() {{\n assert!({array}.{method}().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(3, "all-unguarded")], "{array} through {method}"); + } + for array in ["[1]", "[1, 2]", "[1; 2]", "[[1; 0]]", "[\"[;]\"]"] { + let src = format!("#[test]\nfn t() {{\n assert!({array}.{method}().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{array} through {method}"); + } + } + } + + #[test] + fn all_skips_mapped_arrays_of_named_rectangles() { + for (name, labels, message) in [ + ("chips", "[\"Color (, or Shift+,)\", \"Gradient (. or Shift+.)\", \"None (/)\"]", "one line"), + ("modes", "[\"Draw Normal (Shift+D)\", \"Draw Behind (Shift+D)\", \"Draw Inside (Shift+D)\"]", "side by side"), + ] { + let src = format!( + "#[test]\nfn t() {{\n let {name} = {labels}.map(|label| named_rect(&nodes, label));\n assert!({name}.iter().all(|r| (r.top() - {name}[0].top()).abs() < 0.5), \"{message}: {{{name}:?}}\");\n}}\n" + ); + assert_eq!(hits(&src), [], "{name}"); + let empty = src.replace(labels, "[]"); + assert_eq!(hits(&empty), [(4, "all-unguarded")], "an empty {name} still passes vacuously"); + } + } + + #[test] + fn all_respects_condition_polarity() { + for condition in [ + "!xs.iter().all(|x| *x > 0)", + "!(xs.iter().all(|x| *x > 0))", + "ready() && !xs.iter().all(|x| *x > 0)", + "!xs.iter().all(|x| *x > 0) && ready()", + "xs.iter().all(|x| *x > 0) == false", + "ready() && (xs.iter().all(|x| *x > 0) == false)", + "false == xs.iter().all(|x| *x > 0)", + ] { + let good = format!("#[test]\nfn t() {{\n assert!({condition});\n}}\n"); + assert_eq!(hits(&good), [], "{condition}"); + let bad = format!("#[test]\nfn t() {{\n assert!(({condition}) && ys.iter().all(|y| *y > 0));\n}}\n"); + assert_eq!(hits(&bad), [(3, "all-unguarded")], "a positive operand beside {condition}"); + } + } + + #[test] + fn all_reports_positive_boolean_operands() { + for condition in [ + "xs.iter().all(|x| *x > 0)", + "ready() && xs.iter().all(|x| *x > 0)", + "xs.iter().all(|x| *x > 0) && ready()", + "ready() || xs.iter().all(|x| *x > 0)", + "xs.iter().all(|x| *x > 0) || ready()", + "!!xs.iter().all(|x| *x > 0)", + "!xs.iter().all(|x| *x > 0) == false", + "!(xs.iter().all(|x| *x > 0) == false)", + ] { + let bad = format!("#[test]\nfn t() {{\n assert!({condition});\n}}\n"); + assert_eq!(hits(&bad), [(3, "all-unguarded")], "{condition}"); + let good = bad.replace(" assert!", " assert_eq!(xs.len(), 3);\n assert!"); + assert_eq!(hits(&good), [], "a length check guards {condition}"); + } + } + + #[test] + fn all_guards_use_assertion_operands_and_skip_messages() { + for name in ["assert", "debug_assert", "prop_assert"] { + let good = format!("#[test]\nfn t() {{\n {name}!(xs.len() > 0);\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "{name} condition"); + let bad = format!("#[test]\nfn t() {{\n {name}!(ready(), \"length {{}}\", xs.len());\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&bad), [(4, "all-unguarded")], "{name} message"); + } + for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { + for (left, right) in [("xs.len()", "3"), ("3", "xs.len()")] { + let good = format!("#[test]\nfn t() {{\n {name}!({left}, {right});\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "{name} operands"); + } + let bad = format!("#[test]\nfn t() {{\n {name}!(a, b, \"length {{}}\", xs.len());\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&bad), [(4, "all-unguarded")], "{name} message"); + } + } + + #[test] + fn all_guards_require_checks_of_collection_properties() { + for expr in ["xs.len()", "xs.is_empty()", "xs.iter().count()", "xs.first()", "xs.iter().any(|x| *x > 0)", "xs.iter().next()", "xs.last()"] { + let bad = format!("#[test]\nfn t() {{\n let _ = {expr};\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&bad), [(4, "all-unguarded")], "unused {expr}"); + let good = format!("#[test]\nfn t() {{\n assert_eq!({expr}, expected);\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "checked {expr}"); + } + } + + #[test] + fn all_guards_accept_first_item_access_that_fails_when_empty() { + for expr in ["xs[0]", "xs.first().unwrap()", "xs.first().expect(\"item\")", "xs.iter().next().unwrap()", "xs.iter().next().expect(\"item\")"] + { + let good = format!("#[test]\nfn t() {{\n let _ = {expr};\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "{expr} fails when empty"); + let inner = format!("#[test]\nfn t() {{\n assert!(xs.iter().all(|x| {expr} > 0));\n}}\n"); + assert_eq!(hits(&inner), [(3, "all-unguarded")], "{expr} inside the predicate"); + let message = format!("#[test]\nfn t() {{\n assert!(xs.iter().all(|x| *x > 0), \"item {{:?}}\", {expr});\n}}\n"); + assert_eq!(hits(&message), [(3, "all-unguarded")], "{expr} inside the message"); + } + let literal = "#[test]\nfn t() {\n let _ = [0];\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(literal), [(4, "all-unguarded")], "an array literal does not access an item"); + } + + #[test] + fn all_guards_accept_panicking_first_item_bindings() { + let good = "#[test]\nfn t() {\n let Some(x) = xs.first() else { panic!(\"empty\") };\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(good), []); + let bad = "#[test]\nfn t() {\n let Some(x) = xs.first() else { skip(); };\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(bad), [(4, "all-unguarded")]); + } + + #[test] + fn all_hits_count_changes_anywhere_in_their_test() { + let src = "#[should_panic]\n#[test]\nfn t() {\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\nfn other() {}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.len(), 1); + assert_eq!(found[0].line, 5); + let guarded = src.replace(" assert!(xs.iter()", " assert!(!xs.is_empty());\n assert!(xs.iter()"); + assert_eq!(hits(&guarded), [], "the guard prevents the finding before deletion"); + for line in [1, 2, 3, 4, 5, 6] { + assert!(touches(&found[0], Some(&[line].into_iter().collect())), "test line {line}"); + } + assert!(!touches(&found[0], Some(&[7].into_iter().collect())), "another function is outside the test"); + let diff = "diff --git a/crates/x/src/tests.rs b/crates/x/src/tests.rs\n--- a/crates/x/src/tests.rs\n+++ b/crates/x/src/tests.rs\n@@ -5 +4,0 @@\n- assert!(!xs.is_empty());\n"; + let changed = parse_diff(diff); + assert!(touches(&found[0], changed["crates/x/src/tests.rs"].as_ref()), "removing a guard changes the test"); + } + + #[test] + fn all_allow_comments_stay_near_the_finding() { + let distant = "#[test]\nfn t() {\n // test-lint: allow all-unguarded empty input is allowed\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(distant), [(5, "all-unguarded")]); + let adjacent = "#[test]\nfn t() {\n let xs = f();\n // test-lint: allow all-unguarded empty input is allowed\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(adjacent), []); + let same = "#[test]\nfn t() {\n assert!(xs.iter().all(|x| *x > 0)); // test-lint: allow all-unguarded empty input is allowed\n}\n"; + assert_eq!(hits(same), []); + } + + #[test] + fn only_weak_checks_are_reported_once_per_test() { + let bad = "#[test]\nfn t() {\n assert!(parse(\"a\").is_ok());\n assert!(!list().is_empty());\n}\n"; + assert_eq!(hits(bad), [(2, "only-weak")]); + let good = "#[test]\nfn t() {\n assert!(parse(\"a\").is_ok());\n assert_eq!(parse(\"a\").unwrap(), 1);\n}\n"; + assert_eq!(hits(good), []); + let refusal = "#[test]\nfn t() {\n assert!(parse(\"\").is_err());\n}\n"; + assert_eq!(hits(refusal), [], "is_err is not on the plan's list"); + let compound = "#[test]\nfn t() {\n assert!(a.is_some() && a == Some(2));\n}\n"; + assert_eq!(hits(compound), []); + } + + #[test] + fn self_compare_needs_the_same_plain_expression() { + let bad = "#[test]\nfn t() {\n let x = f();\n assert_eq!(x.len(), x.len());\n assert_eq!(&x, x);\n}\n"; + assert_eq!(hits(bad), [(4, "self-compare"), (5, "self-compare")]); + let good = "#[test]\nfn t() {\n assert_eq!(write(&doc), write(&doc), \"deterministic\");\n assert_eq!(f(\"a\"), f(\"b\"));\n assert_ne!(\"a b\", \"ab\");\n assert_ne!(x /* one */, x.y);\n assert_ne!(' ', ':');\n}\n"; + assert_eq!(hits(good), [], "literal text, including its spaces, is compared"); + } + + #[test] + fn self_compare_counts_changes_through_the_second_operand() { + let src = "#[test]\nfn t() {\n assert_eq!(\n actual,\n actual,\n \"comparison\"\n );\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.len(), 1); + let hit = &found[0]; + assert_eq!(hit.rule, Rule::SelfCompare); + assert_eq!((hit.line, hit.first, hit.last), (3, 3, 5)); + for line in [3, 4, 5] { + assert!(touches(hit, Some(&[line].into_iter().collect())), "changed line {line}"); + } + for line in [2, 6, 7] { + assert!(!touches(hit, Some(&[line].into_iter().collect())), "changed line {line}"); + } + assert_eq!(hits(&src.replacen(" actual,", " expected,", 1)), []); + } + + #[test] + fn self_compare_keeps_exemptions_near_the_macro_opening() { + let src = "#[test]\nfn t() {\n assert_eq!( // MARKER\n actual, // OPERAND\n actual\n );\n}\n"; + let allow = "test-lint: allow self-compare checks the lint"; + assert_eq!(hits(&src.replace("MARKER", allow)), []); + assert_eq!(hits(&src.replace(" assert_eq!", &format!(" // {allow}\n assert_eq!"))), []); + assert_eq!(hits(&src.replace("OPERAND", allow)), [(3, "self-compare")]); + } + + #[test] + fn a_process_test_must_read_its_output() { + let bad = "#[test]\nfn t() {\n let out = Command::new(bin()).arg(\"x\").output().unwrap();\n assert!(out.status.success());\n}\n"; + assert_eq!(hits(bad), [(2, "exit-status-only")]); + let good = "#[test]\nfn t() {\n let out = Command::new(bin()).output().unwrap();\n assert!(out.status.success());\n assert_eq!(out.stdout, b\"ok\\n\");\n}\n"; + assert_eq!(hits(good), []); + } + + #[test] + fn process_status_checks_accept_every_comparison_assertion() { + for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {name}!(out.status.code(), Some(0), \"{{:?}}\", out.stderr);\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{name}"); + let good = bad.replace("Some(0)", "parse_code(&out.stdout)"); + assert_eq!(hits(&good), [], "{name} reads output in its second operand"); + } + } + + #[test] + fn process_status_checks_accept_either_compared_operand() { + for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { + for (expected, status) in [("Some(0)", "out.status.code()"), ("true", "out.status.success()")] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {name}!({expected}, {status}, \"{{:?}}\", out.stdout);\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{name} with {status} on the right"); + let good = bad.replace(expected, "parse_status(&out.stderr)"); + assert_eq!(hits(&good), [], "{name} reads output in its first operand"); + let message = bad.replace(status, "expected_status"); + assert_eq!(hits(&message), [], "{name} has no status check in its operands"); + } + } + } + + #[test] + fn process_output_in_failure_messages_does_not_count_as_reading() { + for assertion in ["assert!(out.status.success()", "debug_assert!(out.status.success()", "prop_assert!(out.status.success()"] { + let bad = + format!("#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {assertion}, \"{{:?}}\", out.stderr);\n}}\n"); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{assertion}"); + let good = bad.replace("out.status.success()", "out.status.success() && out.stdout == expected"); + assert_eq!(hits(&good), [], "output in the condition of {assertion}"); + } + for assertion in ["assert_eq", "assert_ne"] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {assertion}!(out.status.code(), f::(), \"{{:?}}\", out.stderr);\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{assertion}"); + let good = bad.replace("f::()", "from_slice(&out.stdout)"); + assert_eq!(hits(&good), [], "output in the second operand of {assertion}"); + } + } + + #[test] + fn stream_configuration_does_not_count_as_reading_output() { + for stream in ["stdout", "stderr", "stdin"] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).{stream}(Stdio::piped()).output().unwrap();\n assert!(out.status.success());\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{stream} configuration"); + let good = bad.replace(" assert!", " let _ = out.stderr;\n assert!"); + assert_eq!(hits(&good), [], "reading a field after {stream} configuration"); + } + let bad = "#[test]\nfn t() {\n let out = Command::new(bin()).stdout (std::process::Stdio::piped()).output().unwrap();\n assert!(out.status.success());\n}\n"; + assert_eq!(hits(bad), [(2, "exit-status-only")]); + let good = bad.replace("std::process::Stdio::piped()", "output.stdout"); + assert_eq!(hits(&good), [], "a field read in a builder argument counts"); + } + + #[test] + fn output_inspection_counts_outside_failure_messages() { + for read in [ + "out.stdout", + "out.stderr", + "String::from_utf8(out.stdout)", + "fs::read(path)", + "read_to_string(path)", + "from_slice(data)", + "from_str(text)", + "text.contains(needle)", + ] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n assert!(out.status.success(), \"{{:?}}\", {read});\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{read} in a message"); + let good = bad.replace(" assert!", &format!(" let _ = {read};\n assert!")); + assert_eq!(hits(&good), [], "{read} outside a message"); + } + } + + #[test] + fn failure_messages_are_removed_for_every_standard_assertion() { + for name in [ + "assert", + "debug_assert", + "prop_assert", + "assert_eq", + "assert_ne", + "debug_assert_eq", + "debug_assert_ne", + "prop_assert_eq", + "prop_assert_ne", + ] { + let operands = if guard_arg_count(name) == 1 { "true" } else { "left, right" }; + let bad = format!("#[test]\nfn t() {{\n assert!(xs.iter().all(|x| *x > 0));\n {name}!({operands}, \"{{:?}}\", xs[0]);\n}}\n"); + assert_eq!(hits(&bad), [(3, "all-unguarded")], "{name} message"); + let good = bad.replace(" assert!", " let _ = xs[0];\n assert!"); + assert_eq!(hits(&good), [], "access outside the {name} message"); + } + } + + #[test] + fn assertion_arguments_keep_turbofish_groups_and_split_comparisons() { + for operand in ["f::()", "f::>()", "f :: ()"] { + let src = format!("{operand}, expected, message"); + let m = mask(&src); + let args: Vec<&str> = split_args(&m, 0, m.len()).into_iter().map(|(from, to)| src[from..to].trim()).collect(); + assert_eq!(args, [operand, "expected", "message"], "{operand}"); + let comparison = format!("a < b, {operand} > c, message"); + let m = mask(&comparison); + let args: Vec<&str> = split_args(&m, 0, m.len()).into_iter().map(|(from, to)| comparison[from..to].trim()).collect(); + assert_eq!(args, ["a < b", &format!("{operand} > c"), "message"], "comparisons around {operand}"); + } + } + + #[test] + fn a_test_needs_an_assertion_or_an_asserting_helper() { + let bad = "#[test]\nfn t() {\n let d = open(\"x\").unwrap();\n d.save();\n}\n"; + assert_eq!(hits(bad), [(2, "no-assertion")]); + let panics = "fn f() {}\n/// Panics.\n#[should_panic(expected = \"x\")]\n#[test]\nfn p() {\n f();\n}\n"; + assert_eq!(hits(panics), [], "#[should_panic] before #[test]"); + let src = "fn same(a: u8, b: u8) {\n assert_eq!(a, b);\n}\nfn twice(a: u8) {\n same(a, a);\n}\n#[test]\nfn t() {\n twice(f());\n}\n#[test]\n#[should_panic]\nfn p() {\n f();\n}\n#[test]\nfn q() {\n check_round_trip(f());\n}\n"; + let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), src.to_owned())]); + assert!(helpers["crates/x"].contains("twice"), "{helpers:?}"); + let ctx = Ctx { helpers, ci_env: HashSet::new() }; + assert_eq!(hits_in("crates/x/tests/it.rs", src, &ctx), []); + assert_eq!(hits_in("crates/y/tests/it.rs", src, &ctx), [(8, "no-assertion")], "another crate's helper does not count"); + let kit = asserting_helpers(&[("crates/testkit/src/lib.rs".to_owned(), src.to_owned()), ("crates/y/src/lib.rs".to_owned(), String::new())]); + assert!(kit["crates/y"].contains("twice"), "testkit helpers count in every crate: {kit:?}"); + assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx { helpers: HashMap::new(), ci_env: HashSet::new() }), [(8, "no-assertion")]); + } + + #[test] + fn generic_asserting_calls_count_for_functions_and_methods() { + for call in ["check_round_trip::()", "check_round_trip::>(x)", "value.check::()", "value.check :: >> ()"] { + let src = format!("#[test]\nfn t() {{\n {call};\n}}\n"); + assert_eq!(hits(&src), [], "{call}"); + } + for expression in ["check_round_trip::", "value.check::", "round_trip::()", "value.round_trip::()"] { + let src = format!("#[test]\nfn t() {{\n let _ = {expression};\n}}\n"); + assert_eq!(hits(&src), [(2, "no-assertion")], "{expression}"); + } + } + + #[test] + fn generic_crate_helpers_count_through_other_helpers() { + let defs = "fn same(a: T, b: T) { assert_eq!(a, b); }\nfn twice(a: T) { same::(a, a); }\nfn idle() {}\n"; + let helpers = asserting_helpers(&[("crates/x/tests/helpers.rs".to_owned(), defs.to_owned())]); + assert!(helpers["crates/x"].contains("same")); + assert!(helpers["crates/x"].contains("twice")); + assert!(!helpers["crates/x"].contains("idle")); + let ctx = Ctx { helpers, ci_env: HashSet::new() }; + for call in ["same::(a, b)", "twice::>>(x)"] { + let src = format!("#[test]\nfn t() {{\n {call};\n}}\n"); + assert_eq!(hits_in("crates/x/tests/it.rs", &src, &ctx), [], "{call}"); + assert_eq!(hits_in("crates/y/tests/it.rs", &src, &ctx), [(2, "no-assertion")], "{call} in another crate"); + } + for expression in ["idle::()", "same::", "value.same::()"] { + let src = format!("#[test]\nfn t() {{\n let _ = {expression};\n}}\n"); + assert_eq!(hits_in("crates/x/tests/it.rs", &src, &ctx), [(2, "no-assertion")], "{expression}"); + } + } + + #[test] + fn early_returns_on_values_are_reported_and_resource_skips_are_not() { + let bad = "#[test]\nfn t() {\n let Some(n) = find() else { return };\n assert_eq!(n, 2);\n}\n"; + assert_eq!(hits(bad), [(3, "early-return")]); + let fonts = "#[test]\nfn t() {\n let Some(face) = installed_family(\"Kufi\") else { return; };\n assert_eq!(face.n, 2);\n}\n"; + assert_eq!(hits(fonts), []); + let closure = "#[test]\nfn t() {\n let f = |x: u8| { if x == 0 { return; } g(x) };\n assert_eq!(f(1), ());\n}\n"; + assert_eq!(hits(closure), []); + let last = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n if g() { return; }\n}\n"; + assert_eq!(hits(last), []); + let value = "#[test]\nfn t() -> Result<(), String> {\n if f()? == 0 { return Ok(()); }\n assert_eq!(g(), 1);\n Ok(())\n}\n"; + assert_eq!(hits(value), [(3, "early-return")]); + let checked = "#[test]\nfn t() {\n for _ in 0..9 {\n if g() == 1 {\n assert_eq!(f(), 2);\n return;\n }\n }\n panic!(\"never stable\");\n}\n"; + assert_eq!(hits(checked), [], "a return after an assertion in its block"); + let said = "#[test]\nfn t() {\n if !link(\"a\") {\n eprintln!(\"skipped: no links here\");\n return;\n }\n assert_eq!(f(), 2);\n}\n"; + assert_eq!(hits(said), [], "a return after a printed skip note"); + let commented = "#[test]\nfn t() {\n let Some(w) = width() else { return }; // no wide font here\n assert_eq!(w, 2);\n}\n"; + assert_eq!(hits(commented), [], "a return whose line says why"); + let quiet = "#[test]\nfn t() {\n if !link(\"a\") {\n return;\n }\n assert_eq!(f(), 2);\n}\n"; + assert_eq!(hits(quiet), [(4, "early-return")]); + } + + #[test] + fn ignore_needs_a_reason() { + let bad = "#[test]\n#[ignore]\nfn t() {\n assert_eq!(f(), 1);\n}\n#[ignore = \" \"]\n#[test]\nfn u() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(bad), [(2, "ignore-without-reason"), (6, "ignore-without-reason")]); + let good = "#[test]\n#[ignore = \"a benchmark: run with --ignored\"]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(good), []); + } + + #[test] + fn ignore_accepts_non_empty_raw_string_reasons() { + for hashes in ["", "#", "##", "########"] { + for reason in ["requires an external service", " service ", r"service \ path"] { + let literal = format!("r{hashes}\"{reason}\"{hashes}"); + let src = format!("#[test]\n#[ignore = {literal}]\nfn t() {{ assert_eq!(f(), 1); }}\n"); + assert_eq!(hits(&src), [], "{literal}"); + } + for reason in ["", " ", "\t\n"] { + let literal = format!("r{hashes}\"{reason}\"{hashes}"); + let src = format!("#[test]\n#[ignore = {literal}]\nfn t() {{ assert_eq!(f(), 1); }}\n"); + assert_eq!(hits(&src), [(2, "ignore-without-reason")], "{literal}"); + } + } + } + + #[test] + fn env_gates_need_a_variable_ci_sets() { + let bad = "#[test]\nfn t() {\n let Ok(dir) = std::env::var(\"MY_SAMPLES\") else { return };\n assert_eq!(count(&dir), 3);\n}\n"; + assert_eq!(hits(bad), [(3, "env-gate-unset")]); + let ci = "#[test]\nfn t() {\n if std::env::var(\"SET_IN_CI\").is_ok() { assert_eq!(f(), 1); }\n assert_eq!(std::env::var(\"CARGO_PKG_NAME\").unwrap(), \"x\");\n}\n"; + assert_eq!(hits(ci), []); + let child = "const CHILD: &str = \"X_TEST_CHILD\";\n#[test]\nfn t() {\n if std::env::var_os(\"X_TEST_CHILD\").is_some() { assert_eq!(f(), 1); }\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(child), []); + } + + #[test] + fn env_gates_ignore_commented_out_setters() { + for setter in ["cmd.env(\"MY_SAMPLES\", dir);", "std::env::set_var(\"MY_SAMPLES\", \"x\");", "const X: &str = \"MY_SAMPLES\";"] { + for comment in [format!("// {setter}"), format!("/* {setter} */"), format!("/* outer /* {setter} */ end */")] { + let src = + format!("{comment}\n#[test]\nfn t() {{\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(dir, expected);\n}}\n"); + assert_eq!(hits(&src), [(4, "env-gate-unset")], "{comment}"); + } + } + } + + #[test] + fn env_gates_keep_code_setters_and_literal_contents() { + for setter in [ + "cmd . env ( \"MY_SAMPLES\", dir);", + "std::env::set_var ( \"MY_SAMPLES\", \"x\");", + "set_var(\"MY_SAMPLES\", \"x\");", + "use std::env::set_var; fn setup() { set_var(\"MY_SAMPLES\", \"x\"); }", + "cmd.set_var(\"MY_SAMPLES\", \"x\");", + "const X: &str = \"MY_SAMPLES\";", + "cmd.env(/* name */ \"MY_SAMPLES\", dir);", + ] { + let src = format!("{setter}\n#[test]\nfn t() {{\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(dir, expected);\n}}\n"); + assert_eq!(hits(&src), [], "{setter}"); + assert_eq!(hits(&src.replacen("MY_SAMPLES", "OTHER_SAMPLES", 1)), [(4, "env-gate-unset")], "{setter}"); + } + let src = "let a = \"https://host/*path*/\"; /* removed */ let b = r#\"// kept /* kept */\"#; // removed\nlet c = '/';"; + let masked = String::from_utf8(mask_comments(src)).unwrap(); + assert!(masked.contains("\"https://host/*path*/\"")); + assert!(masked.contains("r#\"// kept /* kept */\"#")); + assert!(masked.contains("let c = '/';")); + assert!(!masked.contains("removed")); + } + + #[test] + fn env_gates_require_setter_call_boundaries() { + for reader in [ + "read_env(\"MY_SAMPLES\");", + "cmd.read_env(\"MY_SAMPLES\");", + "env(\"MY_SAMPLES\", dir);", + "my_set_var(\"MY_SAMPLES\", \"x\");", + "std::env::my_set_var(\"MY_SAMPLES\", \"x\");", + "cmd.my_set_var(\"MY_SAMPLES\", \"x\");", + ] { + let src = format!("{reader}\n#[test]\nfn t() {{\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(dir, expected);\n}}\n"); + assert_eq!(hits(&src), [(4, "env-gate-unset")], "{reader}"); + } + } + + #[test] + fn sleep_in_test_code_is_reported() { + let bad = "fn wait() {\n std::thread::sleep(Duration::from_millis(5));\n}\n#[test]\nfn t() {\n thread::sleep(D);\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(bad), [(2, "sleep"), (6, "sleep")]); + let good = "fn sleep(d: D) {}\n#[test]\nfn t() {\n run(\"$.sleep(250)\");\n clock.sleep(D);\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(good), []); + let shipped = "pub fn wait() {\n std::thread::sleep(D);\n}\n#[cfg(test)]\nmod tests {}\n"; + assert_eq!(hits_in("crates/x/src/lib.rs", shipped, &ctx()), [], "code before #[cfg(test)] is not test code"); + assert_eq!(hits_in("xtask/src/test_lint.rs", shipped, &ctx()), [], "a name that only starts with test is not a test file"); + let after = "#[cfg(test)]\nmod tests {\n fn w() { thread::sleep(D); }\n}\npub fn later() {\n thread::sleep(D);\n}\n"; + assert_eq!(hits_in("crates/x/src/lib.rs", after, &ctx()), [(3, "sleep")], "code after a #[cfg(test)] module is not test code"); + for test_file in [ + "crates/x/src/tests.rs", + "crates/x/src/tests_wheel.rs", + "crates/x/src/widget_tests.rs", + "crates/x/tests/it/a.rs", + "crates/testkit/src/lib.rs", + ] { + assert_eq!(hits_in(test_file, shipped, &ctx()), [(2, "sleep")], "{test_file}"); + } + } + + #[test] + fn reading_rust_source_is_reported_outside_the_audits() { + let bad = "#[test]\nfn t() {\n let src = include_str!(\"../lib.rs\");\n assert_eq!(src.matches(\"x\").count(), 1);\n}\n"; + assert_eq!(hits(bad), [(3, "reads-source")]); + let walk = "#[test]\nfn t() {\n let n = files().filter(|p| p.ends_with(\".rs\")).count();\n assert_eq!(n, 4);\n}\n"; + assert_eq!(hits(walk), [(3, "reads-source")]); + assert_eq!(hits_in(SOURCE_AUDITS[0], bad, &ctx()), []); + let data = "#[test]\nfn t() {\n let s = include_str!(\"fixtures/a.svg\");\n assert_eq!(s.len(), 4);\n}\n"; + assert_eq!(hits(data), []); + } + + #[test] + fn allow_comments_need_the_rule_and_a_reason() { + let src = "#[test]\nfn t() {\n // test-lint: allow sleep the file clock has a 2 ms step\n thread::sleep(D);\n thread::sleep(D); // test-lint: allow sleep same\n assert_eq!(f(), 1);\n thread::sleep(D); // test-lint: allow sleep\n thread::sleep(D); // test-lint: allow early-return wrong rule\n}\n// test-lint: allow no-assertion a smoke test of the panic-free reader\n#[test]\nfn u() {\n let _ = read(b\"junk\");\n}\n"; + assert_eq!(hits(src), [(7, "sleep"), (8, "sleep")], "an allow covers its own line and the next, and needs a reason"); + let strings = "#[test]\nfn t() {\n let s = \"test-lint: allow sleep in a string\"; thread::sleep(D);\n let r = r#\"test-lint: allow sleep raw\"#; thread::sleep(D);\n /* test-lint: allow sleep a block comment */ thread::sleep(D);\n assert_eq!(s, r);\n}\n"; + assert_eq!(hits(strings), [(3, "sleep"), (4, "sleep")], "a marker in a literal is not an exemption"); + } + + #[test] + fn comments_and_strings_are_not_code() { + let src = "#[test]\nfn t() {\n // assert!(x.iter().all(|y| y))\n let s = \"thread::sleep(d); #[ignore]\";\n let r = r#\"env::var(\"NOPE\")\"#;\n let c = '\"';\n assert_eq!(s, r);\n}\n"; + assert_eq!(hits(src), []); + } + + #[test] + fn tests_are_found_by_their_attributes() { + let src = "#[cfg(test)]\nmod tests {\n #[tokio::test]\n async fn a() {}\n #[test_case(1)]\n fn b(n: u8) {}\n proptest! {\n #[test]\n fn c(x in 0..9u8) {}\n }\n #[test]\n fn d() -> Result<(), String> { Ok(()) }\n fn not_a_test() {}\n}\n"; + let names: Vec = tests_in(&mask(src)).into_iter().map(|t| t.name).collect(); + assert_eq!(names, ["a", "b", "c", "d"]); + } + + #[test] + fn changed_lines_come_from_the_new_side_of_each_hunk() { + let diff = "diff --git a/crates/x/src/a.rs b/crates/x/src/a.rs\nindex 1..2 100644\n--- a/crates/x/src/a.rs\n+++ b/crates/x/src/a.rs\n@@ -3,0 +4,2 @@ fn f() {\n+a\n+b\n@@ -10 +12 @@\n-c\n+d\n@@ -20,2 +21,0 @@\n-e\ndiff --git a/crates/x/src/n.rs b/crates/x/src/n.rs\nnew file mode 100644\n--- /dev/null\n+++ b/crates/x/src/n.rs\n@@ -0,0 +1,3 @@\n"; + let got = parse_diff(diff); + assert_eq!(got.len(), 2); + assert_eq!(got["crates/x/src/a.rs"], Some([4, 5, 12, 21, 22].into_iter().collect())); + assert_eq!(got["crates/x/src/n.rs"], None); + } + + #[test] + fn deleting_the_first_attribute_changes_the_remaining_test() { + let path = "crates/x/src/tests.rs"; + for (prefix, anchor) in [("", 0), ("fn before() {}\n", 1)] { + let src = format!("{prefix}#[test]\nfn t() {{}}\n#[test]\nfn other() {{}}\n"); + let before = src.replacen("#[test]", "#[should_panic]\n#[test]", 1); + assert!(lint_file(path, &before, &ctx()).iter().all(|h| h.test != "t"), "the attribute prevents the finding"); + let found = lint_file(path, &src, &ctx()); + assert_eq!(found.len(), 2); + let old = anchor + 1; + let diff = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -{old} +{anchor},0 @@\n-#[should_panic]\n"); + let changed = parse_diff(&diff); + let expected = if anchor == 0 { vec![1] } else { vec![anchor, anchor + 1] }; + assert_eq!(changed[path], Some(expected.into_iter().collect())); + assert_eq!(found[0].rule, Rule::NoAssertion); + assert_eq!(found[0].test, "t"); + assert!(touches(&found[0], changed[path].as_ref()), "the deletion changes the remaining test"); + assert!(!touches(&found[1], changed[path].as_ref()), "the following test is unchanged"); + } + } + + #[test] + fn only_hits_on_changed_lines_count() { + let src = "#[test]\nfn old() {\n f();\n}\n#[test]\nfn new() {\n g();\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.len(), 2); + let changed: BTreeSet = [7].into_iter().collect(); + let counted: Vec<&str> = found.iter().filter(|h| touches(h, Some(&changed))).map(|h| h.test.as_str()).collect(); + assert_eq!(counted, ["new"]); + assert_eq!(found.iter().filter(|h| touches(h, None)).count(), 2); + assert_eq!(found.iter().filter(|h| touches(h, Some(&BTreeSet::new()))).count(), 0); + } + + #[test] + fn options_reject_unknown_and_repeated_arguments() { + assert_eq!(Options::parse(&[]), Ok(Options::default())); + assert_eq!(Options::parse(&["--base", "abc"]), Ok(Options { all: false, base: Some("abc".into()) })); + assert_eq!(Options::parse(&["--all"]), Ok(Options { all: true, base: None })); + for bad in [&["--base"][..], &["--base", "--all"], &["--all", "--all"], &["--fix"], &["--all", "--base", "x"]] { + assert!(Options::parse(bad).unwrap_err().starts_with("test-lint:"), "{bad:?}"); + } + } + + #[test] + fn workflow_variables_count_as_set() { + let names: Vec = upper_words("env:\n AFFINITY_CORPUS_REQUIRED: 1\n run: X=1 cargo test # A\n").collect(); + assert_eq!(names, ["AFFINITY_CORPUS_REQUIRED"]); + assert!(set_by_system("CARGO_MANIFEST_DIR") && set_by_system("HOME") && !set_by_system("MY_SAMPLES")); + } + + #[test] + fn workflow_mapping_keys_count_without_reads_or_comments() { + let assigned: Vec = upper_words("env:\n MY_SAMPLES: fixtures\n - OTHER_SAMPLES: fixtures\n EMPTY_SAMPLES:\n").collect(); + assert_eq!(assigned, ["MY_SAMPLES", "OTHER_SAMPLES", "EMPTY_SAMPLES"]); + let reads = "# MY_SAMPLES: fixtures\nif: env.MY_SAMPLES != ''\nrun: echo $OTHER_SAMPLES ${EMPTY_SAMPLES}\nvalue: ${{ env.MY_SAMPLES }}\n"; + assert_eq!(upper_words(reads).collect::>(), Vec::::new()); + } + + #[test] + fn workflow_script_assignments_count_without_reads_or_comments() { + for assignment in [ + " MY_SAMPLES=value", + " export MY_SAMPLES=value", + " run: MY_SAMPLES=value cargo test", + " echo \"MY_SAMPLES=value\" >> \"$GITHUB_ENV\"", + " echo 'MY_SAMPLES=value' >> \"$GITHUB_ENV\"", + " MY_SAMPLES=value # OTHER_SAMPLES=value", + " MY_SAMPLES=\"#value\"", + " MY_SAMPLES=", + " - MY_SAMPLES=value", + ] { + assert_eq!(upper_words(assignment).collect::>(), ["MY_SAMPLES"], "{assignment}"); + let commented = format!("# {assignment}"); + assert_eq!(upper_words(&commented).collect::>(), Vec::::new(), "{commented}"); + } + let reads = "env.MY_SAMPLES=value\n${{ env.MY_SAMPLES }}\n$MY_SAMPLES\n${MY_SAMPLES}\nMY_SAMPLES==value\n"; + assert_eq!(upper_words(reads).collect::>(), Vec::::new()); + } + + #[test] + fn workflow_mentions_do_not_suppress_unset_gates() { + let src = "#[test]\nfn t() {\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; + for workflow in ["if: env.MY_SAMPLES != ''", "run: echo $MY_SAMPLES", "# MY_SAMPLES=value"] { + let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words(workflow).collect() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [(3, "env-gate-unset")], "{workflow}"); + } + for workflow in ["env:\n MY_SAMPLES: fixtures", "run: |\n export MY_SAMPLES=fixtures", "with:\n env: |\n MY_SAMPLES=fixtures"] { + let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words(workflow).collect() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [], "{workflow}"); + } + } +}