]> git.lizzy.rs Git - rust.git/blob - tests/compile-test.rs
Auto merge of #8210 - guerinoni:master, r=Manishearth
[rust.git] / tests / compile-test.rs
1 #![feature(test)] // compiletest_rs requires this attribute
2 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
3 #![warn(rust_2018_idioms, unused_lifetimes)]
4
5 use compiletest_rs as compiletest;
6 use compiletest_rs::common::Mode as TestMode;
7
8 use std::collections::HashMap;
9 use std::env::{self, remove_var, set_var, var_os};
10 use std::ffi::{OsStr, OsString};
11 use std::fs;
12 use std::io;
13 use std::path::{Path, PathBuf};
14
15 mod cargo;
16
17 // whether to run internal tests or not
18 const RUN_INTERNAL_TESTS: bool = cfg!(feature = "internal");
19
20 /// All crates used in UI tests are listed here
21 static TEST_DEPENDENCIES: &[&str] = &[
22     "clippy_utils",
23     "derive_new",
24     "futures",
25     "if_chain",
26     "itertools",
27     "quote",
28     "regex",
29     "serde",
30     "serde_derive",
31     "syn",
32     "tokio",
33     "parking_lot",
34 ];
35
36 // Test dependencies may need an `extern crate` here to ensure that they show up
37 // in the depinfo file (otherwise cargo thinks they are unused)
38 #[allow(unused_extern_crates)]
39 extern crate clippy_utils;
40 #[allow(unused_extern_crates)]
41 extern crate derive_new;
42 #[allow(unused_extern_crates)]
43 extern crate futures;
44 #[allow(unused_extern_crates)]
45 extern crate if_chain;
46 #[allow(unused_extern_crates)]
47 extern crate itertools;
48 #[allow(unused_extern_crates)]
49 extern crate parking_lot;
50 #[allow(unused_extern_crates)]
51 extern crate quote;
52 #[allow(unused_extern_crates)]
53 extern crate syn;
54 #[allow(unused_extern_crates)]
55 extern crate tokio;
56
57 /// Produces a string with an `--extern` flag for all UI test crate
58 /// dependencies.
59 ///
60 /// The dependency files are located by parsing the depinfo file for this test
61 /// module. This assumes the `-Z binary-dep-depinfo` flag is enabled. All test
62 /// dependencies must be added to Cargo.toml at the project root. Test
63 /// dependencies that are not *directly* used by this test module require an
64 /// `extern crate` declaration.
65 fn extern_flags() -> String {
66     let current_exe_depinfo = {
67         let mut path = env::current_exe().unwrap();
68         path.set_extension("d");
69         std::fs::read_to_string(path).unwrap()
70     };
71     let mut crates: HashMap<&str, &str> = HashMap::with_capacity(TEST_DEPENDENCIES.len());
72     for line in current_exe_depinfo.lines() {
73         // each dependency is expected to have a Makefile rule like `/path/to/crate-hash.rlib:`
74         let parse_name_path = || {
75             if line.starts_with(char::is_whitespace) {
76                 return None;
77             }
78             let path_str = line.strip_suffix(':')?;
79             let path = Path::new(path_str);
80             if !matches!(path.extension()?.to_str()?, "rlib" | "so" | "dylib" | "dll") {
81                 return None;
82             }
83             let (name, _hash) = path.file_stem()?.to_str()?.rsplit_once('-')?;
84             // the "lib" prefix is not present for dll files
85             let name = name.strip_prefix("lib").unwrap_or(name);
86             Some((name, path_str))
87         };
88         if let Some((name, path)) = parse_name_path() {
89             if TEST_DEPENDENCIES.contains(&name) {
90                 // A dependency may be listed twice if it is available in sysroot,
91                 // and the sysroot dependencies are listed first. As of the writing,
92                 // this only seems to apply to if_chain.
93                 crates.insert(name, path);
94             }
95         }
96     }
97     let not_found: Vec<&str> = TEST_DEPENDENCIES
98         .iter()
99         .copied()
100         .filter(|n| !crates.contains_key(n))
101         .collect();
102     assert!(
103         not_found.is_empty(),
104         "dependencies not found in depinfo: {:?}\n\
105         help: Make sure the `-Z binary-dep-depinfo` rust flag is enabled\n\
106         help: Try adding to dev-dependencies in Cargo.toml",
107         not_found
108     );
109     crates
110         .into_iter()
111         .map(|(name, path)| format!(" --extern {}={}", name, path))
112         .collect()
113 }
114
115 fn default_config() -> compiletest::Config {
116     let mut config = compiletest::Config {
117         edition: Some("2021".into()),
118         ..compiletest::Config::default()
119     };
120
121     if let Ok(filters) = env::var("TESTNAME") {
122         config.filters = filters.split(',').map(std::string::ToString::to_string).collect();
123     }
124
125     if let Some(path) = option_env!("RUSTC_LIB_PATH") {
126         let path = PathBuf::from(path);
127         config.run_lib_path = path.clone();
128         config.compile_lib_path = path;
129     }
130     let current_exe_path = std::env::current_exe().unwrap();
131     let deps_path = current_exe_path.parent().unwrap();
132     let profile_path = deps_path.parent().unwrap();
133
134     // Using `-L dependency={}` enforces that external dependencies are added with `--extern`.
135     // This is valuable because a) it allows us to monitor what external dependencies are used
136     // and b) it ensures that conflicting rlibs are resolved properly.
137     let host_libs = option_env!("HOST_LIBS")
138         .map(|p| format!(" -L dependency={}", Path::new(p).join("deps").display()))
139         .unwrap_or_default();
140     config.target_rustcflags = Some(format!(
141         "--emit=metadata -Dwarnings -Zui-testing -L dependency={}{}{}",
142         deps_path.display(),
143         host_libs,
144         extern_flags(),
145     ));
146
147     config.build_base = profile_path.join("test");
148     config.rustc_path = profile_path.join(if cfg!(windows) {
149         "clippy-driver.exe"
150     } else {
151         "clippy-driver"
152     });
153     config
154 }
155
156 fn run_ui(cfg: &mut compiletest::Config) {
157     cfg.mode = TestMode::Ui;
158     cfg.src_base = Path::new("tests").join("ui");
159     // use tests/clippy.toml
160     let _g = VarGuard::set("CARGO_MANIFEST_DIR", std::fs::canonicalize("tests").unwrap());
161     compiletest::run_tests(cfg);
162 }
163
164 fn run_ui_test(cfg: &mut compiletest::Config) {
165     cfg.mode = TestMode::Ui;
166     cfg.src_base = Path::new("tests").join("ui_test");
167     let _g = VarGuard::set("CARGO_MANIFEST_DIR", std::fs::canonicalize("tests").unwrap());
168     let rustcflags = cfg.target_rustcflags.get_or_insert_with(Default::default);
169     let len = rustcflags.len();
170     rustcflags.push_str(" --test");
171     compiletest::run_tests(cfg);
172     if let Some(ref mut flags) = &mut cfg.target_rustcflags {
173         flags.truncate(len);
174     }
175 }
176
177 fn run_internal_tests(cfg: &mut compiletest::Config) {
178     // only run internal tests with the internal-tests feature
179     if !RUN_INTERNAL_TESTS {
180         return;
181     }
182     cfg.mode = TestMode::Ui;
183     cfg.src_base = Path::new("tests").join("ui-internal");
184     compiletest::run_tests(cfg);
185 }
186
187 fn run_ui_toml(config: &mut compiletest::Config) {
188     fn run_tests(config: &compiletest::Config, mut tests: Vec<tester::TestDescAndFn>) -> Result<bool, io::Error> {
189         let mut result = true;
190         let opts = compiletest::test_opts(config);
191         for dir in fs::read_dir(&config.src_base)? {
192             let dir = dir?;
193             if !dir.file_type()?.is_dir() {
194                 continue;
195             }
196             let dir_path = dir.path();
197             let _g = VarGuard::set("CARGO_MANIFEST_DIR", &dir_path);
198             for file in fs::read_dir(&dir_path)? {
199                 let file = file?;
200                 let file_path = file.path();
201                 if file.file_type()?.is_dir() {
202                     continue;
203                 }
204                 if file_path.extension() != Some(OsStr::new("rs")) {
205                     continue;
206                 }
207                 let paths = compiletest::common::TestPaths {
208                     file: file_path,
209                     base: config.src_base.clone(),
210                     relative_dir: dir_path.file_name().unwrap().into(),
211                 };
212                 let test_name = compiletest::make_test_name(config, &paths);
213                 let index = tests
214                     .iter()
215                     .position(|test| test.desc.name == test_name)
216                     .expect("The test should be in there");
217                 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
218             }
219         }
220         Ok(result)
221     }
222
223     config.mode = TestMode::Ui;
224     config.src_base = Path::new("tests").join("ui-toml").canonicalize().unwrap();
225
226     let tests = compiletest::make_tests(config);
227
228     let res = run_tests(config, tests);
229     match res {
230         Ok(true) => {},
231         Ok(false) => panic!("Some tests failed"),
232         Err(e) => {
233             panic!("I/O failure during tests: {:?}", e);
234         },
235     }
236 }
237
238 fn run_ui_cargo(config: &mut compiletest::Config) {
239     fn run_tests(
240         config: &compiletest::Config,
241         filters: &[String],
242         mut tests: Vec<tester::TestDescAndFn>,
243     ) -> Result<bool, io::Error> {
244         let mut result = true;
245         let opts = compiletest::test_opts(config);
246
247         for dir in fs::read_dir(&config.src_base)? {
248             let dir = dir?;
249             if !dir.file_type()?.is_dir() {
250                 continue;
251             }
252
253             // Use the filter if provided
254             let dir_path = dir.path();
255             for filter in filters {
256                 if !dir_path.ends_with(filter) {
257                     continue;
258                 }
259             }
260
261             for case in fs::read_dir(&dir_path)? {
262                 let case = case?;
263                 if !case.file_type()?.is_dir() {
264                     continue;
265                 }
266
267                 let src_path = case.path().join("src");
268
269                 // When switching between branches, if the previous branch had a test
270                 // that the current branch does not have, the directory is not removed
271                 // because an ignored Cargo.lock file exists.
272                 if !src_path.exists() {
273                     continue;
274                 }
275
276                 env::set_current_dir(&src_path)?;
277                 for file in fs::read_dir(&src_path)? {
278                     let file = file?;
279                     if file.file_type()?.is_dir() {
280                         continue;
281                     }
282
283                     // Search for the main file to avoid running a test for each file in the project
284                     let file_path = file.path();
285                     match file_path.file_name().and_then(OsStr::to_str) {
286                         Some("main.rs") => {},
287                         _ => continue,
288                     }
289                     let _g = VarGuard::set("CLIPPY_CONF_DIR", case.path());
290                     let paths = compiletest::common::TestPaths {
291                         file: file_path,
292                         base: config.src_base.clone(),
293                         relative_dir: src_path.strip_prefix(&config.src_base).unwrap().into(),
294                     };
295                     let test_name = compiletest::make_test_name(config, &paths);
296                     let index = tests
297                         .iter()
298                         .position(|test| test.desc.name == test_name)
299                         .expect("The test should be in there");
300                     result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
301                 }
302             }
303         }
304         Ok(result)
305     }
306
307     if cargo::is_rustc_test_suite() {
308         return;
309     }
310
311     config.mode = TestMode::Ui;
312     config.src_base = Path::new("tests").join("ui-cargo").canonicalize().unwrap();
313
314     let tests = compiletest::make_tests(config);
315
316     let current_dir = env::current_dir().unwrap();
317     let res = run_tests(config, &config.filters, tests);
318     env::set_current_dir(current_dir).unwrap();
319
320     match res {
321         Ok(true) => {},
322         Ok(false) => panic!("Some tests failed"),
323         Err(e) => {
324             panic!("I/O failure during tests: {:?}", e);
325         },
326     }
327 }
328
329 fn prepare_env() {
330     set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
331     set_var("__CLIPPY_INTERNAL_TESTS", "true");
332     //set_var("RUST_BACKTRACE", "0");
333 }
334
335 #[test]
336 fn compile_test() {
337     prepare_env();
338     let mut config = default_config();
339     run_ui(&mut config);
340     run_ui_test(&mut config);
341     run_ui_toml(&mut config);
342     run_ui_cargo(&mut config);
343     run_internal_tests(&mut config);
344 }
345
346 /// Restores an env var on drop
347 #[must_use]
348 struct VarGuard {
349     key: &'static str,
350     value: Option<OsString>,
351 }
352
353 impl VarGuard {
354     fn set(key: &'static str, val: impl AsRef<OsStr>) -> Self {
355         let value = var_os(key);
356         set_var(key, val);
357         Self { key, value }
358     }
359 }
360
361 impl Drop for VarGuard {
362     fn drop(&mut self) {
363         match self.value.as_deref() {
364             None => remove_var(self.key),
365             Some(value) => set_var(self.key, value),
366         }
367     }
368 }