]> git.proxmox.com Git - rustc.git/blob - src/tools/tidy/src/unit_tests.rs
New upstream version 1.66.0+dfsg1
[rustc.git] / src / tools / tidy / src / unit_tests.rs
1 //! Tidy check to ensure `#[test]` and `#[bench]` are not used directly inside `core`.
2 //!
3 //! `#![no_core]` libraries cannot be tested directly due to duplicating lang
4 //! items. All tests and benchmarks must be written externally in `core/{tests,benches}`.
5 //!
6 //! Outside of core tests and benchmarks should be outlined into separate files
7 //! named `tests.rs` or `benches.rs`, or directories named `tests` or `benches` unconfigured
8 //! during normal build.
9
10 use crate::walk::{filter_dirs, walk};
11 use std::path::Path;
12
13 pub fn check(root_path: &Path, bad: &mut bool) {
14 let core = &root_path.join("core");
15 let core_tests = &core.join("tests");
16 let core_benches = &core.join("benches");
17 let is_core = |path: &Path| {
18 path.starts_with(core) && !(path.starts_with(core_tests) || path.starts_with(core_benches))
19 };
20
21 let mut skip = |path: &Path| {
22 let file_name = path.file_name().unwrap_or_default();
23 if path.is_dir() {
24 filter_dirs(path)
25 || path.ends_with("src/test")
26 || path.ends_with("src/doc")
27 || (file_name == "tests" || file_name == "benches") && !is_core(path)
28 } else {
29 let extension = path.extension().unwrap_or_default();
30 extension != "rs"
31 || (file_name == "tests.rs" || file_name == "benches.rs") && !is_core(path)
32 // UI tests with different names
33 || path.ends_with("src/thread/local/dynamic_tests.rs")
34 || path.ends_with("src/sync/mpsc/sync_tests.rs")
35 }
36 };
37
38 walk(root_path, &mut skip, &mut |entry, contents| {
39 let path = entry.path();
40 let is_core = path.starts_with(core);
41 for (i, line) in contents.lines().enumerate() {
42 let line = line.trim();
43 let is_test = || line.contains("#[test]") && !line.contains("`#[test]");
44 let is_bench = || line.contains("#[bench]") && !line.contains("`#[bench]");
45 if !line.starts_with("//") && (is_test() || is_bench()) {
46 let explanation = if is_core {
47 "core unit tests and benchmarks must be placed into \
48 `core/tests` or `core/benches`"
49 } else {
50 "unit tests and benchmarks must be placed into \
51 separate files or directories named \
52 `tests.rs`, `benches.rs`, `tests` or `benches`"
53 };
54 let name = if is_test() { "test" } else { "bench" };
55 tidy_error!(
56 bad,
57 "`{}:{}` contains `#[{}]`; {}",
58 path.display(),
59 i + 1,
60 name,
61 explanation,
62 );
63 return;
64 }
65 }
66 });
67 }