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 and the commit-scoped co-change check both decide subjecthood here, so they
67    /// cannot 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 => false,
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 the file's extension is one of `extensions`.
271fn has_extension(path: &Path, extensions: &[&str]) -> bool {
272    path.extension()
273        .and_then(|ext| ext.to_str())
274        .is_some_and(|ext| extensions.contains(&ext))
275}
276
277/// `true` for a TypeScript declaration file (`*.d.ts` / `*.d.mts` / `*.d.cts`).
278fn is_declaration(path: &Path) -> bool {
279    let name = file_name_of(path);
280    name.ends_with(".d.ts") || name.ends_with(".d.mts") || name.ends_with(".d.cts")
281}
282
283/// `true` when Python `base` and `head` tokenize identically. Comments and blank lines
284/// never reach a token — the parser's `full-lexer` feature is off — while `Indent` /
285/// `Dedent` do, so re-indenting a statement is a code change.
286fn python_same_code(base: &str, head: &str) -> bool {
287    match (python_tokens(base), python_tokens(head)) {
288        (Some(base), Some(head)) => base == head,
289        _ => false,
290    }
291}
292
293/// `true` when Python `source` holds a function or control flow anywhere in it. A module
294/// that fails to parse is `true`: the presence rule keeps a module it couldn't read as a subject.
295fn python_has_behavior(source: &str) -> bool {
296    let Ok(suite) = ast::Suite::parse(source, "<source>") else {
297        return true;
298    };
299    let mut visitor = BehaviorVisitor { found: false };
300    for stmt in suite {
301        visitor.visit_stmt(stmt);
302    }
303    visitor.found
304}
305
306/// Records the first function or control-flow node the walk reaches.
307struct BehaviorVisitor {
308    found: bool,
309}
310
311impl Visitor for BehaviorVisitor {
312    fn visit_stmt_function_def(&mut self, _: ast::StmtFunctionDef) {
313        self.found = true;
314    }
315
316    fn visit_stmt_async_function_def(&mut self, _: ast::StmtAsyncFunctionDef) {
317        self.found = true;
318    }
319
320    fn visit_expr_lambda(&mut self, _: ast::ExprLambda) {
321        self.found = true;
322    }
323
324    fn visit_stmt_if(&mut self, _: ast::StmtIf) {
325        self.found = true;
326    }
327
328    fn visit_stmt_for(&mut self, _: ast::StmtFor) {
329        self.found = true;
330    }
331
332    fn visit_stmt_async_for(&mut self, _: ast::StmtAsyncFor) {
333        self.found = true;
334    }
335
336    fn visit_stmt_while(&mut self, _: ast::StmtWhile) {
337        self.found = true;
338    }
339
340    fn visit_stmt_try(&mut self, _: ast::StmtTry) {
341        self.found = true;
342    }
343
344    fn visit_stmt_try_star(&mut self, _: ast::StmtTryStar) {
345        self.found = true;
346    }
347
348    fn visit_stmt_with(&mut self, _: ast::StmtWith) {
349        self.found = true;
350    }
351
352    fn visit_stmt_async_with(&mut self, _: ast::StmtAsyncWith) {
353        self.found = true;
354    }
355
356    fn visit_stmt_match(&mut self, _: ast::StmtMatch) {
357        self.found = true;
358    }
359
360    fn visit_expr_if_exp(&mut self, _: ast::ExprIfExp) {
361        self.found = true;
362    }
363
364    // The generated `generic_visit_comprehension` and `generic_visit_keyword` are no-ops, so
365    // a lambda in a comprehension's iterable or a call's keyword argument needs a walk here.
366    fn visit_comprehension(&mut self, node: ast::Comprehension) {
367        self.found |= !node.ifs.is_empty();
368        self.visit_expr(node.iter);
369    }
370
371    fn visit_keyword(&mut self, node: ast::Keyword) {
372        self.visit_expr(node.value);
373    }
374}
375
376/// The token stream of Python `source`, or `None` when `source` is not a valid module.
377fn python_tokens(source: &str) -> Option<Vec<Tok>> {
378    let tokens: Vec<Tok> = lex(source, Mode::Module)
379        .map(|token| token.ok().map(|(tok, _)| tok))
380        .collect::<Option<_>>()?;
381    // The lexer accepts token sequences the grammar rejects (`def f() return 1` lexes
382    // cleanly), so the parse decides validity while the tokens carry the comparison.
383    ast::Suite::parse(source, "<source>").ok()?;
384    Some(tokens)
385}
386
387/// The file extension, lossily decoded (empty if there is none).
388fn extension_of(path: &Path) -> String {
389    path.extension()
390        .map(|ext| ext.to_string_lossy().into_owned())
391        .unwrap_or_default()
392}
393
394/// The file name, lossily decoded.
395fn file_name_of(path: &Path) -> String {
396    path.file_name()
397        .map(|name| name.to_string_lossy().into_owned())
398        .unwrap_or_default()
399}
400
401/// The file stem (the name without its extension), lossily decoded.
402fn stem_of(path: &Path) -> String {
403    path.file_stem()
404        .map(|stem| stem.to_string_lossy().into_owned())
405        .unwrap_or_default()
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411
412    #[test]
413    fn python_tracks_py_files() {
414        assert!(Language::Python.tracks(Path::new("a.py")));
415        assert!(Language::Python.tracks(Path::new("pkg/widget.py")));
416        assert!(!Language::Python.tracks(Path::new("a.pyi")));
417        assert!(!Language::Python.tracks(Path::new("a.txt")));
418        assert!(!Language::Python.tracks(Path::new("README")));
419    }
420
421    #[test]
422    fn python_recognizes_test_files_by_stem_suffix() {
423        assert!(Language::Python.is_test(Path::new("widget_test.py")));
424        assert!(Language::Python.is_test(Path::new("pkg/helper_test.py")));
425        assert!(!Language::Python.is_test(Path::new("widget.py")));
426    }
427
428    #[test]
429    fn python_conftest_is_support_not_a_subject() {
430        assert!(Language::Python.is_support(Path::new("conftest.py")));
431        assert!(Language::Python.is_support(Path::new("pkg/conftest.py")));
432        assert!(!Language::Python.is_support(Path::new("widget.py")));
433        assert!(!Language::Python.is_support(Path::new("widget_test.py")));
434        assert!(!Language::TypeScript.is_support(Path::new("conftest.ts")));
435    }
436
437    #[test]
438    fn python_expected_test_path_is_the_colocated_twin() {
439        assert_eq!(
440            Language::Python.expected_test_path(Path::new("pkg/widget.py")),
441            PathBuf::from("pkg/widget_test.py")
442        );
443        assert_eq!(
444            Language::Python.expected_test_path(Path::new("widget.py")),
445            PathBuf::from("widget_test.py")
446        );
447    }
448
449    #[test]
450    fn typescript_tracks_ts_tsx_mts_cts_but_not_declarations() {
451        assert!(Language::TypeScript.tracks(Path::new("widget.ts")));
452        assert!(Language::TypeScript.tracks(Path::new("pkg/button.tsx")));
453        assert!(Language::TypeScript.tracks(Path::new("service.mts")));
454        assert!(Language::TypeScript.tracks(Path::new("legacy.cts")));
455        assert!(!Language::TypeScript.tracks(Path::new("types.d.ts")));
456        assert!(!Language::TypeScript.tracks(Path::new("ambient.d.mts")));
457        assert!(!Language::TypeScript.tracks(Path::new("globals.d.cts")));
458        assert!(!Language::TypeScript.tracks(Path::new("widget.py")));
459        assert!(!Language::TypeScript.tracks(Path::new("README")));
460    }
461
462    #[test]
463    fn typescript_recognizes_test_files_by_suffix() {
464        assert!(Language::TypeScript.is_test(Path::new("widget.test.ts")));
465        assert!(Language::TypeScript.is_test(Path::new("pkg/button.test.tsx")));
466        assert!(Language::TypeScript.is_test(Path::new("service.test.mts")));
467        assert!(Language::TypeScript.is_test(Path::new("legacy.test.cts")));
468        assert!(!Language::TypeScript.is_test(Path::new("widget.ts")));
469        assert!(!Language::TypeScript.is_test(Path::new("button.tsx")));
470        assert!(!Language::TypeScript.is_test(Path::new("service.mts")));
471    }
472
473    #[test]
474    fn typescript_expected_test_path_keeps_the_extension() {
475        assert_eq!(
476            Language::TypeScript.expected_test_path(Path::new("pkg/widget.ts")),
477            PathBuf::from("pkg/widget.test.ts")
478        );
479        assert_eq!(
480            Language::TypeScript.expected_test_path(Path::new("button.tsx")),
481            PathBuf::from("button.test.tsx")
482        );
483        assert_eq!(
484            Language::TypeScript.expected_test_path(Path::new("service.mts")),
485            PathBuf::from("service.test.mts")
486        );
487        assert_eq!(
488            Language::TypeScript.expected_test_path(Path::new("legacy.cts")),
489            PathBuf::from("legacy.test.cts")
490        );
491    }
492
493    #[test]
494    fn typescript_subject_skips_type_only_modules() {
495        let ts = Path::new("aliases.ts");
496        assert!(!Language::TypeScript.is_subject("export type Alias = string;\n", ts));
497        assert!(!Language::TypeScript.is_subject("export interface Shape { kind: string }\n", ts));
498        assert!(!Language::TypeScript.is_subject("import type { A } from './a';\n", ts));
499    }
500
501    #[test]
502    fn typescript_subject_needs_a_function_or_control_flow() {
503        let ts = Path::new("widget.ts");
504        assert!(Language::TypeScript.is_subject("export const x = () => 1;\n", ts));
505        assert!(Language::TypeScript.is_subject(
506            "export type Alias = string;\nexport const x = () => 1;\n",
507            ts
508        ));
509        assert!(!Language::TypeScript.is_subject("export const x = 1;\n", ts));
510        assert!(!Language::TypeScript.is_subject("", ts));
511        assert!(!Language::TypeScript.is_subject("   \n\t\n", ts));
512        assert!(!Language::TypeScript.is_subject("// nothing here\n", ts));
513        assert!(!Language::TypeScript.is_subject("/* a\n   block\n   comment */\n", ts));
514    }
515
516    fn py_subject(source: &str) -> bool {
517        Language::Python.is_subject(source, Path::new("widget.py"))
518    }
519
520    #[test]
521    fn python_declaration_only_module_is_not_a_subject() {
522        assert!(!py_subject("x = 1\n"));
523        assert!(!py_subject("Alias = str\n"));
524        assert!(!py_subject(
525            "\"\"\"pkg.\"\"\"\nfrom ._version import __version__\n__all__ = [\"__version__\"]\n"
526        ));
527        assert!(!py_subject("class Color(Enum):\n    RED = 1\n"));
528        assert!(!py_subject(
529            "@dataclass\nclass Point:\n    x: int\n    y: int\n"
530        ));
531        assert!(!py_subject("logger = getLogger(__name__)\n"));
532        assert!(!py_subject("TIMEOUT = 30 * 60\nNAME = f\"{TIMEOUT}s\"\n"));
533        assert!(!py_subject("\"\"\"Package docstring.\"\"\"\n"));
534        assert!(!py_subject(""));
535        assert!(!py_subject("\n   \n"));
536        assert!(!py_subject("# just a comment\n   # another\n"));
537    }
538
539    #[test]
540    fn python_short_circuit_and_a_plain_comprehension_are_not_control_flow() {
541        assert!(!py_subject("DEBUG = os.environ.get(\"DEBUG\") or \"0\"\n"));
542        assert!(!py_subject("READY = a and b\n"));
543        assert!(!py_subject("NAMES = [c.name for c in Color]\n"));
544        assert!(!py_subject("BY_NAME = {c.name: c for c in Color}\n"));
545    }
546
547    #[test]
548    fn python_every_function_form_is_a_subject() {
549        assert!(py_subject("def f():\n    return 1\n"));
550        assert!(py_subject("async def f():\n    return 1\n"));
551        assert!(py_subject("HANDLERS = {\"id\": lambda x: x}\n"));
552        assert!(py_subject(
553            "class Widget:\n    def run(self):\n        return 1\n"
554        ));
555        assert!(py_subject(
556            "class Runner(Protocol):\n    def run(self) -> int: ...\n"
557        ));
558    }
559
560    #[test]
561    fn python_every_control_flow_form_is_a_subject() {
562        assert!(py_subject("if DEBUG:\n    LEVEL = 10\n"));
563        assert!(py_subject("for i in range(3):\n    pass\n"));
564        assert!(py_subject("async for i in aiter():\n    pass\n"));
565        assert!(py_subject("while True:\n    pass\n"));
566        assert!(py_subject(
567            "try:\n    import x\nexcept ImportError:\n    x = None\n"
568        ));
569        assert!(py_subject(
570            "try:\n    import x\nexcept* ImportError:\n    x = None\n"
571        ));
572        assert!(py_subject("with open(p) as f:\n    DATA = f.read()\n"));
573        assert!(py_subject("async with lock:\n    pass\n"));
574        assert!(py_subject("match cmd:\n    case \"go\":\n        pass\n"));
575        assert!(py_subject("LEVEL = 10 if DEBUG else 20\n"));
576        assert!(py_subject("EVENS = [n for n in range(9) if n % 2 == 0]\n"));
577    }
578
579    #[test]
580    fn python_control_flow_nested_in_an_expression_is_a_subject() {
581        assert!(py_subject("CONFIG = {\"level\": (10 if DEBUG else 20)}\n"));
582        assert!(py_subject("run(callback=lambda: None)\n"));
583        assert!(py_subject(
584            "ORDERED = [x for x in sorted(xs, key=lambda x: x.id)]\n"
585        ));
586    }
587
588    #[test]
589    fn python_unparsable_content_stays_a_subject() {
590        assert!(py_subject("def f(:\n"));
591    }
592
593    const PY_WIDGET: &str = "def widget():\n    return 1\n";
594
595    #[test]
596    fn python_same_code_ignores_comments_and_formatting() {
597        let py = Path::new("widget.py");
598        assert!(Language::Python.same_code(
599            "# widget helpers\ndef widget():\n    return 1\n",
600            "# widget utilities\ndef widget():\n    return 1\n",
601            py
602        ));
603        assert!(Language::Python.same_code(
604            "# widget helpers\ndef widget():\n    return 1\n",
605            PY_WIDGET,
606            py
607        ));
608        assert!(Language::Python.same_code(PY_WIDGET, "def widget():\n\n    return 1\n", py));
609        assert!(Language::Python.same_code("def widget():   \n    return 1   \n", PY_WIDGET, py));
610    }
611
612    #[test]
613    fn python_same_code_sees_every_edit_the_interpreter_sees() {
614        let py = Path::new("widget.py");
615        assert!(!Language::Python.same_code(PY_WIDGET, "def widget():\n    return 2\n", py));
616        assert!(!Language::Python.same_code(
617            "\"\"\"Widget helpers.\"\"\"\ndef widget():\n    return 1\n",
618            "\"\"\"Widget utilities.\"\"\"\ndef widget():\n    return 1\n",
619            py
620        ));
621        assert!(!Language::Python.same_code(
622            "def widget():\n    return \"one\"\n",
623            "def widget():\n    return \"two\"\n",
624            py
625        ));
626        assert!(!Language::Python.same_code(
627            "def widget(flag):\n    if flag:\n        count = 1\n    return count\n",
628            "def widget(flag):\n    if flag:\n        count = 1\n        return count\n",
629            py
630        ));
631    }
632
633    #[test]
634    fn python_same_code_holds_unparseable_content_apart() {
635        let py = Path::new("widget.py");
636        assert!(!Language::Python.same_code(
637            "def widget(:\n    return 1\n",
638            "# note\ndef widget(:\n    return 1\n",
639            py
640        ));
641        assert!(!Language::Python.same_code(
642            "def widget() return 1\n",
643            "# note\ndef widget() return 1\n",
644            py
645        ));
646        assert!(!Language::Python.same_code(PY_WIDGET, "def widget() return 1\n", py));
647        assert!(!Language::Python.same_code("def widget() return 1\n", PY_WIDGET, py));
648    }
649
650    #[test]
651    fn typescript_same_code_reads_the_emitted_module() {
652        let ts = Path::new("widget.ts");
653        assert!(Language::TypeScript.same_code(
654            "// widget factory\nexport const widget = () => 1;\n",
655            "export const widget = () => 1;\n",
656            ts
657        ));
658        assert!(!Language::TypeScript.same_code(
659            "export const widget = () => 1;\n",
660            "export const widget = () => 2;\n",
661            ts
662        ));
663    }
664
665    #[test]
666    fn rust_same_code_never_answers_equal() {
667        assert!(!Language::Rust.same_code("fn f() {}\n", "fn f() {}\n", Path::new("lib.rs")));
668    }
669
670    #[test]
671    fn rust_has_no_file_based_colocated_convention() {
672        assert!(!Language::Rust.tracks(Path::new("lib.rs")));
673        assert!(!Language::Rust.is_test(Path::new("lib_test.rs")));
674        assert!(!Language::Rust.is_subject("fn main() {}\n", Path::new("main.rs")));
675        assert_eq!(
676            Language::Rust.expected_test_path(Path::new("src/lib.rs")),
677            PathBuf::from("src/lib.rs")
678        );
679    }
680
681    /// `(has_testable_fn, has_test_module)` for a Rust source snippet.
682    fn presence(src: &str) -> (bool, bool) {
683        let ast = syn::parse_file(src).expect("snippet parses");
684        let mut visitor = PresenceVisitor::default();
685        visitor.visit_file(&ast);
686        (visitor.has_testable_fn, visitor.has_test_module)
687    }
688
689    #[test]
690    fn rust_presence_free_fn_with_test_module_is_covered() {
691        assert_eq!(
692            presence(
693                "pub fn make(n: u8) -> u8 { n + 1 }\n\
694                 #[cfg(test)]\nmod tests { #[test] fn t() {} }\n"
695            ),
696            (true, true)
697        );
698    }
699
700    #[test]
701    fn rust_presence_free_fn_without_test_module_needs_one() {
702        assert_eq!(
703            presence("pub fn make(n: u8) -> u8 { n + 1 }\n"),
704            (true, false)
705        );
706    }
707
708    #[test]
709    fn rust_presence_type_only_file_is_not_a_subject() {
710        assert_eq!(presence("pub struct Point { pub x: u8 }\n"), (false, false));
711    }
712
713    #[test]
714    fn rust_presence_impl_method_is_testable() {
715        assert_eq!(
716            presence("pub struct W;\nimpl W { pub fn go(&self) -> u8 { 1 } }\n"),
717            (true, false)
718        );
719    }
720
721    #[test]
722    fn rust_presence_trait_default_is_testable_but_bare_signature_is_not() {
723        assert_eq!(
724            presence("pub trait T { fn d(&self) -> u8 { 1 } }\n"),
725            (true, false)
726        );
727        assert_eq!(
728            presence("pub trait T { fn s(&self) -> u8; }\n"),
729            (false, false)
730        );
731    }
732
733    #[test]
734    fn rust_presence_test_module_functions_are_not_subjects() {
735        assert_eq!(
736            presence("#[cfg(test)]\nmod tests { fn helper() {} #[test] fn t() {} }\n"),
737            (false, true)
738        );
739    }
740
741    #[test]
742    fn rust_presence_cfg_test_gated_free_fn_is_not_a_subject() {
743        assert_eq!(
744            presence("#[cfg(test)]\nfn only_in_tests() {}\n"),
745            (false, false)
746        );
747    }
748}