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::path::{Path, PathBuf};
15 use test_utils::IS_RUSTC_TEST_SUITE;
19 // whether to run internal tests or not
20 const RUN_INTERNAL_TESTS: bool = cfg!(feature = "internal");
22 /// All crates used in UI tests are listed here
23 static TEST_DEPENDENCIES: &[&str] = &[
38 // Test dependencies may need an `extern crate` here to ensure that they show up
39 // in the depinfo file (otherwise cargo thinks they are unused)
40 #[allow(unused_extern_crates)]
41 extern crate clippy_utils;
42 #[allow(unused_extern_crates)]
43 extern crate derive_new;
44 #[allow(unused_extern_crates)]
46 #[allow(unused_extern_crates)]
47 extern crate if_chain;
48 #[allow(unused_extern_crates)]
49 extern crate itertools;
50 #[allow(unused_extern_crates)]
51 extern crate parking_lot;
52 #[allow(unused_extern_crates)]
54 #[allow(unused_extern_crates)]
56 #[allow(unused_extern_crates)]
59 /// Produces a string with an `--extern` flag for all UI test crate
62 /// The dependency files are located by parsing the depinfo file for this test
63 /// module. This assumes the `-Z binary-dep-depinfo` flag is enabled. All test
64 /// dependencies must be added to Cargo.toml at the project root. Test
65 /// dependencies that are not *directly* used by this test module require an
66 /// `extern crate` declaration.
67 fn extern_flags() -> String {
68 let current_exe_depinfo = {
69 let mut path = env::current_exe().unwrap();
70 path.set_extension("d");
71 std::fs::read_to_string(path).unwrap()
73 let mut crates: HashMap<&str, &str> = HashMap::with_capacity(TEST_DEPENDENCIES.len());
74 for line in current_exe_depinfo.lines() {
75 // each dependency is expected to have a Makefile rule like `/path/to/crate-hash.rlib:`
76 let parse_name_path = || {
77 if line.starts_with(char::is_whitespace) {
80 let path_str = line.strip_suffix(':')?;
81 let path = Path::new(path_str);
82 if !matches!(path.extension()?.to_str()?, "rlib" | "so" | "dylib" | "dll") {
85 let (name, _hash) = path.file_stem()?.to_str()?.rsplit_once('-')?;
86 // the "lib" prefix is not present for dll files
87 let name = name.strip_prefix("lib").unwrap_or(name);
88 Some((name, path_str))
90 if let Some((name, path)) = parse_name_path() {
91 if TEST_DEPENDENCIES.contains(&name) {
92 // A dependency may be listed twice if it is available in sysroot,
93 // and the sysroot dependencies are listed first. As of the writing,
94 // this only seems to apply to if_chain.
95 crates.insert(name, path);
99 let not_found: Vec<&str> = TEST_DEPENDENCIES
102 .filter(|n| !crates.contains_key(n))
105 not_found.is_empty(),
106 "dependencies not found in depinfo: {:?}\n\
107 help: Make sure the `-Z binary-dep-depinfo` rust flag is enabled\n\
108 help: Try adding to dev-dependencies in Cargo.toml",
113 .map(|(name, path)| format!(" --extern {}={}", name, path))
117 fn default_config() -> compiletest::Config {
118 let mut config = compiletest::Config {
119 edition: Some("2021".into()),
120 ..compiletest::Config::default()
123 if let Ok(filters) = env::var("TESTNAME") {
124 config.filters = filters.split(',').map(std::string::ToString::to_string).collect();
127 if let Some(path) = option_env!("RUSTC_LIB_PATH") {
128 let path = PathBuf::from(path);
129 config.run_lib_path = path.clone();
130 config.compile_lib_path = path;
132 let current_exe_path = std::env::current_exe().unwrap();
133 let deps_path = current_exe_path.parent().unwrap();
134 let profile_path = deps_path.parent().unwrap();
136 // Using `-L dependency={}` enforces that external dependencies are added with `--extern`.
137 // This is valuable because a) it allows us to monitor what external dependencies are used
138 // and b) it ensures that conflicting rlibs are resolved properly.
139 let host_libs = option_env!("HOST_LIBS")
140 .map(|p| format!(" -L dependency={}", Path::new(p).join("deps").display()))
141 .unwrap_or_default();
142 config.target_rustcflags = Some(format!(
143 "--emit=metadata -Dwarnings -Zui-testing -L dependency={}{}{}",
149 config.build_base = profile_path.join("test");
150 config.rustc_path = profile_path.join(if cfg!(windows) {
158 fn run_ui(cfg: &mut compiletest::Config) {
159 cfg.mode = TestMode::Ui;
160 cfg.src_base = Path::new("tests").join("ui");
161 // use tests/clippy.toml
162 let _g = VarGuard::set("CARGO_MANIFEST_DIR", std::fs::canonicalize("tests").unwrap());
163 compiletest::run_tests(cfg);
166 fn run_ui_test(cfg: &mut compiletest::Config) {
167 cfg.mode = TestMode::Ui;
168 cfg.src_base = Path::new("tests").join("ui_test");
169 let _g = VarGuard::set("CARGO_MANIFEST_DIR", std::fs::canonicalize("tests").unwrap());
170 let rustcflags = cfg.target_rustcflags.get_or_insert_with(Default::default);
171 let len = rustcflags.len();
172 rustcflags.push_str(" --test");
173 compiletest::run_tests(cfg);
174 if let Some(ref mut flags) = &mut cfg.target_rustcflags {
179 fn run_internal_tests(cfg: &mut compiletest::Config) {
180 // only run internal tests with the internal-tests feature
181 if !RUN_INTERNAL_TESTS {
184 cfg.mode = TestMode::Ui;
185 cfg.src_base = Path::new("tests").join("ui-internal");
186 compiletest::run_tests(cfg);
189 fn run_ui_toml(config: &mut compiletest::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 config.mode = TestMode::Ui;
226 config.src_base = Path::new("tests").join("ui-toml").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);
240 fn run_ui_cargo(config: &mut compiletest::Config) {
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 config.mode = TestMode::Ui;
314 config.src_base = Path::new("tests").join("ui-cargo").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");
334 let mut config = default_config();
336 run_ui_test(&mut config);
337 run_ui_toml(&mut config);
338 run_ui_cargo(&mut config);
339 run_internal_tests(&mut config);
342 /// Restores an env var on drop
346 value: Option<OsString>,
350 fn set(key: &'static str, val: impl AsRef<OsStr>) -> Self {
351 let value = var_os(key);
357 impl Drop for VarGuard {
359 match self.value.as_deref() {
360 None => remove_var(self.key),
361 Some(value) => set_var(self.key, value),