mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 21:12:57 -05:00
xtask: test-lint reads renames, cfg_attr paths, casts and arm bindings
- changed mode diffs with --no-renames, so an exact rename lists the old path as deleted and the new path as added, and both seed the route walk. - census reads a cast of the loop binding (k as usize) as the entry, and no longer reads a field or path segment named like it (config.k, m::k). - reads-source takes the file name from the final .join(...) component; a final component that is not a literal is an unknown file. - mirror keeps whitespace inside string literals when it compares lookup keys, so "A B" and "AB" are different entries. - fixture-only resolves a name bound by a match arm's pattern to that arm, not to an outer let; a guard still reads the outer binding. - never-run follows #[cfg_attr(<cond>, path = "...")] overrides: the selected path is loaded where the condition holds, and the default path elsewhere. - never-run treats tests/<dir>/mod.rs as loaded by the test targets beside it, like a crate root. - exact-pixel no longer reports two rects compared by their difference (a.width() - b.width()).
This commit is contained in:
1 parent
e1c1b04f25
commit
186e6db9ba
1 file changed
+245
-21
+245
-21
@@ -343,9 +343,9 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> {
|
||||
let base_off: RefCell<HashMap<String, HashSet<(String, usize)>>> = RefCell::new(HashMap::new());
|
||||
let newly_off = |path: &str, src: &str, hit: &Hit| {
|
||||
let mut cache = base_off.borrow_mut();
|
||||
let off = cache.entry(path.to_owned()).or_insert_with(|| {
|
||||
lint_file(path, src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test, h.line)).collect()
|
||||
});
|
||||
let off = cache
|
||||
.entry(path.to_owned())
|
||||
.or_insert_with(|| lint_file(path, src, &base_ctx).into_iter().filter(|h| h.rule == Rule::NeverRun).map(|h| (h.test, h.line)).collect());
|
||||
!off.contains(&(hit.test.clone(), hit.line))
|
||||
};
|
||||
let (mut counted, mut older) = (vec![], 0usize);
|
||||
@@ -560,6 +560,8 @@ fn changed_lines(root: &Path, base: &str) -> Result<BTreeMap<String, Option<BTre
|
||||
"--inter-hunk-context=0",
|
||||
"--no-color",
|
||||
"--no-ext-diff",
|
||||
// A rename shows as a deletion and an addition, so both paths count as changed.
|
||||
"--no-renames",
|
||||
"--src-prefix=a/",
|
||||
"--dst-prefix=b/",
|
||||
base,
|
||||
@@ -1782,13 +1784,20 @@ fn round_trip_call(op: &str, var: &str) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `s` contains the identifier `var` as a whole word.
|
||||
/// Whether the (whitespace-free) `s` reads the binding `var`: a whole word that is not a field or
|
||||
/// path segment (`config.k`, `m::k`), alone or cast to a primitive (`k as usize` reads `kasusize`).
|
||||
fn reads_ident(s: &str, var: &str) -> bool {
|
||||
const PRIMITIVES: &[&str] =
|
||||
&["usize", "isize", "u128", "i128", "u64", "i64", "u32", "i32", "u16", "i16", "u8", "i8", "f64", "f32", "char", "bool"];
|
||||
let b = s.as_bytes();
|
||||
let ends = |rest: &str| !rest.bytes().next().is_some_and(is_ident);
|
||||
!var.is_empty()
|
||||
&& s.match_indices(var).any(|(at, _)| {
|
||||
let end = at + var.len();
|
||||
!(at > 0 && is_ident(b[at - 1])) && !b.get(end).copied().is_some_and(is_ident)
|
||||
let field = at > 0 && b[at - 1] == b'.' && !(at > 1 && b[at - 2] == b'.');
|
||||
let path = at > 1 && &b[at - 2..at] == b"::";
|
||||
let cast = s[end..].strip_prefix("as").is_some_and(|r| PRIMITIVES.iter().any(|t| r.strip_prefix(t).is_some_and(ends)));
|
||||
!(at > 0 && is_ident(b[at - 1])) && !field && !path && (ends(&s[end..]) || cast)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3084,8 +3093,12 @@ fn reads_source_hits(file: &File) -> Vec<Hit> {
|
||||
let rs = match word {
|
||||
b"ends_with" => literal == "\".rs\"",
|
||||
// The last path literal in the argument names the file read: `root.join("src/lib.rs")`,
|
||||
// `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`.
|
||||
b"read_to_string" => last_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")),
|
||||
// `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`. A final
|
||||
// component that is not a literal (`.join(name)`) names an unknown file.
|
||||
b"read_to_string" => {
|
||||
let last = arg.rfind(".join(").and_then(|at| matching(arg.as_bytes(), at + 5).map(|close| &arg[at + 6..close]));
|
||||
last_literal(last.unwrap_or(&arg)).is_some_and(|l| l.ends_with(".rs\""))
|
||||
}
|
||||
_ => arg.trim_end_matches('#').ends_with(".rs\""),
|
||||
};
|
||||
if rs {
|
||||
@@ -3191,7 +3204,35 @@ fn first_arithmetic(op: &str) -> Option<usize> {
|
||||
fn head_args(f: &File, code: &[u8], (from, to): (usize, usize)) -> Option<Vec<String>> {
|
||||
let open = from + f.m.get(from..to)?.iter().position(|&c| c == b'(')?;
|
||||
let close = matching(&f.m, open)?;
|
||||
Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm(code.get(a..b).unwrap_or(&f.src[a..b]))).collect())
|
||||
Some(split_args(&f.m, open + 1, close).into_iter().map(|(a, b)| norm_outside_literals(code.get(a..b).unwrap_or(&f.src[a..b]))).collect())
|
||||
}
|
||||
|
||||
/// [`norm`] that keeps whitespace inside string literals: `"A B"` and `"AB"` are different keys.
|
||||
fn norm_outside_literals(b: &[u8]) -> String {
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let mut in_str = false;
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
let c = b[i];
|
||||
if in_str {
|
||||
out.push(c);
|
||||
if c == b'\\' {
|
||||
if let Some(&n) = b.get(i + 1) {
|
||||
out.push(n);
|
||||
i += 1;
|
||||
}
|
||||
} else if c == b'"' {
|
||||
in_str = false;
|
||||
}
|
||||
} else if c == b'"' && !(i > 0 && b[i - 1] == b'\'' && b.get(i + 1) == Some(&b'\'')) {
|
||||
in_str = true;
|
||||
out.push(c);
|
||||
} else if !c.is_ascii_whitespace() {
|
||||
out.push(c);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
/// An argument that names an entry rather than a quantity: a string or integer literal, or a local,
|
||||
@@ -3321,13 +3362,67 @@ fn reaching_init(body: &[u8], name: &str, before: usize) -> Option<Option<(Strin
|
||||
let pattern = norm(pattern.as_bytes());
|
||||
open < before && before < close && !words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty()
|
||||
});
|
||||
match (loop_at, &found) {
|
||||
// A match arm's pattern binds its names inside that arm only.
|
||||
let inner = loop_at.max(arm_binding(body, name, before));
|
||||
match (inner, &found) {
|
||||
(Some(l), Some((_, at))) if *at > l => found.map(|(init, _)| init),
|
||||
(Some(_), _) => Some(None),
|
||||
(None, _) => found.map(|(init, _)| init),
|
||||
}
|
||||
}
|
||||
|
||||
/// The offset of the `=>` of the innermost match arm whose pattern binds `name` and whose body
|
||||
/// holds `before`: `Some(n) => assert_eq!(n, 1)` binds `n`, `None => …` does not.
|
||||
fn arm_binding(body: &[u8], name: &str, before: usize) -> Option<usize> {
|
||||
let mut found = None;
|
||||
for arrow in (0..before.min(body.len().saturating_sub(1))).filter(|&i| &body[i..i + 2] == b"=>") {
|
||||
// The pattern runs back to the `{` or `,` that opens the arm.
|
||||
let mut depth = 0usize;
|
||||
let mut start = arrow;
|
||||
while start > 0 {
|
||||
match body[start - 1] {
|
||||
b')' | b']' | b'}' => depth += 1,
|
||||
b'(' | b'[' | b'{' if depth == 0 => break,
|
||||
b'(' | b'[' | b'{' => depth -= 1,
|
||||
b',' if depth == 0 => break,
|
||||
_ => {}
|
||||
}
|
||||
start -= 1;
|
||||
}
|
||||
// A guard (`Some(x) if x == n`) reads names; it does not bind them.
|
||||
let guard = words(body, b"if", start, arrow).first().copied().unwrap_or(arrow);
|
||||
let pattern = norm(&body[start..guard]);
|
||||
if words(pattern.as_bytes(), name.as_bytes(), 0, pattern.len()).is_empty() {
|
||||
continue;
|
||||
}
|
||||
// The arm's body: a block, or an expression up to the `,` or brace that ends the arm.
|
||||
let from = skip_ws(body, arrow + 2);
|
||||
let end = match body.get(from) {
|
||||
Some(b'{') => matching(body, from),
|
||||
_ => {
|
||||
let mut depth = 0usize;
|
||||
(from..body.len()).find(|&i| match body[i] {
|
||||
b'(' | b'[' | b'{' => {
|
||||
depth += 1;
|
||||
false
|
||||
}
|
||||
b')' | b']' | b'}' if depth == 0 => true,
|
||||
b')' | b']' | b'}' => {
|
||||
depth -= 1;
|
||||
false
|
||||
}
|
||||
b',' => depth == 0,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
};
|
||||
if end.is_some_and(|end| before < end) {
|
||||
found = Some(arrow);
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// [`reaching_init`] over `let` bindings alone, with the position of the binding that decides it.
|
||||
fn let_init(body: &[u8], name: &str, before: usize) -> Option<(Option<(String, usize)>, usize)> {
|
||||
let mut found = None;
|
||||
@@ -3644,13 +3739,20 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize, usize)> {
|
||||
|
||||
/// The module name a file declares and the files that may declare it with `mod <name>;`, or `None`
|
||||
/// for a crate root (`lib.rs`, `main.rs`, `build.rs`, a file directly in `tests`, `benches` or
|
||||
/// `examples` beside a crate's `src`, or a file directly in `src/bin`). A `tests` directory under
|
||||
/// `examples` beside a crate's `src`, or a file directly in `src/bin`), and for a `mod.rs` one
|
||||
/// directory below those, which their roots load (`tests/common/mod.rs`). A `tests` directory under
|
||||
/// `src` holds modules, not test targets.
|
||||
fn module_parent(path: &str) -> Option<(&str, Vec<String>)> {
|
||||
let (dir, file) = path.rsplit_once('/')?;
|
||||
let outside_src = |d: &str| dir.strip_suffix(d).is_some_and(|crate_dir| !crate_dir.split('/').any(|s| s == "src"));
|
||||
let root_dir = ["/tests", "/benches", "/examples"].iter().any(|d| outside_src(d)) || dir.ends_with("/src/bin");
|
||||
if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") {
|
||||
let is_root_dir = |dir: &str| {
|
||||
let outside_src = |d: &str| dir.strip_suffix(d).is_some_and(|crate_dir| !crate_dir.split('/').any(|s| s == "src"));
|
||||
["/tests", "/benches", "/examples"].iter().any(|d| outside_src(d)) || dir.ends_with("/src/bin")
|
||||
};
|
||||
let root_dir = is_root_dir(dir);
|
||||
// `tests/common/mod.rs` is loaded by the target roots beside it (`tests/smoke.rs` with
|
||||
// `mod common;`), which are not listed here, so it counts as reached like a root.
|
||||
let beside_roots = file == "mod.rs" && dir.rsplit_once('/').is_some_and(|(up, _)| is_root_dir(up));
|
||||
if ["lib.rs", "main.rs", "build.rs"].contains(&file) || (root_dir && file != "mod.rs") || beside_roots {
|
||||
return None;
|
||||
}
|
||||
let (name, parent) = if file == "mod.rs" { dir.rsplit_once('/').map(|(p, n)| (n, p))? } else { (file.strip_suffix(".rs")?, dir) };
|
||||
@@ -3689,22 +3791,38 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec<String>,
|
||||
continue;
|
||||
}
|
||||
let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1);
|
||||
let loads = match path_attr(&m, src.as_bytes(), item, at) {
|
||||
Some(rel) => override_path(dir, file, mod_rs, want.chain, &rel) == want.path,
|
||||
// A `cfg_attr` override loads its path where its condition holds, and the default (or a
|
||||
// plain `#[path]`) elsewhere.
|
||||
let conditional = cfg_attr_paths(&m, src.as_bytes(), item, at);
|
||||
let overrides_here = |rel: &str| override_path(dir, file, mod_rs, want.chain, rel) == want.path;
|
||||
let fallback = match path_attr(&m, src.as_bytes(), item, at) {
|
||||
Some(rel) => overrides_here(&rel),
|
||||
None => {
|
||||
&m[start..end] == want.name.as_bytes()
|
||||
&& [format!("{}.rs", want.name), format!("{}/mod.rs", want.name)].iter().any(|rel| join_path(&default_dir, rel) == want.path)
|
||||
}
|
||||
};
|
||||
if !loads {
|
||||
continue;
|
||||
}
|
||||
let selected: Vec<&str> = conditional.iter().filter(|(_, rel)| overrides_here(rel)).map(|(c, _)| c.as_str()).collect();
|
||||
let route = match (fallback, selected.is_empty(), conditional.is_empty()) {
|
||||
(true, _, true) => None,
|
||||
(true, true, false) => Some(format!("not(any({}))", conditional.iter().map(|(c, _)| c.as_str()).collect::<Vec<_>>().join(","))),
|
||||
(true, false, false) => {
|
||||
let others: Vec<&str> = conditional.iter().filter(|(_, rel)| !overrides_here(rel)).map(|(c, _)| c.as_str()).collect();
|
||||
(!others.is_empty()).then(|| format!("not(any({}))", others.join(",")))
|
||||
}
|
||||
(false, true, _) => continue,
|
||||
(false, false, _) => Some(format!("any({})", selected.join(","))),
|
||||
};
|
||||
// Inner attributes cover the file, and [`cfgs_over`] reads them.
|
||||
let attrs: Vec<CfgAttr> = cfg_attrs(&m, src.as_bytes(), item, at).into_iter().filter(|a| !a.inner).collect();
|
||||
at_lines.push(lines.of(at));
|
||||
// Every line of a multiline attribute counts: an edit inside its predicate changes it.
|
||||
at_lines.extend(attrs.iter().flat_map(|a| lines.of(a.at)..=lines.of(a.end)));
|
||||
let mut preds: Vec<String> = attrs.into_iter().map(|a| a.pred).collect();
|
||||
if let Some(route) = route {
|
||||
preds.push(route);
|
||||
at_lines.extend(lines.of(skip_ws(&m, item))..=lines.of(at));
|
||||
}
|
||||
for (p, a, e) in cfgs_over(&m, src.as_bytes(), at) {
|
||||
preds.push(p);
|
||||
at_lines.extend(lines.of(a)..=lines.of(e));
|
||||
@@ -3747,7 +3865,9 @@ fn path_children(src: &str, parent: &str) -> Vec<(String, Vec<String>)> {
|
||||
continue;
|
||||
}
|
||||
let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1);
|
||||
if let Some(rel) = path_attr(&m, src.as_bytes(), item, at) {
|
||||
let rels =
|
||||
path_attr(&m, src.as_bytes(), item, at).into_iter().chain(cfg_attr_paths(&m, src.as_bytes(), item, at).into_iter().map(|(_, r)| r));
|
||||
for rel in rels {
|
||||
let chain = inline_mods(&m, src.as_bytes(), at);
|
||||
out.push((override_path(dir, file, mod_rs, &chain, &rel), chain));
|
||||
}
|
||||
@@ -3819,6 +3939,31 @@ fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option<String> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The `#[cfg_attr(<condition>, path = "…")]` overrides in `m[from..to]`, each as its condition and
|
||||
/// path.
|
||||
fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, String)> {
|
||||
let mut out = vec![];
|
||||
for at in words(m, b"cfg_attr", from, to) {
|
||||
if !m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")) {
|
||||
continue;
|
||||
}
|
||||
let open = skip_ws(m, at + "cfg_attr".len());
|
||||
let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue };
|
||||
let text = pred_text(&src[open + 1..close]);
|
||||
let cuts = top_level_at(&text, ",");
|
||||
let Some(&first) = cuts.first() else { continue };
|
||||
let mut start = first + 1;
|
||||
for cut in cuts[1..].iter().copied().chain([text.len()]) {
|
||||
let arg = text.get(start..cut).unwrap_or("");
|
||||
if let Some(rel) = arg.strip_prefix("path=\"").and_then(|r| r.strip_suffix('"')) {
|
||||
out.push((text[..first].to_owned(), rel.to_owned()));
|
||||
}
|
||||
start = cut + 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `rel` joined to the directory `base`, with `.` and `..` resolved.
|
||||
fn join_path(base: &str, rel: &str) -> String {
|
||||
let mut parts: Vec<&str> = base.split('/').filter(|s| !s.is_empty()).collect();
|
||||
@@ -4028,8 +4173,14 @@ fn names_rect(op: &str) -> bool {
|
||||
if b.get(after) == Some(&b'(') {
|
||||
after = matching(b, after).map_or(b.len(), |c| c + 1);
|
||||
}
|
||||
let rest = &op[after..];
|
||||
if rest.is_empty() || RECT_PARTS.iter().any(|p| rest.starts_with(p)) {
|
||||
// The rect and its parts make up the whole operand: `a.width() - b.width()` compares two
|
||||
// rects, not one with a number.
|
||||
let mut rest = &op[after..];
|
||||
while let Some(r) = RECT_PARTS.iter().chain(&[".x", ".y"]).find_map(|p| rest.strip_prefix(p)) {
|
||||
rest = r;
|
||||
}
|
||||
let lead = op[..i].trim_start_matches(['&', '*', '(']);
|
||||
if rest.trim_start_matches(')').is_empty() && !lead.contains(['+', '-', '*', '/', '%', ',']) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -4112,6 +4263,13 @@ mod tests {
|
||||
let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
|
||||
let fixed = "#[test]\nfn t() {\n for expected in CASES {\n assert_eq!(lookup(\"baseline\"), expected);\n }\n}\n";
|
||||
assert_eq!(census(fixed), [], "a lookup of a fixed key is not a round trip of the entry");
|
||||
let cast = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(k as usize), k);\n }\n}\n";
|
||||
assert_eq!(census(cast), [(2, "census")], "a cast of the entry is still the entry");
|
||||
let fixed_cast = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(FIXED as usize), k);\n }\n}\n";
|
||||
assert_eq!(census(fixed_cast), [], "a cast of a fixed key");
|
||||
let field =
|
||||
"#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(lookup(config.k), k);\n assert_eq!(lookup(keys::k), k);\n }\n}\n";
|
||||
assert_eq!(census(field), [], "a field or path named like the binding is a fixed key");
|
||||
let derived = "#[test]\nfn t() {\n for k in Kind::ALL {\n assert_eq!(Kind::from_id(k.id()), Some(k));\n }\n}\n";
|
||||
assert_eq!(census(derived), [(2, "census")]);
|
||||
let successor = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(1 + lookup(k), k);\n }\n}\n";
|
||||
@@ -5660,6 +5818,10 @@ mod tests {
|
||||
assert_eq!(only("mirror", order), [], "positions of two entries in one list");
|
||||
let commented = "#[test]\nfn t() {\n assert_eq!(at(\"B\" /* later entry */), at(\"A\") + 1);\n}\n";
|
||||
assert_eq!(only("mirror", commented), [], "a comment beside a key");
|
||||
let spaced = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at(\"AB\") + 1);\n}\n";
|
||||
assert_eq!(only("mirror", spaced), [], "a space inside a key makes a different entry");
|
||||
let same_key = "#[test]\nfn t() {\n assert_eq!(at(\"A B\"), at( \"A B\" ) + 1);\n}\n";
|
||||
assert_eq!(only("mirror", same_key), [(3, "mirror")], "spaces between tokens do not");
|
||||
let offset =
|
||||
"#[test]\nfn t() {\n assert_eq!(bounds(&s, copies[0]), bounds(&s, id) + dv);\n assert_eq!(board(&s, 3), board(&s, 2) + step);\n}\n";
|
||||
assert_eq!(only("mirror", offset), [], "two objects of one document, one moved from the other");
|
||||
@@ -5678,6 +5840,10 @@ mod tests {
|
||||
assert_eq!(only("fixture-only", fixture), [(2, "fixture-only")]);
|
||||
let result = "#[test]\nfn t() {\n let input = vec![1, 2, 3];\n let out = process(&input);\n assert_eq!(out.len(), 3);\n}\n";
|
||||
assert_eq!(only("fixture-only", result), [], "the result of the code under test");
|
||||
let arm = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(n) => assert_eq!(n, 1),\n None => assert_eq!(n, 0),\n }\n}\n";
|
||||
assert_eq!(only("fixture-only", arm), [], "a match arm binds its own n");
|
||||
let outer = "#[test]\nfn t() {\n let n = 0;\n match compute() {\n Some(m) if m == n => assert_eq!(n, 0),\n _ => assert_eq!(n, 0),\n }\n}\n";
|
||||
assert_eq!(only("fixture-only", outer), [(2, "fixture-only")], "a guard reads the outer n");
|
||||
let changed = "#[test]\nfn t() {\n let mut input = vec![1, 2, 3];\n process(&mut input);\n assert_eq!(input.len(), 3);\n}\n";
|
||||
assert_eq!(only("fixture-only", changed), [], "a mutable local the code changes");
|
||||
let borrowed = "#[test]\nfn t() {\n let input = &mut [3, 1];\n sort(input);\n assert_eq!(*input, [1, 3]);\n}\n";
|
||||
@@ -5921,6 +6087,18 @@ mod tests {
|
||||
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
||||
assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")], "src/tests holds modules, not test targets");
|
||||
assert_eq!(module_parent("crates/x/tests/fonts.rs"), None, "a test target beside src");
|
||||
let files: HashMap<&str, &str> = [
|
||||
("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"../tests/common/mod.rs\"]\nmod common;\n"),
|
||||
("crates/x/tests/smoke.rs", "mod common;\n"),
|
||||
("crates/x/tests/common/mod.rs", ""),
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
||||
let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s)));
|
||||
let shared = "crates/x/tests/common/mod.rs".to_owned();
|
||||
let shared_ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&shared), &read, &overrides), ..self::ctx() };
|
||||
assert_eq!(hits_in(&shared, test, &shared_ctx), [], "a test target beside it loads the shared module on every target");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -5955,6 +6133,45 @@ mod tests {
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_run_follows_a_path_selected_by_cfg_attr() {
|
||||
let files: HashMap<&str, &str> = [
|
||||
("crates/x/src/lib.rs", "#[cfg_attr(unix, path = \"live.rs\")]\nmod platform;\n#[cfg(target_os = \"macos\")]\nmod live;\n"),
|
||||
("crates/x/src/live.rs", ""),
|
||||
("crates/x/src/platform.rs", ""),
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
||||
let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s)));
|
||||
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
||||
let live = "crates/x/src/live.rs".to_owned();
|
||||
let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&live), &read, &overrides), ..ctx() };
|
||||
assert_eq!(hits_in(&live, test, &ctx), [], "Linux loads live.rs through the cfg_attr path");
|
||||
let platform = "crates/x/src/platform.rs".to_owned();
|
||||
let gates = module_gates(std::slice::from_ref(&platform), &read, &overrides);
|
||||
assert_eq!(gates.get(&platform).map(|g| g.preds.clone()), Some(vec!["not(any(unix))".to_owned()]), "the default path elsewhere");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_lines_lists_both_paths_of_an_exact_rename() {
|
||||
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
let root = std::env::temp_dir().join(format!("test-lint-rename-{}-{unique}", std::process::id()));
|
||||
std::fs::create_dir_all(root.join("crates/x/src/bin")).unwrap();
|
||||
git(&root, &["init", "--quiet"]).unwrap();
|
||||
let src = "#[path = \"../shared.rs\"]\nmod shared;\nfn main() {}\n";
|
||||
std::fs::write(root.join("crates/x/src/bin/tool.rs"), src).unwrap();
|
||||
git(&root, &["add", "."]).unwrap();
|
||||
let base = git(&root, &["write-tree"]).unwrap();
|
||||
std::fs::create_dir_all(root.join("crates/x/src/disabled")).unwrap();
|
||||
std::fs::rename(root.join("crates/x/src/bin/tool.rs"), root.join("crates/x/src/disabled/tool.rs")).unwrap();
|
||||
git(&root, &["add", "-A"]).unwrap();
|
||||
let changed = changed_lines(&root, &base).unwrap();
|
||||
assert_eq!(changed.get("crates/x/src/bin/tool.rs"), Some(&None), "the old path counts as deleted");
|
||||
assert_eq!(changed.get("crates/x/src/disabled/tool.rs"), Some(&None), "the new path counts as added");
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_run_joins_inline_and_override_routes() {
|
||||
for (lib, child) in [
|
||||
@@ -6208,6 +6425,8 @@ mod tests {
|
||||
assert_eq!(px("assert!(rect.width() == 120.0);"), [(4, "exact-pixel")]);
|
||||
assert_eq!(px("assert!(panel_rect.contains_rect(button_rect));"), [], "a relationship");
|
||||
assert_eq!(px("assert!(rect.width() >= SPACING);"), []);
|
||||
assert_eq!(px("assert_eq!(left_rect.width() - right_rect.width(), 0.0);"), [], "two rects compared by their difference");
|
||||
assert_eq!(px("assert_eq!(left_rect.width(), 120.0);"), [(4, "exact-pixel")]);
|
||||
assert_eq!(px("assert_eq!(rects.len(), 3);"), [], "a count");
|
||||
assert_eq!(px("assert_eq!(correct, 3);"), [], "a word that only contains rect");
|
||||
assert_eq!(px("assert_eq!(tabs_rect(&app).min.y, 0.0);"), [(4, "exact-pixel")], "a call that returns a rect");
|
||||
@@ -6229,6 +6448,11 @@ mod tests {
|
||||
assert_eq!(only("reads-source", comment), [], "a Rust path only in a comment");
|
||||
let dir = "#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(\"data.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
||||
assert_eq!(only("reads-source", dir), [], "a directory named like a Rust file");
|
||||
let unknown = "#[test]\nfn t() {\n let name = \"data.json\";\n let s = fs::read_to_string(root.join(\"fixtures.rs\").join(name)).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
||||
assert_eq!(only("reads-source", unknown), [], "a final component that is not a literal");
|
||||
let joined =
|
||||
"#[test]\nfn t() {\n let s = fs::read_to_string(root.join(\"src\").join(\"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
||||
assert_eq!(only("reads-source", joined), [(3, "reads-source")], "a final join that names a .rs file");
|
||||
let formatted = "#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"fixtures/{}.txt\", \"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
|
||||
assert_eq!(only("reads-source", formatted), [], "a format argument is not the file read");
|
||||
let format_rs =
|
||||
|
||||
Reference in new issue
Block a user