1 #![feature(test)] // compiletest_rs requires this attribute
2 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
3 #![warn(rust_2018_idioms, unused_lifetimes)]
5 use compiletest_rs as compiletest;
6 use compiletest_rs::common::Mode as TestMode;
8 use std::collections::HashMap;
9 use std::env::{self, remove_var, set_var, var_os};
10 use std::ffi::{OsStr, OsString};
13 use std::path::{Path, PathBuf};
17 // whether to run internal tests or not
18 const RUN_INTERNAL_TESTS: bool = cfg!(feature = "internal-lints");
20 /// All crates used in UI tests are listed here
21 static TEST_DEPENDENCIES: &[&str] = &[
34 // Test dependencies may need an `extern crate` here to ensure that they show up
35 // in the depinfo file (otherwise cargo thinks they are unused)
36 #[allow(unused_extern_crates)]
37 extern crate clippy_utils;
38 #[allow(unused_extern_crates)]
39 extern crate derive_new;
40 #[allow(unused_extern_crates)]
41 extern crate if_chain;
42 #[allow(unused_extern_crates)]
43 extern crate itertools;
44 #[allow(unused_extern_crates)]
45 extern crate parking_lot;
46 #[allow(unused_extern_crates)]
48 #[allow(unused_extern_crates)]
51 /// Produces a string with an `--extern` flag for all UI test crate
54 /// The dependency files are located by parsing the depinfo file for this test
55 /// module. This assumes the `-Z binary-dep-depinfo` flag is enabled. All test
56 /// dependencies must be added to Cargo.toml at the project root. Test
57 /// dependencies that are not *directly* used by this test module require an
58 /// `extern crate` declaration.
59 fn extern_flags() -> String {
60 let current_exe_depinfo = {
61 let mut path = env::current_exe().unwrap();
62 path.set_extension("d");
63 std::fs::read_to_string(path).unwrap()
65 let mut crates: HashMap<&str, &str> = HashMap::with_capacity(TEST_DEPENDENCIES.len());
66 for line in current_exe_depinfo.lines() {
67 // each dependency is expected to have a Makefile rule like `/path/to/crate-hash.rlib:`
68 let parse_name_path = || {
69 if line.starts_with(char::is_whitespace) {
72 let path_str = line.strip_suffix(':')?;
73 let path = Path::new(path_str);
74 if !matches!(path.extension()?.to_str()?, "rlib" | "so" | "dylib" | "dll") {
77 let (name, _hash) = path.file_stem()?.to_str()?.rsplit_once('-')?;
78 // the "lib" prefix is not present for dll files
79 let name = name.strip_prefix("lib").unwrap_or(name);
80 Some((name, path_str))
82 if let Some((name, path)) = parse_name_path() {
83 if TEST_DEPENDENCIES.contains(&name) {
84 // A dependency may be listed twice if it is available in sysroot,
85 // and the sysroot dependencies are listed first. As of the writing,
86 // this only seems to apply to if_chain.
87 crates.insert(name, path);
91 let not_found: Vec<&str> = TEST_DEPENDENCIES
94 .filter(|n| !crates.contains_key(n))
98 "dependencies not found in depinfo: {:?}\n\
99 help: Make sure the `-Z binary-dep-depinfo` rust flag is enabled\n\
100 help: Try adding to dev-dependencies in Cargo.toml",
105 .map(|(name, path)| format!(" --extern {}={}", name, path))
109 fn default_config() -> compiletest::Config {
110 let mut config = compiletest::Config {
111 edition: Some("2021".into()),
112 ..compiletest::Config::default()
115 if let Ok(filters) = env::var("TESTNAME") {
116 config.filters = filters.split(',').map(std::string::ToString::to_string).collect();
119 if let Some(path) = option_env!("RUSTC_LIB_PATH") {
120 let path = PathBuf::from(path);
121 config.run_lib_path = path.clone();
122 config.compile_lib_path = path;
124 let current_exe_path = std::env::current_exe().unwrap();
125 let deps_path = current_exe_path.parent().unwrap();
126 let profile_path = deps_path.parent().unwrap();
128 // Using `-L dependency={}` enforces that external dependencies are added with `--extern`.
129 // This is valuable because a) it allows us to monitor what external dependencies are used
130 // and b) it ensures that conflicting rlibs are resolved properly.
131 let host_libs = option_env!("HOST_LIBS")
132 .map(|p| format!(" -L dependency={}", Path::new(p).join("deps").display()))
133 .unwrap_or_default();
134 config.target_rustcflags = Some(format!(
135 "--emit=metadata -Dwarnings -Zui-testing -L dependency={}{}{}",
141 config.build_base = profile_path.join("test");
142 config.rustc_path = profile_path.join(if cfg!(windows) {
150 fn run_ui(cfg: &mut compiletest::Config) {
151 cfg.mode = TestMode::Ui;
152 cfg.src_base = Path::new("tests").join("ui");
153 // use tests/clippy.toml
154 let _g = VarGuard::set("CARGO_MANIFEST_DIR", std::fs::canonicalize("tests").unwrap());
155 compiletest::run_tests(cfg);
158 fn run_ui_test(cfg: &mut compiletest::Config) {
159 cfg.mode = TestMode::Ui;
160 cfg.src_base = Path::new("tests").join("ui_test");
161 let _g = VarGuard::set("CARGO_MANIFEST_DIR", std::fs::canonicalize("tests").unwrap());
162 let rustcflags = cfg.target_rustcflags.get_or_insert_with(Default::default);
163 let len = rustcflags.len();
164 rustcflags.push_str(" --test");
165 compiletest::run_tests(cfg);
166 if let Some(ref mut flags) = &mut cfg.target_rustcflags {
171 fn run_internal_tests(cfg: &mut compiletest::Config) {
172 // only run internal tests with the internal-tests feature
173 if !RUN_INTERNAL_TESTS {
176 cfg.mode = TestMode::Ui;
177 cfg.src_base = Path::new("tests").join("ui-internal");
178 compiletest::run_tests(cfg);
181 fn run_ui_toml(config: &mut compiletest::Config) {
182 fn run_tests(config: &compiletest::Config, mut tests: Vec<tester::TestDescAndFn>) -> Result<bool, io::Error> {
183 let mut result = true;
184 let opts = compiletest::test_opts(config);
185 for dir in fs::read_dir(&config.src_base)? {
187 if !dir.file_type()?.is_dir() {
190 let dir_path = dir.path();
191 let _g = VarGuard::set("CARGO_MANIFEST_DIR", &dir_path);
192 for file in fs::read_dir(&dir_path)? {
194 let file_path = file.path();
195 if file.file_type()?.is_dir() {
198 if file_path.extension() != Some(OsStr::new("rs")) {
201 let paths = compiletest::common::TestPaths {
203 base: config.src_base.clone(),
204 relative_dir: dir_path.file_name().unwrap().into(),
206 let test_name = compiletest::make_test_name(config, &paths);
209 .position(|test| test.desc.name == test_name)
210 .expect("The test should be in there");
211 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
217 config.mode = TestMode::Ui;
218 config.src_base = Path::new("tests").join("ui-toml").canonicalize().unwrap();
220 let tests = compiletest::make_tests(config);
222 let res = run_tests(config, tests);
225 Ok(false) => panic!("Some tests failed"),
227 panic!("I/O failure during tests: {:?}", e);
232 fn run_ui_cargo(config: &mut compiletest::Config) {
234 config: &compiletest::Config,
236 mut tests: Vec<tester::TestDescAndFn>,
237 ) -> Result<bool, io::Error> {
238 let mut result = true;
239 let opts = compiletest::test_opts(config);
241 for dir in fs::read_dir(&config.src_base)? {
243 if !dir.file_type()?.is_dir() {
247 // Use the filter if provided
248 let dir_path = dir.path();
249 for filter in filters {
250 if !dir_path.ends_with(filter) {
255 for case in fs::read_dir(&dir_path)? {
257 if !case.file_type()?.is_dir() {
261 let src_path = case.path().join("src");
263 // When switching between branches, if the previous branch had a test
264 // that the current branch does not have, the directory is not removed
265 // because an ignored Cargo.lock file exists.
266 if !src_path.exists() {
270 env::set_current_dir(&src_path)?;
271 for file in fs::read_dir(&src_path)? {
273 if file.file_type()?.is_dir() {
277 // Search for the main file to avoid running a test for each file in the project
278 let file_path = file.path();
279 match file_path.file_name().and_then(OsStr::to_str) {
280 Some("main.rs") => {},
283 let _g = VarGuard::set("CLIPPY_CONF_DIR", case.path());
284 let paths = compiletest::common::TestPaths {
286 base: config.src_base.clone(),
287 relative_dir: src_path.strip_prefix(&config.src_base).unwrap().into(),
289 let test_name = compiletest::make_test_name(config, &paths);
292 .position(|test| test.desc.name == test_name)
293 .expect("The test should be in there");
294 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
301 if cargo::is_rustc_test_suite() {
305 config.mode = TestMode::Ui;
306 config.src_base = Path::new("tests").join("ui-cargo").canonicalize().unwrap();
308 let tests = compiletest::make_tests(config);
310 let current_dir = env::current_dir().unwrap();
311 let res = run_tests(config, &config.filters, tests);
312 env::set_current_dir(current_dir).unwrap();
316 Ok(false) => panic!("Some tests failed"),
318 panic!("I/O failure during tests: {:?}", e);
324 set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
325 set_var("__CLIPPY_INTERNAL_TESTS", "true");
326 //set_var("RUST_BACKTRACE", "0");
332 let mut config = default_config();
334 run_ui_test(&mut config);
335 run_ui_toml(&mut config);
336 run_ui_cargo(&mut config);
337 run_internal_tests(&mut config);
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),