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] = &[
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)]
45 #[allow(unused_extern_crates)]
46 extern crate clippy_utils;
47 #[allow(unused_extern_crates)]
48 extern crate derive_new;
49 #[allow(unused_extern_crates)]
51 #[allow(unused_extern_crates)]
52 extern crate if_chain;
53 #[allow(unused_extern_crates)]
54 extern crate itertools;
55 #[allow(unused_extern_crates)]
56 extern crate parking_lot;
57 #[allow(unused_extern_crates)]
59 #[allow(unused_extern_crates)]
60 extern crate rustc_semver;
61 #[allow(unused_extern_crates)]
63 #[allow(unused_extern_crates)]
66 /// Produces a string with an `--extern` flag for all UI test crate
69 /// The dependency files are located by parsing the depinfo file for this test
70 /// module. This assumes the `-Z binary-dep-depinfo` flag is enabled. All test
71 /// dependencies must be added to Cargo.toml at the project root. Test
72 /// dependencies that are not *directly* used by this test module require an
73 /// `extern crate` declaration.
74 static EXTERN_FLAGS: SyncLazy<String> = SyncLazy::new(|| {
75 let current_exe_depinfo = {
76 let mut path = env::current_exe().unwrap();
77 path.set_extension("d");
78 fs::read_to_string(path).unwrap()
80 let mut crates: HashMap<&str, &str> = HashMap::with_capacity(TEST_DEPENDENCIES.len());
81 for line in current_exe_depinfo.lines() {
82 // each dependency is expected to have a Makefile rule like `/path/to/crate-hash.rlib:`
83 let parse_name_path = || {
84 if line.starts_with(char::is_whitespace) {
87 let path_str = line.strip_suffix(':')?;
88 let path = Path::new(path_str);
89 if !matches!(path.extension()?.to_str()?, "rlib" | "so" | "dylib" | "dll") {
92 let (name, _hash) = path.file_stem()?.to_str()?.rsplit_once('-')?;
93 // the "lib" prefix is not present for dll files
94 let name = name.strip_prefix("lib").unwrap_or(name);
95 Some((name, path_str))
97 if let Some((name, path)) = parse_name_path() {
98 if TEST_DEPENDENCIES.contains(&name) {
99 // A dependency may be listed twice if it is available in sysroot,
100 // and the sysroot dependencies are listed first. As of the writing,
101 // this only seems to apply to if_chain.
102 crates.insert(name, path);
106 let not_found: Vec<&str> = TEST_DEPENDENCIES
109 .filter(|n| !crates.contains_key(n))
112 not_found.is_empty(),
113 "dependencies not found in depinfo: {:?}\n\
114 help: Make sure the `-Z binary-dep-depinfo` rust flag is enabled\n\
115 help: Try adding to dev-dependencies in Cargo.toml\n\
116 help: Be sure to also add `extern crate ...;` to tests/compile-test.rs",
121 .map(|(name, path)| format!(" --extern {}={}", name, path))
125 fn base_config(test_dir: &str) -> compiletest::Config {
126 let mut config = compiletest::Config {
127 edition: Some("2021".into()),
129 ..compiletest::Config::default()
132 if let Ok(filters) = env::var("TESTNAME") {
133 config.filters = filters.split(',').map(ToString::to_string).collect();
136 if let Some(path) = option_env!("RUSTC_LIB_PATH") {
137 let path = PathBuf::from(path);
138 config.run_lib_path = path.clone();
139 config.compile_lib_path = path;
141 let current_exe_path = env::current_exe().unwrap();
142 let deps_path = current_exe_path.parent().unwrap();
143 let profile_path = deps_path.parent().unwrap();
145 // Using `-L dependency={}` enforces that external dependencies are added with `--extern`.
146 // This is valuable because a) it allows us to monitor what external dependencies are used
147 // and b) it ensures that conflicting rlibs are resolved properly.
148 let host_libs = option_env!("HOST_LIBS")
149 .map(|p| format!(" -L dependency={}", Path::new(p).join("deps").display()))
150 .unwrap_or_default();
151 config.target_rustcflags = Some(format!(
152 "--emit=metadata -Dwarnings -Zui-testing -L dependency={}{}{}",
158 config.src_base = Path::new("tests").join(test_dir);
159 config.build_base = profile_path.join("test").join(test_dir);
160 config.rustc_path = profile_path.join(if cfg!(windows) {
169 let config = base_config("ui");
170 // use tests/clippy.toml
171 let _g = VarGuard::set("CARGO_MANIFEST_DIR", fs::canonicalize("tests").unwrap());
172 let _threads = VarGuard::set(
174 // if RUST_TEST_THREADS is set, adhere to it, otherwise override it
175 env::var("RUST_TEST_THREADS").unwrap_or_else(|_| {
176 std::thread::available_parallelism()
177 .map_or(1, std::num::NonZeroUsize::get)
181 compiletest::run_tests(&config);
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 /// Restores an env var on drop
348 value: Option<OsString>,
352 fn set(key: &'static str, val: impl AsRef<OsStr>) -> Self {
353 let value = var_os(key);
359 impl Drop for VarGuard {
361 match self.value.as_deref() {
362 None => remove_var(self.key),
363 Some(value) => set_var(self.key, value),