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] = &[
43 // Test dependencies may need an `extern crate` here to ensure that they show up
44 // in the depinfo file (otherwise cargo thinks they are unused)
45 #[allow(unused_extern_crates)]
47 #[allow(unused_extern_crates)]
48 extern crate clippy_lints;
49 #[allow(unused_extern_crates)]
50 extern crate clippy_utils;
51 #[allow(unused_extern_crates)]
52 extern crate derive_new;
53 #[allow(unused_extern_crates)]
55 #[allow(unused_extern_crates)]
56 extern crate if_chain;
57 #[allow(unused_extern_crates)]
58 extern crate itertools;
59 #[allow(unused_extern_crates)]
60 extern crate parking_lot;
61 #[allow(unused_extern_crates)]
63 #[allow(unused_extern_crates)]
64 extern crate rustc_semver;
65 #[allow(unused_extern_crates)]
67 #[allow(unused_extern_crates)]
70 /// Produces a string with an `--extern` flag for all UI test crate
73 /// The dependency files are located by parsing the depinfo file for this test
74 /// module. This assumes the `-Z binary-dep-depinfo` flag is enabled. All test
75 /// dependencies must be added to Cargo.toml at the project root. Test
76 /// dependencies that are not *directly* used by this test module require an
77 /// `extern crate` declaration.
78 static EXTERN_FLAGS: SyncLazy<String> = SyncLazy::new(|| {
79 let current_exe_depinfo = {
80 let mut path = env::current_exe().unwrap();
81 path.set_extension("d");
82 fs::read_to_string(path).unwrap()
84 let mut crates: HashMap<&str, &str> = HashMap::with_capacity(TEST_DEPENDENCIES.len());
85 for line in current_exe_depinfo.lines() {
86 // each dependency is expected to have a Makefile rule like `/path/to/crate-hash.rlib:`
87 let parse_name_path = || {
88 if line.starts_with(char::is_whitespace) {
91 let path_str = line.strip_suffix(':')?;
92 let path = Path::new(path_str);
93 if !matches!(path.extension()?.to_str()?, "rlib" | "so" | "dylib" | "dll") {
96 let (name, _hash) = path.file_stem()?.to_str()?.rsplit_once('-')?;
97 // the "lib" prefix is not present for dll files
98 let name = name.strip_prefix("lib").unwrap_or(name);
99 Some((name, path_str))
101 if let Some((name, path)) = parse_name_path() {
102 if TEST_DEPENDENCIES.contains(&name) {
103 // A dependency may be listed twice if it is available in sysroot,
104 // and the sysroot dependencies are listed first. As of the writing,
105 // this only seems to apply to if_chain.
106 crates.insert(name, path);
110 let not_found: Vec<&str> = TEST_DEPENDENCIES
113 .filter(|n| !crates.contains_key(n))
116 not_found.is_empty(),
117 "dependencies not found in depinfo: {:?}\n\
118 help: Make sure the `-Z binary-dep-depinfo` rust flag is enabled\n\
119 help: Try adding to dev-dependencies in Cargo.toml\n\
120 help: Be sure to also add `extern crate ...;` to tests/compile-test.rs",
125 .map(|(name, path)| format!(" --extern {}={}", name, path))
129 fn base_config(test_dir: &str) -> compiletest::Config {
130 let mut config = compiletest::Config {
131 edition: Some("2021".into()),
136 if let Ok(filters) = env::var("TESTNAME") {
137 config.filters = filters.split(',').map(ToString::to_string).collect();
140 if let Some(path) = option_env!("RUSTC_LIB_PATH") {
141 let path = PathBuf::from(path);
142 config.run_lib_path = path.clone();
143 config.compile_lib_path = path;
145 let current_exe_path = env::current_exe().unwrap();
146 let deps_path = current_exe_path.parent().unwrap();
147 let profile_path = deps_path.parent().unwrap();
149 // Using `-L dependency={}` enforces that external dependencies are added with `--extern`.
150 // This is valuable because a) it allows us to monitor what external dependencies are used
151 // and b) it ensures that conflicting rlibs are resolved properly.
152 let host_libs = option_env!("HOST_LIBS")
153 .map(|p| format!(" -L dependency={}", Path::new(p).join("deps").display()))
154 .unwrap_or_default();
155 config.target_rustcflags = Some(format!(
156 "--emit=metadata -Dwarnings -Zui-testing -L dependency={}{}{}",
162 config.src_base = Path::new("tests").join(test_dir);
163 config.build_base = profile_path.join("test").join(test_dir);
164 config.rustc_path = profile_path.join(if cfg!(windows) {
173 let mut config = base_config("ui");
174 config.rustfix_coverage = true;
175 // use tests/clippy.toml
176 let _g = VarGuard::set("CARGO_MANIFEST_DIR", fs::canonicalize("tests").unwrap());
177 let _threads = VarGuard::set(
179 // if RUST_TEST_THREADS is set, adhere to it, otherwise override it
180 env::var("RUST_TEST_THREADS").unwrap_or_else(|_| {
181 std::thread::available_parallelism()
182 .map_or(1, std::num::NonZeroUsize::get)
186 compiletest::run_tests(&config);
187 check_rustfix_coverage();
190 fn run_internal_tests() {
191 // only run internal tests with the internal-tests feature
192 if !RUN_INTERNAL_TESTS {
195 let config = base_config("ui-internal");
196 compiletest::run_tests(&config);
200 fn run_tests(config: &compiletest::Config, mut tests: Vec<tester::TestDescAndFn>) -> Result<bool, io::Error> {
201 let mut result = true;
202 let opts = compiletest::test_opts(config);
203 for dir in fs::read_dir(&config.src_base)? {
205 if !dir.file_type()?.is_dir() {
208 let dir_path = dir.path();
209 let _g = VarGuard::set("CARGO_MANIFEST_DIR", &dir_path);
210 for file in fs::read_dir(&dir_path)? {
212 let file_path = file.path();
213 if file.file_type()?.is_dir() {
216 if file_path.extension() != Some(OsStr::new("rs")) {
219 let paths = compiletest::common::TestPaths {
221 base: config.src_base.clone(),
222 relative_dir: dir_path.file_name().unwrap().into(),
224 let test_name = compiletest::make_test_name(config, &paths);
227 .position(|test| test.desc.name == test_name)
228 .expect("The test should be in there");
229 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
235 let mut config = base_config("ui-toml");
236 config.src_base = config.src_base.canonicalize().unwrap();
238 let tests = compiletest::make_tests(&config);
240 let res = run_tests(&config, tests);
243 Ok(false) => panic!("Some tests failed"),
245 panic!("I/O failure during tests: {:?}", e);
252 config: &compiletest::Config,
254 mut tests: Vec<tester::TestDescAndFn>,
255 ) -> Result<bool, io::Error> {
256 let mut result = true;
257 let opts = compiletest::test_opts(config);
259 for dir in fs::read_dir(&config.src_base)? {
261 if !dir.file_type()?.is_dir() {
265 // Use the filter if provided
266 let dir_path = dir.path();
267 for filter in filters {
268 if !dir_path.ends_with(filter) {
273 for case in fs::read_dir(&dir_path)? {
275 if !case.file_type()?.is_dir() {
279 let src_path = case.path().join("src");
281 // When switching between branches, if the previous branch had a test
282 // that the current branch does not have, the directory is not removed
283 // because an ignored Cargo.lock file exists.
284 if !src_path.exists() {
288 env::set_current_dir(&src_path)?;
290 let cargo_toml_path = case.path().join("Cargo.toml");
291 let cargo_content = fs::read(&cargo_toml_path)?;
292 let cargo_parsed: toml::Value = toml::from_str(
293 std::str::from_utf8(&cargo_content).expect("`Cargo.toml` is not a valid utf-8 file!"),
295 .expect("Can't parse `Cargo.toml`");
297 let _g = VarGuard::set("CARGO_MANIFEST_DIR", case.path());
298 let _h = VarGuard::set(
299 "CARGO_PKG_RUST_VERSION",
302 .and_then(|p| p.get("rust-version"))
303 .and_then(toml::Value::as_str)
307 for file in fs::read_dir(&src_path)? {
309 if file.file_type()?.is_dir() {
313 // Search for the main file to avoid running a test for each file in the project
314 let file_path = file.path();
315 match file_path.file_name().and_then(OsStr::to_str) {
316 Some("main.rs") => {},
319 let _g = VarGuard::set("CLIPPY_CONF_DIR", case.path());
320 let paths = compiletest::common::TestPaths {
322 base: config.src_base.clone(),
323 relative_dir: src_path.strip_prefix(&config.src_base).unwrap().into(),
325 let test_name = compiletest::make_test_name(config, &paths);
328 .position(|test| test.desc.name == test_name)
329 .expect("The test should be in there");
330 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
337 if IS_RUSTC_TEST_SUITE {
341 let mut config = base_config("ui-cargo");
342 config.src_base = config.src_base.canonicalize().unwrap();
344 let tests = compiletest::make_tests(&config);
346 let current_dir = env::current_dir().unwrap();
347 let res = run_tests(&config, &config.filters, tests);
348 env::set_current_dir(current_dir).unwrap();
352 Ok(false) => panic!("Some tests failed"),
354 panic!("I/O failure during tests: {:?}", e);
361 set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
365 run_internal_tests();
368 const RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS: &[&str] = &[
370 "borrow_deref_ref_unfixable.rs",
371 "cast_size_32bit.rs",
373 "cmp_owned/without_suggestion.rs",
375 "deref_addrof_double_trigger.rs",
376 "doc/unbalanced_ticks.rs",
377 "eprint_with_newline.rs",
378 "explicit_counter_loop.rs",
379 "iter_skip_next_unfixable.rs",
385 "mem_replace_macro.rs",
386 "needless_arbitrary_self_type_unfixable.rs",
387 "needless_borrow_pat.rs",
388 "needless_for_each_unfixable.rs",
389 "nonminimal_bool.rs",
391 "print_with_newline.rs",
392 "redundant_static_lifetimes_multiple.rs",
393 "ref_binding_to_reference.rs",
395 "result_map_unit_fn_unfixable.rs",
397 "single_component_path_imports_nested_first.rs",
399 "toplevel_ref_arg_non_rustfix.rs",
401 "unnecessary_clone.rs",
402 "unnecessary_lazy_eval_unfixable.rs",
404 "write_literal_2.rs",
405 "write_with_newline.rs",
408 fn check_rustfix_coverage() {
409 let missing_coverage_path = Path::new("target/debug/test/ui/rustfix_missing_coverage.txt");
411 if let Ok(missing_coverage_contents) = std::fs::read_to_string(missing_coverage_path) {
412 assert!(RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS.iter().is_sorted_by_key(Path::new));
414 for rs_path in missing_coverage_contents.lines() {
415 if Path::new(rs_path).starts_with("tests/ui/crashes") {
418 let filename = Path::new(rs_path).strip_prefix("tests/ui/").unwrap();
420 RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS
421 .binary_search_by_key(&filename, Path::new)
423 "`{}` runs `MachineApplicable` diagnostics but is missing a `run-rustfix` annotation. \
424 Please either add `// run-rustfix` at the top of the file or add the file to \
425 `RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS` in `tests/compile-test.rs`.",
433 fn rustfix_coverage_known_exceptions_accuracy() {
434 for filename in RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS {
435 let rs_path = Path::new("tests/ui").join(filename);
438 "`{}` does not exists",
439 rs_path.strip_prefix(env!("CARGO_MANIFEST_DIR")).unwrap().display()
441 let fixed_path = rs_path.with_extension("fixed");
443 !fixed_path.exists(),
445 fixed_path.strip_prefix(env!("CARGO_MANIFEST_DIR")).unwrap().display()
450 /// Restores an env var on drop
454 value: Option<OsString>,
458 fn set(key: &'static str, val: impl AsRef<OsStr>) -> Self {
459 let value = var_os(key);
465 impl Drop for VarGuard {
467 match self.value.as_deref() {
468 None => remove_var(self.key),
469 Some(value) => set_var(self.key, value),