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] = &[
33 // Test dependencies may need an `extern crate` here to ensure that they show up
34 // in the depinfo file (otherwise cargo thinks they are unused)
35 #[allow(unused_extern_crates)]
36 extern crate clippy_utils;
37 #[allow(unused_extern_crates)]
38 extern crate derive_new;
39 #[allow(unused_extern_crates)]
40 extern crate if_chain;
41 #[allow(unused_extern_crates)]
42 extern crate itertools;
43 #[allow(unused_extern_crates)]
45 #[allow(unused_extern_crates)]
48 /// Produces a string with an `--extern` flag for all UI test crate
51 /// The dependency files are located by parsing the depinfo file for this test
52 /// module. This assumes the `-Z binary-dep-depinfo` flag is enabled. All test
53 /// dependencies must be added to Cargo.toml at the project root. Test
54 /// dependencies that are not *directly* used by this test module require an
55 /// `extern crate` declaration.
56 fn extern_flags() -> String {
57 let current_exe_depinfo = {
58 let mut path = env::current_exe().unwrap();
59 path.set_extension("d");
60 std::fs::read_to_string(path).unwrap()
62 let mut crates: HashMap<&str, &str> = HashMap::with_capacity(TEST_DEPENDENCIES.len());
63 for line in current_exe_depinfo.lines() {
64 // each dependency is expected to have a Makefile rule like `/path/to/crate-hash.rlib:`
65 let parse_name_path = || {
66 if line.starts_with(char::is_whitespace) {
69 let path_str = line.strip_suffix(':')?;
70 let path = Path::new(path_str);
71 if !matches!(path.extension()?.to_str()?, "rlib" | "so" | "dylib" | "dll") {
74 let (name, _hash) = path.file_stem()?.to_str()?.rsplit_once('-')?;
75 // the "lib" prefix is not present for dll files
76 let name = name.strip_prefix("lib").unwrap_or(name);
77 Some((name, path_str))
79 if let Some((name, path)) = parse_name_path() {
80 if TEST_DEPENDENCIES.contains(&name) {
81 // A dependency may be listed twice if it is available in sysroot,
82 // and the sysroot dependencies are listed first. As of the writing,
83 // this only seems to apply to if_chain.
84 crates.insert(name, path);
88 let not_found: Vec<&str> = TEST_DEPENDENCIES
91 .filter(|n| !crates.contains_key(n))
95 "dependencies not found in depinfo: {:?}\n\
96 help: Make sure the `-Z binary-dep-depinfo` rust flag is enabled\n\
97 help: Try adding to dev-dependencies in Cargo.toml",
102 .map(|(name, path)| format!(" --extern {}={}", name, path))
106 fn default_config() -> compiletest::Config {
107 let mut config = compiletest::Config::default();
109 if let Ok(filters) = env::var("TESTNAME") {
110 config.filters = filters.split(',').map(std::string::ToString::to_string).collect();
113 if let Some(path) = option_env!("RUSTC_LIB_PATH") {
114 let path = PathBuf::from(path);
115 config.run_lib_path = path.clone();
116 config.compile_lib_path = path;
118 let current_exe_path = std::env::current_exe().unwrap();
119 let deps_path = current_exe_path.parent().unwrap();
120 let profile_path = deps_path.parent().unwrap();
122 // Using `-L dependency={}` enforces that external dependencies are added with `--extern`.
123 // This is valuable because a) it allows us to monitor what external dependencies are used
124 // and b) it ensures that conflicting rlibs are resolved properly.
125 let host_libs = option_env!("HOST_LIBS")
126 .map(|p| format!(" -L dependency={}", Path::new(p).join("deps").display()))
127 .unwrap_or_default();
128 config.target_rustcflags = Some(format!(
129 "--emit=metadata -Dwarnings -Zui-testing -L dependency={}{}{}",
135 config.build_base = profile_path.join("test");
136 config.rustc_path = profile_path.join(if cfg!(windows) {
144 fn run_ui(cfg: &mut compiletest::Config) {
145 cfg.mode = TestMode::Ui;
146 cfg.src_base = Path::new("tests").join("ui");
147 // use tests/clippy.toml
148 let _g = VarGuard::set("CARGO_MANIFEST_DIR", std::fs::canonicalize("tests").unwrap());
149 compiletest::run_tests(cfg);
152 fn run_ui_test(cfg: &mut compiletest::Config) {
153 cfg.mode = TestMode::Ui;
154 cfg.src_base = Path::new("tests").join("ui_test");
155 let _g = VarGuard::set("CARGO_MANIFEST_DIR", std::fs::canonicalize("tests").unwrap());
156 let rustcflags = cfg.target_rustcflags.get_or_insert_with(Default::default);
157 let len = rustcflags.len();
158 rustcflags.push_str(" --test");
159 compiletest::run_tests(cfg);
160 if let Some(ref mut flags) = &mut cfg.target_rustcflags {
165 fn run_internal_tests(cfg: &mut compiletest::Config) {
166 // only run internal tests with the internal-tests feature
167 if !RUN_INTERNAL_TESTS {
170 cfg.mode = TestMode::Ui;
171 cfg.src_base = Path::new("tests").join("ui-internal");
172 compiletest::run_tests(cfg);
175 fn run_ui_toml(config: &mut compiletest::Config) {
176 fn run_tests(config: &compiletest::Config, mut tests: Vec<tester::TestDescAndFn>) -> Result<bool, io::Error> {
177 let mut result = true;
178 let opts = compiletest::test_opts(config);
179 for dir in fs::read_dir(&config.src_base)? {
181 if !dir.file_type()?.is_dir() {
184 let dir_path = dir.path();
185 let _g = VarGuard::set("CARGO_MANIFEST_DIR", &dir_path);
186 for file in fs::read_dir(&dir_path)? {
188 let file_path = file.path();
189 if file.file_type()?.is_dir() {
192 if file_path.extension() != Some(OsStr::new("rs")) {
195 let paths = compiletest::common::TestPaths {
197 base: config.src_base.clone(),
198 relative_dir: dir_path.file_name().unwrap().into(),
200 let test_name = compiletest::make_test_name(config, &paths);
203 .position(|test| test.desc.name == test_name)
204 .expect("The test should be in there");
205 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
211 config.mode = TestMode::Ui;
212 config.src_base = Path::new("tests").join("ui-toml").canonicalize().unwrap();
214 let tests = compiletest::make_tests(config);
216 let res = run_tests(config, tests);
219 Ok(false) => panic!("Some tests failed"),
221 panic!("I/O failure during tests: {:?}", e);
226 fn run_ui_cargo(config: &mut compiletest::Config) {
228 config: &compiletest::Config,
230 mut tests: Vec<tester::TestDescAndFn>,
231 ) -> Result<bool, io::Error> {
232 let mut result = true;
233 let opts = compiletest::test_opts(config);
235 for dir in fs::read_dir(&config.src_base)? {
237 if !dir.file_type()?.is_dir() {
241 // Use the filter if provided
242 let dir_path = dir.path();
243 for filter in filters {
244 if !dir_path.ends_with(filter) {
249 for case in fs::read_dir(&dir_path)? {
251 if !case.file_type()?.is_dir() {
255 let src_path = case.path().join("src");
257 // When switching between branches, if the previous branch had a test
258 // that the current branch does not have, the directory is not removed
259 // because an ignored Cargo.lock file exists.
260 if !src_path.exists() {
264 env::set_current_dir(&src_path)?;
265 for file in fs::read_dir(&src_path)? {
267 if file.file_type()?.is_dir() {
271 // Search for the main file to avoid running a test for each file in the project
272 let file_path = file.path();
273 match file_path.file_name().and_then(OsStr::to_str) {
274 Some("main.rs") => {},
277 let _g = VarGuard::set("CLIPPY_CONF_DIR", case.path());
278 let paths = compiletest::common::TestPaths {
280 base: config.src_base.clone(),
281 relative_dir: src_path.strip_prefix(&config.src_base).unwrap().into(),
283 let test_name = compiletest::make_test_name(config, &paths);
286 .position(|test| test.desc.name == test_name)
287 .expect("The test should be in there");
288 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
295 if cargo::is_rustc_test_suite() {
299 config.mode = TestMode::Ui;
300 config.src_base = Path::new("tests").join("ui-cargo").canonicalize().unwrap();
302 let tests = compiletest::make_tests(config);
304 let current_dir = env::current_dir().unwrap();
305 let res = run_tests(config, &config.filters, tests);
306 env::set_current_dir(current_dir).unwrap();
310 Ok(false) => panic!("Some tests failed"),
312 panic!("I/O failure during tests: {:?}", e);
318 set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
319 set_var("__CLIPPY_INTERNAL_TESTS", "true");
320 //set_var("RUST_BACKTRACE", "0");
326 let mut config = default_config();
328 run_ui_test(&mut config);
329 run_ui_toml(&mut config);
330 run_ui_cargo(&mut config);
331 run_internal_tests(&mut config);
334 /// Restores an env var on drop
338 value: Option<OsString>,
342 fn set(key: &'static str, val: impl AsRef<OsStr>) -> Self {
343 let value = var_os(key);
349 impl Drop for VarGuard {
351 match self.value.as_deref() {
352 None => remove_var(self.key),
353 Some(value) => set_var(self.key, value),