]> git.lizzy.rs Git - rust.git/blob - tests/compile-test.rs
removing unsafe from test fn's && renaming shrink to sugg_span
[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 use test_utils::IS_RUSTC_TEST_SUITE;
16
17 mod test_utils;
18
19 // whether to run internal tests or not
20 const RUN_INTERNAL_TESTS: bool = cfg!(feature = "internal");
21
22 /// All crates used in UI tests are listed here
23 static TEST_DEPENDENCIES: &[&str] = &[
24     "clippy_utils",
25     "derive_new",
26     "futures",
27     "if_chain",
28     "itertools",
29     "quote",
30     "regex",
31     "serde",
32     "serde_derive",
33     "syn",
34     "tokio",
35     "parking_lot",
36 ];
37
38 // Test dependencies may need an `extern crate` here to ensure that they show up
39 // in the depinfo file (otherwise cargo thinks they are unused)
40 #[allow(unused_extern_crates)]
41 extern crate clippy_utils;
42 #[allow(unused_extern_crates)]
43 extern crate derive_new;
44 #[allow(unused_extern_crates)]
45 extern crate futures;
46 #[allow(unused_extern_crates)]
47 extern crate if_chain;
48 #[allow(unused_extern_crates)]
49 extern crate itertools;
50 #[allow(unused_extern_crates)]
51 extern crate parking_lot;
52 #[allow(unused_extern_crates)]
53 extern crate quote;
54 #[allow(unused_extern_crates)]
55 extern crate syn;
56 #[allow(unused_extern_crates)]
57 extern crate tokio;
58
59 /// Produces a string with an `--extern` flag for all UI test crate
60 /// dependencies.
61 ///
62 /// The dependency files are located by parsing the depinfo file for this test
63 /// module. This assumes the `-Z binary-dep-depinfo` flag is enabled. All test
64 /// dependencies must be added to Cargo.toml at the project root. Test
65 /// dependencies that are not *directly* used by this test module require an
66 /// `extern crate` declaration.
67 fn extern_flags() -> String {
68     let current_exe_depinfo = {
69         let mut path = env::current_exe().unwrap();
70         path.set_extension("d");
71         std::fs::read_to_string(path).unwrap()
72     };
73     let mut crates: HashMap<&str, &str> = HashMap::with_capacity(TEST_DEPENDENCIES.len());
74     for line in current_exe_depinfo.lines() {
75         // each dependency is expected to have a Makefile rule like `/path/to/crate-hash.rlib:`
76         let parse_name_path = || {
77             if line.starts_with(char::is_whitespace) {
78                 return None;
79             }
80             let path_str = line.strip_suffix(':')?;
81             let path = Path::new(path_str);
82             if !matches!(path.extension()?.to_str()?, "rlib" | "so" | "dylib" | "dll") {
83                 return None;
84             }
85             let (name, _hash) = path.file_stem()?.to_str()?.rsplit_once('-')?;
86             // the "lib" prefix is not present for dll files
87             let name = name.strip_prefix("lib").unwrap_or(name);
88             Some((name, path_str))
89         };
90         if let Some((name, path)) = parse_name_path() {
91             if TEST_DEPENDENCIES.contains(&name) {
92                 // A dependency may be listed twice if it is available in sysroot,
93                 // and the sysroot dependencies are listed first. As of the writing,
94                 // this only seems to apply to if_chain.
95                 crates.insert(name, path);
96             }
97         }
98     }
99     let not_found: Vec<&str> = TEST_DEPENDENCIES
100         .iter()
101         .copied()
102         .filter(|n| !crates.contains_key(n))
103         .collect();
104     assert!(
105         not_found.is_empty(),
106         "dependencies not found in depinfo: {:?}\n\
107         help: Make sure the `-Z binary-dep-depinfo` rust flag is enabled\n\
108         help: Try adding to dev-dependencies in Cargo.toml",
109         not_found
110     );
111     crates
112         .into_iter()
113         .map(|(name, path)| format!(" --extern {}={}", name, path))
114         .collect()
115 }
116
117 fn default_config() -> compiletest::Config {
118     let mut config = compiletest::Config {
119         edition: Some("2021".into()),
120         ..compiletest::Config::default()
121     };
122
123     if let Ok(filters) = env::var("TESTNAME") {
124         config.filters = filters.split(',').map(std::string::ToString::to_string).collect();
125     }
126
127     if let Some(path) = option_env!("RUSTC_LIB_PATH") {
128         let path = PathBuf::from(path);
129         config.run_lib_path = path.clone();
130         config.compile_lib_path = path;
131     }
132     let current_exe_path = std::env::current_exe().unwrap();
133     let deps_path = current_exe_path.parent().unwrap();
134     let profile_path = deps_path.parent().unwrap();
135
136     // Using `-L dependency={}` enforces that external dependencies are added with `--extern`.
137     // This is valuable because a) it allows us to monitor what external dependencies are used
138     // and b) it ensures that conflicting rlibs are resolved properly.
139     let host_libs = option_env!("HOST_LIBS")
140         .map(|p| format!(" -L dependency={}", Path::new(p).join("deps").display()))
141         .unwrap_or_default();
142     config.target_rustcflags = Some(format!(
143         "--emit=metadata -Dwarnings -Zui-testing -L dependency={}{}{}",
144         deps_path.display(),
145         host_libs,
146         extern_flags(),
147     ));
148
149     config.build_base = profile_path.join("test");
150     config.rustc_path = profile_path.join(if cfg!(windows) {
151         "clippy-driver.exe"
152     } else {
153         "clippy-driver"
154     });
155     config
156 }
157
158 fn run_ui(cfg: &mut compiletest::Config) {
159     cfg.mode = TestMode::Ui;
160     cfg.src_base = Path::new("tests").join("ui");
161     // use tests/clippy.toml
162     let _g = VarGuard::set("CARGO_MANIFEST_DIR", std::fs::canonicalize("tests").unwrap());
163     compiletest::run_tests(cfg);
164 }
165
166 fn run_ui_test(cfg: &mut compiletest::Config) {
167     cfg.mode = TestMode::Ui;
168     cfg.src_base = Path::new("tests").join("ui_test");
169     let _g = VarGuard::set("CARGO_MANIFEST_DIR", std::fs::canonicalize("tests").unwrap());
170     let rustcflags = cfg.target_rustcflags.get_or_insert_with(Default::default);
171     let len = rustcflags.len();
172     rustcflags.push_str(" --test");
173     compiletest::run_tests(cfg);
174     if let Some(ref mut flags) = &mut cfg.target_rustcflags {
175         flags.truncate(len);
176     }
177 }
178
179 fn run_internal_tests(cfg: &mut compiletest::Config) {
180     // only run internal tests with the internal-tests feature
181     if !RUN_INTERNAL_TESTS {
182         return;
183     }
184     cfg.mode = TestMode::Ui;
185     cfg.src_base = Path::new("tests").join("ui-internal");
186     compiletest::run_tests(cfg);
187 }
188
189 fn run_ui_toml(config: &mut compiletest::Config) {
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     config.mode = TestMode::Ui;
226     config.src_base = Path::new("tests").join("ui-toml").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(config: &mut compiletest::Config) {
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     config.mode = TestMode::Ui;
314     config.src_base = Path::new("tests").join("ui-cargo").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 fn prepare_env() {
332     set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
333     set_var("__CLIPPY_INTERNAL_TESTS", "true");
334     //set_var("RUST_BACKTRACE", "0");
335 }
336
337 #[test]
338 fn compile_test() {
339     prepare_env();
340     let mut config = default_config();
341     run_ui(&mut config);
342     run_ui_test(&mut config);
343     run_ui_toml(&mut config);
344     run_ui_cargo(&mut config);
345     run_internal_tests(&mut config);
346 }
347
348 /// Restores an env var on drop
349 #[must_use]
350 struct VarGuard {
351     key: &'static str,
352     value: Option<OsString>,
353 }
354
355 impl VarGuard {
356     fn set(key: &'static str, val: impl AsRef<OsStr>) -> Self {
357         let value = var_os(key);
358         set_var(key, val);
359         Self { key, value }
360     }
361 }
362
363 impl Drop for VarGuard {
364     fn drop(&mut self) {
365         match self.value.as_deref() {
366             None => remove_var(self.key),
367             Some(value) => set_var(self.key, value),
368         }
369     }
370 }