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