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