]> git.lizzy.rs Git - rust.git/blob - tests/compile-test.rs
Auto merge of #6555 - stanislav-tkach:patch-1, r=flip1995
[rust.git] / tests / compile-test.rs
1 #![feature(test)] // compiletest_rs requires this attribute
2 #![feature(once_cell)]
3
4 use compiletest_rs as compiletest;
5 use compiletest_rs::common::Mode as TestMode;
6
7 use std::env::{self, set_var, var};
8 use std::ffi::OsStr;
9 use std::fs;
10 use std::io;
11 use std::path::{Path, PathBuf};
12
13 mod cargo;
14
15 // whether to run internal tests or not
16 const RUN_INTERNAL_TESTS: bool = cfg!(feature = "internal-lints");
17
18 fn host_lib() -> PathBuf {
19     option_env!("HOST_LIBS").map_or(cargo::CARGO_TARGET_DIR.join(env!("PROFILE")), PathBuf::from)
20 }
21
22 fn clippy_driver_path() -> PathBuf {
23     option_env!("CLIPPY_DRIVER_PATH").map_or(cargo::TARGET_LIB.join("clippy-driver"), PathBuf::from)
24 }
25
26 // When we'll want to use `extern crate ..` for a dependency that is used
27 // both by the crate and the compiler itself, we can't simply pass -L flags
28 // as we'll get a duplicate matching versions. Instead, disambiguate with
29 // `--extern dep=path`.
30 // See https://github.com/rust-lang/rust-clippy/issues/4015.
31 //
32 // FIXME: We cannot use `cargo build --message-format=json` to resolve to dependency files.
33 //        Because it would force-rebuild if the options passed to `build` command is not the same
34 //        as what we manually pass to `cargo` invocation
35 fn third_party_crates() -> String {
36     use std::collections::HashMap;
37     static CRATES: &[&str] = &["serde", "serde_derive", "regex", "clippy_lints", "syn", "quote"];
38     let dep_dir = cargo::TARGET_LIB.join("deps");
39     let mut crates: HashMap<&str, PathBuf> = HashMap::with_capacity(CRATES.len());
40     for entry in fs::read_dir(dep_dir).unwrap() {
41         let path = match entry {
42             Ok(entry) => entry.path(),
43             Err(_) => continue,
44         };
45         if let Some(name) = path.file_name().and_then(OsStr::to_str) {
46             for dep in CRATES {
47                 if name.starts_with(&format!("lib{}-", dep)) && name.ends_with(".rlib") {
48                     if let Some(old) = crates.insert(dep, path.clone()) {
49                         panic!("Found multiple rlibs for crate `{}`: `{:?}` and `{:?}", dep, old, path);
50                     }
51                     break;
52                 }
53             }
54         }
55     }
56
57     let v: Vec<_> = crates
58         .into_iter()
59         .map(|(dep, path)| format!("--extern {}={}", dep, path.display()))
60         .collect();
61     v.join(" ")
62 }
63
64 fn default_config() -> compiletest::Config {
65     let mut config = compiletest::Config::default();
66
67     if let Ok(name) = env::var("TESTNAME") {
68         config.filter = Some(name);
69     }
70
71     if let Some(path) = option_env!("RUSTC_LIB_PATH") {
72         let path = PathBuf::from(path);
73         config.run_lib_path = path.clone();
74         config.compile_lib_path = path;
75     }
76
77     config.target_rustcflags = Some(format!(
78         "--emit=metadata -L {0} -L {1} -Dwarnings -Zui-testing {2}",
79         host_lib().join("deps").display(),
80         cargo::TARGET_LIB.join("deps").display(),
81         third_party_crates(),
82     ));
83
84     config.build_base = if cargo::is_rustc_test_suite() {
85         // This make the stderr files go to clippy OUT_DIR on rustc repo build dir
86         let mut path = PathBuf::from(env!("OUT_DIR"));
87         path.push("test_build_base");
88         path
89     } else {
90         host_lib().join("test_build_base")
91     };
92     config.rustc_path = clippy_driver_path();
93     config
94 }
95
96 fn run_mode(cfg: &mut compiletest::Config) {
97     cfg.mode = TestMode::Ui;
98     cfg.src_base = Path::new("tests").join("ui");
99     compiletest::run_tests(&cfg);
100 }
101
102 fn run_internal_tests(cfg: &mut compiletest::Config) {
103     // only run internal tests with the internal-tests feature
104     if !RUN_INTERNAL_TESTS {
105         return;
106     }
107     cfg.mode = TestMode::Ui;
108     cfg.src_base = Path::new("tests").join("ui-internal");
109     compiletest::run_tests(&cfg);
110 }
111
112 fn run_ui_toml(config: &mut compiletest::Config) {
113     fn run_tests(config: &compiletest::Config, mut tests: Vec<tester::TestDescAndFn>) -> Result<bool, io::Error> {
114         let mut result = true;
115         let opts = compiletest::test_opts(config);
116         for dir in fs::read_dir(&config.src_base)? {
117             let dir = dir?;
118             if !dir.file_type()?.is_dir() {
119                 continue;
120             }
121             let dir_path = dir.path();
122             set_var("CARGO_MANIFEST_DIR", &dir_path);
123             for file in fs::read_dir(&dir_path)? {
124                 let file = file?;
125                 let file_path = file.path();
126                 if file.file_type()?.is_dir() {
127                     continue;
128                 }
129                 if file_path.extension() != Some(OsStr::new("rs")) {
130                     continue;
131                 }
132                 let paths = compiletest::common::TestPaths {
133                     file: file_path,
134                     base: config.src_base.clone(),
135                     relative_dir: dir_path.file_name().unwrap().into(),
136                 };
137                 let test_name = compiletest::make_test_name(&config, &paths);
138                 let index = tests
139                     .iter()
140                     .position(|test| test.desc.name == test_name)
141                     .expect("The test should be in there");
142                 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
143             }
144         }
145         Ok(result)
146     }
147
148     config.mode = TestMode::Ui;
149     config.src_base = Path::new("tests").join("ui-toml").canonicalize().unwrap();
150
151     let tests = compiletest::make_tests(&config);
152
153     let manifest_dir = var("CARGO_MANIFEST_DIR").unwrap_or_default();
154     let res = run_tests(&config, tests);
155     set_var("CARGO_MANIFEST_DIR", &manifest_dir);
156     match res {
157         Ok(true) => {},
158         Ok(false) => panic!("Some tests failed"),
159         Err(e) => {
160             panic!("I/O failure during tests: {:?}", e);
161         },
162     }
163 }
164
165 fn run_ui_cargo(config: &mut compiletest::Config) {
166     fn run_tests(
167         config: &compiletest::Config,
168         filter: &Option<String>,
169         mut tests: Vec<tester::TestDescAndFn>,
170     ) -> Result<bool, io::Error> {
171         let mut result = true;
172         let opts = compiletest::test_opts(config);
173
174         for dir in fs::read_dir(&config.src_base)? {
175             let dir = dir?;
176             if !dir.file_type()?.is_dir() {
177                 continue;
178             }
179
180             // Use the filter if provided
181             let dir_path = dir.path();
182             match &filter {
183                 Some(name) if !dir_path.ends_with(name) => continue,
184                 _ => {},
185             }
186
187             for case in fs::read_dir(&dir_path)? {
188                 let case = case?;
189                 if !case.file_type()?.is_dir() {
190                     continue;
191                 }
192
193                 let src_path = case.path().join("src");
194
195                 // When switching between branches, if the previous branch had a test
196                 // that the current branch does not have, the directory is not removed
197                 // because an ignored Cargo.lock file exists.
198                 if !src_path.exists() {
199                     continue;
200                 }
201
202                 env::set_current_dir(&src_path)?;
203                 for file in fs::read_dir(&src_path)? {
204                     let file = file?;
205                     if file.file_type()?.is_dir() {
206                         continue;
207                     }
208
209                     // Search for the main file to avoid running a test for each file in the project
210                     let file_path = file.path();
211                     match file_path.file_name().and_then(OsStr::to_str) {
212                         Some("main.rs") => {},
213                         _ => continue,
214                     }
215                     let paths = compiletest::common::TestPaths {
216                         file: file_path,
217                         base: config.src_base.clone(),
218                         relative_dir: src_path.strip_prefix(&config.src_base).unwrap().into(),
219                     };
220                     let test_name = compiletest::make_test_name(&config, &paths);
221                     let index = tests
222                         .iter()
223                         .position(|test| test.desc.name == test_name)
224                         .expect("The test should be in there");
225                     result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
226                 }
227             }
228         }
229         Ok(result)
230     }
231
232     if cargo::is_rustc_test_suite() {
233         return;
234     }
235
236     config.mode = TestMode::Ui;
237     config.src_base = Path::new("tests").join("ui-cargo").canonicalize().unwrap();
238
239     let tests = compiletest::make_tests(&config);
240
241     let current_dir = env::current_dir().unwrap();
242     let filter = env::var("TESTNAME").ok();
243     let res = run_tests(&config, &filter, tests);
244     env::set_current_dir(current_dir).unwrap();
245
246     match res {
247         Ok(true) => {},
248         Ok(false) => panic!("Some tests failed"),
249         Err(e) => {
250             panic!("I/O failure during tests: {:?}", e);
251         },
252     }
253 }
254
255 fn prepare_env() {
256     set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
257     set_var("__CLIPPY_INTERNAL_TESTS", "true");
258     //set_var("RUST_BACKTRACE", "0");
259 }
260
261 #[test]
262 fn compile_test() {
263     prepare_env();
264     let mut config = default_config();
265     run_mode(&mut config);
266     run_ui_toml(&mut config);
267     run_ui_cargo(&mut config);
268     run_internal_tests(&mut config);
269 }