Skip to main content

testing_conventions/
colocated_test.rs

1//! The unit `colocated-test` check.
2
3use std::collections::{BTreeSet, HashSet};
4use std::path::{Path, PathBuf};
5
6use anyhow::{anyhow, Context, Result};
7use rustpython_ast::Visitor;
8use rustpython_parser::lexer::lex;
9use rustpython_parser::{ast, Mode, Parse, Tok};
10use syn::visit::{self, Visit};
11
12/// A language whose colocated unit-test convention can be checked.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
14pub enum Language {
15    /// `foo.py` → colocated `foo_test.py`.
16    #[value(name = "python")]
17    Python,
18    /// `foo-bar.ts` → colocated `foo-bar.test.ts`, across `.ts`/`.tsx`/`.mts`/`.cts`;
19    /// declaration files (`.d.ts`/`.d.mts`/`.d.cts`) are ignored.
20    #[value(name = "typescript")]
21    TypeScript,
22    /// Rust units are inline `#[cfg(test)]` modules, not separate files, so the
23    /// file-pairing walk below does not apply to Rust; its arm of the rule checks
24    /// inline-`#[cfg(test)]` *presence* instead ([`missing_inline_tests`]). The
25    /// variant is also accepted by the other `--language` rules (e.g. `packaging`).
26    #[value(name = "rust")]
27    Rust,
28}
29
30impl Language {
31    /// `true` for a file this language's check tracks (source *or* test).
32    pub(crate) fn tracks(self, path: &Path) -> bool {
33        match self {
34            Language::Python => has_extension(path, &["py"]),
35            Language::TypeScript => {
36                has_extension(path, &["ts", "tsx", "mts", "cts"]) && !is_declaration(path)
37            }
38            Language::Rust => false,
39        }
40    }
41
42    /// `true` when `path` is itself a unit test, never a subject.
43    pub(crate) fn is_test(self, path: &Path) -> bool {
44        match self {
45            Language::Python => stem_of(path).ends_with("_test"),
46            Language::TypeScript => {
47                let name = file_name_of(path);
48                name.ends_with(".test.ts")
49                    || name.ends_with(".test.tsx")
50                    || name.ends_with(".test.mts")
51                    || name.ends_with(".test.cts")
52            }
53            Language::Rust => false,
54        }
55    }
56
57    /// `true` when `path` is test *support* — Python's `conftest.py`, never a subject.
58    pub(crate) fn is_support(self, path: &Path) -> bool {
59        match self {
60            Language::Python => file_name_of(path) == "conftest.py",
61            Language::TypeScript | Language::Rust => false,
62        }
63    }
64
65    /// `true` when `source` at `path` holds a function or control flow anywhere in it.
66    /// Presence, the commit-scoped co-change check, and mutation all decide subjecthood
67    /// here, so none of them can disagree about what has behavior.
68    pub(crate) fn is_subject(self, source: &str, path: &Path) -> bool {
69        match self {
70            Language::Python => python_has_behavior(source),
71            Language::TypeScript => crate::ts::has_behavior(source, path),
72            Language::Rust => rust_has_behavior(source),
73        }
74    }
75
76    /// `true` when `base` and `head` — the file at `path` before and after an edit — hold
77    /// the same code once comments and formatting whitespace are normalized away. Content
78    /// that fails to parse on either side is **not** equal.
79    pub(crate) fn same_code(self, base: &str, head: &str, path: &Path) -> bool {
80        match self {
81            Language::Python => python_same_code(base, head),
82            Language::TypeScript => crate::ts::same_code(base, head, path),
83            // Unreachable for Rust; `false` keeps any caller that arrives flagged.
84            Language::Rust => false,
85        }
86    }
87
88    /// The colocated test `source` is expected to have.
89    pub(crate) fn expected_test_path(self, source: &Path) -> PathBuf {
90        match self {
91            Language::Python => source.with_file_name(format!("{}_test.py", stem_of(source))),
92            Language::TypeScript => {
93                source.with_file_name(format!("{}.test.{}", stem_of(source), extension_of(source)))
94            }
95            // Unreachable for Rust (nothing is tracked); a harmless identity.
96            Language::Rust => source.to_path_buf(),
97        }
98    }
99}
100
101/// Every source file under `root` (for `language`) with no colocated unit test, sorted.
102/// `exempt` holds the rule's `root`-relative paths resolved from config
103/// ([`crate::config::resolve_exempt`]).
104pub fn missing_unit_tests(
105    root: impl AsRef<Path>,
106    language: Language,
107    exempt: &BTreeSet<String>,
108) -> Result<Vec<PathBuf>> {
109    let root = root.as_ref();
110    let mut files = Vec::new();
111    collect_files(root, language, &mut files)?;
112    // `<package root>/tests/` belongs to the suite tiers, so nothing under it is a subject.
113    let manifest = match language {
114        Language::Python => Some("pyproject.toml"),
115        Language::TypeScript => Some("package.json"),
116        Language::Rust => None,
117    };
118    if let Some(tests) = manifest.and_then(|m| crate::tiers::suite_tests_dir(root, m)) {
119        files.retain(|file| !file.starts_with(&tests));
120    }
121
122    let present: HashSet<&Path> = files.iter().map(PathBuf::as_path).collect();
123
124    let mut orphans: Vec<PathBuf> = Vec::new();
125    for source in &files {
126        if language.is_test(source) || language.is_support(source) {
127            continue;
128        }
129        if present.contains(language.expected_test_path(source).as_path()) {
130            continue;
131        }
132        // Read only for a file that lacks a twin, so the common case costs no file read.
133        let contents = std::fs::read_to_string(source)
134            .with_context(|| format!("reading source file `{}`", source.display()))?;
135        if !language.is_subject(&contents, source) {
136            continue;
137        }
138        let relative = source
139            .strip_prefix(root)
140            .unwrap_or(source)
141            .to_string_lossy()
142            .replace('\\', "/");
143        if exempt.contains(&relative) {
144            continue;
145        }
146        orphans.push(source.clone());
147    }
148    orphans.sort();
149    Ok(orphans)
150}
151
152/// Recursively collect every file `language` tracks under `dir` into `out`.
153pub(crate) fn collect_files(dir: &Path, language: Language, out: &mut Vec<PathBuf>) -> Result<()> {
154    let entries =
155        std::fs::read_dir(dir).with_context(|| format!("reading directory `{}`", dir.display()))?;
156    for entry in entries {
157        let path = crate::walk::dir_entry(entry, dir)?.path();
158        if path.is_dir() {
159            collect_files(&path, language, out)?;
160        } else if language.tracks(&path) {
161            out.push(path);
162        }
163    }
164    Ok(())
165}
166
167/// Every Rust source file under `root` that defines testable behavior — a function with a
168/// body, outside any `#[cfg(test)]` module — but carries no inline `#[cfg(test)]` module,
169/// sorted. `exempt` holds the rule's `root`-relative paths resolved from config.
170pub fn missing_inline_tests(
171    root: impl AsRef<Path>,
172    exempt: &BTreeSet<String>,
173) -> Result<Vec<PathBuf>> {
174    let root = root.as_ref();
175    let mut files = Vec::new();
176    collect_rust_source_files(root, &mut files)?;
177    files.sort();
178
179    let mut orphans = Vec::new();
180    for file in &files {
181        let source = std::fs::read_to_string(file)
182            .with_context(|| format!("reading source file `{}`", file.display()))?;
183        let ast = syn::parse_file(&source)
184            .map_err(|err| anyhow!("parsing `{}`: {err}", file.display()))?;
185        let mut visitor = PresenceVisitor::default();
186        visitor.visit_file(&ast);
187        if !visitor.has_testable_fn || visitor.has_test_module {
188            continue;
189        }
190        let relative = file
191            .strip_prefix(root)
192            .unwrap_or(file)
193            .to_string_lossy()
194            .replace('\\', "/");
195        if exempt.contains(&relative) {
196            continue;
197        }
198        orphans.push(file.clone());
199    }
200    // `files` is already sorted, so `orphans` is in order.
201    Ok(orphans)
202}
203
204/// Recursively collect `*.rs` unit-source files under `dir` into `out`, skipping the
205/// non-unit trees — `tests/`, `benches/`, `examples/`, `target/` — and `build.rs`.
206pub(crate) fn collect_rust_source_files(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
207    let entries =
208        std::fs::read_dir(dir).with_context(|| format!("reading directory `{}`", dir.display()))?;
209    for entry in entries {
210        let path = crate::walk::dir_entry(entry, dir)?.path();
211        if path.is_dir() {
212            let skip = matches!(
213                path.file_name().and_then(|name| name.to_str()),
214                Some("tests" | "benches" | "examples" | "target")
215            );
216            if !skip {
217                collect_rust_source_files(&path, out)?;
218            }
219        } else if has_extension(&path, &["rs"]) && file_name_of(&path) != "build.rs" {
220            out.push(path);
221        }
222    }
223    Ok(())
224}
225
226/// Answers, for a parsed Rust file, whether it defines testable behavior outside any
227/// `#[cfg(test)]` module and whether it carries an inline `#[cfg(test)]` module.
228#[derive(Default)]
229struct PresenceVisitor {
230    test_depth: usize,
231    has_testable_fn: bool,
232    has_test_module: bool,
233}
234
235impl<'ast> Visit<'ast> for PresenceVisitor {
236    fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
237        let is_test = crate::isolation::has_cfg_test(&node.attrs);
238        if is_test {
239            self.has_test_module = true;
240            self.test_depth += 1;
241        }
242        visit::visit_item_mod(self, node);
243        if is_test {
244            self.test_depth -= 1;
245        }
246    }
247
248    fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
249        if self.test_depth == 0 && !crate::isolation::has_cfg_test(&node.attrs) {
250            self.has_testable_fn = true;
251        }
252        visit::visit_item_fn(self, node);
253    }
254
255    fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
256        if self.test_depth == 0 {
257            self.has_testable_fn = true;
258        }
259        visit::visit_impl_item_fn(self, node);
260    }
261
262    fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
263        if self.test_depth == 0 && node.default.is_some() {
264            self.has_testable_fn = true;
265        }
266        visit::visit_trait_item_fn(self, node);
267    }
268}
269
270/// `true` when `source` holds an `fn` or a closure anywhere — free function, method, default
271/// trait method, or closure expression (a `static`'s `Lazy::new(|| ..)` counts, sitting outside
272/// any `fn`). A file that fails to parse is `true`: mutation and colocated-test keep it a subject.
273fn rust_has_behavior(source: &str) -> bool {
274    let Ok(file) = syn::parse_file(source) else {
275        return true;
276    };
277    let mut visitor = BehaviorPresenceVisitor { found: false };
278    visitor.visit_file(&file);
279    visitor.found
280}
281
282/// Records whether the walk reached any function item or closure.
283struct BehaviorPresenceVisitor {
284    found: bool,
285}
286
287impl<'ast> Visit<'ast> for BehaviorPresenceVisitor {
288    fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
289        self.found = true;
290        visit::visit_item_fn(self, node);
291    }
292
293    fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
294        self.found = true;
295        visit::visit_impl_item_fn(self, node);
296    }
297
298    fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
299        if node.default.is_some() {
300            self.found = true;
301        }
302        visit::visit_trait_item_fn(self, node);
303    }
304
305    fn visit_expr_closure(&mut self, node: &'ast syn::ExprClosure) {
306        self.found = true;
307        visit::visit_expr_closure(self, node);
308    }
309}
310
311/// `true` when the file's extension is one of `extensions`.
312fn has_extension(path: &Path, extensions: &[&str]) -> bool {
313    path.extension()
314        .and_then(|ext| ext.to_str())
315        .is_some_and(|ext| extensions.contains(&ext))
316}
317
318/// `true` for a TypeScript declaration file (`*.d.ts` / `*.d.mts` / `*.d.cts`).
319fn is_declaration(path: &Path) -> bool {
320    let name = file_name_of(path);
321    name.ends_with(".d.ts") || name.ends_with(".d.mts") || name.ends_with(".d.cts")
322}
323
324/// `true` when Python `base` and `head` tokenize identically. Comments and blank lines
325/// never reach a token — the parser's `full-lexer` feature is off — while `Indent` /
326/// `Dedent` do, so re-indenting a statement is a code change.
327fn python_same_code(base: &str, head: &str) -> bool {
328    match (python_tokens(base), python_tokens(head)) {
329        (Some(base), Some(head)) => base == head,
330        _ => false,
331    }
332}
333
334/// `true` when Python `source` holds a function or control flow anywhere in it. A module
335/// that fails to parse is `true`: the presence rule keeps a module it couldn't read as a subject.
336fn python_has_behavior(source: &str) -> bool {
337    let Ok(suite) = ast::Suite::parse(source, "<source>") else {
338        return true;
339    };
340    let mut visitor = BehaviorVisitor { found: false };
341    for stmt in suite {
342        visitor.visit_stmt(stmt);
343    }
344    visitor.found
345}
346
347/// Records the first function or control-flow node the walk reaches.
348struct BehaviorVisitor {
349    found: bool,
350}
351
352impl Visitor for BehaviorVisitor {
353    fn visit_stmt_function_def(&mut self, _: ast::StmtFunctionDef) {
354        self.found = true;
355    }
356
357    fn visit_stmt_async_function_def(&mut self, _: ast::StmtAsyncFunctionDef) {
358        self.found = true;
359    }
360
361    fn visit_expr_lambda(&mut self, _: ast::ExprLambda) {
362        self.found = true;
363    }
364
365    fn visit_stmt_if(&mut self, _: ast::StmtIf) {
366        self.found = true;
367    }
368
369    fn visit_stmt_for(&mut self, _: ast::StmtFor) {
370        self.found = true;
371    }
372
373    fn visit_stmt_async_for(&mut self, _: ast::StmtAsyncFor) {
374        self.found = true;
375    }
376
377    fn visit_stmt_while(&mut self, _: ast::StmtWhile) {
378        self.found = true;
379    }
380
381    fn visit_stmt_try(&mut self, _: ast::StmtTry) {
382        self.found = true;
383    }
384
385    fn visit_stmt_try_star(&mut self, _: ast::StmtTryStar) {
386        self.found = true;
387    }
388
389    fn visit_stmt_with(&mut self, _: ast::StmtWith) {
390        self.found = true;
391    }
392
393    fn visit_stmt_async_with(&mut self, _: ast::StmtAsyncWith) {
394        self.found = true;
395    }
396
397    fn visit_stmt_match(&mut self, _: ast::StmtMatch) {
398        self.found = true;
399    }
400
401    fn visit_expr_if_exp(&mut self, _: ast::ExprIfExp) {
402        self.found = true;
403    }
404
405    // The generated `generic_visit_comprehension` and `generic_visit_keyword` are no-ops, so
406    // a lambda in a comprehension's iterable or a call's keyword argument needs a walk here.
407    fn visit_comprehension(&mut self, node: ast::Comprehension) {
408        self.found |= !node.ifs.is_empty();
409        self.visit_expr(node.iter);
410    }
411
412    fn visit_keyword(&mut self, node: ast::Keyword) {
413        self.visit_expr(node.value);
414    }
415}
416
417/// The token stream of Python `source`, or `None` when `source` is not a valid module.
418fn python_tokens(source: &str) -> Option<Vec<Tok>> {
419    let tokens: Vec<Tok> = lex(source, Mode::Module)
420        .map(|token| token.ok().map(|(tok, _)| tok))
421        .collect::<Option<_>>()?;
422    // The lexer accepts token sequences the grammar rejects (`def f() return 1` lexes
423    // cleanly), so the parse decides validity while the tokens carry the comparison.
424    ast::Suite::parse(source, "<source>").ok()?;
425    Some(tokens)
426}
427
428/// The file extension, lossily decoded (empty if there is none).
429fn extension_of(path: &Path) -> String {
430    path.extension()
431        .map(|ext| ext.to_string_lossy().into_owned())
432        .unwrap_or_default()
433}
434
435/// The file name, lossily decoded.
436fn file_name_of(path: &Path) -> String {
437    path.file_name()
438        .map(|name| name.to_string_lossy().into_owned())
439        .unwrap_or_default()
440}
441
442/// The file stem (the name without its extension), lossily decoded.
443fn stem_of(path: &Path) -> String {
444    path.file_stem()
445        .map(|stem| stem.to_string_lossy().into_owned())
446        .unwrap_or_default()
447}
448
449#[cfg(test)]
450mod tests {
451    use super::*;
452
453    #[test]
454    fn python_tracks_py_files() {
455        assert!(Language::Python.tracks(Path::new("a.py")));
456        assert!(Language::Python.tracks(Path::new("pkg/widget.py")));
457        assert!(!Language::Python.tracks(Path::new("a.pyi")));
458        assert!(!Language::Python.tracks(Path::new("a.txt")));
459        assert!(!Language::Python.tracks(Path::new("README")));
460    }
461
462    #[test]
463    fn python_recognizes_test_files_by_stem_suffix() {
464        assert!(Language::Python.is_test(Path::new("widget_test.py")));
465        assert!(Language::Python.is_test(Path::new("pkg/helper_test.py")));
466        assert!(!Language::Python.is_test(Path::new("widget.py")));
467    }
468
469    #[test]
470    fn python_conftest_is_support_not_a_subject() {
471        assert!(Language::Python.is_support(Path::new("conftest.py")));
472        assert!(Language::Python.is_support(Path::new("pkg/conftest.py")));
473        assert!(!Language::Python.is_support(Path::new("widget.py")));
474        assert!(!Language::Python.is_support(Path::new("widget_test.py")));
475        assert!(!Language::TypeScript.is_support(Path::new("conftest.ts")));
476    }
477
478    #[test]
479    fn python_expected_test_path_is_the_colocated_twin() {
480        assert_eq!(
481            Language::Python.expected_test_path(Path::new("pkg/widget.py")),
482            PathBuf::from("pkg/widget_test.py")
483        );
484        assert_eq!(
485            Language::Python.expected_test_path(Path::new("widget.py")),
486            PathBuf::from("widget_test.py")
487        );
488    }
489
490    #[test]
491    fn typescript_tracks_ts_tsx_mts_cts_but_not_declarations() {
492        assert!(Language::TypeScript.tracks(Path::new("widget.ts")));
493        assert!(Language::TypeScript.tracks(Path::new("pkg/button.tsx")));
494        assert!(Language::TypeScript.tracks(Path::new("service.mts")));
495        assert!(Language::TypeScript.tracks(Path::new("legacy.cts")));
496        assert!(!Language::TypeScript.tracks(Path::new("types.d.ts")));
497        assert!(!Language::TypeScript.tracks(Path::new("ambient.d.mts")));
498        assert!(!Language::TypeScript.tracks(Path::new("globals.d.cts")));
499        assert!(!Language::TypeScript.tracks(Path::new("widget.py")));
500        assert!(!Language::TypeScript.tracks(Path::new("README")));
501    }
502
503    #[test]
504    fn typescript_recognizes_test_files_by_suffix() {
505        assert!(Language::TypeScript.is_test(Path::new("widget.test.ts")));
506        assert!(Language::TypeScript.is_test(Path::new("pkg/button.test.tsx")));
507        assert!(Language::TypeScript.is_test(Path::new("service.test.mts")));
508        assert!(Language::TypeScript.is_test(Path::new("legacy.test.cts")));
509        assert!(!Language::TypeScript.is_test(Path::new("widget.ts")));
510        assert!(!Language::TypeScript.is_test(Path::new("button.tsx")));
511        assert!(!Language::TypeScript.is_test(Path::new("service.mts")));
512    }
513
514    #[test]
515    fn typescript_expected_test_path_keeps_the_extension() {
516        assert_eq!(
517            Language::TypeScript.expected_test_path(Path::new("pkg/widget.ts")),
518            PathBuf::from("pkg/widget.test.ts")
519        );
520        assert_eq!(
521            Language::TypeScript.expected_test_path(Path::new("button.tsx")),
522            PathBuf::from("button.test.tsx")
523        );
524        assert_eq!(
525            Language::TypeScript.expected_test_path(Path::new("service.mts")),
526            PathBuf::from("service.test.mts")
527        );
528        assert_eq!(
529            Language::TypeScript.expected_test_path(Path::new("legacy.cts")),
530            PathBuf::from("legacy.test.cts")
531        );
532    }
533
534    #[test]
535    fn typescript_subject_skips_type_only_modules() {
536        let ts = Path::new("aliases.ts");
537        assert!(!Language::TypeScript.is_subject("export type Alias = string;\n", ts));
538        assert!(!Language::TypeScript.is_subject("export interface Shape { kind: string }\n", ts));
539        assert!(!Language::TypeScript.is_subject("import type { A } from './a';\n", ts));
540    }
541
542    #[test]
543    fn typescript_subject_needs_a_function_or_control_flow() {
544        let ts = Path::new("widget.ts");
545        assert!(Language::TypeScript.is_subject("export const x = () => 1;\n", ts));
546        assert!(Language::TypeScript.is_subject(
547            "export type Alias = string;\nexport const x = () => 1;\n",
548            ts
549        ));
550        assert!(!Language::TypeScript.is_subject("export const x = 1;\n", ts));
551        assert!(!Language::TypeScript.is_subject("", ts));
552        assert!(!Language::TypeScript.is_subject("   \n\t\n", ts));
553        assert!(!Language::TypeScript.is_subject("// nothing here\n", ts));
554        assert!(!Language::TypeScript.is_subject("/* a\n   block\n   comment */\n", ts));
555    }
556
557    fn py_subject(source: &str) -> bool {
558        Language::Python.is_subject(source, Path::new("widget.py"))
559    }
560
561    #[test]
562    fn python_declaration_only_module_is_not_a_subject() {
563        assert!(!py_subject("x = 1\n"));
564        assert!(!py_subject("Alias = str\n"));
565        assert!(!py_subject(
566            "\"\"\"pkg.\"\"\"\nfrom ._version import __version__\n__all__ = [\"__version__\"]\n"
567        ));
568        assert!(!py_subject("class Color(Enum):\n    RED = 1\n"));
569        assert!(!py_subject(
570            "@dataclass\nclass Point:\n    x: int\n    y: int\n"
571        ));
572        assert!(!py_subject("logger = getLogger(__name__)\n"));
573        assert!(!py_subject("TIMEOUT = 30 * 60\nNAME = f\"{TIMEOUT}s\"\n"));
574        assert!(!py_subject("\"\"\"Package docstring.\"\"\"\n"));
575        assert!(!py_subject(""));
576        assert!(!py_subject("\n   \n"));
577        assert!(!py_subject("# just a comment\n   # another\n"));
578    }
579
580    #[test]
581    fn python_short_circuit_and_a_plain_comprehension_are_not_control_flow() {
582        assert!(!py_subject("DEBUG = os.environ.get(\"DEBUG\") or \"0\"\n"));
583        assert!(!py_subject("READY = a and b\n"));
584        assert!(!py_subject("NAMES = [c.name for c in Color]\n"));
585        assert!(!py_subject("BY_NAME = {c.name: c for c in Color}\n"));
586    }
587
588    #[test]
589    fn python_every_function_form_is_a_subject() {
590        assert!(py_subject("def f():\n    return 1\n"));
591        assert!(py_subject("async def f():\n    return 1\n"));
592        assert!(py_subject("HANDLERS = {\"id\": lambda x: x}\n"));
593        assert!(py_subject(
594            "class Widget:\n    def run(self):\n        return 1\n"
595        ));
596        assert!(py_subject(
597            "class Runner(Protocol):\n    def run(self) -> int: ...\n"
598        ));
599    }
600
601    #[test]
602    fn python_every_control_flow_form_is_a_subject() {
603        assert!(py_subject("if DEBUG:\n    LEVEL = 10\n"));
604        assert!(py_subject("for i in range(3):\n    pass\n"));
605        assert!(py_subject("async for i in aiter():\n    pass\n"));
606        assert!(py_subject("while True:\n    pass\n"));
607        assert!(py_subject(
608            "try:\n    import x\nexcept ImportError:\n    x = None\n"
609        ));
610        assert!(py_subject(
611            "try:\n    import x\nexcept* ImportError:\n    x = None\n"
612        ));
613        assert!(py_subject("with open(p) as f:\n    DATA = f.read()\n"));
614        assert!(py_subject("async with lock:\n    pass\n"));
615        assert!(py_subject("match cmd:\n    case \"go\":\n        pass\n"));
616        assert!(py_subject("LEVEL = 10 if DEBUG else 20\n"));
617        assert!(py_subject("EVENS = [n for n in range(9) if n % 2 == 0]\n"));
618    }
619
620    #[test]
621    fn python_control_flow_nested_in_an_expression_is_a_subject() {
622        assert!(py_subject("CONFIG = {\"level\": (10 if DEBUG else 20)}\n"));
623        assert!(py_subject("run(callback=lambda: None)\n"));
624        assert!(py_subject(
625            "ORDERED = [x for x in sorted(xs, key=lambda x: x.id)]\n"
626        ));
627    }
628
629    #[test]
630    fn python_unparsable_content_stays_a_subject() {
631        assert!(py_subject("def f(:\n"));
632    }
633
634    const PY_WIDGET: &str = "def widget():\n    return 1\n";
635
636    #[test]
637    fn python_same_code_ignores_comments_and_formatting() {
638        let py = Path::new("widget.py");
639        assert!(Language::Python.same_code(
640            "# widget helpers\ndef widget():\n    return 1\n",
641            "# widget utilities\ndef widget():\n    return 1\n",
642            py
643        ));
644        assert!(Language::Python.same_code(
645            "# widget helpers\ndef widget():\n    return 1\n",
646            PY_WIDGET,
647            py
648        ));
649        assert!(Language::Python.same_code(PY_WIDGET, "def widget():\n\n    return 1\n", py));
650        assert!(Language::Python.same_code("def widget():   \n    return 1   \n", PY_WIDGET, py));
651    }
652
653    #[test]
654    fn python_same_code_sees_every_edit_the_interpreter_sees() {
655        let py = Path::new("widget.py");
656        assert!(!Language::Python.same_code(PY_WIDGET, "def widget():\n    return 2\n", py));
657        assert!(!Language::Python.same_code(
658            "\"\"\"Widget helpers.\"\"\"\ndef widget():\n    return 1\n",
659            "\"\"\"Widget utilities.\"\"\"\ndef widget():\n    return 1\n",
660            py
661        ));
662        assert!(!Language::Python.same_code(
663            "def widget():\n    return \"one\"\n",
664            "def widget():\n    return \"two\"\n",
665            py
666        ));
667        assert!(!Language::Python.same_code(
668            "def widget(flag):\n    if flag:\n        count = 1\n    return count\n",
669            "def widget(flag):\n    if flag:\n        count = 1\n        return count\n",
670            py
671        ));
672    }
673
674    #[test]
675    fn python_same_code_holds_unparseable_content_apart() {
676        let py = Path::new("widget.py");
677        assert!(!Language::Python.same_code(
678            "def widget(:\n    return 1\n",
679            "# note\ndef widget(:\n    return 1\n",
680            py
681        ));
682        assert!(!Language::Python.same_code(
683            "def widget() return 1\n",
684            "# note\ndef widget() return 1\n",
685            py
686        ));
687        assert!(!Language::Python.same_code(PY_WIDGET, "def widget() return 1\n", py));
688        assert!(!Language::Python.same_code("def widget() return 1\n", PY_WIDGET, py));
689    }
690
691    #[test]
692    fn typescript_same_code_reads_the_emitted_module() {
693        let ts = Path::new("widget.ts");
694        assert!(Language::TypeScript.same_code(
695            "// widget factory\nexport const widget = () => 1;\n",
696            "export const widget = () => 1;\n",
697            ts
698        ));
699        assert!(!Language::TypeScript.same_code(
700            "export const widget = () => 1;\n",
701            "export const widget = () => 2;\n",
702            ts
703        ));
704    }
705
706    #[test]
707    fn rust_same_code_never_answers_equal() {
708        assert!(!Language::Rust.same_code("fn f() {}\n", "fn f() {}\n", Path::new("lib.rs")));
709    }
710
711    #[test]
712    fn rust_has_no_file_based_colocated_convention() {
713        assert!(!Language::Rust.tracks(Path::new("lib.rs")));
714        assert!(!Language::Rust.is_test(Path::new("lib_test.rs")));
715        assert!(Language::Rust.is_subject("fn main() {}\n", Path::new("main.rs")));
716        assert_eq!(
717            Language::Rust.expected_test_path(Path::new("src/lib.rs")),
718            PathBuf::from("src/lib.rs")
719        );
720    }
721
722    #[test]
723    fn rust_const_only_file_is_not_a_subject() {
724        assert!(!Language::Rust.is_subject(
725            "pub const TIMEOUT: u64 = 30 * 60;\n",
726            Path::new("settings.rs")
727        ));
728    }
729
730    #[test]
731    fn rust_unparseable_file_is_a_subject() {
732        assert!(Language::Rust.is_subject("fn (", Path::new("broken.rs")));
733    }
734
735    #[test]
736    fn rust_impl_method_is_a_subject() {
737        assert!(Language::Rust.is_subject(
738            "struct Widget;\nimpl Widget {\n    fn run(&self) {}\n}\n",
739            Path::new("widget.rs")
740        ));
741    }
742
743    #[test]
744    fn rust_default_trait_method_is_a_subject() {
745        assert!(Language::Rust.is_subject(
746            "trait Greeter {\n    fn greet(&self) {\n        println!(\"hi\");\n    }\n}\n",
747            Path::new("greeter.rs")
748        ));
749    }
750
751    #[test]
752    fn rust_trait_method_signature_without_a_default_is_not_a_subject() {
753        assert!(!Language::Rust.is_subject(
754            "trait Greeter {\n    fn greet(&self);\n}\n",
755            Path::new("greeter.rs")
756        ));
757    }
758
759    #[test]
760    fn rust_closure_outside_any_fn_is_a_subject() {
761        assert!(Language::Rust.is_subject(
762            "static ADDER: fn(i32) -> i32 = |x| x + 1;\n",
763            Path::new("adder.rs")
764        ));
765    }
766
767    /// `(has_testable_fn, has_test_module)` for a Rust source snippet.
768    fn presence(src: &str) -> (bool, bool) {
769        let ast = syn::parse_file(src).expect("snippet parses");
770        let mut visitor = PresenceVisitor::default();
771        visitor.visit_file(&ast);
772        (visitor.has_testable_fn, visitor.has_test_module)
773    }
774
775    #[test]
776    fn rust_presence_free_fn_with_test_module_is_covered() {
777        assert_eq!(
778            presence(
779                "pub fn make(n: u8) -> u8 { n + 1 }\n\
780                 #[cfg(test)]\nmod tests { #[test] fn t() {} }\n"
781            ),
782            (true, true)
783        );
784    }
785
786    #[test]
787    fn rust_presence_free_fn_without_test_module_needs_one() {
788        assert_eq!(
789            presence("pub fn make(n: u8) -> u8 { n + 1 }\n"),
790            (true, false)
791        );
792    }
793
794    #[test]
795    fn rust_presence_type_only_file_is_not_a_subject() {
796        assert_eq!(presence("pub struct Point { pub x: u8 }\n"), (false, false));
797    }
798
799    #[test]
800    fn rust_presence_impl_method_is_testable() {
801        assert_eq!(
802            presence("pub struct W;\nimpl W { pub fn go(&self) -> u8 { 1 } }\n"),
803            (true, false)
804        );
805    }
806
807    #[test]
808    fn rust_presence_trait_default_is_testable_but_bare_signature_is_not() {
809        assert_eq!(
810            presence("pub trait T { fn d(&self) -> u8 { 1 } }\n"),
811            (true, false)
812        );
813        assert_eq!(
814            presence("pub trait T { fn s(&self) -> u8; }\n"),
815            (false, false)
816        );
817    }
818
819    #[test]
820    fn rust_presence_test_module_functions_are_not_subjects() {
821        assert_eq!(
822            presence("#[cfg(test)]\nmod tests { fn helper() {} #[test] fn t() {} }\n"),
823            (false, true)
824        );
825    }
826
827    #[test]
828    fn rust_presence_cfg_test_gated_free_fn_is_not_a_subject() {
829        assert_eq!(
830            presence("#[cfg(test)]\nfn only_in_tests() {}\n"),
831            (false, false)
832        );
833    }
834}