]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/tests/compile-test.rs
26a47d237065a9f0c16cc3db6638a014b9ae86b7
[rust.git] / src / tools / clippy / tests / compile-test.rs
1 #![feature(test)] // compiletest_rs requires this attribute
2
3 use compiletest_rs as compiletest;
4 use compiletest_rs::common::Mode as TestMode;
5
6 use std::env::{self, set_var};
7 use std::ffi::OsStr;
8 use std::fs;
9 use std::io;
10 use std::path::{Path, PathBuf};
11
12 mod cargo;
13
14 fn host_lib() -> PathBuf {
15     option_env!("HOST_LIBS").map_or(cargo::CARGO_TARGET_DIR.join(env!("PROFILE")), PathBuf::from)
16 }
17
18 fn clippy_driver_path() -> PathBuf {
19     option_env!("CLIPPY_DRIVER_PATH").map_or(cargo::TARGET_LIB.join("clippy-driver"), PathBuf::from)
20 }
21
22 // When we'll want to use `extern crate ..` for a dependency that is used
23 // both by the crate and the compiler itself, we can't simply pass -L flags
24 // as we'll get a duplicate matching versions. Instead, disambiguate with
25 // `--extern dep=path`.
26 // See https://github.com/rust-lang/rust-clippy/issues/4015.
27 //
28 // FIXME: We cannot use `cargo build --message-format=json` to resolve to dependency files.
29 //        Because it would force-rebuild if the options passed to `build` command is not the same
30 //        as what we manually pass to `cargo` invocation
31 fn third_party_crates() -> String {
32     use std::collections::HashMap;
33     static CRATES: &[&str] = &["serde", "serde_derive", "regex", "clippy_lints", "syn", "quote"];
34     let dep_dir = cargo::TARGET_LIB.join("deps");
35     let mut crates: HashMap<&str, PathBuf> = HashMap::with_capacity(CRATES.len());
36     for entry in fs::read_dir(dep_dir).unwrap() {
37         let path = match entry {
38             Ok(entry) => entry.path(),
39             Err(_) => continue,
40         };
41         if let Some(name) = path.file_name().and_then(OsStr::to_str) {
42             for dep in CRATES {
43                 if name.starts_with(&format!("lib{}-", dep)) && name.ends_with(".rlib") {
44                     if let Some(old) = crates.insert(dep, path.clone()) {
45                         panic!("Found multiple rlibs for crate `{}`: `{:?}` and `{:?}", dep, old, path);
46                     }
47                     break;
48                 }
49             }
50         }
51     }
52
53     let v: Vec<_> = crates
54         .into_iter()
55         .map(|(dep, path)| format!("--extern {}={}", dep, path.display()))
56         .collect();
57     v.join(" ")
58 }
59
60 fn default_config() -> compiletest::Config {
61     let mut config = compiletest::Config::default();
62
63     if let Ok(name) = env::var("TESTNAME") {
64         config.filter = Some(name);
65     }
66
67     if let Some(path) = option_env!("RUSTC_LIB_PATH") {
68         let path = PathBuf::from(path);
69         config.run_lib_path = path.clone();
70         config.compile_lib_path = path;
71     }
72
73     config.target_rustcflags = Some(format!(
74         "-L {0} -L {1} -Dwarnings -Zui-testing {2}",
75         host_lib().join("deps").display(),
76         cargo::TARGET_LIB.join("deps").display(),
77         third_party_crates(),
78     ));
79
80     config.build_base = if cargo::is_rustc_test_suite() {
81         // This make the stderr files go to clippy OUT_DIR on rustc repo build dir
82         let mut path = PathBuf::from(env!("OUT_DIR"));
83         path.push("test_build_base");
84         path
85     } else {
86         host_lib().join("test_build_base")
87     };
88     config.rustc_path = clippy_driver_path();
89     config
90 }
91
92 fn run_mode(cfg: &mut compiletest::Config) {
93     cfg.mode = TestMode::Ui;
94     cfg.src_base = Path::new("tests").join("ui");
95     compiletest::run_tests(&cfg);
96 }
97
98 fn run_ui_toml(config: &mut compiletest::Config) {
99     fn run_tests(config: &compiletest::Config, mut tests: Vec<tester::TestDescAndFn>) -> Result<bool, io::Error> {
100         let mut result = true;
101         let opts = compiletest::test_opts(config);
102         for dir in fs::read_dir(&config.src_base)? {
103             let dir = dir?;
104             if !dir.file_type()?.is_dir() {
105                 continue;
106             }
107             let dir_path = dir.path();
108             set_var("CARGO_MANIFEST_DIR", &dir_path);
109             for file in fs::read_dir(&dir_path)? {
110                 let file = file?;
111                 let file_path = file.path();
112                 if file.file_type()?.is_dir() {
113                     continue;
114                 }
115                 if file_path.extension() != Some(OsStr::new("rs")) {
116                     continue;
117                 }
118                 let paths = compiletest::common::TestPaths {
119                     file: file_path,
120                     base: config.src_base.clone(),
121                     relative_dir: dir_path.file_name().unwrap().into(),
122                 };
123                 let test_name = compiletest::make_test_name(&config, &paths);
124                 let index = tests
125                     .iter()
126                     .position(|test| test.desc.name == test_name)
127                     .expect("The test should be in there");
128                 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
129             }
130         }
131         Ok(result)
132     }
133
134     config.mode = TestMode::Ui;
135     config.src_base = Path::new("tests").join("ui-toml").canonicalize().unwrap();
136
137     let tests = compiletest::make_tests(&config);
138
139     let res = run_tests(&config, tests);
140     match res {
141         Ok(true) => {},
142         Ok(false) => panic!("Some tests failed"),
143         Err(e) => {
144             panic!("I/O failure during tests: {:?}", e);
145         },
146     }
147 }
148
149 fn run_ui_cargo(config: &mut compiletest::Config) {
150     if cargo::is_rustc_test_suite() {
151         return;
152     }
153     fn run_tests(
154         config: &compiletest::Config,
155         filter: &Option<String>,
156         mut tests: Vec<tester::TestDescAndFn>,
157     ) -> Result<bool, io::Error> {
158         let mut result = true;
159         let opts = compiletest::test_opts(config);
160
161         for dir in fs::read_dir(&config.src_base)? {
162             let dir = dir?;
163             if !dir.file_type()?.is_dir() {
164                 continue;
165             }
166
167             // Use the filter if provided
168             let dir_path = dir.path();
169             match &filter {
170                 Some(name) if !dir_path.ends_with(name) => continue,
171                 _ => {},
172             }
173
174             for case in fs::read_dir(&dir_path)? {
175                 let case = case?;
176                 if !case.file_type()?.is_dir() {
177                     continue;
178                 }
179
180                 let src_path = case.path().join("src");
181
182                 // When switching between branches, if the previous branch had a test
183                 // that the current branch does not have, the directory is not removed
184                 // because an ignored Cargo.lock file exists.
185                 if !src_path.exists() {
186                     continue;
187                 }
188
189                 env::set_current_dir(&src_path)?;
190                 for file in fs::read_dir(&src_path)? {
191                     let file = file?;
192                     if file.file_type()?.is_dir() {
193                         continue;
194                     }
195
196                     // Search for the main file to avoid running a test for each file in the project
197                     let file_path = file.path();
198                     match file_path.file_name().and_then(OsStr::to_str) {
199                         Some("main.rs") => {},
200                         _ => continue,
201                     }
202
203                     let paths = compiletest::common::TestPaths {
204                         file: file_path,
205                         base: config.src_base.clone(),
206                         relative_dir: src_path.strip_prefix(&config.src_base).unwrap().into(),
207                     };
208                     let test_name = compiletest::make_test_name(&config, &paths);
209                     let index = tests
210                         .iter()
211                         .position(|test| test.desc.name == test_name)
212                         .expect("The test should be in there");
213                     result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
214                 }
215             }
216         }
217         Ok(result)
218     }
219
220     config.mode = TestMode::Ui;
221     config.src_base = Path::new("tests").join("ui-cargo").canonicalize().unwrap();
222
223     let tests = compiletest::make_tests(&config);
224
225     let current_dir = env::current_dir().unwrap();
226     let filter = env::var("TESTNAME").ok();
227     let res = run_tests(&config, &filter, tests);
228     env::set_current_dir(current_dir).unwrap();
229
230     match res {
231         Ok(true) => {},
232         Ok(false) => panic!("Some tests failed"),
233         Err(e) => {
234             panic!("I/O failure during tests: {:?}", e);
235         },
236     }
237 }
238
239 fn prepare_env() {
240     set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
241     set_var("CLIPPY_TESTS", "true");
242     //set_var("RUST_BACKTRACE", "0");
243 }
244
245 #[test]
246 fn compile_test() {
247     prepare_env();
248     let mut config = default_config();
249     run_mode(&mut config);
250     run_ui_toml(&mut config);
251     run_ui_cargo(&mut config);
252 }