1 #![feature(test)] // compiletest_rs requires this attribute
4 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
5 #![warn(rust_2018_idioms, unused_lifetimes)]
7 use compiletest_rs as compiletest;
8 use compiletest_rs::common::Mode as TestMode;
10 use std::collections::HashMap;
11 use std::env::{self, remove_var, set_var, var_os};
12 use std::ffi::{OsStr, OsString};
15 use std::path::{Path, PathBuf};
16 use std::sync::LazyLock;
17 use test_utils::IS_RUSTC_TEST_SUITE;
21 // whether to run internal tests or not
22 const RUN_INTERNAL_TESTS: bool = cfg!(feature = "internal");
24 /// All crates used in UI tests are listed here
25 static TEST_DEPENDENCIES: &[&str] = &[
41 // Test dependencies may need an `extern crate` here to ensure that they show up
42 // in the depinfo file (otherwise cargo thinks they are unused)
43 #[allow(unused_extern_crates)]
44 extern crate clippy_utils;
45 #[allow(unused_extern_crates)]
46 extern crate derive_new;
47 #[allow(unused_extern_crates)]
49 #[allow(unused_extern_crates)]
50 extern crate if_chain;
51 #[allow(unused_extern_crates)]
52 extern crate itertools;
53 #[allow(unused_extern_crates)]
54 extern crate parking_lot;
55 #[allow(unused_extern_crates)]
57 #[allow(unused_extern_crates)]
58 extern crate rustc_semver;
59 #[allow(unused_extern_crates)]
61 #[allow(unused_extern_crates)]
64 /// Produces a string with an `--extern` flag for all UI test crate
67 /// The dependency files are located by parsing the depinfo file for this test
68 /// module. This assumes the `-Z binary-dep-depinfo` flag is enabled. All test
69 /// dependencies must be added to Cargo.toml at the project root. Test
70 /// dependencies that are not *directly* used by this test module require an
71 /// `extern crate` declaration.
72 static EXTERN_FLAGS: LazyLock<String> = LazyLock::new(|| {
73 let current_exe_depinfo = {
74 let mut path = env::current_exe().unwrap();
75 path.set_extension("d");
76 fs::read_to_string(path).unwrap()
78 let mut crates: HashMap<&str, &str> = HashMap::with_capacity(TEST_DEPENDENCIES.len());
79 for line in current_exe_depinfo.lines() {
80 // each dependency is expected to have a Makefile rule like `/path/to/crate-hash.rlib:`
81 let parse_name_path = || {
82 if line.starts_with(char::is_whitespace) {
85 let path_str = line.strip_suffix(':')?;
86 let path = Path::new(path_str);
87 if !matches!(path.extension()?.to_str()?, "rlib" | "so" | "dylib" | "dll") {
90 let (name, _hash) = path.file_stem()?.to_str()?.rsplit_once('-')?;
91 // the "lib" prefix is not present for dll files
92 let name = name.strip_prefix("lib").unwrap_or(name);
93 Some((name, path_str))
95 if let Some((name, path)) = parse_name_path() {
96 if TEST_DEPENDENCIES.contains(&name) {
97 // A dependency may be listed twice if it is available in sysroot,
98 // and the sysroot dependencies are listed first. As of the writing,
99 // this only seems to apply to if_chain.
100 crates.insert(name, path);
104 let not_found: Vec<&str> = TEST_DEPENDENCIES
107 .filter(|n| !crates.contains_key(n))
110 not_found.is_empty(),
111 "dependencies not found in depinfo: {:?}\n\
112 help: Make sure the `-Z binary-dep-depinfo` rust flag is enabled\n\
113 help: Try adding to dev-dependencies in Cargo.toml\n\
114 help: Be sure to also add `extern crate ...;` to tests/compile-test.rs",
119 .map(|(name, path)| format!(" --extern {}={}", name, path))
123 fn base_config(test_dir: &str) -> compiletest::Config {
124 let mut config = compiletest::Config {
125 edition: Some("2021".into()),
127 ..compiletest::Config::default()
130 if let Ok(filters) = env::var("TESTNAME") {
131 config.filters = filters.split(',').map(ToString::to_string).collect();
134 if let Some(path) = option_env!("RUSTC_LIB_PATH") {
135 let path = PathBuf::from(path);
136 config.run_lib_path = path.clone();
137 config.compile_lib_path = path;
139 let current_exe_path = env::current_exe().unwrap();
140 let deps_path = current_exe_path.parent().unwrap();
141 let profile_path = deps_path.parent().unwrap();
143 // Using `-L dependency={}` enforces that external dependencies are added with `--extern`.
144 // This is valuable because a) it allows us to monitor what external dependencies are used
145 // and b) it ensures that conflicting rlibs are resolved properly.
146 let host_libs = option_env!("HOST_LIBS")
147 .map(|p| format!(" -L dependency={}", Path::new(p).join("deps").display()))
148 .unwrap_or_default();
149 config.target_rustcflags = Some(format!(
150 "--emit=metadata -Dwarnings -Zui-testing -L dependency={}{}{}",
156 config.src_base = Path::new("tests").join(test_dir);
157 config.build_base = profile_path.join("test").join(test_dir);
158 config.rustc_path = profile_path.join(if cfg!(windows) {
167 let mut config = base_config("ui");
168 config.rustfix_coverage = true;
169 // use tests/clippy.toml
170 let _g = VarGuard::set("CARGO_MANIFEST_DIR", fs::canonicalize("tests").unwrap());
171 let _threads = VarGuard::set(
173 // if RUST_TEST_THREADS is set, adhere to it, otherwise override it
174 env::var("RUST_TEST_THREADS").unwrap_or_else(|_| {
175 std::thread::available_parallelism()
176 .map_or(1, std::num::NonZeroUsize::get)
180 compiletest::run_tests(&config);
181 check_rustfix_coverage();
184 fn run_internal_tests() {
185 // only run internal tests with the internal-tests feature
186 if !RUN_INTERNAL_TESTS {
189 let config = base_config("ui-internal");
190 compiletest::run_tests(&config);
194 fn run_tests(config: &compiletest::Config, mut tests: Vec<tester::TestDescAndFn>) -> Result<bool, io::Error> {
195 let mut result = true;
196 let opts = compiletest::test_opts(config);
197 for dir in fs::read_dir(&config.src_base)? {
199 if !dir.file_type()?.is_dir() {
202 let dir_path = dir.path();
203 let _g = VarGuard::set("CARGO_MANIFEST_DIR", &dir_path);
204 for file in fs::read_dir(&dir_path)? {
206 let file_path = file.path();
207 if file.file_type()?.is_dir() {
210 if file_path.extension() != Some(OsStr::new("rs")) {
213 let paths = compiletest::common::TestPaths {
215 base: config.src_base.clone(),
216 relative_dir: dir_path.file_name().unwrap().into(),
218 let test_name = compiletest::make_test_name(config, &paths);
221 .position(|test| test.desc.name == test_name)
222 .expect("The test should be in there");
223 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
229 let mut config = base_config("ui-toml");
230 config.src_base = config.src_base.canonicalize().unwrap();
232 let tests = compiletest::make_tests(&config);
234 let res = run_tests(&config, tests);
237 Ok(false) => panic!("Some tests failed"),
239 panic!("I/O failure during tests: {:?}", e);
246 config: &compiletest::Config,
248 mut tests: Vec<tester::TestDescAndFn>,
249 ) -> Result<bool, io::Error> {
250 let mut result = true;
251 let opts = compiletest::test_opts(config);
253 for dir in fs::read_dir(&config.src_base)? {
255 if !dir.file_type()?.is_dir() {
259 // Use the filter if provided
260 let dir_path = dir.path();
261 for filter in filters {
262 if !dir_path.ends_with(filter) {
267 for case in fs::read_dir(&dir_path)? {
269 if !case.file_type()?.is_dir() {
273 let src_path = case.path().join("src");
275 // When switching between branches, if the previous branch had a test
276 // that the current branch does not have, the directory is not removed
277 // because an ignored Cargo.lock file exists.
278 if !src_path.exists() {
282 env::set_current_dir(&src_path)?;
283 for file in fs::read_dir(&src_path)? {
285 if file.file_type()?.is_dir() {
289 // Search for the main file to avoid running a test for each file in the project
290 let file_path = file.path();
291 match file_path.file_name().and_then(OsStr::to_str) {
292 Some("main.rs") => {},
295 let _g = VarGuard::set("CLIPPY_CONF_DIR", case.path());
296 let paths = compiletest::common::TestPaths {
298 base: config.src_base.clone(),
299 relative_dir: src_path.strip_prefix(&config.src_base).unwrap().into(),
301 let test_name = compiletest::make_test_name(config, &paths);
304 .position(|test| test.desc.name == test_name)
305 .expect("The test should be in there");
306 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
313 if IS_RUSTC_TEST_SUITE {
317 let mut config = base_config("ui-cargo");
318 config.src_base = config.src_base.canonicalize().unwrap();
320 let tests = compiletest::make_tests(&config);
322 let current_dir = env::current_dir().unwrap();
323 let res = run_tests(&config, &config.filters, tests);
324 env::set_current_dir(current_dir).unwrap();
328 Ok(false) => panic!("Some tests failed"),
330 panic!("I/O failure during tests: {:?}", e);
337 set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
341 run_internal_tests();
344 const RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS: &[&str] = &[
346 "borrow_deref_ref_unfixable.rs",
347 "cast_size_32bit.rs",
349 "cmp_owned/without_suggestion.rs",
351 "deref_addrof_double_trigger.rs",
352 "doc/unbalanced_ticks.rs",
353 "eprint_with_newline.rs",
354 "explicit_counter_loop.rs",
355 "iter_skip_next_unfixable.rs",
361 "mem_replace_macro.rs",
362 "needless_arbitrary_self_type_unfixable.rs",
363 "needless_borrow_pat.rs",
364 "needless_for_each_unfixable.rs",
365 "nonminimal_bool.rs",
367 "print_with_newline.rs",
368 "redundant_static_lifetimes_multiple.rs",
369 "ref_binding_to_reference.rs",
371 "result_map_unit_fn_unfixable.rs",
373 "single_component_path_imports_nested_first.rs",
375 "toplevel_ref_arg_non_rustfix.rs",
377 "unnecessary_clone.rs",
378 "unnecessary_lazy_eval_unfixable.rs",
380 "write_literal_2.rs",
381 "write_with_newline.rs",
384 fn check_rustfix_coverage() {
385 let missing_coverage_path = Path::new("target/debug/test/ui/rustfix_missing_coverage.txt");
387 if let Ok(missing_coverage_contents) = std::fs::read_to_string(missing_coverage_path) {
388 assert!(RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS.iter().is_sorted_by_key(Path::new));
390 for rs_path in missing_coverage_contents.lines() {
391 if Path::new(rs_path).starts_with("tests/ui/crashes") {
394 let filename = Path::new(rs_path).strip_prefix("tests/ui/").unwrap();
396 RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS
397 .binary_search_by_key(&filename, Path::new)
399 "`{}` runs `MachineApplicable` diagnostics but is missing a `run-rustfix` annotation. \
400 Please either add `// run-rustfix` at the top of the file or add the file to \
401 `RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS` in `tests/compile-test.rs`.",
409 fn rustfix_coverage_known_exceptions_accuracy() {
410 for filename in RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS {
411 let rs_path = Path::new("tests/ui").join(filename);
414 "`{}` does not exists",
415 rs_path.strip_prefix(env!("CARGO_MANIFEST_DIR")).unwrap().display()
417 let fixed_path = rs_path.with_extension("fixed");
419 !fixed_path.exists(),
421 fixed_path.strip_prefix(env!("CARGO_MANIFEST_DIR")).unwrap().display()
426 /// Restores an env var on drop
430 value: Option<OsString>,
434 fn set(key: &'static str, val: impl AsRef<OsStr>) -> Self {
435 let value = var_os(key);
441 impl Drop for VarGuard {
443 match self.value.as_deref() {
444 None => remove_var(self.key),
445 Some(value) => set_var(self.key, value),