testing-conventions 0.0.123

Enforce testing conventions in libraries (Python, TypeScript, and Rust).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
//! The unit `colocated-test` check.

use std::collections::{BTreeSet, HashSet};
use std::path::{Path, PathBuf};

use anyhow::{anyhow, Context, Result};
use rustpython_ast::Visitor;
use rustpython_parser::lexer::lex;
use rustpython_parser::{ast, Mode, Parse, Tok};
use syn::visit::{self, Visit};

/// A language whose colocated unit-test convention can be checked.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum Language {
    /// `foo.py` → colocated `foo_test.py`.
    #[value(name = "python")]
    Python,
    /// `foo-bar.ts` → colocated `foo-bar.test.ts`, across `.ts`/`.tsx`/`.mts`/`.cts`;
    /// declaration files (`.d.ts`/`.d.mts`/`.d.cts`) are ignored.
    #[value(name = "typescript")]
    TypeScript,
    /// Rust units are inline `#[cfg(test)]` modules, not separate files, so the
    /// file-pairing walk below does not apply to Rust; its arm of the rule checks
    /// inline-`#[cfg(test)]` *presence* instead ([`missing_inline_tests`]). The
    /// variant is also accepted by the other `--language` rules (e.g. `packaging`).
    #[value(name = "rust")]
    Rust,
}

impl Language {
    /// `true` for a file this language's check tracks (source *or* test).
    pub(crate) fn tracks(self, path: &Path) -> bool {
        match self {
            Language::Python => has_extension(path, &["py"]),
            Language::TypeScript => {
                has_extension(path, &["ts", "tsx", "mts", "cts"]) && !is_declaration(path)
            }
            Language::Rust => false,
        }
    }

    /// `true` when `path` is itself a unit test, never a subject.
    pub(crate) fn is_test(self, path: &Path) -> bool {
        match self {
            Language::Python => stem_of(path).ends_with("_test"),
            Language::TypeScript => {
                let name = file_name_of(path);
                name.ends_with(".test.ts")
                    || name.ends_with(".test.tsx")
                    || name.ends_with(".test.mts")
                    || name.ends_with(".test.cts")
            }
            Language::Rust => false,
        }
    }

    /// `true` when `path` is test *support* — Python's `conftest.py`, never a subject.
    pub(crate) fn is_support(self, path: &Path) -> bool {
        match self {
            Language::Python => file_name_of(path) == "conftest.py",
            Language::TypeScript | Language::Rust => false,
        }
    }

    /// `true` when `source` at `path` holds a function or control flow anywhere in it.
    /// Presence, the commit-scoped co-change check, and mutation all decide subjecthood
    /// here, so none of them can disagree about what has behavior.
    pub(crate) fn is_subject(self, source: &str, path: &Path) -> bool {
        match self {
            Language::Python => python_has_behavior(source),
            Language::TypeScript => crate::ts::has_behavior(source, path),
            Language::Rust => rust_has_behavior(source),
        }
    }

    /// `true` when `base` and `head` — the file at `path` before and after an edit — hold
    /// the same code once comments and formatting whitespace are normalized away. Content
    /// that fails to parse on either side is **not** equal.
    pub(crate) fn same_code(self, base: &str, head: &str, path: &Path) -> bool {
        match self {
            Language::Python => python_same_code(base, head),
            Language::TypeScript => crate::ts::same_code(base, head, path),
            // Unreachable for Rust; `false` keeps any caller that arrives flagged.
            Language::Rust => false,
        }
    }

    /// The colocated test `source` is expected to have.
    pub(crate) fn expected_test_path(self, source: &Path) -> PathBuf {
        match self {
            Language::Python => source.with_file_name(format!("{}_test.py", stem_of(source))),
            Language::TypeScript => {
                source.with_file_name(format!("{}.test.{}", stem_of(source), extension_of(source)))
            }
            // Unreachable for Rust (nothing is tracked); a harmless identity.
            Language::Rust => source.to_path_buf(),
        }
    }
}

/// Every source file under `root` (for `language`) with no colocated unit test, sorted.
/// `exempt` holds the rule's `root`-relative paths resolved from config
/// ([`crate::config::resolve_exempt`]).
pub fn missing_unit_tests(
    root: impl AsRef<Path>,
    language: Language,
    exempt: &BTreeSet<String>,
) -> Result<Vec<PathBuf>> {
    let root = root.as_ref();
    let mut files = Vec::new();
    collect_files(root, language, &mut files)?;
    // `<package root>/tests/` belongs to the suite tiers, so nothing under it is a subject.
    let manifest = match language {
        Language::Python => Some("pyproject.toml"),
        Language::TypeScript => Some("package.json"),
        Language::Rust => None,
    };
    if let Some(tests) = manifest.and_then(|m| crate::tiers::suite_tests_dir(root, m)) {
        files.retain(|file| !file.starts_with(&tests));
    }

    let present: HashSet<&Path> = files.iter().map(PathBuf::as_path).collect();

    let mut orphans: Vec<PathBuf> = Vec::new();
    for source in &files {
        if language.is_test(source) || language.is_support(source) {
            continue;
        }
        if present.contains(language.expected_test_path(source).as_path()) {
            continue;
        }
        // Read only for a file that lacks a twin, so the common case costs no file read.
        let contents = std::fs::read_to_string(source)
            .with_context(|| format!("reading source file `{}`", source.display()))?;
        if !language.is_subject(&contents, source) {
            continue;
        }
        let relative = source
            .strip_prefix(root)
            .unwrap_or(source)
            .to_string_lossy()
            .replace('\\', "/");
        if exempt.contains(&relative) {
            continue;
        }
        orphans.push(source.clone());
    }
    orphans.sort();
    Ok(orphans)
}

/// Recursively collect every file `language` tracks under `dir` into `out`.
pub(crate) fn collect_files(dir: &Path, language: Language, out: &mut Vec<PathBuf>) -> Result<()> {
    let entries =
        std::fs::read_dir(dir).with_context(|| format!("reading directory `{}`", dir.display()))?;
    for entry in entries {
        let path = crate::walk::dir_entry(entry, dir)?.path();
        if path.is_dir() {
            collect_files(&path, language, out)?;
        } else if language.tracks(&path) {
            out.push(path);
        }
    }
    Ok(())
}

/// Every Rust source file under `root` that defines testable behavior — a function with a
/// body, outside any `#[cfg(test)]` module — but carries no inline `#[cfg(test)]` module,
/// sorted. `exempt` holds the rule's `root`-relative paths resolved from config.
pub fn missing_inline_tests(
    root: impl AsRef<Path>,
    exempt: &BTreeSet<String>,
) -> Result<Vec<PathBuf>> {
    let root = root.as_ref();
    let mut files = Vec::new();
    collect_rust_source_files(root, &mut files)?;
    files.sort();

    let mut orphans = Vec::new();
    for file in &files {
        let source = std::fs::read_to_string(file)
            .with_context(|| format!("reading source file `{}`", file.display()))?;
        let ast = syn::parse_file(&source)
            .map_err(|err| anyhow!("parsing `{}`: {err}", file.display()))?;
        let mut visitor = PresenceVisitor::default();
        visitor.visit_file(&ast);
        if !visitor.has_testable_fn || visitor.has_test_module {
            continue;
        }
        let relative = file
            .strip_prefix(root)
            .unwrap_or(file)
            .to_string_lossy()
            .replace('\\', "/");
        if exempt.contains(&relative) {
            continue;
        }
        orphans.push(file.clone());
    }
    // `files` is already sorted, so `orphans` is in order.
    Ok(orphans)
}

/// Recursively collect `*.rs` unit-source files under `dir` into `out`, skipping the
/// non-unit trees — `tests/`, `benches/`, `examples/`, `target/` — and `build.rs`.
pub(crate) fn collect_rust_source_files(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
    let entries =
        std::fs::read_dir(dir).with_context(|| format!("reading directory `{}`", dir.display()))?;
    for entry in entries {
        let path = crate::walk::dir_entry(entry, dir)?.path();
        if path.is_dir() {
            let skip = matches!(
                path.file_name().and_then(|name| name.to_str()),
                Some("tests" | "benches" | "examples" | "target")
            );
            if !skip {
                collect_rust_source_files(&path, out)?;
            }
        } else if has_extension(&path, &["rs"]) && file_name_of(&path) != "build.rs" {
            out.push(path);
        }
    }
    Ok(())
}

/// Answers, for a parsed Rust file, whether it defines testable behavior outside any
/// `#[cfg(test)]` module and whether it carries an inline `#[cfg(test)]` module.
#[derive(Default)]
struct PresenceVisitor {
    test_depth: usize,
    has_testable_fn: bool,
    has_test_module: bool,
}

impl<'ast> Visit<'ast> for PresenceVisitor {
    fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
        let is_test = crate::isolation::has_cfg_test(&node.attrs);
        if is_test {
            self.has_test_module = true;
            self.test_depth += 1;
        }
        visit::visit_item_mod(self, node);
        if is_test {
            self.test_depth -= 1;
        }
    }

    fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
        if self.test_depth == 0
            && !crate::isolation::has_cfg_test(&node.attrs)
            && !is_logic_free_main(node)
        {
            self.has_testable_fn = true;
        }
        visit::visit_item_fn(self, node);
    }

    fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
        if self.test_depth == 0 {
            self.has_testable_fn = true;
        }
        visit::visit_impl_item_fn(self, node);
    }

    fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
        if self.test_depth == 0 && node.default.is_some() {
            self.has_testable_fn = true;
        }
        visit::visit_trait_item_fn(self, node);
    }
}

/// `true` when `node` is a logic-free entry point: `fn main` whose body is one argument-free call
/// and nothing else, as in `fn main() -> ExitCode { mycrate::entrypoint::main() }`.
///
/// Rust requires a `main` in a binary root, so that file cannot be emptied the way a library module
/// can. A `main` of this exact shape holds no decision to test — every one of them, the argv read
/// included, sits behind the call in the library, where a test reaches it — so it counts as a
/// declaration. The shape is deliberately narrow: exactly one statement, and that statement a call
/// through a path taking no arguments. A second statement, an argument, an operator, a `?`, a
/// `match`, a method call — anything that could encode a decision — makes it a subject again.
fn is_logic_free_main(node: &syn::ItemFn) -> bool {
    if node.sig.ident != "main" {
        return false;
    }
    let [syn::Stmt::Expr(syn::Expr::Call(call), _)] = &node.block.stmts[..] else {
        return false;
    };
    call.args.is_empty() && matches!(*call.func, syn::Expr::Path(_))
}

/// `true` when `source` holds an `fn` or a closure anywhere — free function, method, default
/// trait method, or closure expression (a `static`'s `Lazy::new(|| ..)` counts, sitting outside
/// any `fn`). A file that fails to parse is `true`: mutation and colocated-test keep it a subject.
fn rust_has_behavior(source: &str) -> bool {
    let Ok(file) = syn::parse_file(source) else {
        return true;
    };
    let mut visitor = BehaviorPresenceVisitor { found: false };
    visitor.visit_file(&file);
    visitor.found
}

/// Records whether the walk reached any function item or closure.
struct BehaviorPresenceVisitor {
    found: bool,
}

impl<'ast> Visit<'ast> for BehaviorPresenceVisitor {
    fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
        self.found = true;
        visit::visit_item_fn(self, node);
    }

    fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
        self.found = true;
        visit::visit_impl_item_fn(self, node);
    }

    fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
        if node.default.is_some() {
            self.found = true;
        }
        visit::visit_trait_item_fn(self, node);
    }

    fn visit_expr_closure(&mut self, node: &'ast syn::ExprClosure) {
        self.found = true;
        visit::visit_expr_closure(self, node);
    }
}

/// `true` when the file's extension is one of `extensions`.
fn has_extension(path: &Path, extensions: &[&str]) -> bool {
    path.extension()
        .and_then(|ext| ext.to_str())
        .is_some_and(|ext| extensions.contains(&ext))
}

/// `true` for a TypeScript declaration file (`*.d.ts` / `*.d.mts` / `*.d.cts`).
fn is_declaration(path: &Path) -> bool {
    let name = file_name_of(path);
    name.ends_with(".d.ts") || name.ends_with(".d.mts") || name.ends_with(".d.cts")
}

/// `true` when Python `base` and `head` tokenize identically. Comments and blank lines
/// never reach a token — the parser's `full-lexer` feature is off — while `Indent` /
/// `Dedent` do, so re-indenting a statement is a code change.
fn python_same_code(base: &str, head: &str) -> bool {
    match (python_tokens(base), python_tokens(head)) {
        (Some(base), Some(head)) => base == head,
        _ => false,
    }
}

/// `true` when Python `source` holds a function or control flow anywhere in it. A module
/// that fails to parse is `true`: the presence rule keeps a module it couldn't read as a subject.
fn python_has_behavior(source: &str) -> bool {
    let Ok(suite) = ast::Suite::parse(source, "<source>") else {
        return true;
    };
    let mut visitor = BehaviorVisitor { found: false };
    for stmt in suite {
        visitor.visit_stmt(stmt);
    }
    visitor.found
}

/// Records the first function or control-flow node the walk reaches.
struct BehaviorVisitor {
    found: bool,
}

impl Visitor for BehaviorVisitor {
    fn visit_stmt_function_def(&mut self, _: ast::StmtFunctionDef) {
        self.found = true;
    }

    fn visit_stmt_async_function_def(&mut self, _: ast::StmtAsyncFunctionDef) {
        self.found = true;
    }

    fn visit_expr_lambda(&mut self, _: ast::ExprLambda) {
        self.found = true;
    }

    fn visit_stmt_if(&mut self, _: ast::StmtIf) {
        self.found = true;
    }

    fn visit_stmt_for(&mut self, _: ast::StmtFor) {
        self.found = true;
    }

    fn visit_stmt_async_for(&mut self, _: ast::StmtAsyncFor) {
        self.found = true;
    }

    fn visit_stmt_while(&mut self, _: ast::StmtWhile) {
        self.found = true;
    }

    fn visit_stmt_try(&mut self, _: ast::StmtTry) {
        self.found = true;
    }

    fn visit_stmt_try_star(&mut self, _: ast::StmtTryStar) {
        self.found = true;
    }

    fn visit_stmt_with(&mut self, _: ast::StmtWith) {
        self.found = true;
    }

    fn visit_stmt_async_with(&mut self, _: ast::StmtAsyncWith) {
        self.found = true;
    }

    fn visit_stmt_match(&mut self, _: ast::StmtMatch) {
        self.found = true;
    }

    fn visit_expr_if_exp(&mut self, _: ast::ExprIfExp) {
        self.found = true;
    }

    // The generated `generic_visit_comprehension` and `generic_visit_keyword` are no-ops, so
    // a lambda in a comprehension's iterable or a call's keyword argument needs a walk here.
    fn visit_comprehension(&mut self, node: ast::Comprehension) {
        self.found |= !node.ifs.is_empty();
        self.visit_expr(node.iter);
    }

    fn visit_keyword(&mut self, node: ast::Keyword) {
        self.visit_expr(node.value);
    }
}

/// The token stream of Python `source`, or `None` when `source` is not a valid module.
fn python_tokens(source: &str) -> Option<Vec<Tok>> {
    let tokens: Vec<Tok> = lex(source, Mode::Module)
        .map(|token| token.ok().map(|(tok, _)| tok))
        .collect::<Option<_>>()?;
    // The lexer accepts token sequences the grammar rejects (`def f() return 1` lexes
    // cleanly), so the parse decides validity while the tokens carry the comparison.
    ast::Suite::parse(source, "<source>").ok()?;
    Some(tokens)
}

/// The file extension, lossily decoded (empty if there is none).
fn extension_of(path: &Path) -> String {
    path.extension()
        .map(|ext| ext.to_string_lossy().into_owned())
        .unwrap_or_default()
}

/// The file name, lossily decoded.
fn file_name_of(path: &Path) -> String {
    path.file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default()
}

/// The file stem (the name without its extension), lossily decoded.
fn stem_of(path: &Path) -> String {
    path.file_stem()
        .map(|stem| stem.to_string_lossy().into_owned())
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn python_tracks_py_files() {
        assert!(Language::Python.tracks(Path::new("a.py")));
        assert!(Language::Python.tracks(Path::new("pkg/widget.py")));
        assert!(!Language::Python.tracks(Path::new("a.pyi")));
        assert!(!Language::Python.tracks(Path::new("a.txt")));
        assert!(!Language::Python.tracks(Path::new("README")));
    }

    #[test]
    fn python_recognizes_test_files_by_stem_suffix() {
        assert!(Language::Python.is_test(Path::new("widget_test.py")));
        assert!(Language::Python.is_test(Path::new("pkg/helper_test.py")));
        assert!(!Language::Python.is_test(Path::new("widget.py")));
    }

    #[test]
    fn python_conftest_is_support_not_a_subject() {
        assert!(Language::Python.is_support(Path::new("conftest.py")));
        assert!(Language::Python.is_support(Path::new("pkg/conftest.py")));
        assert!(!Language::Python.is_support(Path::new("widget.py")));
        assert!(!Language::Python.is_support(Path::new("widget_test.py")));
        assert!(!Language::TypeScript.is_support(Path::new("conftest.ts")));
    }

    #[test]
    fn python_expected_test_path_is_the_colocated_twin() {
        assert_eq!(
            Language::Python.expected_test_path(Path::new("pkg/widget.py")),
            PathBuf::from("pkg/widget_test.py")
        );
        assert_eq!(
            Language::Python.expected_test_path(Path::new("widget.py")),
            PathBuf::from("widget_test.py")
        );
    }

    #[test]
    fn typescript_tracks_ts_tsx_mts_cts_but_not_declarations() {
        assert!(Language::TypeScript.tracks(Path::new("widget.ts")));
        assert!(Language::TypeScript.tracks(Path::new("pkg/button.tsx")));
        assert!(Language::TypeScript.tracks(Path::new("service.mts")));
        assert!(Language::TypeScript.tracks(Path::new("legacy.cts")));
        assert!(!Language::TypeScript.tracks(Path::new("types.d.ts")));
        assert!(!Language::TypeScript.tracks(Path::new("ambient.d.mts")));
        assert!(!Language::TypeScript.tracks(Path::new("globals.d.cts")));
        assert!(!Language::TypeScript.tracks(Path::new("widget.py")));
        assert!(!Language::TypeScript.tracks(Path::new("README")));
    }

    #[test]
    fn typescript_recognizes_test_files_by_suffix() {
        assert!(Language::TypeScript.is_test(Path::new("widget.test.ts")));
        assert!(Language::TypeScript.is_test(Path::new("pkg/button.test.tsx")));
        assert!(Language::TypeScript.is_test(Path::new("service.test.mts")));
        assert!(Language::TypeScript.is_test(Path::new("legacy.test.cts")));
        assert!(!Language::TypeScript.is_test(Path::new("widget.ts")));
        assert!(!Language::TypeScript.is_test(Path::new("button.tsx")));
        assert!(!Language::TypeScript.is_test(Path::new("service.mts")));
    }

    #[test]
    fn typescript_expected_test_path_keeps_the_extension() {
        assert_eq!(
            Language::TypeScript.expected_test_path(Path::new("pkg/widget.ts")),
            PathBuf::from("pkg/widget.test.ts")
        );
        assert_eq!(
            Language::TypeScript.expected_test_path(Path::new("button.tsx")),
            PathBuf::from("button.test.tsx")
        );
        assert_eq!(
            Language::TypeScript.expected_test_path(Path::new("service.mts")),
            PathBuf::from("service.test.mts")
        );
        assert_eq!(
            Language::TypeScript.expected_test_path(Path::new("legacy.cts")),
            PathBuf::from("legacy.test.cts")
        );
    }

    #[test]
    fn typescript_subject_skips_type_only_modules() {
        let ts = Path::new("aliases.ts");
        assert!(!Language::TypeScript.is_subject("export type Alias = string;\n", ts));
        assert!(!Language::TypeScript.is_subject("export interface Shape { kind: string }\n", ts));
        assert!(!Language::TypeScript.is_subject("import type { A } from './a';\n", ts));
    }

    #[test]
    fn typescript_subject_needs_a_function_or_control_flow() {
        let ts = Path::new("widget.ts");
        assert!(Language::TypeScript.is_subject("export const x = () => 1;\n", ts));
        assert!(Language::TypeScript.is_subject(
            "export type Alias = string;\nexport const x = () => 1;\n",
            ts
        ));
        assert!(!Language::TypeScript.is_subject("export const x = 1;\n", ts));
        assert!(!Language::TypeScript.is_subject("", ts));
        assert!(!Language::TypeScript.is_subject("   \n\t\n", ts));
        assert!(!Language::TypeScript.is_subject("// nothing here\n", ts));
        assert!(!Language::TypeScript.is_subject("/* a\n   block\n   comment */\n", ts));
    }

    fn py_subject(source: &str) -> bool {
        Language::Python.is_subject(source, Path::new("widget.py"))
    }

    #[test]
    fn python_declaration_only_module_is_not_a_subject() {
        assert!(!py_subject("x = 1\n"));
        assert!(!py_subject("Alias = str\n"));
        assert!(!py_subject(
            "\"\"\"pkg.\"\"\"\nfrom ._version import __version__\n__all__ = [\"__version__\"]\n"
        ));
        assert!(!py_subject("class Color(Enum):\n    RED = 1\n"));
        assert!(!py_subject(
            "@dataclass\nclass Point:\n    x: int\n    y: int\n"
        ));
        assert!(!py_subject("logger = getLogger(__name__)\n"));
        assert!(!py_subject("TIMEOUT = 30 * 60\nNAME = f\"{TIMEOUT}s\"\n"));
        assert!(!py_subject("\"\"\"Package docstring.\"\"\"\n"));
        assert!(!py_subject(""));
        assert!(!py_subject("\n   \n"));
        assert!(!py_subject("# just a comment\n   # another\n"));
    }

    #[test]
    fn python_short_circuit_and_a_plain_comprehension_are_not_control_flow() {
        assert!(!py_subject("DEBUG = os.environ.get(\"DEBUG\") or \"0\"\n"));
        assert!(!py_subject("READY = a and b\n"));
        assert!(!py_subject("NAMES = [c.name for c in Color]\n"));
        assert!(!py_subject("BY_NAME = {c.name: c for c in Color}\n"));
    }

    #[test]
    fn python_every_function_form_is_a_subject() {
        assert!(py_subject("def f():\n    return 1\n"));
        assert!(py_subject("async def f():\n    return 1\n"));
        assert!(py_subject("HANDLERS = {\"id\": lambda x: x}\n"));
        assert!(py_subject(
            "class Widget:\n    def run(self):\n        return 1\n"
        ));
        assert!(py_subject(
            "class Runner(Protocol):\n    def run(self) -> int: ...\n"
        ));
    }

    #[test]
    fn python_every_control_flow_form_is_a_subject() {
        assert!(py_subject("if DEBUG:\n    LEVEL = 10\n"));
        assert!(py_subject("for i in range(3):\n    pass\n"));
        assert!(py_subject("async for i in aiter():\n    pass\n"));
        assert!(py_subject("while True:\n    pass\n"));
        assert!(py_subject(
            "try:\n    import x\nexcept ImportError:\n    x = None\n"
        ));
        assert!(py_subject(
            "try:\n    import x\nexcept* ImportError:\n    x = None\n"
        ));
        assert!(py_subject("with open(p) as f:\n    DATA = f.read()\n"));
        assert!(py_subject("async with lock:\n    pass\n"));
        assert!(py_subject("match cmd:\n    case \"go\":\n        pass\n"));
        assert!(py_subject("LEVEL = 10 if DEBUG else 20\n"));
        assert!(py_subject("EVENS = [n for n in range(9) if n % 2 == 0]\n"));
    }

    #[test]
    fn python_control_flow_nested_in_an_expression_is_a_subject() {
        assert!(py_subject("CONFIG = {\"level\": (10 if DEBUG else 20)}\n"));
        assert!(py_subject("run(callback=lambda: None)\n"));
        assert!(py_subject(
            "ORDERED = [x for x in sorted(xs, key=lambda x: x.id)]\n"
        ));
    }

    #[test]
    fn python_unparsable_content_stays_a_subject() {
        assert!(py_subject("def f(:\n"));
    }

    const PY_WIDGET: &str = "def widget():\n    return 1\n";

    #[test]
    fn python_same_code_ignores_comments_and_formatting() {
        let py = Path::new("widget.py");
        assert!(Language::Python.same_code(
            "# widget helpers\ndef widget():\n    return 1\n",
            "# widget utilities\ndef widget():\n    return 1\n",
            py
        ));
        assert!(Language::Python.same_code(
            "# widget helpers\ndef widget():\n    return 1\n",
            PY_WIDGET,
            py
        ));
        assert!(Language::Python.same_code(PY_WIDGET, "def widget():\n\n    return 1\n", py));
        assert!(Language::Python.same_code("def widget():   \n    return 1   \n", PY_WIDGET, py));
    }

    #[test]
    fn python_same_code_sees_every_edit_the_interpreter_sees() {
        let py = Path::new("widget.py");
        assert!(!Language::Python.same_code(PY_WIDGET, "def widget():\n    return 2\n", py));
        assert!(!Language::Python.same_code(
            "\"\"\"Widget helpers.\"\"\"\ndef widget():\n    return 1\n",
            "\"\"\"Widget utilities.\"\"\"\ndef widget():\n    return 1\n",
            py
        ));
        assert!(!Language::Python.same_code(
            "def widget():\n    return \"one\"\n",
            "def widget():\n    return \"two\"\n",
            py
        ));
        assert!(!Language::Python.same_code(
            "def widget(flag):\n    if flag:\n        count = 1\n    return count\n",
            "def widget(flag):\n    if flag:\n        count = 1\n        return count\n",
            py
        ));
    }

    #[test]
    fn python_same_code_holds_unparseable_content_apart() {
        let py = Path::new("widget.py");
        assert!(!Language::Python.same_code(
            "def widget(:\n    return 1\n",
            "# note\ndef widget(:\n    return 1\n",
            py
        ));
        assert!(!Language::Python.same_code(
            "def widget() return 1\n",
            "# note\ndef widget() return 1\n",
            py
        ));
        assert!(!Language::Python.same_code(PY_WIDGET, "def widget() return 1\n", py));
        assert!(!Language::Python.same_code("def widget() return 1\n", PY_WIDGET, py));
    }

    #[test]
    fn typescript_same_code_reads_the_emitted_module() {
        let ts = Path::new("widget.ts");
        assert!(Language::TypeScript.same_code(
            "// widget factory\nexport const widget = () => 1;\n",
            "export const widget = () => 1;\n",
            ts
        ));
        assert!(!Language::TypeScript.same_code(
            "export const widget = () => 1;\n",
            "export const widget = () => 2;\n",
            ts
        ));
    }

    #[test]
    fn rust_same_code_never_answers_equal() {
        assert!(!Language::Rust.same_code("fn f() {}\n", "fn f() {}\n", Path::new("lib.rs")));
    }

    #[test]
    fn rust_has_no_file_based_colocated_convention() {
        assert!(!Language::Rust.tracks(Path::new("lib.rs")));
        assert!(!Language::Rust.is_test(Path::new("lib_test.rs")));
        assert!(Language::Rust.is_subject("fn main() {}\n", Path::new("main.rs")));
        assert_eq!(
            Language::Rust.expected_test_path(Path::new("src/lib.rs")),
            PathBuf::from("src/lib.rs")
        );
    }

    #[test]
    fn rust_const_only_file_is_not_a_subject() {
        assert!(!Language::Rust.is_subject(
            "pub const TIMEOUT: u64 = 30 * 60;\n",
            Path::new("settings.rs")
        ));
    }

    #[test]
    fn rust_unparseable_file_is_a_subject() {
        assert!(Language::Rust.is_subject("fn (", Path::new("broken.rs")));
    }

    #[test]
    fn rust_impl_method_is_a_subject() {
        assert!(Language::Rust.is_subject(
            "struct Widget;\nimpl Widget {\n    fn run(&self) {}\n}\n",
            Path::new("widget.rs")
        ));
    }

    #[test]
    fn rust_default_trait_method_is_a_subject() {
        assert!(Language::Rust.is_subject(
            "trait Greeter {\n    fn greet(&self) {\n        println!(\"hi\");\n    }\n}\n",
            Path::new("greeter.rs")
        ));
    }

    #[test]
    fn rust_trait_method_signature_without_a_default_is_not_a_subject() {
        assert!(!Language::Rust.is_subject(
            "trait Greeter {\n    fn greet(&self);\n}\n",
            Path::new("greeter.rs")
        ));
    }

    #[test]
    fn rust_closure_outside_any_fn_is_a_subject() {
        assert!(Language::Rust.is_subject(
            "static ADDER: fn(i32) -> i32 = |x| x + 1;\n",
            Path::new("adder.rs")
        ));
    }

    /// `(has_testable_fn, has_test_module)` for a Rust source snippet.
    fn presence(src: &str) -> (bool, bool) {
        let ast = syn::parse_file(src).expect("snippet parses");
        let mut visitor = PresenceVisitor::default();
        visitor.visit_file(&ast);
        (visitor.has_testable_fn, visitor.has_test_module)
    }

    #[test]
    fn rust_presence_free_fn_with_test_module_is_covered() {
        assert_eq!(
            presence(
                "pub fn make(n: u8) -> u8 { n + 1 }\n\
                 #[cfg(test)]\nmod tests { #[test] fn t() {} }\n"
            ),
            (true, true)
        );
    }

    #[test]
    fn rust_presence_free_fn_without_test_module_needs_one() {
        assert_eq!(
            presence("pub fn make(n: u8) -> u8 { n + 1 }\n"),
            (true, false)
        );
    }

    #[test]
    fn rust_presence_type_only_file_is_not_a_subject() {
        assert_eq!(presence("pub struct Point { pub x: u8 }\n"), (false, false));
    }

    #[test]
    fn rust_presence_impl_method_is_testable() {
        assert_eq!(
            presence("pub struct W;\nimpl W { pub fn go(&self) -> u8 { 1 } }\n"),
            (true, false)
        );
    }

    #[test]
    fn rust_presence_logic_free_main_is_a_declaration() {
        assert_eq!(
            presence("fn main() -> ExitCode { mycrate::entrypoint::main() }\n"),
            (false, false)
        );
        assert_eq!(presence("fn main() { mycrate::run() }\n"), (false, false));
        // A trailing semicolon is the same single call.
        assert_eq!(presence("fn main() { mycrate::run(); }\n"), (false, false));
    }

    #[test]
    fn rust_presence_a_main_that_could_hold_a_decision_is_a_subject() {
        // An argument is somewhere a decision hides — which args, which order, which default.
        assert_eq!(
            presence("fn main() { mycrate::run(std::env::args_os()) }\n"),
            (true, false)
        );
        // Two statements: the second is unreviewed behavior.
        assert_eq!(
            presence("fn main() { setup(); mycrate::run() }\n"),
            (true, false)
        );
        // `?`, an operator, control flow, and a method call each carry their own branch.
        assert_eq!(presence("fn main() { mycrate::run()? }\n"), (true, false));
        assert_eq!(
            presence("fn main() { mycrate::run().into() }\n"),
            (true, false)
        );
        assert_eq!(
            presence("fn main() { if x { a() } else { b() } }\n"),
            (true, false)
        );
        assert_eq!(presence("fn main() {}\n"), (true, false));
    }

    #[test]
    fn rust_presence_only_main_earns_the_declaration_reading() {
        assert_eq!(presence("fn run() { mycrate::go() }\n"), (true, false));
    }

    #[test]
    fn rust_presence_trait_default_is_testable_but_bare_signature_is_not() {
        assert_eq!(
            presence("pub trait T { fn d(&self) -> u8 { 1 } }\n"),
            (true, false)
        );
        assert_eq!(
            presence("pub trait T { fn s(&self) -> u8; }\n"),
            (false, false)
        );
    }

    #[test]
    fn rust_presence_test_module_functions_are_not_subjects() {
        assert_eq!(
            presence("#[cfg(test)]\nmod tests { fn helper() {} #[test] fn t() {} }\n"),
            (false, true)
        );
    }

    #[test]
    fn rust_presence_cfg_test_gated_free_fn_is_not_a_subject() {
        assert_eq!(
            presence("#[cfg(test)]\nfn only_in_tests() {}\n"),
            (false, false)
        );
    }
}