]> git.lizzy.rs Git - rust.git/blob - tests/system.rs
26b1edaff5bf05c19689c81b443061966a7a3043
[rust.git] / tests / system.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 extern crate rustfmt_nightly as rustfmt;
12 extern crate diff;
13 extern crate regex;
14 extern crate term;
15
16 use std::collections::HashMap;
17 use std::fs;
18 use std::io::{self, Read, BufRead, BufReader};
19 use std::path::{Path, PathBuf};
20
21 use rustfmt::*;
22 use rustfmt::filemap::{write_system_newlines, FileMap};
23 use rustfmt::config::{Config, ReportTactic};
24 use rustfmt::rustfmt_diff::*;
25
26 const DIFF_CONTEXT_SIZE: usize = 3;
27
28 fn get_path_string(dir_entry: io::Result<fs::DirEntry>) -> String {
29     let path = dir_entry.expect("Couldn't get DirEntry").path();
30
31     path.to_str().expect("Couldn't stringify path").to_owned()
32 }
33
34 // Integration tests. The files in the tests/source are formatted and compared
35 // to their equivalent in tests/target. The target file and config can be
36 // overridden by annotations in the source file. The input and output must match
37 // exactly.
38 // FIXME(#28) would be good to check for error messages and fail on them, or at
39 // least report.
40 #[test]
41 fn system_tests() {
42     // Get all files in the tests/source directory.
43     let files = fs::read_dir("tests/source").expect("Couldn't read source dir");
44     // Turn a DirEntry into a String that represents the relative path to the
45     // file.
46     let files = files.map(get_path_string);
47     let (_reports, count, fails) = check_files(files);
48
49     // Display results.
50     println!("Ran {} system tests.", count);
51     assert!(fails == 0, "{} system tests failed", fails);
52 }
53
54 // Do the same for tests/coverage-source directory
55 // the only difference is the coverage mode
56 #[test]
57 fn coverage_tests() {
58     let files = fs::read_dir("tests/coverage/source").expect("Couldn't read source dir");
59     let files = files.map(get_path_string);
60     let (_reports, count, fails) = check_files(files);
61
62     println!("Ran {} tests in coverage mode.", count);
63     assert!(fails == 0, "{} tests failed", fails);
64 }
65
66 #[test]
67 fn checkstyle_test() {
68     let filename = "tests/writemode/source/fn-single-line.rs";
69     let expected_filename = "tests/writemode/target/checkstyle.xml";
70     assert_output(filename, expected_filename);
71 }
72
73
74 // Helper function for comparing the results of rustfmt
75 // to a known output file generated by one of the write modes.
76 fn assert_output(source: &str, expected_filename: &str) {
77     let config = read_config(&source);
78     let (file_map, _report) = format_file(source, &config);
79
80     // Populate output by writing to a vec.
81     let mut out = vec![];
82     let _ = filemap::write_all_files(&file_map, &mut out, &config);
83     let output = String::from_utf8(out).unwrap();
84
85     let mut expected_file = fs::File::open(&expected_filename).expect("Couldn't open target");
86     let mut expected_text = String::new();
87     expected_file
88         .read_to_string(&mut expected_text)
89         .expect("Failed reading target");
90
91     let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
92     if compare.len() > 0 {
93         let mut failures = HashMap::new();
94         failures.insert(source.to_string(), compare);
95         print_mismatches(failures);
96         assert!(false, "Text does not match expected output");
97     }
98 }
99
100 // Idempotence tests. Files in tests/target are checked to be unaltered by
101 // rustfmt.
102 #[test]
103 fn idempotence_tests() {
104     // Get all files in the tests/target directory.
105     let files = fs::read_dir("tests/target")
106         .expect("Couldn't read target dir")
107         .map(get_path_string);
108     let (_reports, count, fails) = check_files(files);
109
110     // Display results.
111     println!("Ran {} idempotent tests.", count);
112     assert!(fails == 0, "{} idempotent tests failed", fails);
113 }
114
115 // Run rustfmt on itself. This operation must be idempotent. We also check that
116 // no warnings are emitted.
117 #[test]
118 fn self_tests() {
119     let files = fs::read_dir("src/bin")
120         .expect("Couldn't read src dir")
121         .chain(fs::read_dir("tests").expect("Couldn't read tests dir"))
122         .map(get_path_string);
123     // Hack because there's no `IntoIterator` impl for `[T; N]`.
124     let files = files.chain(Some("src/lib.rs".to_owned()).into_iter());
125     let files = files.chain(Some("build.rs".to_owned()).into_iter());
126
127     let (reports, count, fails) = check_files(files);
128     let mut warnings = 0;
129
130     // Display results.
131     println!("Ran {} self tests.", count);
132     assert!(fails == 0, "{} self tests failed", fails);
133
134     for format_report in reports {
135         println!("{}", format_report);
136         warnings += format_report.warning_count();
137     }
138
139     assert!(
140         warnings == 0,
141         "Rustfmt's code generated {} warnings",
142         warnings
143     );
144 }
145
146 #[test]
147 fn stdin_formatting_smoke_test() {
148     let input = Input::Text("fn main () {}".to_owned());
149     let config = Config::default();
150     let (error_summary, file_map, _report) = format_input::<io::Stdout>(input, &config, None)
151         .unwrap();
152     assert!(error_summary.has_no_errors());
153     for &(ref file_name, ref text) in &file_map {
154         if file_name == "stdin" {
155             assert!(text.to_string() == "fn main() {}\n");
156             return;
157         }
158     }
159     panic!("no stdin");
160 }
161
162 #[test]
163 fn format_lines_errors_are_reported() {
164     let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
165     let input = Input::Text(format!("fn {}() {{}}", long_identifier));
166     let config = Config::default();
167     let (error_summary, _file_map, _report) = format_input::<io::Stdout>(input, &config, None)
168         .unwrap();
169     assert!(error_summary.has_formatting_errors());
170 }
171
172 // For each file, run rustfmt and collect the output.
173 // Returns the number of files checked and the number of failures.
174 fn check_files<I>(files: I) -> (Vec<FormatReport>, u32, u32)
175 where
176     I: Iterator<Item = String>,
177 {
178     let mut count = 0;
179     let mut fails = 0;
180     let mut reports = vec![];
181
182     for file_name in files.filter(|f| f.ends_with(".rs")) {
183         println!("Testing '{}'...", file_name);
184
185         match idempotent_check(file_name) {
186             Ok(ref report) if report.has_warnings() => {
187                 print!("{}", report);
188                 fails += 1;
189             }
190             Ok(report) => reports.push(report),
191             Err(msg) => {
192                 print_mismatches(msg);
193                 fails += 1;
194             }
195         }
196
197         count += 1;
198     }
199
200     (reports, count, fails)
201 }
202
203 fn print_mismatches(result: HashMap<String, Vec<Mismatch>>) {
204     let mut t = term::stdout().unwrap();
205
206     for (file_name, diff) in result {
207         print_diff(diff, |line_num| {
208             format!("\nMismatch at {}:{}:", file_name, line_num)
209         });
210     }
211
212     t.reset().unwrap();
213 }
214
215 fn read_config(filename: &str) -> Config {
216     let sig_comments = read_significant_comments(&filename);
217     // Look for a config file... If there is a 'config' property in the significant comments, use
218     // that. Otherwise, if there are no significant comments at all, look for a config file with
219     // the same name as the test file.
220     let mut config = if !sig_comments.is_empty() {
221         get_config(sig_comments.get("config").map(|x| &(*x)[..]))
222     } else {
223         get_config(
224             Path::new(filename)
225                 .with_extension("toml")
226                 .file_name()
227                 .and_then(std::ffi::OsStr::to_str),
228         )
229     };
230
231     for (key, val) in &sig_comments {
232         if key != "target" && key != "config" {
233             config.override_value(key, val);
234         }
235     }
236
237     // Don't generate warnings for to-do items.
238     config.set().report_todo(ReportTactic::Never);
239
240     config
241 }
242
243 fn format_file<P: Into<PathBuf>>(filename: P, config: &Config) -> (FileMap, FormatReport) {
244     let input = Input::File(filename.into());
245     let (_error_summary, file_map, report) = format_input::<io::Stdout>(input, &config, None)
246         .unwrap();
247     return (file_map, report);
248 }
249
250 pub fn idempotent_check(filename: String) -> Result<FormatReport, HashMap<String, Vec<Mismatch>>> {
251     let sig_comments = read_significant_comments(&filename);
252     let config = read_config(&filename);
253     let (file_map, format_report) = format_file(filename, &config);
254
255     let mut write_result = HashMap::new();
256     for &(ref filename, ref text) in &file_map {
257         let mut v = Vec::new();
258         // Won't panic, as we're not doing any IO.
259         write_system_newlines(&mut v, text, &config).unwrap();
260         // Won't panic, we are writing correct utf8.
261         let one_result = String::from_utf8(v).unwrap();
262         write_result.insert(filename.clone(), one_result);
263     }
264
265     let target = sig_comments.get("target").map(|x| &(*x)[..]);
266
267     handle_result(write_result, target).map(|_| format_report)
268 }
269
270 // Reads test config file using the supplied (optional) file name. If there's no file name or the
271 // file doesn't exist, just return the default config. Otherwise, the file must be read
272 // successfully.
273 fn get_config(config_file: Option<&str>) -> Config {
274     let config_file_name = match config_file {
275         None => return Default::default(),
276         Some(file_name) => {
277             let mut full_path = "tests/config/".to_owned();
278             full_path.push_str(&file_name);
279             if !Path::new(&full_path).exists() {
280                 return Default::default();
281             };
282             full_path
283         }
284     };
285
286     let mut def_config_file = fs::File::open(config_file_name).expect("Couldn't open config");
287     let mut def_config = String::new();
288     def_config_file
289         .read_to_string(&mut def_config)
290         .expect("Couldn't read config");
291
292     Config::from_toml(&def_config).expect("Invalid toml")
293 }
294
295 // Reads significant comments of the form: // rustfmt-key: value
296 // into a hash map.
297 fn read_significant_comments(file_name: &str) -> HashMap<String, String> {
298     let file = fs::File::open(file_name).expect(&format!("Couldn't read file {}", file_name));
299     let reader = BufReader::new(file);
300     let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
301     let regex = regex::Regex::new(&pattern).expect("Failed creating pattern 1");
302
303     // Matches lines containing significant comments or whitespace.
304     let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
305         .expect("Failed creating pattern 2");
306
307     reader
308         .lines()
309         .map(|line| line.expect("Failed getting line"))
310         .take_while(|line| line_regex.is_match(&line))
311         .filter_map(|line| {
312             regex.captures_iter(&line).next().map(|capture| {
313                 (
314                     capture
315                         .get(1)
316                         .expect("Couldn't unwrap capture")
317                         .as_str()
318                         .to_owned(),
319                     capture
320                         .get(2)
321                         .expect("Couldn't unwrap capture")
322                         .as_str()
323                         .to_owned(),
324                 )
325             })
326         })
327         .collect()
328 }
329
330 // Compare output to input.
331 // TODO: needs a better name, more explanation.
332 fn handle_result(
333     result: HashMap<String, String>,
334     target: Option<&str>,
335 ) -> Result<(), HashMap<String, Vec<Mismatch>>> {
336     let mut failures = HashMap::new();
337
338     for (file_name, fmt_text) in result {
339         // If file is in tests/source, compare to file with same name in tests/target.
340         let target = get_target(&file_name, target);
341         let open_error = format!("Couldn't open target {:?}", &target);
342         let mut f = fs::File::open(&target).expect(&open_error);
343
344         let mut text = String::new();
345         let read_error = format!("Failed reading target {:?}", &target);
346         f.read_to_string(&mut text).expect(&read_error);
347
348         if fmt_text != text {
349             let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
350             assert!(
351                 !diff.is_empty(),
352                 "Empty diff? Maybe due to a missing a newline at the end of a file?"
353             );
354             failures.insert(file_name, diff);
355         }
356     }
357
358     if failures.is_empty() {
359         Ok(())
360     } else {
361         Err(failures)
362     }
363 }
364
365 // Map source file paths to their target paths.
366 fn get_target(file_name: &str, target: Option<&str>) -> String {
367     if file_name.contains("source") {
368         let target_file_name = file_name.replace("source", "target");
369         if let Some(replace_name) = target {
370             Path::new(&target_file_name)
371                 .with_file_name(replace_name)
372                 .into_os_string()
373                 .into_string()
374                 .unwrap()
375         } else {
376             target_file_name
377         }
378     } else {
379         // This is either and idempotence check or a self check
380         file_name.to_owned()
381     }
382 }
383
384 #[test]
385 fn rustfmt_diff_make_diff_tests() {
386     let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
387     assert_eq!(
388         diff,
389         vec![
390             Mismatch {
391                 line_number: 1,
392                 lines: vec![
393                     DiffLine::Context("a".into()),
394                     DiffLine::Resulting("b".into()),
395                     DiffLine::Expected("e".into()),
396                     DiffLine::Context("c".into()),
397                     DiffLine::Context("d".into()),
398                 ],
399             },
400         ]
401     );
402 }
403
404 #[test]
405 fn rustfmt_diff_no_diff_test() {
406     let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
407     assert_eq!(diff, vec![]);
408 }