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