Skip to main content

stern4rust/
unit_test_finder.rs

1// Copyright 2025 Umberto Gotti <umberto.gotti@umbertogotti.dev>
2// Licensed under the MIT License
3// SPDX-License-Identifier: MIT
4
5use proc_macro2::TokenTree;
6use quote::ToTokens;
7use syn::Attribute;
8use syn::Item;
9use syn::spanned::Spanned;
10
11use crate::source_file::SourceFile;
12use crate::unit_test_site::UnitTestSite;
13
14// Finds tests, and the machinery of tests, in the production source tree.
15//
16// Three shapes, and all three are about the same thing: code that exists only
17// when the tests are being built. A function carrying a test attribute is the
18// obvious one. `#[cfg(test)]` is the usual one. `#[cfg_attr(test, ...)]` is the
19// third, and it is the one worth spelling out -- a type carrying a derive only
20// under test is a type that means one thing to the tests and another to the
21// shipped build.
22//
23// Only the test-gated spelling counts. `#[cfg_attr(feature = "serde", ...)]` is
24// ordinary library work and is left alone, as is `#[cfg(feature = "...")]`:
25// both gate on something the shipped build can also select.
26pub struct UnitTestFinder;
27
28impl UnitTestFinder {
29    // None means the file does not parse. readable-source reports that.
30    pub fn sites(file: &SourceFile) -> Option<Vec<UnitTestSite>> {
31        let syntax = syn::parse_file(&file.contents()).ok()?;
32        Some(Self::in_items(file, &syntax.items))
33    }
34
35    // Descends into inline modules, because nesting is where a gate is easiest
36    // to miss by eye. An item already reported is not descended into: the
37    // module is the offence, and listing every test inside it would report the
38    // same decision once per test.
39    fn in_items(file: &SourceFile, items: &[Item]) -> Vec<UnitTestSite> {
40        let mut sites = Vec::new();
41        for item in items {
42            if let Some(site) = Self::site_of(file, item) {
43                sites.push(site);
44                continue;
45            }
46            if let Item::Mod(module) = item {
47                if let Some((_, inner)) = &module.content {
48                    sites.extend(Self::in_items(file, inner));
49                }
50            }
51        }
52        sites
53    }
54
55    fn site_of(file: &SourceFile, item: &Item) -> Option<UnitTestSite> {
56        let line = item.span().start().line.max(1);
57        let attrs = Self::attributes(item);
58        let subject = Self::describe(file, item, line);
59        let mirror = Self::mirror_of(file.relative_path());
60
61        if attrs.iter().any(Self::is_cfg_attr_test) {
62            return Some(UnitTestSite::new(
63                line,
64                &format!("the `#[cfg_attr(test, ...)]` on the {subject}"),
65                &format!(
66                    "apply the attribute unconditionally, or move what it guards into {mirror}"
67                ),
68            ));
69        }
70        if attrs.iter().any(Self::is_cfg_test) {
71            return Some(UnitTestSite::new(
72                line,
73                &format!("the `#[cfg(test)]` {subject}"),
74                &format!("move the tests to {mirror} and delete this from the source tree"),
75            ));
76        }
77        if attrs.iter().any(Self::is_test) {
78            return Some(UnitTestSite::new(
79                line,
80                &format!("the test {subject}"),
81                &format!("move the tests to {mirror} and delete this from the source tree"),
82            ));
83        }
84        None
85    }
86
87    // Only when the predicate gates on test. `cfg_attr` is how a crate applies
88    // a derive behind a feature, which is ordinary library work and none of
89    // this rule's business -- what is forbidden is a type that means one thing
90    // to the tests and another to the shipped build.
91    fn is_cfg_attr_test(attr: &Attribute) -> bool {
92        attr.path().is_ident("cfg_attr") && Self::mentions_test(attr)
93    }
94
95    // A predicate rather than the literal text, since `any(test, ...)` and
96    // `not(test)` gate on test just as effectively.
97    fn is_cfg_test(attr: &Attribute) -> bool {
98        attr.path().is_ident("cfg") && Self::mentions_test(attr)
99    }
100
101    // `#[test]`, `#[tokio::test]` and any other harness spelled the same way.
102    fn is_test(attr: &Attribute) -> bool {
103        attr.path()
104            .segments
105            .last()
106            .is_some_and(|segment| segment.ident == "test")
107    }
108
109    // An identifier, not a substring, so `#[cfg(feature = "test")]` is a
110    // feature named test rather than a test gate -- the string literal never
111    // arrives as an Ident.
112    fn mentions_test(attr: &Attribute) -> bool {
113        Self::has_test_ident(attr.meta.to_token_stream())
114    }
115
116    fn has_test_ident(stream: proc_macro2::TokenStream) -> bool {
117        stream.into_iter().any(|tree| match tree {
118            TokenTree::Ident(ident) => ident == "test",
119            TokenTree::Group(group) => Self::has_test_ident(group.stream()),
120            _ => false,
121        })
122    }
123
124    // src/<path>.rs mirrors onto tests/<path>_tests.rs, which is the same
125    // pairing twin4rust enforces, so the correction names the file that should
126    // already exist rather than describing a policy.
127    fn mirror_of(relative_path: &str) -> String {
128        let without_root = relative_path.strip_prefix("src/").unwrap_or(relative_path);
129        let stem = without_root.strip_suffix(".rs").unwrap_or(without_root);
130        format!("tests/{stem}_tests.rs")
131    }
132
133    fn describe(file: &SourceFile, item: &Item, line: usize) -> String {
134        match item {
135            Item::Const(inner) => format!("constant `{}`", inner.ident),
136            Item::Enum(inner) => format!("enum `{}`", inner.ident),
137            Item::Fn(inner) => format!("function `{}`", inner.sig.ident),
138            Item::Mod(inner) => format!("module `{}`", inner.ident),
139            Item::Static(inner) => format!("static `{}`", inner.ident),
140            Item::Struct(inner) => format!("struct `{}`", inner.ident),
141            Item::Trait(inner) => format!("trait `{}`", inner.ident),
142            Item::Type(inner) => format!("type alias `{}`", inner.ident),
143            _ => format!("`{}`", Self::source_line(file, line)),
144        }
145    }
146
147    fn source_line(file: &SourceFile, line: usize) -> String {
148        file.lines()
149            .get(line.saturating_sub(1))
150            .map_or_else(String::new, |text| text.trim().to_string())
151    }
152
153    fn attributes(item: &Item) -> &[Attribute] {
154        match item {
155            Item::Const(inner) => &inner.attrs,
156            Item::Enum(inner) => &inner.attrs,
157            Item::ExternCrate(inner) => &inner.attrs,
158            Item::Fn(inner) => &inner.attrs,
159            Item::ForeignMod(inner) => &inner.attrs,
160            Item::Impl(inner) => &inner.attrs,
161            Item::Macro(inner) => &inner.attrs,
162            Item::Mod(inner) => &inner.attrs,
163            Item::Static(inner) => &inner.attrs,
164            Item::Struct(inner) => &inner.attrs,
165            Item::Trait(inner) => &inner.attrs,
166            Item::TraitAlias(inner) => &inner.attrs,
167            Item::Type(inner) => &inner.attrs,
168            Item::Union(inner) => &inner.attrs,
169            Item::Use(inner) => &inner.attrs,
170            _ => &[],
171        }
172    }
173}