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::lazy::SyncLazy;
16 use std::path::{Path, PathBuf};
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: SyncLazy<String> = SyncLazy::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",
118 .map(|(name, path)| format!(" --extern {}={}", name, path))
122 fn base_config(test_dir: &str) -> compiletest::Config {
123 let mut config = compiletest::Config {
124 edition: Some("2021".into()),
126 ..compiletest::Config::default()
129 if let Ok(filters) = env::var("TESTNAME") {
130 config.filters = filters.split(',').map(ToString::to_string).collect();
133 if let Some(path) = option_env!("RUSTC_LIB_PATH") {
134 let path = PathBuf::from(path);
135 config.run_lib_path = path.clone();
136 config.compile_lib_path = path;
138 let current_exe_path = env::current_exe().unwrap();
139 let deps_path = current_exe_path.parent().unwrap();
140 let profile_path = deps_path.parent().unwrap();
142 // Using `-L dependency={}` enforces that external dependencies are added with `--extern`.
143 // This is valuable because a) it allows us to monitor what external dependencies are used
144 // and b) it ensures that conflicting rlibs are resolved properly.
145 let host_libs = option_env!("HOST_LIBS")
146 .map(|p| format!(" -L dependency={}", Path::new(p).join("deps").display()))
147 .unwrap_or_default();
148 config.target_rustcflags = Some(format!(
149 "--emit=metadata -Dwarnings -Zui-testing -L dependency={}{}{}",
155 config.src_base = Path::new("tests").join(test_dir);
156 config.build_base = profile_path.join("test").join(test_dir);
157 config.rustc_path = profile_path.join(if cfg!(windows) {
166 let mut config = base_config("ui");
167 config.rustfix_coverage = true;
168 // use tests/clippy.toml
169 let _g = VarGuard::set("CARGO_MANIFEST_DIR", fs::canonicalize("tests").unwrap());
170 let _threads = VarGuard::set(
172 // if RUST_TEST_THREADS is set, adhere to it, otherwise override it
173 env::var("RUST_TEST_THREADS").unwrap_or_else(|_| {
174 std::thread::available_parallelism()
175 .map_or(1, std::num::NonZeroUsize::get)
179 compiletest::run_tests(&config);
180 check_rustfix_coverage();
183 fn run_internal_tests() {
184 // only run internal tests with the internal-tests feature
185 if !RUN_INTERNAL_TESTS {
188 let config = base_config("ui-internal");
189 compiletest::run_tests(&config);
193 fn run_tests(config: &compiletest::Config, mut tests: Vec<tester::TestDescAndFn>) -> Result<bool, io::Error> {
194 let mut result = true;
195 let opts = compiletest::test_opts(config);
196 for dir in fs::read_dir(&config.src_base)? {
198 if !dir.file_type()?.is_dir() {
201 let dir_path = dir.path();
202 let _g = VarGuard::set("CARGO_MANIFEST_DIR", &dir_path);
203 for file in fs::read_dir(&dir_path)? {
205 let file_path = file.path();
206 if file.file_type()?.is_dir() {
209 if file_path.extension() != Some(OsStr::new("rs")) {
212 let paths = compiletest::common::TestPaths {
214 base: config.src_base.clone(),
215 relative_dir: dir_path.file_name().unwrap().into(),
217 let test_name = compiletest::make_test_name(config, &paths);
220 .position(|test| test.desc.name == test_name)
221 .expect("The test should be in there");
222 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
228 let mut config = base_config("ui-toml");
229 config.src_base = config.src_base.canonicalize().unwrap();
231 let tests = compiletest::make_tests(&config);
233 let res = run_tests(&config, tests);
236 Ok(false) => panic!("Some tests failed"),
238 panic!("I/O failure during tests: {:?}", e);
245 config: &compiletest::Config,
247 mut tests: Vec<tester::TestDescAndFn>,
248 ) -> Result<bool, io::Error> {
249 let mut result = true;
250 let opts = compiletest::test_opts(config);
252 for dir in fs::read_dir(&config.src_base)? {
254 if !dir.file_type()?.is_dir() {
258 // Use the filter if provided
259 let dir_path = dir.path();
260 for filter in filters {
261 if !dir_path.ends_with(filter) {
266 for case in fs::read_dir(&dir_path)? {
268 if !case.file_type()?.is_dir() {
272 let src_path = case.path().join("src");
274 // When switching between branches, if the previous branch had a test
275 // that the current branch does not have, the directory is not removed
276 // because an ignored Cargo.lock file exists.
277 if !src_path.exists() {
281 env::set_current_dir(&src_path)?;
282 for file in fs::read_dir(&src_path)? {
284 if file.file_type()?.is_dir() {
288 // Search for the main file to avoid running a test for each file in the project
289 let file_path = file.path();
290 match file_path.file_name().and_then(OsStr::to_str) {
291 Some("main.rs") => {},
294 let _g = VarGuard::set("CLIPPY_CONF_DIR", case.path());
295 let paths = compiletest::common::TestPaths {
297 base: config.src_base.clone(),
298 relative_dir: src_path.strip_prefix(&config.src_base).unwrap().into(),
300 let test_name = compiletest::make_test_name(config, &paths);
303 .position(|test| test.desc.name == test_name)
304 .expect("The test should be in there");
305 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
312 if IS_RUSTC_TEST_SUITE {
316 let mut config = base_config("ui-cargo");
317 config.src_base = config.src_base.canonicalize().unwrap();
319 let tests = compiletest::make_tests(&config);
321 let current_dir = env::current_dir().unwrap();
322 let res = run_tests(&config, &config.filters, tests);
323 env::set_current_dir(current_dir).unwrap();
327 Ok(false) => panic!("Some tests failed"),
329 panic!("I/O failure during tests: {:?}", e);
336 set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
340 run_internal_tests();
343 const RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS: &[&str] = &[
345 "cast_size_32bit.rs",
347 "cmp_owned/without_suggestion.rs",
348 "crashes/ice-6250.rs",
349 "crashes/ice-6251.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 let filename = Path::new(rs_path).strip_prefix("tests/ui/").unwrap();
393 RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS
394 .binary_search_by_key(&filename, Path::new)
396 "`{}` runs `MachineApplicable` diagnostics but is missing a `run-rustfix` annotation. \
397 Please either add `// run-rustfix` at the top of the file or add the file to \
398 `RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS` in `tests/compile-test.rs`.",
406 fn rustfix_coverage_known_exceptions_accuracy() {
407 for filename in RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS {
408 let rs_path = Path::new("tests/ui").join(filename);
411 "`{}` does not exists",
412 rs_path.strip_prefix(env!("CARGO_MANIFEST_DIR")).unwrap().display()
414 let fixed_path = rs_path.with_extension("fixed");
416 !fixed_path.exists(),
418 fixed_path.strip_prefix(env!("CARGO_MANIFEST_DIR")).unwrap().display()
423 /// Restores an env var on drop
427 value: Option<OsString>,
431 fn set(key: &'static str, val: impl AsRef<OsStr>) -> Self {
432 let value = var_os(key);
438 impl Drop for VarGuard {
440 match self.value.as_deref() {
441 None => remove_var(self.key),
442 Some(value) => set_var(self.key, value),