]> git.lizzy.rs Git - rust.git/blob - tests/compile-test.rs
Added negative test cases and ran cargo dev fmt
[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                     crates.entry(dep).or_insert(path);
53                     break;
54                 }
55             }
56         }
57     }
58
59     let v: Vec<_> = crates
60         .into_iter()
61         .map(|(dep, path)| format!("--extern {}={}", dep, path.display()))
62         .collect();
63     v.join(" ")
64 }
65
66 fn default_config() -> compiletest::Config {
67     let mut config = compiletest::Config::default();
68
69     if let Ok(name) = env::var("TESTNAME") {
70         config.filter = Some(name);
71     }
72
73     if let Some(path) = option_env!("RUSTC_LIB_PATH") {
74         let path = PathBuf::from(path);
75         config.run_lib_path = path.clone();
76         config.compile_lib_path = path;
77     }
78
79     config.target_rustcflags = Some(format!(
80         "-L {0} -L {1} -Dwarnings -Zui-testing {2}",
81         host_lib().join("deps").display(),
82         cargo::TARGET_LIB.join("deps").display(),
83         third_party_crates(),
84     ));
85
86     config.build_base = if cargo::is_rustc_test_suite() {
87         // This make the stderr files go to clippy OUT_DIR on rustc repo build dir
88         let mut path = PathBuf::from(env!("OUT_DIR"));
89         path.push("test_build_base");
90         path
91     } else {
92         host_lib().join("test_build_base")
93     };
94     config.rustc_path = clippy_driver_path();
95     config
96 }
97
98 fn run_mode(cfg: &mut compiletest::Config) {
99     cfg.mode = TestMode::Ui;
100     cfg.src_base = Path::new("tests").join("ui");
101     compiletest::run_tests(&cfg);
102 }
103
104 fn run_ui_toml(config: &mut compiletest::Config) {
105     fn run_tests(config: &compiletest::Config, mut tests: Vec<tester::TestDescAndFn>) -> Result<bool, io::Error> {
106         let mut result = true;
107         let opts = compiletest::test_opts(config);
108         for dir in fs::read_dir(&config.src_base)? {
109             let dir = dir?;
110             if !dir.file_type()?.is_dir() {
111                 continue;
112             }
113             let dir_path = dir.path();
114             set_var("CARGO_MANIFEST_DIR", &dir_path);
115             for file in fs::read_dir(&dir_path)? {
116                 let file = file?;
117                 let file_path = file.path();
118                 if file.file_type()?.is_dir() {
119                     continue;
120                 }
121                 if file_path.extension() != Some(OsStr::new("rs")) {
122                     continue;
123                 }
124                 let paths = compiletest::common::TestPaths {
125                     file: file_path,
126                     base: config.src_base.clone(),
127                     relative_dir: dir_path.file_name().unwrap().into(),
128                 };
129                 let test_name = compiletest::make_test_name(&config, &paths);
130                 let index = tests
131                     .iter()
132                     .position(|test| test.desc.name == test_name)
133                     .expect("The test should be in there");
134                 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
135             }
136         }
137         Ok(result)
138     }
139
140     config.mode = TestMode::Ui;
141     config.src_base = Path::new("tests").join("ui-toml").canonicalize().unwrap();
142
143     let tests = compiletest::make_tests(&config);
144
145     let res = run_tests(&config, tests);
146     match res {
147         Ok(true) => {},
148         Ok(false) => panic!("Some tests failed"),
149         Err(e) => {
150             panic!("I/O failure during tests: {:?}", e);
151         },
152     }
153 }
154
155 fn run_ui_cargo(config: &mut compiletest::Config) {
156     fn run_tests(
157         config: &compiletest::Config,
158         filter: &Option<String>,
159         mut tests: Vec<tester::TestDescAndFn>,
160     ) -> Result<bool, io::Error> {
161         let mut result = true;
162         let opts = compiletest::test_opts(config);
163
164         for dir in fs::read_dir(&config.src_base)? {
165             let dir = dir?;
166             if !dir.file_type()?.is_dir() {
167                 continue;
168             }
169
170             // Use the filter if provided
171             let dir_path = dir.path();
172             match &filter {
173                 Some(name) if !dir_path.ends_with(name) => continue,
174                 _ => {},
175             }
176
177             for case in fs::read_dir(&dir_path)? {
178                 let case = case?;
179                 if !case.file_type()?.is_dir() {
180                     continue;
181                 }
182
183                 let src_path = case.path().join("src");
184                 env::set_current_dir(&src_path)?;
185
186                 for file in fs::read_dir(&src_path)? {
187                     let file = file?;
188                     if file.file_type()?.is_dir() {
189                         continue;
190                     }
191
192                     // Search for the main file to avoid running a test for each file in the project
193                     let file_path = file.path();
194                     match file_path.file_name().and_then(OsStr::to_str) {
195                         Some("main.rs") => {},
196                         _ => continue,
197                     }
198
199                     let paths = compiletest::common::TestPaths {
200                         file: file_path,
201                         base: config.src_base.clone(),
202                         relative_dir: src_path.strip_prefix(&config.src_base).unwrap().into(),
203                     };
204                     let test_name = compiletest::make_test_name(&config, &paths);
205                     let index = tests
206                         .iter()
207                         .position(|test| test.desc.name == test_name)
208                         .expect("The test should be in there");
209                     result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
210                 }
211             }
212         }
213         Ok(result)
214     }
215
216     if cargo::is_rustc_test_suite() {
217         return;
218     }
219
220     config.mode = TestMode::Ui;
221     config.src_base = Path::new("tests").join("ui-cargo").canonicalize().unwrap();
222
223     let tests = compiletest::make_tests(&config);
224
225     let current_dir = env::current_dir().unwrap();
226     let filter = env::var("TESTNAME").ok();
227     let res = run_tests(&config, &filter, tests);
228     env::set_current_dir(current_dir).unwrap();
229
230     match res {
231         Ok(true) => {},
232         Ok(false) => panic!("Some tests failed"),
233         Err(e) => {
234             panic!("I/O failure during tests: {:?}", e);
235         },
236     }
237 }
238
239 fn prepare_env() {
240     set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
241     set_var("CLIPPY_TESTS", "true");
242     //set_var("RUST_BACKTRACE", "0");
243 }
244
245 #[test]
246 fn compile_test() {
247     prepare_env();
248     let mut config = default_config();
249     run_mode(&mut config);
250     run_ui_toml(&mut config);
251     run_ui_cargo(&mut config);
252 }