tidy/
ui_tests.rs

1//! Tidy check to ensure below in UI test directories:
2//! - there are no stray `.stderr` files
3
4use std::collections::BTreeSet;
5use std::ffi::OsStr;
6use std::fs;
7use std::io::Write;
8use std::path::{Path, PathBuf};
9
10use crate::diagnostics::{CheckId, RunningCheck, TidyCtx};
11
12const ISSUES_TXT_HEADER: &str = r#"============================================================
13    ⚠️⚠️⚠️NOTHING SHOULD EVER BE ADDED TO THIS LIST⚠️⚠️⚠️
14============================================================
15"#;
16
17pub fn check(root_path: &Path, tidy_ctx: TidyCtx) {
18    let path = &root_path.join("tests");
19    let mut check = tidy_ctx.start_check(CheckId::new("ui_tests").path(path));
20    let bless = tidy_ctx.is_bless_enabled();
21
22    // the list of files in ui tests that are allowed to start with `issue-XXXX`
23    // BTreeSet because we would like a stable ordering so --bless works
24    let mut prev_line = "";
25    let mut is_sorted = true;
26    let allowed_issue_names: BTreeSet<_> = include_str!("issues.txt")
27        .strip_prefix(ISSUES_TXT_HEADER)
28        .unwrap()
29        .lines()
30        .inspect(|&line| {
31            if prev_line > line {
32                is_sorted = false;
33            }
34
35            prev_line = line;
36        })
37        .collect();
38
39    if !is_sorted && !bless {
40        check.error(
41            "`src/tools/tidy/src/issues.txt` is not in order, mostly because you modified it manually,
42            please only update it with command `x test tidy --bless`"
43        );
44    }
45
46    deny_new_top_level_ui_tests(&mut check, &path.join("ui"));
47
48    let remaining_issue_names = recursively_check_ui_tests(&mut check, path, &allowed_issue_names);
49
50    // if there are any file names remaining, they were moved on the fs.
51    // our data must remain up to date, so it must be removed from issues.txt
52    // do this automatically on bless, otherwise issue a tidy error
53    if bless && (!remaining_issue_names.is_empty() || !is_sorted) {
54        let tidy_src = root_path.join("src/tools/tidy/src");
55        // instead of overwriting the file, recreate it and use an "atomic rename"
56        // so we don't bork things on panic or a contributor using Ctrl+C
57        let blessed_issues_path = tidy_src.join("issues_blessed.txt");
58        let mut blessed_issues_txt = fs::File::create(&blessed_issues_path).unwrap();
59        blessed_issues_txt.write_all(ISSUES_TXT_HEADER.as_bytes()).unwrap();
60        // If we changed paths to use the OS separator, reassert Unix chauvinism for blessing.
61        for filename in allowed_issue_names.difference(&remaining_issue_names) {
62            writeln!(blessed_issues_txt, "{filename}").unwrap();
63        }
64        let old_issues_path = tidy_src.join("issues.txt");
65        fs::rename(blessed_issues_path, old_issues_path).unwrap();
66    } else {
67        for file_name in remaining_issue_names {
68            let mut p = PathBuf::from(path);
69            p.push(file_name);
70            check.error(format!(
71                "file `{}` no longer exists and should be removed from the exclusions in `src/tools/tidy/src/issues.txt`",
72                p.display()
73            ));
74        }
75    }
76}
77
78fn deny_new_top_level_ui_tests(check: &mut RunningCheck, tests_path: &Path) {
79    // See <https://github.com/rust-lang/compiler-team/issues/902> where we propose banning adding
80    // new ui tests *directly* under `tests/ui/`. For more context, see:
81    //
82    // - <https://github.com/rust-lang/rust/issues/73494>
83    // - <https://github.com/rust-lang/rust/issues/133895>
84
85    let top_level_ui_tests = ignore::WalkBuilder::new(tests_path)
86        .max_depth(Some(1))
87        .follow_links(false)
88        .build()
89        .flatten()
90        .filter(|e| {
91            let file_name = e.file_name();
92            file_name != ".gitattributes" && file_name != "README.md"
93        })
94        .filter(|e| !e.file_type().is_some_and(|f| f.is_dir()));
95
96    for entry in top_level_ui_tests {
97        check.error(format!(
98            "ui tests should be added under meaningful subdirectories: `{}`, see https://github.com/rust-lang/compiler-team/issues/902",
99            entry.path().display()
100        ));
101    }
102}
103
104fn recursively_check_ui_tests<'issues>(
105    check: &mut RunningCheck,
106    path: &Path,
107    allowed_issue_names: &'issues BTreeSet<&'issues str>,
108) -> BTreeSet<&'issues str> {
109    let mut remaining_issue_names: BTreeSet<&str> = allowed_issue_names.clone();
110
111    let (ui, ui_fulldeps) = (path.join("ui"), path.join("ui-fulldeps"));
112    let paths = [ui.as_path(), ui_fulldeps.as_path()];
113    crate::walk::walk_no_read(&paths, |_, _| false, &mut |entry| {
114        let file_path = entry.path();
115        if let Some(ext) = file_path.extension().and_then(OsStr::to_str) {
116            check_unexpected_extension(check, file_path, ext);
117
118            // NB: We do not use file_stem() as some file names have multiple `.`s and we
119            // must strip all of them.
120            let testname =
121                file_path.file_name().unwrap().to_str().unwrap().split_once('.').unwrap().0;
122            if ext == "stderr" || ext == "stdout" || ext == "fixed" {
123                check_stray_output_snapshot(check, file_path, testname);
124                check_empty_output_snapshot(check, file_path);
125            }
126
127            deny_new_nondescriptive_test_names(
128                check,
129                path,
130                &mut remaining_issue_names,
131                file_path,
132                testname,
133                ext,
134            );
135        }
136    });
137    remaining_issue_names
138}
139
140fn check_unexpected_extension(check: &mut RunningCheck, file_path: &Path, ext: &str) {
141    const EXPECTED_TEST_FILE_EXTENSIONS: &[&str] = &[
142        "rs",     // test source files
143        "stderr", // expected stderr file, corresponds to a rs file
144        "svg",    // expected svg file, corresponds to a rs file, equivalent to stderr
145        "stdout", // expected stdout file, corresponds to a rs file
146        "fixed",  // expected source file after applying fixes
147        "md",     // test directory descriptions
148        "ftl",    // translation tests
149    ];
150
151    const EXTENSION_EXCEPTION_PATHS: &[&str] = &[
152        "tests/ui/asm/named-asm-labels.s", // loading an external asm file to test named labels lint
153        "tests/ui/codegen/mismatched-data-layout.json", // testing mismatched data layout w/ custom targets
154        "tests/ui/check-cfg/my-awesome-platform.json",  // testing custom targets with cfgs
155        "tests/ui/argfile/commandline-argfile-badutf8.args", // passing args via a file
156        "tests/ui/argfile/commandline-argfile.args",    // passing args via a file
157        "tests/ui/crate-loading/auxiliary/libfoo.rlib", // testing loading a manually created rlib
158        "tests/ui/include-macros/data.bin", // testing including data with the include macros
159        "tests/ui/include-macros/file.txt", // testing including data with the include macros
160        "tests/ui/macros/macro-expanded-include/file.txt", // testing including data with the include macros
161        "tests/ui/macros/not-utf8.bin", // testing including data with the include macros
162        "tests/ui/macros/syntax-extension-source-utils-files/includeme.fragment", // more include
163        "tests/ui/proc-macro/auxiliary/included-file.txt", // more include
164        "tests/ui/unpretty/auxiliary/data.txt", // more include
165        "tests/ui/invalid/foo.natvis.xml", // sample debugger visualizer
166        "tests/ui/sanitizer/dataflow-abilist.txt", // dataflow sanitizer ABI list file
167        "tests/ui/shell-argfiles/shell-argfiles.args", // passing args via a file
168        "tests/ui/shell-argfiles/shell-argfiles-badquotes.args", // passing args via a file
169        "tests/ui/shell-argfiles/shell-argfiles-via-argfile-shell.args", // passing args via a file
170        "tests/ui/shell-argfiles/shell-argfiles-via-argfile.args", // passing args via a file
171        "tests/ui/std/windows-bat-args1.bat", // tests escaping arguments through batch files
172        "tests/ui/std/windows-bat-args2.bat", // tests escaping arguments through batch files
173        "tests/ui/std/windows-bat-args3.bat", // tests escaping arguments through batch files
174    ];
175
176    // files that are neither an expected extension or an exception should not exist
177    // they're probably typos or not meant to exist
178    if !(EXPECTED_TEST_FILE_EXTENSIONS.contains(&ext)
179        || EXTENSION_EXCEPTION_PATHS.iter().any(|path| file_path.ends_with(path)))
180    {
181        check.error(format!("file {} has unexpected extension {}", file_path.display(), ext));
182    }
183}
184
185fn check_stray_output_snapshot(check: &mut RunningCheck, file_path: &Path, testname: &str) {
186    // Test output filenames have one of the formats:
187    // ```
188    // $testname.stderr
189    // $testname.$mode.stderr
190    // $testname.$revision.stderr
191    // $testname.$revision.$mode.stderr
192    // ```
193    //
194    // For now, just make sure that there is a corresponding
195    // `$testname.rs` file.
196
197    if !file_path.with_file_name(testname).with_extension("rs").exists()
198        && !testname.contains("ignore-tidy")
199    {
200        check.error(format!("Stray file with UI testing output: {:?}", file_path));
201    }
202}
203
204fn check_empty_output_snapshot(check: &mut RunningCheck, file_path: &Path) {
205    if let Ok(metadata) = fs::metadata(file_path)
206        && metadata.len() == 0
207    {
208        check.error(format!("Empty file with UI testing output: {:?}", file_path));
209    }
210}
211
212fn deny_new_nondescriptive_test_names(
213    check: &mut RunningCheck,
214    path: &Path,
215    remaining_issue_names: &mut BTreeSet<&str>,
216    file_path: &Path,
217    testname: &str,
218    ext: &str,
219) {
220    if ext == "rs"
221        && let Some(test_name) = static_regex!(r"^issues?[-_]?(\d{3,})").captures(testname)
222    {
223        // these paths are always relative to the passed `path` and always UTF8
224        let stripped_path = file_path
225            .strip_prefix(path)
226            .unwrap()
227            .to_str()
228            .unwrap()
229            .replace(std::path::MAIN_SEPARATOR_STR, "/");
230
231        if !remaining_issue_names.remove(stripped_path.as_str())
232            && !stripped_path.starts_with("ui/issues/")
233        {
234            check.error(format!(
235                "file `tests/{stripped_path}` must begin with a descriptive name, consider `{{reason}}-issue-{issue_n}.rs`",
236                issue_n = &test_name[1],
237            ));
238        }
239    }
240}