]> git.lizzy.rs Git - rust.git/blob - tests/compile-test.rs
Auto merge of #7669 - Labelray:if_then_panic, r=giraffate
[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-lints");
19
20 /// All crates used in UI tests are listed here
21 static TEST_DEPENDENCIES: &[&str] = &[
22     "clippy_utils",
23     "derive_new",
24     "if_chain",
25     "itertools",
26     "quote",
27     "regex",
28     "serde",
29     "serde_derive",
30     "syn",
31 ];
32
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)]
44 extern crate quote;
45 #[allow(unused_extern_crates)]
46 extern crate syn;
47
48 /// Produces a string with an `--extern` flag for all UI test crate
49 /// dependencies.
50 ///
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()
61     };
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) {
67                 return None;
68             }
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") {
72                 return None;
73             }
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))
78         };
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);
85             }
86         }
87     }
88     let not_found: Vec<&str> = TEST_DEPENDENCIES
89         .iter()
90         .copied()
91         .filter(|n| !crates.contains_key(n))
92         .collect();
93     assert!(
94         not_found.is_empty(),
95         "dependencies not found in depinfo: {:?}",
96         not_found
97     );
98     crates
99         .into_iter()
100         .map(|(name, path)| format!(" --extern {}={}", name, path))
101         .collect()
102 }
103
104 fn default_config() -> compiletest::Config {
105     let mut config = compiletest::Config::default();
106
107     if let Ok(filters) = env::var("TESTNAME") {
108         config.filters = filters.split(',').map(std::string::ToString::to_string).collect();
109     }
110
111     if let Some(path) = option_env!("RUSTC_LIB_PATH") {
112         let path = PathBuf::from(path);
113         config.run_lib_path = path.clone();
114         config.compile_lib_path = path;
115     }
116     let current_exe_path = std::env::current_exe().unwrap();
117     let deps_path = current_exe_path.parent().unwrap();
118     let profile_path = deps_path.parent().unwrap();
119
120     // Using `-L dependency={}` enforces that external dependencies are added with `--extern`.
121     // This is valuable because a) it allows us to monitor what external dependencies are used
122     // and b) it ensures that conflicting rlibs are resolved properly.
123     let host_libs = option_env!("HOST_LIBS")
124         .map(|p| format!(" -L dependency={}", Path::new(p).join("deps").display()))
125         .unwrap_or_default();
126     config.target_rustcflags = Some(format!(
127         "--emit=metadata -Dwarnings -Zui-testing -L dependency={}{}{}",
128         deps_path.display(),
129         host_libs,
130         extern_flags(),
131     ));
132
133     config.build_base = profile_path.join("test");
134     config.rustc_path = profile_path.join(if cfg!(windows) {
135         "clippy-driver.exe"
136     } else {
137         "clippy-driver"
138     });
139     config
140 }
141
142 fn run_ui(cfg: &mut compiletest::Config) {
143     cfg.mode = TestMode::Ui;
144     cfg.src_base = Path::new("tests").join("ui");
145     // use tests/clippy.toml
146     let _g = VarGuard::set("CARGO_MANIFEST_DIR", std::fs::canonicalize("tests").unwrap());
147     compiletest::run_tests(cfg);
148 }
149
150 fn run_internal_tests(cfg: &mut compiletest::Config) {
151     // only run internal tests with the internal-tests feature
152     if !RUN_INTERNAL_TESTS {
153         return;
154     }
155     cfg.mode = TestMode::Ui;
156     cfg.src_base = Path::new("tests").join("ui-internal");
157     compiletest::run_tests(cfg);
158 }
159
160 fn run_ui_toml(config: &mut compiletest::Config) {
161     fn run_tests(config: &compiletest::Config, mut tests: Vec<tester::TestDescAndFn>) -> Result<bool, io::Error> {
162         let mut result = true;
163         let opts = compiletest::test_opts(config);
164         for dir in fs::read_dir(&config.src_base)? {
165             let dir = dir?;
166             if !dir.file_type()?.is_dir() {
167                 continue;
168             }
169             let dir_path = dir.path();
170             let _g = VarGuard::set("CARGO_MANIFEST_DIR", &dir_path);
171             for file in fs::read_dir(&dir_path)? {
172                 let file = file?;
173                 let file_path = file.path();
174                 if file.file_type()?.is_dir() {
175                     continue;
176                 }
177                 if file_path.extension() != Some(OsStr::new("rs")) {
178                     continue;
179                 }
180                 let paths = compiletest::common::TestPaths {
181                     file: file_path,
182                     base: config.src_base.clone(),
183                     relative_dir: dir_path.file_name().unwrap().into(),
184                 };
185                 let test_name = compiletest::make_test_name(config, &paths);
186                 let index = tests
187                     .iter()
188                     .position(|test| test.desc.name == test_name)
189                     .expect("The test should be in there");
190                 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
191             }
192         }
193         Ok(result)
194     }
195
196     config.mode = TestMode::Ui;
197     config.src_base = Path::new("tests").join("ui-toml").canonicalize().unwrap();
198
199     let tests = compiletest::make_tests(config);
200
201     let res = run_tests(config, tests);
202     match res {
203         Ok(true) => {},
204         Ok(false) => panic!("Some tests failed"),
205         Err(e) => {
206             panic!("I/O failure during tests: {:?}", e);
207         },
208     }
209 }
210
211 fn run_ui_cargo(config: &mut compiletest::Config) {
212     fn run_tests(
213         config: &compiletest::Config,
214         filters: &[String],
215         mut tests: Vec<tester::TestDescAndFn>,
216     ) -> Result<bool, io::Error> {
217         let mut result = true;
218         let opts = compiletest::test_opts(config);
219
220         for dir in fs::read_dir(&config.src_base)? {
221             let dir = dir?;
222             if !dir.file_type()?.is_dir() {
223                 continue;
224             }
225
226             // Use the filter if provided
227             let dir_path = dir.path();
228             for filter in filters {
229                 if !dir_path.ends_with(filter) {
230                     continue;
231                 }
232             }
233
234             for case in fs::read_dir(&dir_path)? {
235                 let case = case?;
236                 if !case.file_type()?.is_dir() {
237                     continue;
238                 }
239
240                 let src_path = case.path().join("src");
241
242                 // When switching between branches, if the previous branch had a test
243                 // that the current branch does not have, the directory is not removed
244                 // because an ignored Cargo.lock file exists.
245                 if !src_path.exists() {
246                     continue;
247                 }
248
249                 env::set_current_dir(&src_path)?;
250                 for file in fs::read_dir(&src_path)? {
251                     let file = file?;
252                     if file.file_type()?.is_dir() {
253                         continue;
254                     }
255
256                     // Search for the main file to avoid running a test for each file in the project
257                     let file_path = file.path();
258                     match file_path.file_name().and_then(OsStr::to_str) {
259                         Some("main.rs") => {},
260                         _ => continue,
261                     }
262                     let _g = VarGuard::set("CLIPPY_CONF_DIR", case.path());
263                     let paths = compiletest::common::TestPaths {
264                         file: file_path,
265                         base: config.src_base.clone(),
266                         relative_dir: src_path.strip_prefix(&config.src_base).unwrap().into(),
267                     };
268                     let test_name = compiletest::make_test_name(config, &paths);
269                     let index = tests
270                         .iter()
271                         .position(|test| test.desc.name == test_name)
272                         .expect("The test should be in there");
273                     result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
274                 }
275             }
276         }
277         Ok(result)
278     }
279
280     if cargo::is_rustc_test_suite() {
281         return;
282     }
283
284     config.mode = TestMode::Ui;
285     config.src_base = Path::new("tests").join("ui-cargo").canonicalize().unwrap();
286
287     let tests = compiletest::make_tests(config);
288
289     let current_dir = env::current_dir().unwrap();
290     let res = run_tests(config, &config.filters, tests);
291     env::set_current_dir(current_dir).unwrap();
292
293     match res {
294         Ok(true) => {},
295         Ok(false) => panic!("Some tests failed"),
296         Err(e) => {
297             panic!("I/O failure during tests: {:?}", e);
298         },
299     }
300 }
301
302 fn prepare_env() {
303     set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
304     set_var("__CLIPPY_INTERNAL_TESTS", "true");
305     //set_var("RUST_BACKTRACE", "0");
306 }
307
308 #[test]
309 fn compile_test() {
310     prepare_env();
311     let mut config = default_config();
312     run_ui(&mut config);
313     run_ui_toml(&mut config);
314     run_ui_cargo(&mut config);
315     run_internal_tests(&mut config);
316 }
317
318 /// Restores an env var on drop
319 #[must_use]
320 struct VarGuard {
321     key: &'static str,
322     value: Option<OsString>,
323 }
324
325 impl VarGuard {
326     fn set(key: &'static str, val: impl AsRef<OsStr>) -> Self {
327         let value = var_os(key);
328         set_var(key, val);
329         Self { key, value }
330     }
331 }
332
333 impl Drop for VarGuard {
334     fn drop(&mut self) {
335         match self.value.as_deref() {
336             None => remove_var(self.key),
337             Some(value) => set_var(self.key, value),
338         }
339     }
340 }