1use std::collections::BTreeSet;
6use std::path::{Path, PathBuf};
7
8use anyhow::{anyhow, Context, Result};
9use syn::spanned::Spanned;
10use syn::visit::{self, Visit};
11
12pub use crate::violation::Violation;
13
14const RULE_CALL: &str = "no-out-of-module-call";
15const RULE_IMPORT: &str = "no-out-of-module-import";
16const RULE_DOUBLE: &str = "no-first-party-double";
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
20pub enum Language {
21 #[value(name = "rust")]
23 Rust,
24 #[value(name = "typescript")]
27 TypeScript,
28 #[value(name = "python")]
31 Python,
32}
33
34pub fn find_violations(root: impl AsRef<Path>) -> Result<Vec<Violation>> {
38 let root = root.as_ref();
39 let deps = external_deps(root)?;
40
41 let mut files = Vec::new();
42 crate::colocated_test::collect_rust_source_files(root, &mut files)?;
43 files.sort();
44
45 let mut violations = Vec::new();
46 for file in &files {
47 let source = std::fs::read_to_string(file)
48 .with_context(|| format!("reading source file `{}`", file.display()))?;
49 let ast = syn::parse_file(&source)
50 .map_err(|err| anyhow!("parsing `{}`: {err}", file.display()))?;
51 let mut visitor = IsolationVisitor {
52 file,
53 deps: &deps,
54 test_depth: 0,
55 violations: Vec::new(),
56 };
57 visitor.visit_file(&ast);
58 violations.append(&mut visitor.violations);
59 }
60
61 violations.sort_by(|a, b| a.file.cmp(&b.file).then(a.line.cmp(&b.line)));
62 Ok(violations)
63}
64
65pub fn find_integration_violations(root: impl AsRef<Path>) -> Result<Vec<Violation>> {
69 let root = root.as_ref();
70 let first_party = first_party_crates(root)?;
71
72 let mut files = Vec::new();
73 collect_rust_files(root, &mut files)?;
74 files.retain(|file| is_integration_test(root, file));
75 files.sort();
76
77 let mut violations = Vec::new();
78 for file in &files {
79 let source = std::fs::read_to_string(file)
80 .with_context(|| format!("reading source file `{}`", file.display()))?;
81 let ast = syn::parse_file(&source)
82 .map_err(|err| anyhow!("parsing `{}`: {err}", file.display()))?;
83 let mut visitor = DoubleVisitor {
84 file,
85 first_party: &first_party,
86 violations: Vec::new(),
87 };
88 visitor.visit_file(&ast);
89 violations.append(&mut visitor.violations);
90 }
91
92 violations.sort_by(|a, b| a.file.cmp(&b.file).then(a.line.cmp(&b.line)));
93 Ok(violations)
94}
95
96struct DoubleVisitor<'a> {
98 file: &'a Path,
99 first_party: &'a BTreeSet<String>,
100 violations: Vec<Violation>,
101}
102
103impl<'ast> Visit<'ast> for DoubleVisitor<'_> {
104 fn visit_item_use(&mut self, node: &'ast syn::ItemUse) {
105 if has_double_attr(&node.attrs) {
106 let mut imports = Vec::new();
107 flatten_use(&node.tree, &mut Vec::new(), &mut imports);
108 if let Some((segs, is_glob)) = imports.iter().find(|(segs, _)| {
109 segs.first()
110 .is_some_and(|root| self.first_party.contains(root))
111 }) {
112 self.violations.push(Violation {
113 file: self.file.to_path_buf(),
114 line: node.span().start().line,
115 rule: RULE_DOUBLE,
116 message: format!(
117 "integration test doubles first-party `{}` with `#[double]`; \
118 run first-party code for real — only external crates may be doubled",
119 render_use(segs, *is_glob),
120 ),
121 });
122 }
123 }
124 visit::visit_item_use(self, node);
125 }
126}
127
128fn has_double_attr(attrs: &[syn::Attribute]) -> bool {
130 attrs.iter().any(|attr| {
131 attr.path()
132 .segments
133 .last()
134 .is_some_and(|seg| seg.ident == "double")
135 })
136}
137
138fn first_party_crates(root: &Path) -> Result<BTreeSet<String>> {
142 let manifest = root.join("Cargo.toml");
143 let mut set = BTreeSet::new();
144 if !manifest.is_file() {
145 return Ok(set);
146 }
147 let text = std::fs::read_to_string(&manifest)
148 .with_context(|| format!("reading `{}`", manifest.display()))?;
149 let value: toml::Value =
150 toml::from_str(&text).with_context(|| format!("parsing `{}`", manifest.display()))?;
151
152 if let Some(name) = value
153 .get("package")
154 .and_then(|package| package.get("name"))
155 .and_then(toml::Value::as_str)
156 {
157 set.insert(name.replace('-', "_"));
158 }
159 for table_name in ["dependencies", "dev-dependencies"] {
160 if let Some(table) = value.get(table_name).and_then(toml::Value::as_table) {
161 for (name, spec) in table {
162 if spec.as_table().is_some_and(|t| t.contains_key("path")) {
163 set.insert(name.replace('-', "_"));
164 }
165 }
166 }
167 }
168 Ok(set)
169}
170
171fn is_integration_test(root: &Path, file: &Path) -> bool {
175 file.strip_prefix(root)
176 .unwrap_or(file)
177 .components()
178 .any(|component| component.as_os_str() == "tests")
179}
180
181struct IsolationVisitor<'a> {
183 file: &'a Path,
184 deps: &'a BTreeSet<String>,
185 test_depth: usize,
186 violations: Vec<Violation>,
187}
188
189impl<'ast> Visit<'ast> for IsolationVisitor<'_> {
190 fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
191 let is_test = has_cfg_test(&node.attrs);
192 if is_test {
193 self.test_depth += 1;
194 }
195 visit::visit_item_mod(self, node);
196 if is_test {
197 self.test_depth -= 1;
198 }
199 }
200
201 fn visit_expr_call(&mut self, node: &'ast syn::ExprCall) {
202 if self.test_depth > 0 {
203 if let syn::Expr::Path(path_expr) = node.func.as_ref() {
204 if let Some(kind) = classify(&path_expr.path, self.deps) {
205 self.violations.push(Violation {
206 file: self.file.to_path_buf(),
207 line: node.span().start().line,
208 rule: RULE_CALL,
209 message: format!(
210 "unit test calls `{}` out of its own module ({kind}); \
211 inject a trait double — only `super::` is in-module",
212 render_path(&path_expr.path),
213 ),
214 });
215 }
216 }
217 }
218 visit::visit_expr_call(self, node);
219 }
220
221 fn visit_item_use(&mut self, node: &'ast syn::ItemUse) {
222 if self.test_depth > 0 {
223 let mut imports = Vec::new();
224 flatten_use(&node.tree, &mut Vec::new(), &mut imports);
225 for (segs, is_glob) in &imports {
226 if let Some(kind) = classify_use(segs, *is_glob, self.deps) {
227 self.violations.push(Violation {
228 file: self.file.to_path_buf(),
229 line: node.span().start().line,
230 rule: RULE_IMPORT,
231 message: format!(
232 "unit test imports `{}` out of its own module ({kind}); \
233 only `super::` (the unit) and pure `std` belong in a unit test",
234 render_use(segs, *is_glob),
235 ),
236 });
237 }
238 }
239 }
240 visit::visit_item_use(self, node);
241 }
242}
243
244fn classify(path: &syn::Path, deps: &BTreeSet<String>) -> Option<&'static str> {
247 let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
248 match segs.first().map(String::as_str)? {
249 "self" | "Self" => None,
250 "super" => (segs.get(1).map(String::as_str) == Some("super")).then_some("ancestor module"),
251 "crate" => Some("first-party module"),
252 "std" => is_effectful_std(&segs).then_some("effectful std"),
253 "core" | "alloc" => None,
255 other => deps.contains(other).then_some("external crate"),
257 }
258}
259
260fn is_effectful_std(segs: &[String]) -> bool {
264 match segs.get(1).map(String::as_str) {
265 Some("fs" | "net" | "process" | "env" | "thread" | "os") => true,
266 Some("io") => matches!(
267 segs.get(2).map(String::as_str),
268 Some("stdin" | "stdout" | "stderr")
269 ),
270 Some("time") => {
271 matches!(
272 segs.get(2).map(String::as_str),
273 Some("SystemTime" | "Instant")
274 ) && segs.get(3).map(String::as_str) == Some("now")
275 }
276 _ => false,
277 }
278}
279
280fn flatten_use(tree: &syn::UseTree, prefix: &mut Vec<String>, out: &mut Vec<(Vec<String>, bool)>) {
283 match tree {
284 syn::UseTree::Path(path) => {
285 prefix.push(path.ident.to_string());
286 flatten_use(&path.tree, prefix, out);
287 prefix.pop();
288 }
289 syn::UseTree::Name(name) => {
290 let mut full = prefix.clone();
291 full.push(name.ident.to_string());
292 out.push((full, false));
293 }
294 syn::UseTree::Rename(rename) => {
295 let mut full = prefix.clone();
296 full.push(rename.ident.to_string());
297 out.push((full, false));
298 }
299 syn::UseTree::Glob(_) => out.push((prefix.clone(), true)),
300 syn::UseTree::Group(group) => {
301 for item in &group.items {
302 flatten_use(item, prefix, out);
303 }
304 }
305 }
306}
307
308fn classify_use(segs: &[String], is_glob: bool, deps: &BTreeSet<String>) -> Option<&'static str> {
311 match segs.first().map(String::as_str)? {
312 "super" => (segs.get(1).map(String::as_str) == Some("super")).then_some("ancestor module"),
313 "self" | "Self" => None,
314 "crate" => Some("first-party module"),
315 "std" if is_effectful_std(segs) => Some("effectful std"),
316 "std" | "core" | "alloc" => is_glob.then_some("glob import"),
318 other => {
319 if deps.contains(other) {
320 Some("external crate")
321 } else {
322 is_glob.then_some("glob import")
323 }
324 }
325 }
326}
327
328fn render_use(segs: &[String], is_glob: bool) -> String {
330 let mut out = segs.join("::");
331 if is_glob {
332 if !out.is_empty() {
333 out.push_str("::");
334 }
335 out.push('*');
336 }
337 out
338}
339
340fn render_path(path: &syn::Path) -> String {
342 let mut out = String::new();
343 if path.leading_colon.is_some() {
344 out.push_str("::");
345 }
346 for (i, seg) in path.segments.iter().enumerate() {
347 if i > 0 {
348 out.push_str("::");
349 }
350 out.push_str(&seg.ident.to_string());
351 }
352 out
353}
354
355pub(crate) fn has_cfg_test(attrs: &[syn::Attribute]) -> bool {
358 attrs.iter().any(|attr| {
359 attr.path().is_ident("cfg")
360 && attr
361 .meta
362 .require_list()
363 .map(|list| cfg_mentions_test(list.tokens.clone()))
364 .unwrap_or(false)
365 })
366}
367
368fn cfg_mentions_test(tokens: proc_macro2::TokenStream) -> bool {
371 cfg_requires_test(tokens, false)
372}
373
374fn cfg_requires_test(tokens: proc_macro2::TokenStream, negated: bool) -> bool {
377 let mut iter = tokens.into_iter().peekable();
378 while let Some(tt) = iter.next() {
379 match tt {
380 proc_macro2::TokenTree::Ident(id) if id == "not" => {
381 if let Some(proc_macro2::TokenTree::Group(group)) = iter.peek() {
383 let stream = group.stream();
384 iter.next();
385 if cfg_requires_test(stream, !negated) {
386 return true;
387 }
388 }
389 }
390 proc_macro2::TokenTree::Ident(id) => {
391 if !negated && id == "test" {
392 return true;
393 }
394 }
395 proc_macro2::TokenTree::Group(group) if cfg_requires_test(group.stream(), negated) => {
396 return true;
397 }
398 _ => {}
399 }
400 }
401 false
402}
403
404fn external_deps(root: &Path) -> Result<BTreeSet<String>> {
408 let manifest = root.join("Cargo.toml");
409 if !manifest.is_file() {
410 return Ok(BTreeSet::new());
411 }
412 let text = std::fs::read_to_string(&manifest)
413 .with_context(|| format!("reading `{}`", manifest.display()))?;
414 let value: toml::Value =
415 toml::from_str(&text).with_context(|| format!("parsing `{}`", manifest.display()))?;
416 let mut deps = BTreeSet::new();
417 if let Some(table) = value.get("dependencies").and_then(toml::Value::as_table) {
418 for name in table.keys() {
419 deps.insert(name.replace('-', "_"));
420 }
421 }
422 Ok(deps)
423}
424
425fn collect_rust_files(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
426 let entries =
427 std::fs::read_dir(dir).with_context(|| format!("reading directory `{}`", dir.display()))?;
428 for entry in entries {
429 let path = entry
430 .with_context(|| format!("reading an entry under `{}`", dir.display()))?
431 .path();
432 if path.is_dir() {
433 collect_rust_files(&path, out)?;
434 } else if path.extension().and_then(|ext| ext.to_str()) == Some("rs") {
435 out.push(path);
436 }
437 }
438 Ok(())
439}
440
441#[cfg(test)]
442mod tests {
443 use super::*;
444 use std::sync::atomic::{AtomicU64, Ordering};
445
446 fn violations_in(src: &str, deps: &[&str]) -> Vec<Violation> {
448 let ast = syn::parse_file(src).expect("snippet parses");
449 let dep_set: BTreeSet<String> = deps.iter().map(|s| (*s).to_string()).collect();
450 let mut visitor = IsolationVisitor {
451 file: Path::new("snippet.rs"),
452 deps: &dep_set,
453 test_depth: 0,
454 violations: Vec::new(),
455 };
456 visitor.visit_file(&ast);
457 visitor.violations
458 }
459
460 #[test]
461 fn flags_each_out_of_module_form() {
462 let src = "\
463#[cfg(test)]
464mod tests {
465 use super::*;
466 #[test]
467 fn t() {
468 let _ = crate::store::load();
469 let _ = std::fs::read(\"x\");
470 let _ = rand::random::<u8>();
471 let _ = super::super::util::help();
472 }
473}
474";
475 let violations = violations_in(src, &["rand"]);
476 assert_eq!(violations.len(), 4, "got {violations:?}");
477 assert!(violations.iter().all(|v| v.rule == RULE_CALL));
478 }
479
480 #[test]
481 fn allows_in_module_calls() {
482 let src = "\
483#[cfg(test)]
484mod tests {
485 use super::*;
486 use std::io::Cursor;
487 #[test]
488 fn t() {
489 let _ = super::widget();
490 let _ = self::helper();
491 let _ = Cursor::new(b\"x\");
492 let _ = std::collections::HashMap::<u8, u8>::new();
493 assert_eq!(1, 1);
494 }
495}
496";
497 assert!(violations_in(src, &["rand"]).is_empty());
498 }
499
500 #[test]
501 fn ignores_calls_outside_test_modules() {
502 let src = "fn run() { let _ = crate::other::go(); }";
503 assert!(violations_in(src, &[]).is_empty());
504 }
505
506 #[test]
507 fn reports_the_call_line() {
508 let src = "\
510#[cfg(test)]
511mod tests {
512 fn t() {
513 let _ = crate::other::go();
514 }
515}
516";
517 let violations = violations_in(src, &[]);
518 assert_eq!(violations.len(), 1);
519 assert_eq!(violations[0].line, 4);
520 }
521
522 #[test]
523 fn effectful_std_policy() {
524 let segs = |p: &str| p.split("::").map(str::to_string).collect::<Vec<_>>();
525 assert!(is_effectful_std(&segs("std::fs::read")));
526 assert!(is_effectful_std(&segs("std::net::TcpStream::connect")));
527 assert!(is_effectful_std(&segs("std::env::var")));
528 assert!(is_effectful_std(&segs("std::process::exit")));
529 assert!(is_effectful_std(&segs("std::thread::sleep")));
530 assert!(is_effectful_std(&segs("std::time::SystemTime::now")));
531 assert!(is_effectful_std(&segs("std::io::stdout")));
532 assert!(!is_effectful_std(&segs("std::collections::HashMap")));
533 assert!(!is_effectful_std(&segs("std::io::Cursor")));
534 assert!(!is_effectful_std(&segs("std::time::Duration")));
535 assert!(!is_effectful_std(&segs("std::cmp::min")));
536 }
537
538 #[test]
539 fn classify_leading_segment() {
540 let deps: BTreeSet<String> = ["rand"].iter().map(|s| s.to_string()).collect();
541 let path = |s: &str| syn::parse_str::<syn::Path>(s).expect("path parses");
542 assert_eq!(classify(&path("super::foo"), &deps), None);
543 assert_eq!(classify(&path("self::foo"), &deps), None);
544 assert_eq!(classify(&path("Local::new"), &deps), None);
545 assert_eq!(
546 classify(&path("super::super::foo"), &deps),
547 Some("ancestor module")
548 );
549 assert_eq!(
550 classify(&path("crate::a::b"), &deps),
551 Some("first-party module")
552 );
553 assert_eq!(
554 classify(&path("rand::random"), &deps),
555 Some("external crate")
556 );
557 assert_eq!(
558 classify(&path("std::fs::read"), &deps),
559 Some("effectful std")
560 );
561 assert_eq!(classify(&path("std::io::Cursor"), &deps), None);
562 }
563
564 #[test]
565 fn recognizes_cfg_test_attribute() {
566 let module = |s: &str| syn::parse_str::<syn::ItemMod>(s).expect("module parses");
567 assert!(has_cfg_test(&module("#[cfg(test)] mod t {}").attrs));
568 assert!(has_cfg_test(
569 &module("#[cfg(all(test, feature = \"x\"))] mod t {}").attrs
570 ));
571 assert!(!has_cfg_test(
572 &module("#[cfg(feature = \"test\")] mod t {}").attrs
573 ));
574 assert!(!has_cfg_test(&module("mod t {}").attrs));
575 assert!(!has_cfg_test(&module("#[cfg(not(test))] mod t {}").attrs));
576 assert!(!has_cfg_test(
577 &module("#[cfg(all(not(test), unix))] mod t {}").attrs
578 ));
579 assert!(!has_cfg_test(
580 &module("#[cfg(not(all(test, unix)))] mod t {}").attrs
581 ));
582 assert!(has_cfg_test(
583 &module("#[cfg(not(not(test)))] mod t {}").attrs
584 ));
585 }
586
587 #[test]
588 fn flags_each_foreign_import() {
589 let src = "\
590#[cfg(test)]
591mod tests {
592 use super::*;
593 use super::Thing;
594 use crate::other::*;
595 use crate::other::Named;
596 use rand::Rng;
597 use std::fs;
598 use std::collections::HashMap;
599 use std::io::Cursor;
600}
601";
602 let violations = violations_in(src, &["rand"]);
604 assert_eq!(violations.len(), 4, "got {violations:?}");
605 assert!(violations.iter().all(|v| v.rule == RULE_IMPORT));
606 }
607
608 #[test]
609 fn classify_use_roots() {
610 let deps: BTreeSet<String> = ["rand"].iter().map(|s| s.to_string()).collect();
611 let segs = |p: &str| p.split("::").map(str::to_string).collect::<Vec<_>>();
612 assert_eq!(classify_use(&segs("super"), true, &deps), None); assert_eq!(classify_use(&segs("super::Thing"), false, &deps), None);
614 assert_eq!(classify_use(&segs("self::helper"), false, &deps), None);
615 assert_eq!(
616 classify_use(&segs("std::collections::HashMap"), false, &deps),
617 None
618 );
619 assert_eq!(classify_use(&segs("std::io::Cursor"), false, &deps), None);
620 assert_eq!(
621 classify_use(&segs("super::super"), true, &deps),
622 Some("ancestor module")
623 );
624 assert_eq!(
625 classify_use(&segs("crate::other"), true, &deps),
626 Some("first-party module")
627 );
628 assert_eq!(
629 classify_use(&segs("crate::other::Named"), false, &deps),
630 Some("first-party module")
631 );
632 assert_eq!(
633 classify_use(&segs("rand::Rng"), false, &deps),
634 Some("external crate")
635 );
636 assert_eq!(
637 classify_use(&segs("std::fs"), false, &deps),
638 Some("effectful std")
639 );
640 assert_eq!(
641 classify_use(&segs("std::collections"), true, &deps),
642 Some("glob import")
643 );
644 }
645
646 #[test]
647 fn imports_outside_test_modules_are_ignored() {
648 let src = "use crate::other::*; fn run() {}";
649 assert!(violations_in(src, &[]).is_empty());
650 }
651
652 fn integration_violations_in(src: &str, first_party: &[&str]) -> Vec<Violation> {
654 let ast = syn::parse_file(src).expect("snippet parses");
655 let set: BTreeSet<String> = first_party.iter().map(|s| (*s).to_string()).collect();
656 let mut visitor = DoubleVisitor {
657 file: Path::new("integration.rs"),
658 first_party: &set,
659 violations: Vec::new(),
660 };
661 visitor.visit_file(&ast);
662 visitor.violations
663 }
664
665 #[test]
666 fn flags_double_of_first_party_only() {
667 let src = "\
668use mockall_double::double;
669#[double]
670use widget::Renderer;
671#[double]
672use rand::rngs::ThreadRng;
673#[double]
674use crate::support::Helper;
675";
676 let violations = integration_violations_in(src, &["widget"]);
678 assert_eq!(violations.len(), 1, "got {violations:?}");
679 assert_eq!(violations[0].rule, RULE_DOUBLE);
680 }
681
682 #[test]
683 fn ignores_use_without_double() {
684 let src = "use widget::Renderer; fn t() {}";
685 assert!(integration_violations_in(src, &["widget"]).is_empty());
686 }
687
688 #[test]
689 fn recognizes_double_attribute() {
690 let item = |s: &str| syn::parse_str::<syn::ItemUse>(s).expect("use parses");
691 assert!(has_double_attr(&item("#[double] use a::B;").attrs));
692 assert!(has_double_attr(
693 &item("#[mockall_double::double] use a::B;").attrs
694 ));
695 assert!(!has_double_attr(
696 &item("#[allow(unused_imports)] use a::B;").attrs
697 ));
698 assert!(!has_double_attr(&item("use a::B;").attrs));
699 }
700
701 struct TempTree(PathBuf);
702
703 impl TempTree {
704 fn new(files: &[(&str, &str)]) -> Self {
705 static COUNTER: AtomicU64 = AtomicU64::new(0);
706 let root = std::env::temp_dir().join(format!(
707 "tc-isolation-{}-{}",
708 std::process::id(),
709 COUNTER.fetch_add(1, Ordering::Relaxed),
710 ));
711 for (rel, content) in files {
712 let path = root.join(rel);
713 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
714 std::fs::write(path, content).unwrap();
715 }
716 std::fs::create_dir_all(&root).unwrap();
717 TempTree(root)
718 }
719
720 fn path(&self) -> &Path {
721 &self.0
722 }
723 }
724
725 impl Drop for TempTree {
726 fn drop(&mut self) {
727 let _ = std::fs::remove_dir_all(&self.0);
728 }
729 }
730
731 #[test]
732 fn a_tree_without_a_manifest_resolves_to_empty_crate_sets() {
733 let tree = TempTree::new(&[("src/lib.rs", "fn run() {}\n")]);
734 assert!(first_party_crates(tree.path()).unwrap().is_empty());
735 assert!(external_deps(tree.path()).unwrap().is_empty());
736 }
737
738 #[test]
739 fn a_path_dependency_is_first_party_and_a_registry_one_is_not() {
740 let tree = TempTree::new(&[(
741 "Cargo.toml",
742 "[package]\n\
743 name = \"my-crate\"\n\n\
744 [dependencies]\n\
745 sibling-lib = { path = \"../sibling-lib\" }\n\
746 rand = \"0.8\"\n\n\
747 [dev-dependencies]\n\
748 test-support = { path = \"../test-support\" }\n\
749 mockall = \"0.13\"\n",
750 )]);
751
752 let first_party = first_party_crates(tree.path()).unwrap();
753 assert_eq!(
754 first_party,
755 ["my_crate", "sibling_lib", "test_support"]
756 .iter()
757 .map(|s| (*s).to_string())
758 .collect::<BTreeSet<String>>(),
759 "the crate's own name and every path dep, hyphens normalized"
760 );
761
762 let external = external_deps(tree.path()).unwrap();
763 assert_eq!(
764 external,
765 ["rand", "sibling_lib"]
766 .iter()
767 .map(|s| (*s).to_string())
768 .collect::<BTreeSet<String>>(),
769 "`[dependencies]` only — a dev-dependency is test tooling, not a collaborator"
770 );
771 }
772
773 #[test]
774 fn a_call_through_a_non_path_callee_is_left_alone() {
775 let src = "\
776#[cfg(test)]
777mod tests {
778 #[test]
779 fn t() {
780 let _ = (make())(1);
781 }
782}
783";
784 assert!(
785 violations_in(src, &["rand"]).is_empty(),
786 "a callee that is not a path carries no leading segment to classify"
787 );
788 }
789
790 #[test]
791 fn a_renamed_import_is_judged_by_its_source_path() {
792 let src = "\
793#[cfg(test)]
794mod tests {
795 use crate::other::Thing as Local;
796 use super::Widget as W;
797}
798";
799 let violations = violations_in(src, &[]);
800 assert_eq!(violations.len(), 1, "got {violations:?}");
801 assert!(
802 violations[0].message.contains("crate::other::Thing"),
803 "the message names the source path, not the alias: {}",
804 violations[0].message
805 );
806 }
807
808 #[test]
809 fn a_grouped_import_is_flattened_leaf_by_leaf() {
810 let src = "\
811#[cfg(test)]
812mod tests {
813 use crate::other::{Named, deeper::Other};
814 use super::{Widget, helper};
815}
816";
817 let violations = violations_in(src, &[]);
818 assert_eq!(violations.len(), 2, "got {violations:?}");
819 assert!(
820 violations[0].message.contains("crate::other::Named"),
821 "{}",
822 violations[0].message
823 );
824 assert!(
825 violations[1]
826 .message
827 .contains("crate::other::deeper::Other"),
828 "{}",
829 violations[1].message
830 );
831 }
832
833 #[test]
834 fn a_glob_of_an_unresolvable_root_is_still_a_glob_import() {
835 let deps: BTreeSet<String> = ["rand"].iter().map(|s| s.to_string()).collect();
836 let segs = |p: &str| p.split("::").map(str::to_string).collect::<Vec<_>>();
837 assert_eq!(
838 classify_use(&segs("helpers"), true, &deps),
839 Some("glob import"),
840 "a glob is foreign even when `syn` cannot resolve its root"
841 );
842 assert_eq!(
843 classify_use(&segs("helpers::Thing"), false, &deps),
844 None,
845 "a named import of an unresolvable root is the heuristic's documented limit"
846 );
847 }
848
849 #[test]
850 fn a_leading_colon_survives_into_the_message() {
851 let src = "\
852#[cfg(test)]
853mod tests {
854 #[test]
855 fn t() {
856 let _ = ::std::fs::read(\"x\");
857 }
858}
859";
860 let violations = violations_in(src, &[]);
861 assert_eq!(violations.len(), 1, "got {violations:?}");
862 assert!(
863 violations[0].message.contains("`::std::fs::read`"),
864 "{}",
865 violations[0].message
866 );
867 }
868
869 #[test]
870 fn a_bare_cfg_not_is_not_a_test_module() {
871 let module = |s: &str| syn::parse_str::<syn::ItemMod>(s).expect("module parses");
872 assert!(!has_cfg_test(&module("#[cfg(not)] mod t {}").attrs));
873 }
874}