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