1 #![feature(test)] // compiletest_rs requires this attribute
3 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
4 #![warn(rust_2018_idioms, unused_lifetimes)]
6 use compiletest_rs as compiletest;
7 use compiletest_rs::common::Mode as TestMode;
9 use std::collections::HashMap;
10 use std::env::{self, remove_var, set_var, var_os};
11 use std::ffi::{OsStr, OsString};
14 use std::lazy::SyncLazy;
15 use std::path::{Path, PathBuf};
16 use test_utils::IS_RUSTC_TEST_SUITE;
20 // whether to run internal tests or not
21 const RUN_INTERNAL_TESTS: bool = cfg!(feature = "internal");
23 /// All crates used in UI tests are listed here
24 static TEST_DEPENDENCIES: &[&str] = &[
40 // Test dependencies may need an `extern crate` here to ensure that they show up
41 // in the depinfo file (otherwise cargo thinks they are unused)
42 #[allow(unused_extern_crates)]
43 extern crate clippy_utils;
44 #[allow(unused_extern_crates)]
45 extern crate derive_new;
46 #[allow(unused_extern_crates)]
48 #[allow(unused_extern_crates)]
49 extern crate if_chain;
50 #[allow(unused_extern_crates)]
51 extern crate itertools;
52 #[allow(unused_extern_crates)]
53 extern crate parking_lot;
54 #[allow(unused_extern_crates)]
56 #[allow(unused_extern_crates)]
57 extern crate rustc_semver;
58 #[allow(unused_extern_crates)]
60 #[allow(unused_extern_crates)]
63 /// Produces a string with an `--extern` flag for all UI test crate
66 /// The dependency files are located by parsing the depinfo file for this test
67 /// module. This assumes the `-Z binary-dep-depinfo` flag is enabled. All test
68 /// dependencies must be added to Cargo.toml at the project root. Test
69 /// dependencies that are not *directly* used by this test module require an
70 /// `extern crate` declaration.
71 static EXTERN_FLAGS: SyncLazy<String> = SyncLazy::new(|| {
72 let current_exe_depinfo = {
73 let mut path = env::current_exe().unwrap();
74 path.set_extension("d");
75 fs::read_to_string(path).unwrap()
77 let mut crates: HashMap<&str, &str> = HashMap::with_capacity(TEST_DEPENDENCIES.len());
78 for line in current_exe_depinfo.lines() {
79 // each dependency is expected to have a Makefile rule like `/path/to/crate-hash.rlib:`
80 let parse_name_path = || {
81 if line.starts_with(char::is_whitespace) {
84 let path_str = line.strip_suffix(':')?;
85 let path = Path::new(path_str);
86 if !matches!(path.extension()?.to_str()?, "rlib" | "so" | "dylib" | "dll") {
89 let (name, _hash) = path.file_stem()?.to_str()?.rsplit_once('-')?;
90 // the "lib" prefix is not present for dll files
91 let name = name.strip_prefix("lib").unwrap_or(name);
92 Some((name, path_str))
94 if let Some((name, path)) = parse_name_path() {
95 if TEST_DEPENDENCIES.contains(&name) {
96 // A dependency may be listed twice if it is available in sysroot,
97 // and the sysroot dependencies are listed first. As of the writing,
98 // this only seems to apply to if_chain.
99 crates.insert(name, path);
103 let not_found: Vec<&str> = TEST_DEPENDENCIES
106 .filter(|n| !crates.contains_key(n))
109 not_found.is_empty(),
110 "dependencies not found in depinfo: {:?}\n\
111 help: Make sure the `-Z binary-dep-depinfo` rust flag is enabled\n\
112 help: Try adding to dev-dependencies in Cargo.toml",
117 .map(|(name, path)| format!(" --extern {}={}", name, path))
121 fn base_config(test_dir: &str) -> compiletest::Config {
122 let mut config = compiletest::Config {
123 edition: Some("2021".into()),
125 ..compiletest::Config::default()
128 if let Ok(filters) = env::var("TESTNAME") {
129 config.filters = filters.split(',').map(ToString::to_string).collect();
132 if let Some(path) = option_env!("RUSTC_LIB_PATH") {
133 let path = PathBuf::from(path);
134 config.run_lib_path = path.clone();
135 config.compile_lib_path = path;
137 let current_exe_path = env::current_exe().unwrap();
138 let deps_path = current_exe_path.parent().unwrap();
139 let profile_path = deps_path.parent().unwrap();
141 // Using `-L dependency={}` enforces that external dependencies are added with `--extern`.
142 // This is valuable because a) it allows us to monitor what external dependencies are used
143 // and b) it ensures that conflicting rlibs are resolved properly.
144 let host_libs = option_env!("HOST_LIBS")
145 .map(|p| format!(" -L dependency={}", Path::new(p).join("deps").display()))
146 .unwrap_or_default();
147 config.target_rustcflags = Some(format!(
148 "--emit=metadata -Dwarnings -Zui-testing -L dependency={}{}{}",
154 config.src_base = Path::new("tests").join(test_dir);
155 config.build_base = profile_path.join("test").join(test_dir);
156 config.rustc_path = profile_path.join(if cfg!(windows) {
165 let config = base_config("ui");
166 // use tests/clippy.toml
167 let _g = VarGuard::set("CARGO_MANIFEST_DIR", fs::canonicalize("tests").unwrap());
168 let _threads = VarGuard::set(
170 // if RUST_TEST_THREADS is set, adhere to it, otherwise override it
171 env::var("RUST_TEST_THREADS").unwrap_or_else(|_| {
172 std::thread::available_parallelism()
173 .map_or(1, std::num::NonZeroUsize::get)
177 compiletest::run_tests(&config);
180 fn run_internal_tests() {
181 // only run internal tests with the internal-tests feature
182 if !RUN_INTERNAL_TESTS {
185 let config = base_config("ui-internal");
186 compiletest::run_tests(&config);
190 fn run_tests(config: &compiletest::Config, mut tests: Vec<tester::TestDescAndFn>) -> Result<bool, io::Error> {
191 let mut result = true;
192 let opts = compiletest::test_opts(config);
193 for dir in fs::read_dir(&config.src_base)? {
195 if !dir.file_type()?.is_dir() {
198 let dir_path = dir.path();
199 let _g = VarGuard::set("CARGO_MANIFEST_DIR", &dir_path);
200 for file in fs::read_dir(&dir_path)? {
202 let file_path = file.path();
203 if file.file_type()?.is_dir() {
206 if file_path.extension() != Some(OsStr::new("rs")) {
209 let paths = compiletest::common::TestPaths {
211 base: config.src_base.clone(),
212 relative_dir: dir_path.file_name().unwrap().into(),
214 let test_name = compiletest::make_test_name(config, &paths);
217 .position(|test| test.desc.name == test_name)
218 .expect("The test should be in there");
219 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
225 let mut config = base_config("ui-toml");
226 config.src_base = config.src_base.canonicalize().unwrap();
228 let tests = compiletest::make_tests(&config);
230 let res = run_tests(&config, tests);
233 Ok(false) => panic!("Some tests failed"),
235 panic!("I/O failure during tests: {:?}", e);
242 config: &compiletest::Config,
244 mut tests: Vec<tester::TestDescAndFn>,
245 ) -> Result<bool, io::Error> {
246 let mut result = true;
247 let opts = compiletest::test_opts(config);
249 for dir in fs::read_dir(&config.src_base)? {
251 if !dir.file_type()?.is_dir() {
255 // Use the filter if provided
256 let dir_path = dir.path();
257 for filter in filters {
258 if !dir_path.ends_with(filter) {
263 for case in fs::read_dir(&dir_path)? {
265 if !case.file_type()?.is_dir() {
269 let src_path = case.path().join("src");
271 // When switching between branches, if the previous branch had a test
272 // that the current branch does not have, the directory is not removed
273 // because an ignored Cargo.lock file exists.
274 if !src_path.exists() {
278 env::set_current_dir(&src_path)?;
279 for file in fs::read_dir(&src_path)? {
281 if file.file_type()?.is_dir() {
285 // Search for the main file to avoid running a test for each file in the project
286 let file_path = file.path();
287 match file_path.file_name().and_then(OsStr::to_str) {
288 Some("main.rs") => {},
291 let _g = VarGuard::set("CLIPPY_CONF_DIR", case.path());
292 let paths = compiletest::common::TestPaths {
294 base: config.src_base.clone(),
295 relative_dir: src_path.strip_prefix(&config.src_base).unwrap().into(),
297 let test_name = compiletest::make_test_name(config, &paths);
300 .position(|test| test.desc.name == test_name)
301 .expect("The test should be in there");
302 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
309 if IS_RUSTC_TEST_SUITE {
313 let mut config = base_config("ui-cargo");
314 config.src_base = config.src_base.canonicalize().unwrap();
316 let tests = compiletest::make_tests(&config);
318 let current_dir = env::current_dir().unwrap();
319 let res = run_tests(&config, &config.filters, tests);
320 env::set_current_dir(current_dir).unwrap();
324 Ok(false) => panic!("Some tests failed"),
326 panic!("I/O failure during tests: {:?}", e);
333 set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
337 run_internal_tests();
340 /// Restores an env var on drop
344 value: Option<OsString>,
348 fn set(key: &'static str, val: impl AsRef<OsStr>) -> Self {
349 let value = var_os(key);
355 impl Drop for VarGuard {
357 match self.value.as_deref() {
358 None => remove_var(self.key),
359 Some(value) => set_var(self.key, value),