1 #![feature(test)] // compiletest_rs requires this attribute
4 use compiletest_rs as compiletest;
5 use compiletest_rs::common::Mode as TestMode;
7 use std::env::{self, remove_var, set_var, var_os};
8 use std::ffi::{OsStr, OsString};
11 use std::path::{Path, PathBuf};
15 // whether to run internal tests or not
16 const RUN_INTERNAL_TESTS: bool = cfg!(feature = "internal-lints");
18 fn host_lib() -> PathBuf {
19 option_env!("HOST_LIBS").map_or(cargo::CARGO_TARGET_DIR.join(env!("PROFILE")), PathBuf::from)
22 fn clippy_driver_path() -> PathBuf {
23 option_env!("CLIPPY_DRIVER_PATH").map_or(cargo::TARGET_LIB.join("clippy-driver"), PathBuf::from)
26 // When we'll want to use `extern crate ..` for a dependency that is used
27 // both by the crate and the compiler itself, we can't simply pass -L flags
28 // as we'll get a duplicate matching versions. Instead, disambiguate with
29 // `--extern dep=path`.
30 // See https://github.com/rust-lang/rust-clippy/issues/4015.
32 // FIXME: We cannot use `cargo build --message-format=json` to resolve to dependency files.
33 // Because it would force-rebuild if the options passed to `build` command is not the same
34 // as what we manually pass to `cargo` invocation
35 fn third_party_crates() -> String {
36 use std::collections::HashMap;
37 static CRATES: &[&str] = &["serde", "serde_derive", "regex", "clippy_lints", "syn", "quote"];
38 let dep_dir = cargo::TARGET_LIB.join("deps");
39 let mut crates: HashMap<&str, PathBuf> = HashMap::with_capacity(CRATES.len());
40 for entry in fs::read_dir(dep_dir).unwrap() {
41 let path = match entry {
42 Ok(entry) => entry.path(),
45 if let Some(name) = path.file_name().and_then(OsStr::to_str) {
47 if name.starts_with(&format!("lib{}-", dep))
48 && name.rsplit('.').next().map(|ext| ext.eq_ignore_ascii_case("rlib")) == Some(true)
50 if let Some(old) = crates.insert(dep, path.clone()) {
51 panic!("Found multiple rlibs for crate `{}`: `{:?}` and `{:?}", dep, old, path);
59 let v: Vec<_> = crates
61 .map(|(dep, path)| format!("--extern {}={}", dep, path.display()))
66 fn default_config() -> compiletest::Config {
67 let mut config = compiletest::Config::default();
69 if let Ok(filters) = env::var("TESTNAME") {
70 config.filters = filters.split(',').map(std::string::ToString::to_string).collect();
73 if let Some(path) = option_env!("RUSTC_LIB_PATH") {
74 let path = PathBuf::from(path);
75 config.run_lib_path = path.clone();
76 config.compile_lib_path = path;
79 config.target_rustcflags = Some(format!(
80 "--emit=metadata -L {0} -L {1} -Dwarnings -Zui-testing {2}",
81 host_lib().join("deps").display(),
82 cargo::TARGET_LIB.join("deps").display(),
86 config.build_base = host_lib().join("test_build_base");
87 config.rustc_path = clippy_driver_path();
91 fn run_ui(cfg: &mut compiletest::Config) {
92 cfg.mode = TestMode::Ui;
93 cfg.src_base = Path::new("tests").join("ui");
94 // use tests/clippy.toml
95 let _g = VarGuard::set("CARGO_MANIFEST_DIR", std::fs::canonicalize("tests").unwrap());
96 compiletest::run_tests(cfg);
99 fn run_internal_tests(cfg: &mut compiletest::Config) {
100 // only run internal tests with the internal-tests feature
101 if !RUN_INTERNAL_TESTS {
104 cfg.mode = TestMode::Ui;
105 cfg.src_base = Path::new("tests").join("ui-internal");
106 compiletest::run_tests(cfg);
109 fn run_ui_toml(config: &mut compiletest::Config) {
110 fn run_tests(config: &compiletest::Config, mut tests: Vec<tester::TestDescAndFn>) -> Result<bool, io::Error> {
111 let mut result = true;
112 let opts = compiletest::test_opts(config);
113 for dir in fs::read_dir(&config.src_base)? {
115 if !dir.file_type()?.is_dir() {
118 let dir_path = dir.path();
119 let _g = VarGuard::set("CARGO_MANIFEST_DIR", &dir_path);
120 for file in fs::read_dir(&dir_path)? {
122 let file_path = file.path();
123 if file.file_type()?.is_dir() {
126 if file_path.extension() != Some(OsStr::new("rs")) {
129 let paths = compiletest::common::TestPaths {
131 base: config.src_base.clone(),
132 relative_dir: dir_path.file_name().unwrap().into(),
134 let test_name = compiletest::make_test_name(config, &paths);
137 .position(|test| test.desc.name == test_name)
138 .expect("The test should be in there");
139 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
145 config.mode = TestMode::Ui;
146 config.src_base = Path::new("tests").join("ui-toml").canonicalize().unwrap();
148 let tests = compiletest::make_tests(config);
150 let res = run_tests(config, tests);
153 Ok(false) => panic!("Some tests failed"),
155 panic!("I/O failure during tests: {:?}", e);
160 fn run_ui_cargo(config: &mut compiletest::Config) {
162 config: &compiletest::Config,
164 mut tests: Vec<tester::TestDescAndFn>,
165 ) -> Result<bool, io::Error> {
166 let mut result = true;
167 let opts = compiletest::test_opts(config);
169 for dir in fs::read_dir(&config.src_base)? {
171 if !dir.file_type()?.is_dir() {
175 // Use the filter if provided
176 let dir_path = dir.path();
177 for filter in filters {
178 if !dir_path.ends_with(filter) {
183 for case in fs::read_dir(&dir_path)? {
185 if !case.file_type()?.is_dir() {
189 let src_path = case.path().join("src");
191 // When switching between branches, if the previous branch had a test
192 // that the current branch does not have, the directory is not removed
193 // because an ignored Cargo.lock file exists.
194 if !src_path.exists() {
198 env::set_current_dir(&src_path)?;
199 for file in fs::read_dir(&src_path)? {
201 if file.file_type()?.is_dir() {
205 // Search for the main file to avoid running a test for each file in the project
206 let file_path = file.path();
207 match file_path.file_name().and_then(OsStr::to_str) {
208 Some("main.rs") => {},
211 let _g = VarGuard::set("CLIPPY_CONF_DIR", case.path());
212 let paths = compiletest::common::TestPaths {
214 base: config.src_base.clone(),
215 relative_dir: src_path.strip_prefix(&config.src_base).unwrap().into(),
217 let test_name = compiletest::make_test_name(config, &paths);
220 .position(|test| test.desc.name == test_name)
221 .expect("The test should be in there");
222 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
229 if cargo::is_rustc_test_suite() {
233 config.mode = TestMode::Ui;
234 config.src_base = Path::new("tests").join("ui-cargo").canonicalize().unwrap();
236 let tests = compiletest::make_tests(config);
238 let current_dir = env::current_dir().unwrap();
239 let res = run_tests(config, &config.filters, tests);
240 env::set_current_dir(current_dir).unwrap();
244 Ok(false) => panic!("Some tests failed"),
246 panic!("I/O failure during tests: {:?}", e);
252 set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
253 set_var("__CLIPPY_INTERNAL_TESTS", "true");
254 //set_var("RUST_BACKTRACE", "0");
260 let mut config = default_config();
262 run_ui_toml(&mut config);
263 run_ui_cargo(&mut config);
264 run_internal_tests(&mut config);
267 /// Restores an env var on drop
271 value: Option<OsString>,
275 fn set(key: &'static str, val: impl AsRef<OsStr>) -> Self {
276 let value = var_os(key);
282 impl Drop for VarGuard {
284 match self.value.as_deref() {
285 None => remove_var(self.key),
286 Some(value) => set_var(self.key, value),