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