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
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
//! Rust unit-isolation lint: an inline `#[cfg(test)] mod` may call and import only into the
//! unit under test, its parent module reached via `super::`. The AST walk is the deterministic
//! `syn` heuristic; its design and precision limits live in `internals/rust/isolation.md`.

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

use anyhow::{anyhow, Context, Result};
use syn::spanned::Spanned;
use syn::visit::{self, Visit};

pub use crate::violation::Violation;

const RULE_CALL: &str = "no-out-of-module-call";
const RULE_IMPORT: &str = "no-out-of-module-import";
const RULE_DOUBLE: &str = "no-first-party-double";

/// The `unit lint` language selector.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum Language {
    /// Inline `#[cfg(test)]` modules in `*.rs` files (`no-out-of-module-call`).
    #[value(name = "rust")]
    Rust,
    /// `*.test.{ts,tsx,mts,cts}` unit tests (`unmocked-collaborator`);
    /// the detector lives in [`crate::ts`].
    #[value(name = "typescript")]
    TypeScript,
    /// `*_test.py` / `test_*.py` colocated unit tests (`unmocked-collaborator`);
    /// the detector lives in [`crate::lint`].
    #[value(name = "python")]
    Python,
}

/// Every isolation violation in the unit source under crate root `root`, sorted by
/// `(file, line)`. `root`'s `Cargo.toml` names the external crates. `tests/`, `benches/`,
/// `examples/`, and `target/` are not unit source, so a local build changes no result.
pub fn find_violations(root: impl AsRef<Path>) -> Result<Vec<Violation>> {
    let root = root.as_ref();
    let deps = external_deps(root)?;

    let mut files = Vec::new();
    crate::colocated_test::collect_rust_source_files(root, &mut files)?;
    files.sort();

    let mut violations = 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 = IsolationVisitor {
            file,
            deps: &deps,
            test_depth: 0,
            violations: Vec::new(),
        };
        visitor.visit_file(&ast);
        violations.append(&mut visitor.violations);
    }

    violations.sort_by(|a, b| a.file.cmp(&b.file).then(a.line.cmp(&b.line)));
    Ok(violations)
}

/// Every `no-first-party-double` violation in the `tests/` crates under crate root `root`.
/// An integration test runs first-party code for real, so doubling it is the error;
/// doubling an external crate is fine.
pub fn find_integration_violations(root: impl AsRef<Path>) -> Result<Vec<Violation>> {
    let root = root.as_ref();
    let first_party = first_party_crates(root)?;

    let mut files = Vec::new();
    collect_rust_files(root, &mut files)?;
    files.retain(|file| is_integration_test(root, file));
    files.sort();

    let mut violations = 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 = DoubleVisitor {
            file,
            first_party: &first_party,
            violations: Vec::new(),
        };
        visitor.visit_file(&ast);
        violations.append(&mut visitor.violations);
    }

    violations.sort_by(|a, b| a.file.cmp(&b.file).then(a.line.cmp(&b.line)));
    Ok(violations)
}

/// Walks one integration-test file, flagging a `#[double]` of a first-party crate.
struct DoubleVisitor<'a> {
    file: &'a Path,
    first_party: &'a BTreeSet<String>,
    violations: Vec<Violation>,
}

impl<'ast> Visit<'ast> for DoubleVisitor<'_> {
    fn visit_item_use(&mut self, node: &'ast syn::ItemUse) {
        if has_double_attr(&node.attrs) {
            let mut imports = Vec::new();
            flatten_use(&node.tree, &mut Vec::new(), &mut imports);
            if let Some((segs, is_glob)) = imports.iter().find(|(segs, _)| {
                segs.first()
                    .is_some_and(|root| self.first_party.contains(root))
            }) {
                self.violations.push(Violation {
                    file: self.file.to_path_buf(),
                    line: node.span().start().line,
                    rule: RULE_DOUBLE,
                    message: format!(
                        "integration test doubles first-party `{}` with `#[double]`; \
                         run first-party code for real — only external crates may be doubled",
                        render_use(segs, *is_glob),
                    ),
                });
            }
        }
        visit::visit_item_use(self, node);
    }
}

/// `true` for a `#[double]` / `#[mockall_double::double]` attribute.
fn has_double_attr(attrs: &[syn::Attribute]) -> bool {
    attrs.iter().any(|attr| {
        attr.path()
            .segments
            .last()
            .is_some_and(|seg| seg.ident == "double")
    })
}

/// The crate's own `[package].name` plus every `path` dependency, hyphens normalized to
/// underscores. A `tests/` crate names the library under test by crate name rather than
/// `crate::`, so the name is what a `#[double]` import is matched against.
fn first_party_crates(root: &Path) -> Result<BTreeSet<String>> {
    let manifest = root.join("Cargo.toml");
    let mut set = BTreeSet::new();
    if !manifest.is_file() {
        return Ok(set);
    }
    let text = std::fs::read_to_string(&manifest)
        .with_context(|| format!("reading `{}`", manifest.display()))?;
    let value: toml::Value =
        toml::from_str(&text).with_context(|| format!("parsing `{}`", manifest.display()))?;

    if let Some(name) = value
        .get("package")
        .and_then(|package| package.get("name"))
        .and_then(toml::Value::as_str)
    {
        set.insert(name.replace('-', "_"));
    }
    for table_name in ["dependencies", "dev-dependencies"] {
        if let Some(table) = value.get(table_name).and_then(toml::Value::as_table) {
            for (name, spec) in table {
                if spec.as_table().is_some_and(|t| t.contains_key("path")) {
                    set.insert(name.replace('-', "_"));
                }
            }
        }
    }
    Ok(set)
}

/// `true` when `file` (under `root`) is a Rust integration test — a `*.rs` file with a
/// `tests` component. An inline `#[cfg(test)]` unit test doubles its collaborators by
/// design; only a `tests/` crate runs first-party code for real.
fn is_integration_test(root: &Path, file: &Path) -> bool {
    file.strip_prefix(root)
        .unwrap_or(file)
        .components()
        .any(|component| component.as_os_str() == "tests")
}

/// Walks one parsed file, flagging out-of-module calls inside `#[cfg(test)]` modules.
struct IsolationVisitor<'a> {
    file: &'a Path,
    deps: &'a BTreeSet<String>,
    test_depth: usize,
    violations: Vec<Violation>,
}

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

    fn visit_expr_call(&mut self, node: &'ast syn::ExprCall) {
        if self.test_depth > 0 {
            if let syn::Expr::Path(path_expr) = node.func.as_ref() {
                if let Some(kind) = classify(&path_expr.path, self.deps) {
                    self.violations.push(Violation {
                        file: self.file.to_path_buf(),
                        line: node.span().start().line,
                        rule: RULE_CALL,
                        message: format!(
                            "unit test calls `{}` out of its own module ({kind}); \
                             inject a trait double — only `super::` is in-module",
                            render_path(&path_expr.path),
                        ),
                    });
                }
            }
        }
        visit::visit_expr_call(self, node);
    }

    fn visit_item_use(&mut self, node: &'ast syn::ItemUse) {
        if self.test_depth > 0 {
            let mut imports = Vec::new();
            flatten_use(&node.tree, &mut Vec::new(), &mut imports);
            for (segs, is_glob) in &imports {
                if let Some(kind) = classify_use(segs, *is_glob, self.deps) {
                    self.violations.push(Violation {
                        file: self.file.to_path_buf(),
                        line: node.span().start().line,
                        rule: RULE_IMPORT,
                        message: format!(
                            "unit test imports `{}` out of its own module ({kind}); \
                             only `super::` (the unit) and pure `std` belong in a unit test",
                            render_use(segs, *is_glob),
                        ),
                    });
                }
            }
        }
        visit::visit_item_use(self, node);
    }
}

/// Why a call's leading path is out-of-module, or `None` when it stays in-module or is
/// unresolvable — an unresolvable path is not flagged, the `syn` heuristic's known limit.
fn classify(path: &syn::Path, deps: &BTreeSet<String>) -> Option<&'static str> {
    let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
    match segs.first().map(String::as_str)? {
        "self" | "Self" => None,
        "super" => (segs.get(1).map(String::as_str) == Some("super")).then_some("ancestor module"),
        "crate" => Some("first-party module"),
        "std" => is_effectful_std(&segs).then_some("effectful std"),
        // `core`/`alloc` carry no effectful APIs.
        "core" | "alloc" => None,
        // A local type or fn, including one imported by `super::*`, is in-module.
        other => deps.contains(other).then_some("external crate"),
    }
}

/// `true` for an effectful `std` path — net, process, env, threads, OS, the clock, or
/// real-handle I/O. Pure `std` stays in-module: `internals/rust/testing.md` makes
/// `io::Cursor` the idiomatic in-memory unit-test tool.
///
/// `fs` is the deliberate carve-out. Rust privacy makes the inline `#[cfg(test)]` module the
/// only tier that can reach a private item, so a private path-walker can be tested nowhere
/// else — and its argument is a directory that has to exist. `env::temp_dir` rides along
/// because it only names a writable directory; the rest of `env` reads ambient state the test
/// never created, which is the collaborator this rule exists to catch.
fn is_effectful_std(segs: &[String]) -> bool {
    match segs.get(1).map(String::as_str) {
        Some("net" | "process" | "thread" | "os") => true,
        Some("env") => segs.get(2).map(String::as_str) != Some("temp_dir"),
        Some("io") => matches!(
            segs.get(2).map(String::as_str),
            Some("stdin" | "stdout" | "stderr")
        ),
        Some("time") => {
            matches!(
                segs.get(2).map(String::as_str),
                Some("SystemTime" | "Instant")
            ) && segs.get(3).map(String::as_str) == Some("now")
        }
        _ => false,
    }
}

/// Flatten a `use` tree into `(path, is_glob)` leaves: `use a::{b, c::*}` yields
/// `([a, b], false)` and `([a, c], true)`. A rename is judged by its source path.
fn flatten_use(tree: &syn::UseTree, prefix: &mut Vec<String>, out: &mut Vec<(Vec<String>, bool)>) {
    match tree {
        syn::UseTree::Path(path) => {
            prefix.push(path.ident.to_string());
            flatten_use(&path.tree, prefix, out);
            prefix.pop();
        }
        syn::UseTree::Name(name) => {
            let mut full = prefix.clone();
            full.push(name.ident.to_string());
            out.push((full, false));
        }
        syn::UseTree::Rename(rename) => {
            let mut full = prefix.clone();
            full.push(rename.ident.to_string());
            out.push((full, false));
        }
        syn::UseTree::Glob(_) => out.push((prefix.clone(), true)),
        syn::UseTree::Group(group) => {
            for item in &group.items {
                flatten_use(item, prefix, out);
            }
        }
    }
}

/// Why a `use` reaches out of the test's own module, or `None` when it stays in-module.
/// The one legal glob is `super::*`; a named import is judged by its root like a call.
fn classify_use(segs: &[String], is_glob: bool, deps: &BTreeSet<String>) -> Option<&'static str> {
    match segs.first().map(String::as_str)? {
        "super" => (segs.get(1).map(String::as_str) == Some("super")).then_some("ancestor module"),
        "self" | "Self" => None,
        "crate" => Some("first-party module"),
        "std" if is_effectful_std(segs) => Some("effectful std"),
        // A glob of anything but `super` is foreign, even for pure `std`.
        "std" | "core" | "alloc" => is_glob.then_some("glob import"),
        other => {
            if deps.contains(other) {
                Some("external crate")
            } else {
                is_glob.then_some("glob import")
            }
        }
    }
}

/// Render a flattened import for the message: `a::b`, or `a::b::*` for a glob.
fn render_use(segs: &[String], is_glob: bool) -> String {
    let mut out = segs.join("::");
    if is_glob {
        if !out.is_empty() {
            out.push_str("::");
        }
        out.push('*');
    }
    out
}

/// Render a path back to `a::b::c` for the message; generic args are dropped.
fn render_path(path: &syn::Path) -> String {
    let mut out = String::new();
    if path.leading_colon.is_some() {
        out.push_str("::");
    }
    for (i, seg) in path.segments.iter().enumerate() {
        if i > 0 {
            out.push_str("::");
        }
        out.push_str(&seg.ident.to_string());
    }
    out
}

/// `true` when `attrs` carries a `#[cfg(test)]` gate, including `cfg(all(test, …))` and
/// `cfg(any(test, …))` — the signal for an inline unit-test module.
pub(crate) fn has_cfg_test(attrs: &[syn::Attribute]) -> bool {
    attrs.iter().any(|attr| {
        attr.path().is_ident("cfg")
            && attr
                .meta
                .require_list()
                .map(|list| cfg_mentions_test(list.tokens.clone()))
                .unwrap_or(false)
    })
}

/// `true` when a `cfg(...)` predicate positively requires `test`. `#[cfg(not(test))]` gates
/// production code for non-test builds, and a `feature = "test"` string never counts.
fn cfg_mentions_test(tokens: proc_macro2::TokenStream) -> bool {
    cfg_requires_test(tokens, false)
}

/// `true` when a bare `test` ident is reached under an even number of enclosing `not(...)`
/// groups. `negated` flips inside each `not(...)`, so `not(test)` does not qualify.
fn cfg_requires_test(tokens: proc_macro2::TokenStream, negated: bool) -> bool {
    let mut iter = tokens.into_iter().peekable();
    while let Some(tt) = iter.next() {
        match tt {
            proc_macro2::TokenTree::Ident(id) if id == "not" => {
                // `not` applies to the group immediately following it.
                if let Some(proc_macro2::TokenTree::Group(group)) = iter.peek() {
                    let stream = group.stream();
                    iter.next();
                    if cfg_requires_test(stream, !negated) {
                        return true;
                    }
                }
            }
            proc_macro2::TokenTree::Ident(id) => {
                if !negated && id == "test" {
                    return true;
                }
            }
            proc_macro2::TokenTree::Group(group) if cfg_requires_test(group.stream(), negated) => {
                return true;
            }
            _ => {}
        }
    }
    false
}

/// The 1-based lines of the Rust items a `#[cfg(not(test))]` gate keeps out of a test build.
///
/// The unit tier runs `--lib --bins`, which sets `cfg(test)`, so no test reaches those lines.
/// `mutation` drops their mutants — unkillable by construction — and `coverage` drops their
/// regions, which the binary target's test harness instruments as 0-hit. Unparseable source
/// yields no lines, so both checks keep judging what they already judged.
pub(crate) fn lines_hidden_from_tests(source: &str) -> BTreeSet<u32> {
    let Ok(ast) = syn::parse_file(source) else {
        return BTreeSet::new();
    };
    let mut hidden = HiddenItems::default();
    hidden.visit_file(&ast);
    hidden.lines
}

/// Collects the line ranges of gated items. A gated `mod` or `impl` covers everything inside it,
/// so recording the whole span is enough and the walk need not track nesting.
#[derive(Default)]
struct HiddenItems {
    lines: BTreeSet<u32>,
}

impl HiddenItems {
    fn gated(&mut self, attrs: &[syn::Attribute], node: &dyn Spanned) {
        if !has_cfg_not_test(attrs) {
            return;
        }
        let span = node.span();
        self.lines
            .extend(span.start().line as u32..=span.end().line as u32);
    }
}

impl<'ast> Visit<'ast> for HiddenItems {
    fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
        self.gated(&node.attrs, node);
        visit::visit_item_fn(self, node);
    }

    fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
        self.gated(&node.attrs, node);
        visit::visit_item_mod(self, node);
    }

    fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
        self.gated(&node.attrs, node);
        visit::visit_item_impl(self, node);
    }

    fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
        self.gated(&node.attrs, node);
        visit::visit_impl_item_fn(self, node);
    }
}

/// `true` when `attrs` carry a `cfg` gate that no test build can satisfy — `#[cfg(not(test))]`
/// and `#[cfg(all(not(test), unix))]`, but not `#[cfg(any(not(test), unix))]`, which still
/// compiles under `cargo test`.
pub(crate) fn has_cfg_not_test(attrs: &[syn::Attribute]) -> bool {
    attrs.iter().any(|attr| {
        attr.path().is_ident("cfg")
            && attr
                .meta
                .require_list()
                .map(|list| cfg_under_test(list.tokens.clone()) == CfgTruth::False)
                .unwrap_or(false)
    })
}

/// A `cfg(...)` predicate's truth with `test` set and every other condition unknown. Only a
/// definite [`CfgTruth::False`] proves the item is compiled out of a test build.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CfgTruth {
    False,
    True,
    Unknown,
}

/// Evaluate a whole `cfg(...)` predicate list. A `cfg` attribute holds exactly one predicate;
/// anything else is malformed and not ours to judge.
fn cfg_under_test(tokens: proc_macro2::TokenStream) -> CfgTruth {
    match cfg_predicates(tokens).as_slice() {
        [only] => *only,
        _ => CfgTruth::Unknown,
    }
}

/// Evaluate each comma-separated predicate in a `not(…)` / `all(…)` / `any(…)` group.
fn cfg_predicates(tokens: proc_macro2::TokenStream) -> Vec<CfgTruth> {
    let mut out = Vec::new();
    let mut current: Vec<proc_macro2::TokenTree> = Vec::new();
    for tt in tokens {
        match &tt {
            proc_macro2::TokenTree::Punct(punct) if punct.as_char() == ',' => {
                if !current.is_empty() {
                    out.push(cfg_predicate(&current));
                    current.clear();
                }
            }
            _ => current.push(tt),
        }
    }
    if !current.is_empty() {
        out.push(cfg_predicate(&current));
    }
    out
}

/// Evaluate one predicate with `test` set. A bare `test` is true, the three combinators recurse,
/// and everything else — `unix`, `feature = "x"`, an unknown combinator — is
/// [`CfgTruth::Unknown`].
fn cfg_predicate(tokens: &[proc_macro2::TokenTree]) -> CfgTruth {
    use proc_macro2::TokenTree;
    match tokens {
        [TokenTree::Ident(id)] if id == "test" => CfgTruth::True,
        [TokenTree::Ident(id), TokenTree::Group(group)] => {
            let inner = cfg_predicates(group.stream());
            match id.to_string().as_str() {
                // `not` takes exactly one predicate; a malformed `not()` is undecidable, not true.
                "not" => match inner.as_slice() {
                    [only] => cfg_negate(*only),
                    _ => CfgTruth::Unknown,
                },
                "all" => cfg_all(&inner),
                "any" => cfg_any(&inner),
                _ => CfgTruth::Unknown,
            }
        }
        _ => CfgTruth::Unknown,
    }
}

/// `all(…)`: false if any part is false, unknown if any part is unknown. An empty `all()` is true.
fn cfg_all(parts: &[CfgTruth]) -> CfgTruth {
    if parts.contains(&CfgTruth::False) {
        CfgTruth::False
    } else if parts.contains(&CfgTruth::Unknown) {
        CfgTruth::Unknown
    } else {
        CfgTruth::True
    }
}

/// `any(…)`: true if any part is true, unknown if any part is unknown. An empty `any()` is false.
fn cfg_any(parts: &[CfgTruth]) -> CfgTruth {
    if parts.contains(&CfgTruth::True) {
        CfgTruth::True
    } else if parts.contains(&CfgTruth::Unknown) {
        CfgTruth::Unknown
    } else {
        CfgTruth::False
    }
}

/// `not(…)`: an unknown stays unknown, so a gate we cannot decide never drops a mutant.
fn cfg_negate(truth: CfgTruth) -> CfgTruth {
    match truth {
        CfgTruth::False => CfgTruth::True,
        CfgTruth::True => CfgTruth::False,
        CfgTruth::Unknown => CfgTruth::Unknown,
    }
}

/// The crate's `[dependencies]` names, hyphens normalized to underscores — the external
/// crates whose calls are out-of-module. `[dev-dependencies]` are excluded: a unit test
/// uses its framework (`mockall`, `rstest`, …) for real.
fn external_deps(root: &Path) -> Result<BTreeSet<String>> {
    let manifest = root.join("Cargo.toml");
    if !manifest.is_file() {
        return Ok(BTreeSet::new());
    }
    let text = std::fs::read_to_string(&manifest)
        .with_context(|| format!("reading `{}`", manifest.display()))?;
    let value: toml::Value =
        toml::from_str(&text).with_context(|| format!("parsing `{}`", manifest.display()))?;
    let mut deps = BTreeSet::new();
    if let Some(table) = value.get("dependencies").and_then(toml::Value::as_table) {
        for name in table.keys() {
            deps.insert(name.replace('-', "_"));
        }
    }
    Ok(deps)
}

fn collect_rust_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() {
            collect_rust_files(&path, out)?;
        } else if path.extension().and_then(|ext| ext.to_str()) == Some("rs") {
            out.push(path);
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU64, Ordering};

    /// Run the visitor over a source snippet with the given external-crate deps.
    fn violations_in(src: &str, deps: &[&str]) -> Vec<Violation> {
        let ast = syn::parse_file(src).expect("snippet parses");
        let dep_set: BTreeSet<String> = deps.iter().map(|s| (*s).to_string()).collect();
        let mut visitor = IsolationVisitor {
            file: Path::new("snippet.rs"),
            deps: &dep_set,
            test_depth: 0,
            violations: Vec::new(),
        };
        visitor.visit_file(&ast);
        visitor.violations
    }

    #[test]
    fn flags_each_out_of_module_form() {
        let src = "\
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn t() {
        let _ = crate::store::load();
        let _ = std::net::TcpStream::connect(\"x\");
        let _ = rand::random::<u8>();
        let _ = super::super::util::help();
    }
}
";
        let violations = violations_in(src, &["rand"]);
        assert_eq!(violations.len(), 4, "got {violations:?}");
        assert!(violations.iter().all(|v| v.rule == RULE_CALL));
    }

    #[test]
    fn allows_in_module_calls() {
        let src = "\
#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;
    #[test]
    fn t() {
        let _ = super::widget();
        let _ = self::helper();
        let _ = Cursor::new(b\"x\");
        let _ = std::collections::HashMap::<u8, u8>::new();
        assert_eq!(1, 1);
    }
}
";
        assert!(violations_in(src, &["rand"]).is_empty());
    }

    #[test]
    fn ignores_calls_outside_test_modules() {
        let src = "fn run() { let _ = crate::other::go(); }";
        assert!(violations_in(src, &[]).is_empty());
    }

    #[test]
    fn reports_the_call_line() {
        // Line 1 is `#[cfg(test)]`; the flagged call sits on line 4.
        let src = "\
#[cfg(test)]
mod tests {
    fn t() {
        let _ = crate::other::go();
    }
}
";
        let violations = violations_in(src, &[]);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].line, 4);
    }

    #[test]
    fn effectful_std_policy() {
        let segs = |p: &str| p.split("::").map(str::to_string).collect::<Vec<_>>();
        assert!(is_effectful_std(&segs("std::net::TcpStream::connect")));
        assert!(is_effectful_std(&segs("std::env::var")));
        assert!(is_effectful_std(&segs("std::env")));
        assert!(is_effectful_std(&segs("std::process::exit")));
        assert!(is_effectful_std(&segs("std::thread::sleep")));
        assert!(is_effectful_std(&segs("std::time::SystemTime::now")));
        assert!(is_effectful_std(&segs("std::io::stdout")));
        assert!(!is_effectful_std(&segs("std::fs::read")));
        assert!(!is_effectful_std(&segs("std::fs")));
        assert!(!is_effectful_std(&segs("std::env::temp_dir")));
        assert!(!is_effectful_std(&segs("std::collections::HashMap")));
        assert!(!is_effectful_std(&segs("std::io::Cursor")));
        assert!(!is_effectful_std(&segs("std::time::Duration")));
        assert!(!is_effectful_std(&segs("std::cmp::min")));
    }

    #[test]
    fn classify_leading_segment() {
        let deps: BTreeSet<String> = ["rand"].iter().map(|s| s.to_string()).collect();
        let path = |s: &str| syn::parse_str::<syn::Path>(s).expect("path parses");
        assert_eq!(classify(&path("super::foo"), &deps), None);
        assert_eq!(classify(&path("self::foo"), &deps), None);
        assert_eq!(classify(&path("Local::new"), &deps), None);
        assert_eq!(
            classify(&path("super::super::foo"), &deps),
            Some("ancestor module")
        );
        assert_eq!(
            classify(&path("crate::a::b"), &deps),
            Some("first-party module")
        );
        assert_eq!(
            classify(&path("rand::random"), &deps),
            Some("external crate")
        );
        assert_eq!(
            classify(&path("std::net::TcpStream::connect"), &deps),
            Some("effectful std")
        );
        assert_eq!(classify(&path("std::fs::read"), &deps), None);
        assert_eq!(classify(&path("std::io::Cursor"), &deps), None);
    }

    #[test]
    fn recognizes_cfg_test_attribute() {
        let module = |s: &str| syn::parse_str::<syn::ItemMod>(s).expect("module parses");
        assert!(has_cfg_test(&module("#[cfg(test)] mod t {}").attrs));
        assert!(has_cfg_test(
            &module("#[cfg(all(test, feature = \"x\"))] mod t {}").attrs
        ));
        assert!(!has_cfg_test(
            &module("#[cfg(feature = \"test\")] mod t {}").attrs
        ));
        assert!(!has_cfg_test(&module("mod t {}").attrs));
        assert!(!has_cfg_test(&module("#[cfg(not(test))] mod t {}").attrs));
        assert!(!has_cfg_test(
            &module("#[cfg(all(not(test), unix))] mod t {}").attrs
        ));
        assert!(!has_cfg_test(
            &module("#[cfg(not(all(test, unix)))] mod t {}").attrs
        ));
        assert!(has_cfg_test(
            &module("#[cfg(not(not(test)))] mod t {}").attrs
        ));
    }

    #[test]
    fn flags_each_foreign_import() {
        let src = "\
#[cfg(test)]
mod tests {
    use super::*;
    use super::Thing;
    use crate::other::*;
    use crate::other::Named;
    use rand::Rng;
    use std::net;
    use std::fs;
    use std::collections::HashMap;
    use std::io::Cursor;
}
";
        // Flagged: the crate glob, the crate named import, `rand`, and `std::net`. `std::fs`
        // is not — a unit test may build the tree its unit walks.
        let violations = violations_in(src, &["rand"]);
        assert_eq!(violations.len(), 4, "got {violations:?}");
        assert!(violations.iter().all(|v| v.rule == RULE_IMPORT));
    }

    #[test]
    fn classify_use_roots() {
        let deps: BTreeSet<String> = ["rand"].iter().map(|s| s.to_string()).collect();
        let segs = |p: &str| p.split("::").map(str::to_string).collect::<Vec<_>>();
        assert_eq!(classify_use(&segs("super"), true, &deps), None); // `use super::*`
        assert_eq!(classify_use(&segs("super::Thing"), false, &deps), None);
        assert_eq!(classify_use(&segs("self::helper"), false, &deps), None);
        assert_eq!(
            classify_use(&segs("std::collections::HashMap"), false, &deps),
            None
        );
        assert_eq!(classify_use(&segs("std::io::Cursor"), false, &deps), None);
        assert_eq!(
            classify_use(&segs("super::super"), true, &deps),
            Some("ancestor module")
        );
        assert_eq!(
            classify_use(&segs("crate::other"), true, &deps),
            Some("first-party module")
        );
        assert_eq!(
            classify_use(&segs("crate::other::Named"), false, &deps),
            Some("first-party module")
        );
        assert_eq!(
            classify_use(&segs("rand::Rng"), false, &deps),
            Some("external crate")
        );
        assert_eq!(
            classify_use(&segs("std::net"), false, &deps),
            Some("effectful std")
        );
        assert_eq!(classify_use(&segs("std::fs"), false, &deps), None);
        assert_eq!(
            classify_use(&segs("std::collections"), true, &deps),
            Some("glob import")
        );
    }

    #[test]
    fn imports_outside_test_modules_are_ignored() {
        let src = "use crate::other::*; fn run() {}";
        assert!(violations_in(src, &[]).is_empty());
    }

    /// Run the `#[double]` detector over an integration-test snippet.
    fn integration_violations_in(src: &str, first_party: &[&str]) -> Vec<Violation> {
        let ast = syn::parse_file(src).expect("snippet parses");
        let set: BTreeSet<String> = first_party.iter().map(|s| (*s).to_string()).collect();
        let mut visitor = DoubleVisitor {
            file: Path::new("integration.rs"),
            first_party: &set,
            violations: Vec::new(),
        };
        visitor.visit_file(&ast);
        visitor.violations
    }

    #[test]
    fn flags_double_of_first_party_only() {
        let src = "\
use mockall_double::double;
#[double]
use widget::Renderer;
#[double]
use rand::rngs::ThreadRng;
#[double]
use crate::support::Helper;
";
        // Only `widget` is first-party: `rand` is external and `crate::` is the test crate.
        let violations = integration_violations_in(src, &["widget"]);
        assert_eq!(violations.len(), 1, "got {violations:?}");
        assert_eq!(violations[0].rule, RULE_DOUBLE);
    }

    #[test]
    fn ignores_use_without_double() {
        let src = "use widget::Renderer; fn t() {}";
        assert!(integration_violations_in(src, &["widget"]).is_empty());
    }

    #[test]
    fn recognizes_double_attribute() {
        let item = |s: &str| syn::parse_str::<syn::ItemUse>(s).expect("use parses");
        assert!(has_double_attr(&item("#[double] use a::B;").attrs));
        assert!(has_double_attr(
            &item("#[mockall_double::double] use a::B;").attrs
        ));
        assert!(!has_double_attr(
            &item("#[allow(unused_imports)] use a::B;").attrs
        ));
        assert!(!has_double_attr(&item("use a::B;").attrs));
    }

    struct TempTree(PathBuf);

    impl TempTree {
        fn new(files: &[(&str, &str)]) -> Self {
            static COUNTER: AtomicU64 = AtomicU64::new(0);
            let root = std::env::temp_dir().join(format!(
                "tc-isolation-{}-{}",
                std::process::id(),
                COUNTER.fetch_add(1, Ordering::Relaxed),
            ));
            for (rel, content) in files {
                let path = root.join(rel);
                std::fs::create_dir_all(path.parent().unwrap()).unwrap();
                std::fs::write(path, content).unwrap();
            }
            std::fs::create_dir_all(&root).unwrap();
            TempTree(root)
        }

        fn path(&self) -> &Path {
            &self.0
        }
    }

    impl Drop for TempTree {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    #[test]
    fn a_tree_without_a_manifest_resolves_to_empty_crate_sets() {
        let tree = TempTree::new(&[("src/lib.rs", "fn run() {}\n")]);
        assert!(first_party_crates(tree.path()).unwrap().is_empty());
        assert!(external_deps(tree.path()).unwrap().is_empty());
    }

    #[test]
    fn a_path_dependency_is_first_party_and_a_registry_one_is_not() {
        let tree = TempTree::new(&[(
            "Cargo.toml",
            "[package]\n\
             name = \"my-crate\"\n\n\
             [dependencies]\n\
             sibling-lib = { path = \"../sibling-lib\" }\n\
             rand = \"0.8\"\n\n\
             [dev-dependencies]\n\
             test-support = { path = \"../test-support\" }\n\
             mockall = \"0.13\"\n",
        )]);

        let first_party = first_party_crates(tree.path()).unwrap();
        assert_eq!(
            first_party,
            ["my_crate", "sibling_lib", "test_support"]
                .iter()
                .map(|s| (*s).to_string())
                .collect::<BTreeSet<String>>(),
            "the crate's own name and every path dep, hyphens normalized"
        );

        let external = external_deps(tree.path()).unwrap();
        assert_eq!(
            external,
            ["rand", "sibling_lib"]
                .iter()
                .map(|s| (*s).to_string())
                .collect::<BTreeSet<String>>(),
            "`[dependencies]` only — a dev-dependency is test tooling, not a collaborator"
        );
    }

    #[test]
    fn a_call_through_a_non_path_callee_is_left_alone() {
        let src = "\
#[cfg(test)]
mod tests {
    #[test]
    fn t() {
        let _ = (make())(1);
    }
}
";
        assert!(
            violations_in(src, &["rand"]).is_empty(),
            "a callee that is not a path carries no leading segment to classify"
        );
    }

    #[test]
    fn a_renamed_import_is_judged_by_its_source_path() {
        let src = "\
#[cfg(test)]
mod tests {
    use crate::other::Thing as Local;
    use super::Widget as W;
}
";
        let violations = violations_in(src, &[]);
        assert_eq!(violations.len(), 1, "got {violations:?}");
        let m = &violations[0].message;
        assert!(
            m.contains("crate::other::Thing"),
            "the message names the source path, not the alias: {m}"
        );
    }

    #[test]
    fn a_grouped_import_is_flattened_leaf_by_leaf() {
        let src = "\
#[cfg(test)]
mod tests {
    use crate::other::{Named, deeper::Other};
    use super::{Widget, helper};
}
";
        let violations = violations_in(src, &[]);
        assert_eq!(violations.len(), 2, "got {violations:?}");
        let (first, second) = (&violations[0].message, &violations[1].message);
        assert!(first.contains("crate::other::Named"), "{first}");
        assert!(second.contains("crate::other::deeper::Other"), "{second}");
    }

    #[test]
    fn a_glob_of_an_unresolvable_root_is_still_a_glob_import() {
        let deps: BTreeSet<String> = ["rand"].iter().map(|s| s.to_string()).collect();
        let segs = |p: &str| p.split("::").map(str::to_string).collect::<Vec<_>>();
        assert_eq!(
            classify_use(&segs("helpers"), true, &deps),
            Some("glob import"),
            "a glob is foreign even when `syn` cannot resolve its root"
        );
        assert_eq!(
            classify_use(&segs("helpers::Thing"), false, &deps),
            None,
            "a named import of an unresolvable root is the heuristic's documented limit"
        );
    }

    #[test]
    fn a_leading_colon_survives_into_the_message() {
        let src = "\
#[cfg(test)]
mod tests {
    #[test]
    fn t() {
        let _ = ::std::net::TcpStream::connect(\"x\");
    }
}
";
        let violations = violations_in(src, &[]);
        assert_eq!(violations.len(), 1, "got {violations:?}");
        let m = &violations[0].message;
        assert!(m.contains("`::std::net::TcpStream::connect`"), "{m}");
    }

    #[test]
    fn a_bare_cfg_not_is_not_a_test_module() {
        let module = |s: &str| syn::parse_str::<syn::ItemMod>(s).expect("module parses");
        assert!(!has_cfg_test(&module("#[cfg(not)] mod t {}").attrs));
    }

    #[test]
    fn an_unreadable_unit_source_names_the_file() {
        let tree = TempTree::new(&[("src/widget.rs", "")]);
        std::fs::write(tree.path().join("src/widget.rs"), [0xFF, 0xFE]).unwrap();
        let err = find_violations(tree.path()).unwrap_err();
        assert!(
            format!("{err:#}").contains("reading source file"),
            "got: {err:#}"
        );
    }

    #[test]
    fn an_unparsable_unit_source_names_the_file() {
        let tree = TempTree::new(&[("src/widget.rs", "fn broken( {\n")]);
        let err = find_violations(tree.path()).unwrap_err();
        assert!(format!("{err:#}").contains("parsing"), "got: {err:#}");
    }

    #[test]
    fn an_unreadable_integration_source_names_the_file() {
        let tree = TempTree::new(&[("tests/int.rs", "")]);
        std::fs::write(tree.path().join("tests/int.rs"), [0xFF, 0xFE]).unwrap();
        let err = find_integration_violations(tree.path()).unwrap_err();
        assert!(
            format!("{err:#}").contains("reading source file"),
            "got: {err:#}"
        );
    }

    #[test]
    fn an_unparsable_integration_source_names_the_file() {
        let tree = TempTree::new(&[("tests/int.rs", "fn broken( {\n")]);
        let err = find_integration_violations(tree.path()).unwrap_err();
        assert!(format!("{err:#}").contains("parsing"), "got: {err:#}");
    }

    #[test]
    fn integration_violations_are_sorted_by_file_and_line() {
        let tree = TempTree::new(&[
            (
                "Cargo.toml",
                "[package]\nname = \"widget\"\nversion = \"0.0.1\"\n",
            ),
            (
                "tests/int.rs",
                "#[double]\nuse widget::Renderer;\n#[double]\nuse widget::Store;\n",
            ),
        ]);
        let violations = find_integration_violations(tree.path()).unwrap();
        assert_eq!(violations.len(), 2, "got {violations:?}");
        assert!(violations[0].line < violations[1].line);
    }

    #[test]
    fn an_unreadable_manifest_is_an_error_for_both_crate_sets() {
        let tree = TempTree::new(&[("Cargo.toml", "")]);
        std::fs::write(tree.path().join("Cargo.toml"), [0xFF, 0xFE]).unwrap();
        let first = format!("{:#}", first_party_crates(tree.path()).unwrap_err());
        let external = format!("{:#}", external_deps(tree.path()).unwrap_err());
        assert!(first.contains("reading"), "got: {first}");
        assert!(external.contains("reading"), "got: {external}");
    }

    #[test]
    fn an_unparsable_manifest_is_an_error_for_both_crate_sets() {
        let tree = TempTree::new(&[("Cargo.toml", "not = toml =\n")]);
        let first = format!("{:#}", first_party_crates(tree.path()).unwrap_err());
        let external = format!("{:#}", external_deps(tree.path()).unwrap_err());
        assert!(first.contains("parsing"), "got: {first}");
        assert!(external.contains("parsing"), "got: {external}");
    }

    #[test]
    fn a_manifest_without_dependency_tables_resolves_to_the_package_name_alone() {
        let tree = TempTree::new(&[(
            "Cargo.toml",
            "[package]\nname = \"widget\"\nversion = \"0.0.1\"\n",
        )]);
        let first = first_party_crates(tree.path()).unwrap();
        assert_eq!(first.iter().collect::<Vec<_>>(), ["widget"]);
        assert!(external_deps(tree.path()).unwrap().is_empty());
    }

    #[test]
    fn a_registry_only_dependency_table_feeds_external_deps() {
        let tree = TempTree::new(&[("Cargo.toml", "[dependencies]\nserde = \"1\"\n")]);
        let external = external_deps(tree.path()).unwrap();
        assert_eq!(external.iter().collect::<Vec<_>>(), ["serde"]);
    }

    #[test]
    fn a_missing_root_is_an_error_for_integration_collection() {
        let err = find_integration_violations(Path::new("/nonexistent-tc-isolation")).unwrap_err();
        assert!(
            format!("{err:#}").contains("reading directory"),
            "got: {err:#}"
        );
    }

    #[test]
    fn a_cfg_not_test_function_hides_its_own_lines_and_no_others() {
        let source = "\
#[cfg(not(test))]
pub fn main() -> u8 {
    run()
}

fn run() -> u8 {
    1
}
";
        assert_eq!(
            lines_hidden_from_tests(source),
            BTreeSet::from([1, 2, 3, 4])
        );
    }

    #[test]
    fn a_gated_module_hides_everything_inside_it() {
        let source = "\
#[cfg(not(test))]
mod real {
    pub fn go() -> u8 {
        1
    }
}
";
        assert_eq!(
            lines_hidden_from_tests(source),
            BTreeSet::from([1, 2, 3, 4, 5, 6])
        );
    }

    #[test]
    fn a_gated_method_hides_only_that_method() {
        let source = "\
impl Runner {
    #[cfg(not(test))]
    fn go(&self) -> u8 {
        1
    }

    fn stay(&self) -> u8 {
        2
    }
}
";
        assert_eq!(
            lines_hidden_from_tests(source),
            BTreeSet::from([2, 3, 4, 5])
        );
    }

    #[test]
    fn an_ungated_file_hides_nothing() {
        let source = "#[cfg(test)]\nmod tests {\n    fn t() {}\n}\n\nfn go() -> u8 {\n    1\n}\n";

        assert!(lines_hidden_from_tests(source).is_empty());
    }

    #[test]
    fn unparseable_source_hides_nothing() {
        assert!(lines_hidden_from_tests("fn go( {").is_empty());
    }

    /// Whether `attr` on a plain function hides it from the test build.
    fn hides_under(attr: &str) -> bool {
        !lines_hidden_from_tests(&format!("{attr}\nfn go() -> u8 {{\n    1\n}}\n")).is_empty()
    }

    #[test]
    fn a_gate_no_test_build_can_satisfy_hides_the_item() {
        assert!(hides_under("#[cfg(not(test))]"));
        assert!(hides_under("#[cfg(all(not(test), unix))]"));
        assert!(hides_under("#[cfg(not(any(test, unix)))]"));
        assert!(hides_under("#[cfg(any())]"));
        assert!(hides_under("#[cfg(not(all()))]"));
    }

    #[test]
    fn a_gate_a_test_build_can_still_satisfy_hides_nothing() {
        assert!(!hides_under("#[cfg(test)]"));
        assert!(!hides_under("#[cfg(unix)]"));
        assert!(!hides_under("#[cfg(feature = \"x\")]"));
        assert!(!hides_under("#[cfg(any(not(test), unix))]"));
        assert!(!hides_under("#[cfg(not(not(test)))]"));
        assert!(!hides_under("#[cfg(all())]"));
        assert!(!hides_under("#[inline]"));
    }

    #[test]
    fn a_gate_resting_on_a_condition_we_cannot_decide_hides_nothing() {
        assert!(!hides_under("#[cfg(not(unix))]"));
        assert!(!hides_under("#[cfg(all(test, unix))]"));
    }

    #[test]
    fn a_malformed_gate_hides_nothing() {
        assert!(!hides_under("#[cfg(not())]"));
        assert!(!hides_under("#[cfg(nope(test))]"));
        assert!(!hides_under("#[cfg(not(test), unix)]"));
    }
}