Skip to main content

wowlab_tidy/languages/rust/rules/hygiene/
cfg_not_test.rs

1use crate::{Example, FileCtx, Violation, infra::parse, violation};
2
3#[rustfmt::skip]
4const EXAMPLES: &[Example] = &[
5    Example {
6        label: "cfg not test",
7        code: "#[cfg(not(test))]",
8        pass: false,
9    },
10    Example {
11        label: "cfg test",
12        code: "#[cfg(test)]",
13        pass: true,
14    },
15    Example {
16        label: "normal cfg",
17        code: "#[cfg(feature = \"wasm\")]",
18        pass: true,
19    },
20    Example {
21        label: "comment with cfg not test",
22        code: "// #[cfg(not(test))]",
23        pass: true,
24    },
25];
26
27crate::line_rule!(
28    cfg_not_test,
29    "Flag `#[cfg(not(test))]` — use dependency injection or feature flags instead.",
30    "Code gated on #[cfg(not(test))] creates invisible production-only paths that are hard to test and reason about.",
31    Medium,
32);
33
34fn check_cfg_not_test(ctx: &FileCtx<'_>) -> Vec<Violation> {
35    let mut out = Vec::new();
36
37    for (i, line) in ctx.lines.iter().enumerate() {
38        let lineno = i + 1;
39        let trimmed = line.trim();
40
41        if parse::is_comment(trimmed) {
42            continue;
43        }
44
45        if crate::infra::helpers::contains_outside_strings(trimmed, "#[cfg(not(test))]")
46            || crate::infra::helpers::contains_outside_strings(trimmed, "#![cfg(not(test))]")
47        {
48            out.push(violation(
49                ctx.rel,
50                lineno,
51                "#[cfg(not(test))] — use dependency injection or feature flags instead",
52            ));
53        }
54    }
55
56    out
57}
58
59crate::tidy_test!(check_cfg_not_test, {
60    crate::example_tests!(EXAMPLES, check_cfg_not_test);
61});