]> git.lizzy.rs Git - rust.git/blob - tests/compile-test.rs
319256814c3a6c2560d63e83d88e39222823b816
[rust.git] / tests / compile-test.rs
1 #![feature(test)] // compiletest_rs requires this attribute
2 #![feature(once_cell)]
3 #![feature(is_sorted)]
4 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
5 #![warn(rust_2018_idioms, unused_lifetimes)]
6
7 use compiletest_rs as compiletest;
8 use compiletest_rs::common::Mode as TestMode;
9
10 use std::collections::HashMap;
11 use std::env::{self, remove_var, set_var, var_os};
12 use std::ffi::{OsStr, OsString};
13 use std::fs;
14 use std::io;
15 use std::lazy::SyncLazy;
16 use std::path::{Path, PathBuf};
17 use test_utils::IS_RUSTC_TEST_SUITE;
18
19 mod test_utils;
20
21 // whether to run internal tests or not
22 const RUN_INTERNAL_TESTS: bool = cfg!(feature = "internal");
23
24 /// All crates used in UI tests are listed here
25 static TEST_DEPENDENCIES: &[&str] = &[
26     "clap",
27     "clippy_lints",
28     "clippy_utils",
29     "derive_new",
30     "futures",
31     "if_chain",
32     "itertools",
33     "quote",
34     "regex",
35     "serde",
36     "serde_derive",
37     "syn",
38     "tokio",
39     "parking_lot",
40     "rustc_semver",
41 ];
42
43 // Test dependencies may need an `extern crate` here to ensure that they show up
44 // in the depinfo file (otherwise cargo thinks they are unused)
45 #[allow(unused_extern_crates)]
46 extern crate clap;
47 #[allow(unused_extern_crates)]
48 extern crate clippy_lints;
49 #[allow(unused_extern_crates)]
50 extern crate clippy_utils;
51 #[allow(unused_extern_crates)]
52 extern crate derive_new;
53 #[allow(unused_extern_crates)]
54 extern crate futures;
55 #[allow(unused_extern_crates)]
56 extern crate if_chain;
57 #[allow(unused_extern_crates)]
58 extern crate itertools;
59 #[allow(unused_extern_crates)]
60 extern crate parking_lot;
61 #[allow(unused_extern_crates)]
62 extern crate quote;
63 #[allow(unused_extern_crates)]
64 extern crate rustc_semver;
65 #[allow(unused_extern_crates)]
66 extern crate syn;
67 #[allow(unused_extern_crates)]
68 extern crate tokio;
69
70 /// Produces a string with an `--extern` flag for all UI test crate
71 /// dependencies.
72 ///
73 /// The dependency files are located by parsing the depinfo file for this test
74 /// module. This assumes the `-Z binary-dep-depinfo` flag is enabled. All test
75 /// dependencies must be added to Cargo.toml at the project root. Test
76 /// dependencies that are not *directly* used by this test module require an
77 /// `extern crate` declaration.
78 static EXTERN_FLAGS: SyncLazy<String> = SyncLazy::new(|| {
79     let current_exe_depinfo = {
80         let mut path = env::current_exe().unwrap();
81         path.set_extension("d");
82         fs::read_to_string(path).unwrap()
83     };
84     let mut crates: HashMap<&str, &str> = HashMap::with_capacity(TEST_DEPENDENCIES.len());
85     for line in current_exe_depinfo.lines() {
86         // each dependency is expected to have a Makefile rule like `/path/to/crate-hash.rlib:`
87         let parse_name_path = || {
88             if line.starts_with(char::is_whitespace) {
89                 return None;
90             }
91             let path_str = line.strip_suffix(':')?;
92             let path = Path::new(path_str);
93             if !matches!(path.extension()?.to_str()?, "rlib" | "so" | "dylib" | "dll") {
94                 return None;
95             }
96             let (name, _hash) = path.file_stem()?.to_str()?.rsplit_once('-')?;
97             // the "lib" prefix is not present for dll files
98             let name = name.strip_prefix("lib").unwrap_or(name);
99             Some((name, path_str))
100         };
101         if let Some((name, path)) = parse_name_path() {
102             if TEST_DEPENDENCIES.contains(&name) {
103                 // A dependency may be listed twice if it is available in sysroot,
104                 // and the sysroot dependencies are listed first. As of the writing,
105                 // this only seems to apply to if_chain.
106                 crates.insert(name, path);
107             }
108         }
109     }
110     let not_found: Vec<&str> = TEST_DEPENDENCIES
111         .iter()
112         .copied()
113         .filter(|n| !crates.contains_key(n))
114         .collect();
115     assert!(
116         not_found.is_empty(),
117         "dependencies not found in depinfo: {:?}\n\
118         help: Make sure the `-Z binary-dep-depinfo` rust flag is enabled\n\
119         help: Try adding to dev-dependencies in Cargo.toml\n\
120         help: Be sure to also add `extern crate ...;` to tests/compile-test.rs",
121         not_found,
122     );
123     crates
124         .into_iter()
125         .map(|(name, path)| format!(" --extern {}={}", name, path))
126         .collect()
127 });
128
129 fn base_config(test_dir: &str) -> compiletest::Config {
130     let mut config = compiletest::Config {
131         edition: Some("2021".into()),
132         mode: TestMode::Ui,
133         ..Default::default()
134     };
135
136     if let Ok(filters) = env::var("TESTNAME") {
137         config.filters = filters.split(',').map(ToString::to_string).collect();
138     }
139
140     if let Some(path) = option_env!("RUSTC_LIB_PATH") {
141         let path = PathBuf::from(path);
142         config.run_lib_path = path.clone();
143         config.compile_lib_path = path;
144     }
145     let current_exe_path = env::current_exe().unwrap();
146     let deps_path = current_exe_path.parent().unwrap();
147     let profile_path = deps_path.parent().unwrap();
148
149     // Using `-L dependency={}` enforces that external dependencies are added with `--extern`.
150     // This is valuable because a) it allows us to monitor what external dependencies are used
151     // and b) it ensures that conflicting rlibs are resolved properly.
152     let host_libs = option_env!("HOST_LIBS")
153         .map(|p| format!(" -L dependency={}", Path::new(p).join("deps").display()))
154         .unwrap_or_default();
155     config.target_rustcflags = Some(format!(
156         "--emit=metadata -Dwarnings -Zui-testing -L dependency={}{}{}",
157         deps_path.display(),
158         host_libs,
159         &*EXTERN_FLAGS,
160     ));
161
162     config.src_base = Path::new("tests").join(test_dir);
163     config.build_base = profile_path.join("test").join(test_dir);
164     config.rustc_path = profile_path.join(if cfg!(windows) {
165         "clippy-driver.exe"
166     } else {
167         "clippy-driver"
168     });
169     config
170 }
171
172 fn run_ui() {
173     let mut config = base_config("ui");
174     config.rustfix_coverage = true;
175     // use tests/clippy.toml
176     let _g = VarGuard::set("CARGO_MANIFEST_DIR", fs::canonicalize("tests").unwrap());
177     let _threads = VarGuard::set(
178         "RUST_TEST_THREADS",
179         // if RUST_TEST_THREADS is set, adhere to it, otherwise override it
180         env::var("RUST_TEST_THREADS").unwrap_or_else(|_| {
181             std::thread::available_parallelism()
182                 .map_or(1, std::num::NonZeroUsize::get)
183                 .to_string()
184         }),
185     );
186     compiletest::run_tests(&config);
187     check_rustfix_coverage();
188 }
189
190 fn run_internal_tests() {
191     // only run internal tests with the internal-tests feature
192     if !RUN_INTERNAL_TESTS {
193         return;
194     }
195     let config = base_config("ui-internal");
196     compiletest::run_tests(&config);
197 }
198
199 fn run_ui_toml() {
200     fn run_tests(config: &compiletest::Config, mut tests: Vec<tester::TestDescAndFn>) -> Result<bool, io::Error> {
201         let mut result = true;
202         let opts = compiletest::test_opts(config);
203         for dir in fs::read_dir(&config.src_base)? {
204             let dir = dir?;
205             if !dir.file_type()?.is_dir() {
206                 continue;
207             }
208             let dir_path = dir.path();
209             let _g = VarGuard::set("CARGO_MANIFEST_DIR", &dir_path);
210             for file in fs::read_dir(&dir_path)? {
211                 let file = file?;
212                 let file_path = file.path();
213                 if file.file_type()?.is_dir() {
214                     continue;
215                 }
216                 if file_path.extension() != Some(OsStr::new("rs")) {
217                     continue;
218                 }
219                 let paths = compiletest::common::TestPaths {
220                     file: file_path,
221                     base: config.src_base.clone(),
222                     relative_dir: dir_path.file_name().unwrap().into(),
223                 };
224                 let test_name = compiletest::make_test_name(config, &paths);
225                 let index = tests
226                     .iter()
227                     .position(|test| test.desc.name == test_name)
228                     .expect("The test should be in there");
229                 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
230             }
231         }
232         Ok(result)
233     }
234
235     let mut config = base_config("ui-toml");
236     config.src_base = config.src_base.canonicalize().unwrap();
237
238     let tests = compiletest::make_tests(&config);
239
240     let res = run_tests(&config, tests);
241     match res {
242         Ok(true) => {},
243         Ok(false) => panic!("Some tests failed"),
244         Err(e) => {
245             panic!("I/O failure during tests: {:?}", e);
246         },
247     }
248 }
249
250 fn run_ui_cargo() {
251     fn run_tests(
252         config: &compiletest::Config,
253         filters: &[String],
254         mut tests: Vec<tester::TestDescAndFn>,
255     ) -> Result<bool, io::Error> {
256         let mut result = true;
257         let opts = compiletest::test_opts(config);
258
259         for dir in fs::read_dir(&config.src_base)? {
260             let dir = dir?;
261             if !dir.file_type()?.is_dir() {
262                 continue;
263             }
264
265             // Use the filter if provided
266             let dir_path = dir.path();
267             for filter in filters {
268                 if !dir_path.ends_with(filter) {
269                     continue;
270                 }
271             }
272
273             for case in fs::read_dir(&dir_path)? {
274                 let case = case?;
275                 if !case.file_type()?.is_dir() {
276                     continue;
277                 }
278
279                 let src_path = case.path().join("src");
280
281                 // When switching between branches, if the previous branch had a test
282                 // that the current branch does not have, the directory is not removed
283                 // because an ignored Cargo.lock file exists.
284                 if !src_path.exists() {
285                     continue;
286                 }
287
288                 env::set_current_dir(&src_path)?;
289
290                 let cargo_toml_path = case.path().join("Cargo.toml");
291                 let cargo_content = fs::read(&cargo_toml_path)?;
292                 let cargo_parsed: toml::Value = toml::from_str(
293                     std::str::from_utf8(&cargo_content).expect("`Cargo.toml` is not a valid utf-8 file!"),
294                 )
295                 .expect("Can't parse `Cargo.toml`");
296
297                 let _g = VarGuard::set("CARGO_MANIFEST_DIR", case.path());
298                 let _h = VarGuard::set(
299                     "CARGO_PKG_RUST_VERSION",
300                     cargo_parsed
301                         .get("package")
302                         .and_then(|p| p.get("rust-version"))
303                         .and_then(toml::Value::as_str)
304                         .unwrap_or(""),
305                 );
306
307                 for file in fs::read_dir(&src_path)? {
308                     let file = file?;
309                     if file.file_type()?.is_dir() {
310                         continue;
311                     }
312
313                     // Search for the main file to avoid running a test for each file in the project
314                     let file_path = file.path();
315                     match file_path.file_name().and_then(OsStr::to_str) {
316                         Some("main.rs") => {},
317                         _ => continue,
318                     }
319                     let _g = VarGuard::set("CLIPPY_CONF_DIR", case.path());
320                     let paths = compiletest::common::TestPaths {
321                         file: file_path,
322                         base: config.src_base.clone(),
323                         relative_dir: src_path.strip_prefix(&config.src_base).unwrap().into(),
324                     };
325                     let test_name = compiletest::make_test_name(config, &paths);
326                     let index = tests
327                         .iter()
328                         .position(|test| test.desc.name == test_name)
329                         .expect("The test should be in there");
330                     result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
331                 }
332             }
333         }
334         Ok(result)
335     }
336
337     if IS_RUSTC_TEST_SUITE {
338         return;
339     }
340
341     let mut config = base_config("ui-cargo");
342     config.src_base = config.src_base.canonicalize().unwrap();
343
344     let tests = compiletest::make_tests(&config);
345
346     let current_dir = env::current_dir().unwrap();
347     let res = run_tests(&config, &config.filters, tests);
348     env::set_current_dir(current_dir).unwrap();
349
350     match res {
351         Ok(true) => {},
352         Ok(false) => panic!("Some tests failed"),
353         Err(e) => {
354             panic!("I/O failure during tests: {:?}", e);
355         },
356     }
357 }
358
359 #[test]
360 fn compile_test() {
361     set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
362     run_ui();
363     run_ui_toml();
364     run_ui_cargo();
365     run_internal_tests();
366 }
367
368 const RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS: &[&str] = &[
369     "assign_ops2.rs",
370     "borrow_deref_ref_unfixable.rs",
371     "cast_size_32bit.rs",
372     "char_lit_as_u8.rs",
373     "cmp_owned/without_suggestion.rs",
374     "dbg_macro.rs",
375     "deref_addrof_double_trigger.rs",
376     "doc/unbalanced_ticks.rs",
377     "eprint_with_newline.rs",
378     "explicit_counter_loop.rs",
379     "iter_skip_next_unfixable.rs",
380     "let_and_return.rs",
381     "literals.rs",
382     "map_flatten.rs",
383     "map_unwrap_or.rs",
384     "match_bool.rs",
385     "mem_replace_macro.rs",
386     "needless_arbitrary_self_type_unfixable.rs",
387     "needless_borrow_pat.rs",
388     "needless_for_each_unfixable.rs",
389     "nonminimal_bool.rs",
390     "print_literal.rs",
391     "print_with_newline.rs",
392     "redundant_static_lifetimes_multiple.rs",
393     "ref_binding_to_reference.rs",
394     "repl_uninit.rs",
395     "result_map_unit_fn_unfixable.rs",
396     "search_is_some.rs",
397     "single_component_path_imports_nested_first.rs",
398     "string_add.rs",
399     "toplevel_ref_arg_non_rustfix.rs",
400     "unit_arg.rs",
401     "unnecessary_clone.rs",
402     "unnecessary_lazy_eval_unfixable.rs",
403     "write_literal.rs",
404     "write_literal_2.rs",
405     "write_with_newline.rs",
406 ];
407
408 fn check_rustfix_coverage() {
409     let missing_coverage_path = Path::new("target/debug/test/ui/rustfix_missing_coverage.txt");
410
411     if let Ok(missing_coverage_contents) = std::fs::read_to_string(missing_coverage_path) {
412         assert!(RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS.iter().is_sorted_by_key(Path::new));
413
414         for rs_path in missing_coverage_contents.lines() {
415             if Path::new(rs_path).starts_with("tests/ui/crashes") {
416                 continue;
417             }
418             let filename = Path::new(rs_path).strip_prefix("tests/ui/").unwrap();
419             assert!(
420                 RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS
421                     .binary_search_by_key(&filename, Path::new)
422                     .is_ok(),
423                 "`{}` runs `MachineApplicable` diagnostics but is missing a `run-rustfix` annotation. \
424                 Please either add `// run-rustfix` at the top of the file or add the file to \
425                 `RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS` in `tests/compile-test.rs`.",
426                 rs_path,
427             );
428         }
429     }
430 }
431
432 #[test]
433 fn rustfix_coverage_known_exceptions_accuracy() {
434     for filename in RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS {
435         let rs_path = Path::new("tests/ui").join(filename);
436         assert!(
437             rs_path.exists(),
438             "`{}` does not exists",
439             rs_path.strip_prefix(env!("CARGO_MANIFEST_DIR")).unwrap().display()
440         );
441         let fixed_path = rs_path.with_extension("fixed");
442         assert!(
443             !fixed_path.exists(),
444             "`{}` exists",
445             fixed_path.strip_prefix(env!("CARGO_MANIFEST_DIR")).unwrap().display()
446         );
447     }
448 }
449
450 /// Restores an env var on drop
451 #[must_use]
452 struct VarGuard {
453     key: &'static str,
454     value: Option<OsString>,
455 }
456
457 impl VarGuard {
458     fn set(key: &'static str, val: impl AsRef<OsStr>) -> Self {
459         let value = var_os(key);
460         set_var(key, val);
461         Self { key, value }
462     }
463 }
464
465 impl Drop for VarGuard {
466     fn drop(&mut self) {
467         match self.value.as_deref() {
468             None => remove_var(self.key),
469             Some(value) => set_var(self.key, value),
470         }
471     }
472 }