]> git.lizzy.rs Git - rust.git/blob - tests/system.rs
Using `if let` to be more concise
[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 #![feature(rustc_private)]
12
13 #[macro_use]
14 extern crate log;
15 extern crate regex;
16 extern crate rustfmt_nightly as rustfmt;
17 extern crate term;
18
19 use std::collections::HashMap;
20 use std::fs;
21 use std::io::{self, BufRead, BufReader, Read};
22 use std::iter::Peekable;
23 use std::path::{Path, PathBuf};
24 use std::str::Chars;
25
26 use rustfmt::*;
27 use rustfmt::filemap::{write_system_newlines, FileMap};
28 use rustfmt::config::{Color, Config, ReportTactic};
29 use rustfmt::rustfmt_diff::*;
30
31 const DIFF_CONTEXT_SIZE: usize = 3;
32
33 fn get_path_string(dir_entry: io::Result<fs::DirEntry>) -> PathBuf {
34     dir_entry.expect("Couldn't get DirEntry").path().to_owned()
35 }
36
37 // Integration tests. The files in the tests/source are formatted and compared
38 // to their equivalent in tests/target. The target file and config can be
39 // overridden by annotations in the source file. The input and output must match
40 // exactly.
41 #[test]
42 fn system_tests() {
43     // Get all files in the tests/source directory.
44     let files = fs::read_dir("tests/source").expect("Couldn't read source dir");
45     // Turn a DirEntry into a String that represents the relative path to the
46     // file.
47     let files = files.map(get_path_string);
48     let (_reports, count, fails) = check_files(files);
49
50     // Display results.
51     println!("Ran {} system tests.", count);
52     assert_eq!(fails, 0, "{} system tests failed", fails);
53 }
54
55 // Do the same for tests/coverage-source directory
56 // the only difference is the coverage mode
57 #[test]
58 fn coverage_tests() {
59     let files = fs::read_dir("tests/coverage/source").expect("Couldn't read source dir");
60     let files = files.map(get_path_string);
61     let (_reports, count, fails) = check_files(files);
62
63     println!("Ran {} tests in coverage mode.", count);
64     assert_eq!(fails, 0, "{} tests failed", fails);
65 }
66
67 #[test]
68 fn checkstyle_test() {
69     let filename = "tests/writemode/source/fn-single-line.rs";
70     let expected_filename = "tests/writemode/target/checkstyle.xml";
71     assert_output(Path::new(filename), Path::new(expected_filename));
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: &Path, expected_filename: &Path) {
77     let config = read_config(source);
78     let (_error_summary, 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.is_empty() {
93         let mut failures = HashMap::new();
94         failures.insert(source.to_owned(), 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_eq!(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(PathBuf::from("src/lib.rs")).into_iter());
125     let files = files.chain(Some(PathBuf::from("build.rs")).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_eq!(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_eq!(
140         warnings,
141         0,
142         "Rustfmt's code generated {} warnings",
143         warnings
144     );
145 }
146
147 #[test]
148 fn stdin_formatting_smoke_test() {
149     let input = Input::Text("fn main () {}".to_owned());
150     let config = Config::default();
151     let (error_summary, file_map, _report) =
152         format_input::<io::Stdout>(input, &config, None).unwrap();
153     assert!(error_summary.has_no_errors());
154     for &(ref file_name, ref text) in &file_map {
155         if let FileName::Custom(ref file_name) = *file_name {
156             if file_name == "stdin" {
157                 assert_eq!(text.to_string(), "fn main() {}\n");
158                 return;
159             }
160         }
161     }
162     panic!("no stdin");
163 }
164
165 // FIXME(#1990) restore this test
166 // #[test]
167 // fn stdin_disable_all_formatting_test() {
168 //     let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
169 //     let mut child = Command::new("./target/debug/rustfmt")
170 //         .stdin(Stdio::piped())
171 //         .stdout(Stdio::piped())
172 //         .arg("--config-path=./tests/config/disable_all_formatting.toml")
173 //         .spawn()
174 //         .expect("failed to execute child");
175
176 //     {
177 //         let stdin = child.stdin.as_mut().expect("failed to get stdin");
178 //         stdin
179 //             .write_all(input.as_bytes())
180 //             .expect("failed to write stdin");
181 //     }
182 //     let output = child.wait_with_output().expect("failed to wait on child");
183 //     assert!(output.status.success());
184 //     assert!(output.stderr.is_empty());
185 //     assert_eq!(input, String::from_utf8(output.stdout).unwrap());
186 // }
187
188 #[test]
189 fn format_lines_errors_are_reported() {
190     let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
191     let input = Input::Text(format!("fn {}() {{}}", long_identifier));
192     let config = Config::default();
193     let (error_summary, _file_map, _report) =
194         format_input::<io::Stdout>(input, &config, None).unwrap();
195     assert!(error_summary.has_formatting_errors());
196 }
197
198 // For each file, run rustfmt and collect the output.
199 // Returns the number of files checked and the number of failures.
200 fn check_files<I>(files: I) -> (Vec<FormatReport>, u32, u32)
201 where
202     I: Iterator<Item = PathBuf>,
203 {
204     let mut count = 0;
205     let mut fails = 0;
206     let mut reports = vec![];
207
208     for file_name in files.filter(|f| f.extension().map_or(false, |f| f == "rs")) {
209         debug!("Testing '{}'...", file_name.display());
210
211         match idempotent_check(file_name) {
212             Ok(ref report) if report.has_warnings() => {
213                 print!("{}", report);
214                 fails += 1;
215             }
216             Ok(report) => reports.push(report),
217             Err(err) => {
218                 if let IdempotentCheckError::Mismatch(msg) = err {
219                     print_mismatches(msg);
220                 }
221                 fails += 1;
222             }
223         }
224
225         count += 1;
226     }
227
228     (reports, count, fails)
229 }
230
231 fn print_mismatches(result: HashMap<PathBuf, Vec<Mismatch>>) {
232     let mut t = term::stdout().unwrap();
233
234     for (file_name, diff) in result {
235         print_diff(
236             diff,
237             |line_num| format!("\nMismatch at {}:{}:", file_name.display(), line_num),
238             Color::Auto,
239         );
240     }
241
242     t.reset().unwrap();
243 }
244
245 fn read_config(filename: &Path) -> Config {
246     let sig_comments = read_significant_comments(filename);
247     // Look for a config file... If there is a 'config' property in the significant comments, use
248     // that. Otherwise, if there are no significant comments at all, look for a config file with
249     // the same name as the test file.
250     let mut config = if !sig_comments.is_empty() {
251         get_config(sig_comments.get("config").map(Path::new))
252     } else {
253         get_config(filename.with_extension("toml").file_name().map(Path::new))
254     };
255
256     for (key, val) in &sig_comments {
257         if key != "target" && key != "config" {
258             config.override_value(key, val);
259         }
260     }
261
262     // Don't generate warnings for to-do items.
263     config.set().report_todo(ReportTactic::Never);
264
265     config
266 }
267
268 fn format_file<P: Into<PathBuf>>(filepath: P, config: &Config) -> (Summary, FileMap, FormatReport) {
269     let filepath = filepath.into();
270     let input = Input::File(filepath);
271     format_input::<io::Stdout>(input, config, None).unwrap()
272 }
273
274 pub enum IdempotentCheckError {
275     Mismatch(HashMap<PathBuf, Vec<Mismatch>>),
276     Parse,
277 }
278
279 pub fn idempotent_check(filename: PathBuf) -> Result<FormatReport, IdempotentCheckError> {
280     let sig_comments = read_significant_comments(&filename);
281     let config = read_config(&filename);
282     let (error_summary, file_map, format_report) = format_file(filename, &config);
283     if error_summary.has_parsing_errors() {
284         return Err(IdempotentCheckError::Parse);
285     }
286
287     let mut write_result = HashMap::new();
288     for &(ref filename, ref text) in &file_map {
289         let mut v = Vec::new();
290         // Won't panic, as we're not doing any IO.
291         write_system_newlines(&mut v, text, &config).unwrap();
292         // Won't panic, we are writing correct utf8.
293         let one_result = String::from_utf8(v).unwrap();
294         if let FileName::Real(ref filename) = *filename {
295             write_result.insert(filename.to_owned(), one_result);
296         }
297     }
298
299     let target = sig_comments.get("target").map(|x| &(*x)[..]);
300
301     handle_result(write_result, target).map(|_| format_report)
302 }
303
304 // Reads test config file using the supplied (optional) file name. If there's no file name or the
305 // file doesn't exist, just return the default config. Otherwise, the file must be read
306 // successfully.
307 fn get_config(config_file: Option<&Path>) -> Config {
308     let config_file_name = match config_file {
309         None => return Default::default(),
310         Some(file_name) => {
311             let mut full_path = PathBuf::from("tests/config/");
312             full_path.push(file_name);
313             if !full_path.exists() {
314                 return Default::default();
315             };
316             full_path
317         }
318     };
319
320     let mut def_config_file = fs::File::open(config_file_name).expect("Couldn't open config");
321     let mut def_config = String::new();
322     def_config_file
323         .read_to_string(&mut def_config)
324         .expect("Couldn't read config");
325
326     Config::from_toml(&def_config).expect("Invalid toml")
327 }
328
329 // Reads significant comments of the form: // rustfmt-key: value
330 // into a hash map.
331 fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
332     let file =
333         fs::File::open(file_name).expect(&format!("Couldn't read file {}", file_name.display()));
334     let reader = BufReader::new(file);
335     let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
336     let regex = regex::Regex::new(pattern).expect("Failed creating pattern 1");
337
338     // Matches lines containing significant comments or whitespace.
339     let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
340         .expect("Failed creating pattern 2");
341
342     reader
343         .lines()
344         .map(|line| line.expect("Failed getting line"))
345         .take_while(|line| line_regex.is_match(line))
346         .filter_map(|line| {
347             regex.captures_iter(&line).next().map(|capture| {
348                 (
349                     capture
350                         .get(1)
351                         .expect("Couldn't unwrap capture")
352                         .as_str()
353                         .to_owned(),
354                     capture
355                         .get(2)
356                         .expect("Couldn't unwrap capture")
357                         .as_str()
358                         .to_owned(),
359                 )
360             })
361         })
362         .collect()
363 }
364
365 // Compare output to input.
366 // TODO: needs a better name, more explanation.
367 fn handle_result(
368     result: HashMap<PathBuf, String>,
369     target: Option<&str>,
370 ) -> Result<(), IdempotentCheckError> {
371     let mut failures = HashMap::new();
372
373     for (file_name, fmt_text) in result {
374         // If file is in tests/source, compare to file with same name in tests/target.
375         let target = get_target(&file_name, target);
376         let open_error = format!("Couldn't open target {:?}", &target);
377         let mut f = fs::File::open(&target).expect(&open_error);
378
379         let mut text = String::new();
380         let read_error = format!("Failed reading target {:?}", &target);
381         f.read_to_string(&mut text).expect(&read_error);
382
383         // Ignore LF and CRLF difference for Windows.
384         if !string_eq_ignore_newline_repr(&fmt_text, &text) {
385             let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
386             assert!(
387                 !diff.is_empty(),
388                 "Empty diff? Maybe due to a missing a newline at the end of a file?"
389             );
390             failures.insert(file_name, diff);
391         }
392     }
393
394     if failures.is_empty() {
395         Ok(())
396     } else {
397         Err(IdempotentCheckError::Mismatch(failures))
398     }
399 }
400
401 // Map source file paths to their target paths.
402 fn get_target(file_name: &Path, target: Option<&str>) -> PathBuf {
403     if let Some(n) = file_name
404         .components()
405         .position(|c| c.as_os_str() == "source")
406     {
407         let mut target_file_name = PathBuf::new();
408         for (i, c) in file_name.components().enumerate() {
409             if i == n {
410                 target_file_name.push("target");
411             } else {
412                 target_file_name.push(c.as_os_str());
413             }
414         }
415         if let Some(replace_name) = target {
416             target_file_name.with_file_name(replace_name)
417         } else {
418             target_file_name
419         }
420     } else {
421         // This is either and idempotence check or a self check
422         file_name.to_owned()
423     }
424 }
425
426 #[test]
427 fn rustfmt_diff_make_diff_tests() {
428     let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
429     assert_eq!(
430         diff,
431         vec![
432             Mismatch {
433                 line_number: 1,
434                 lines: vec![
435                     DiffLine::Context("a".into()),
436                     DiffLine::Resulting("b".into()),
437                     DiffLine::Expected("e".into()),
438                     DiffLine::Context("c".into()),
439                     DiffLine::Context("d".into()),
440                 ],
441             },
442         ]
443     );
444 }
445
446 #[test]
447 fn rustfmt_diff_no_diff_test() {
448     let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
449     assert_eq!(diff, vec![]);
450 }
451
452 // Compare strings without distinguishing between CRLF and LF
453 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
454     let left = CharsIgnoreNewlineRepr(left.chars().peekable());
455     let right = CharsIgnoreNewlineRepr(right.chars().peekable());
456     left.eq(right)
457 }
458
459 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
460
461 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
462     type Item = char;
463     fn next(&mut self) -> Option<char> {
464         self.0.next().map(|c| {
465             if c == '\r' {
466                 if *self.0.peek().unwrap_or(&'\0') == '\n' {
467                     self.0.next();
468                     '\n'
469                 } else {
470                     '\r'
471                 }
472             } else {
473                 c
474             }
475         })
476     }
477 }
478
479 #[test]
480 fn string_eq_ignore_newline_repr_test() {
481     assert!(string_eq_ignore_newline_repr("", ""));
482     assert!(!string_eq_ignore_newline_repr("", "abc"));
483     assert!(!string_eq_ignore_newline_repr("abc", ""));
484     assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
485     assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
486     assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));
487 }