]> git.lizzy.rs Git - rust.git/blob - tests/system.rs
Cargo fmt and update tests
[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 #[macro_use]
12 extern crate log;
13 extern crate regex;
14 extern crate rustfmt_nightly as rustfmt;
15 extern crate term;
16
17 use std::collections::HashMap;
18 use std::fs;
19 use std::io::{self, BufRead, BufReader, Read};
20 use std::iter::Peekable;
21 use std::path::{Path, PathBuf};
22 use std::str::Chars;
23
24 use rustfmt::*;
25 use rustfmt::filemap::{write_system_newlines, FileMap};
26 use rustfmt::config::{Color, Config, ReportTactic};
27 use rustfmt::rustfmt_diff::*;
28
29 const DIFF_CONTEXT_SIZE: usize = 3;
30
31 fn get_path_string(dir_entry: io::Result<fs::DirEntry>) -> String {
32     let path = dir_entry.expect("Couldn't get DirEntry").path();
33
34     path.to_str().expect("Couldn't stringify 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(filename, expected_filename);
72 }
73
74
75 // Helper function for comparing the results of rustfmt
76 // to a known output file generated by one of the write modes.
77 fn assert_output(source: &str, expected_filename: &str) {
78     let config = read_config(source);
79     let (file_map, _report) = format_file(source, &config);
80
81     // Populate output by writing to a vec.
82     let mut out = vec![];
83     let _ = filemap::write_all_files(&file_map, &mut out, &config);
84     let output = String::from_utf8(out).unwrap();
85
86     let mut expected_file = fs::File::open(&expected_filename).expect("Couldn't open target");
87     let mut expected_text = String::new();
88     expected_file
89         .read_to_string(&mut expected_text)
90         .expect("Failed reading target");
91
92     let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
93     if !compare.is_empty() {
94         let mut failures = HashMap::new();
95         failures.insert(source.to_string(), compare);
96         print_mismatches(failures);
97         assert!(false, "Text does not match expected output");
98     }
99 }
100
101 // Idempotence tests. Files in tests/target are checked to be unaltered by
102 // rustfmt.
103 #[test]
104 fn idempotence_tests() {
105     // Get all files in the tests/target directory.
106     let files = fs::read_dir("tests/target")
107         .expect("Couldn't read target dir")
108         .map(get_path_string);
109     let (_reports, count, fails) = check_files(files);
110
111     // Display results.
112     println!("Ran {} idempotent tests.", count);
113     assert_eq!(fails, 0, "{} idempotent tests failed", fails);
114 }
115
116 // Run rustfmt on itself. This operation must be idempotent. We also check that
117 // no warnings are emitted.
118 #[test]
119 fn self_tests() {
120     let files = fs::read_dir("src/bin")
121         .expect("Couldn't read src dir")
122         .chain(fs::read_dir("tests").expect("Couldn't read tests dir"))
123         .map(get_path_string);
124     // Hack because there's no `IntoIterator` impl for `[T; N]`.
125     let files = files.chain(Some("src/lib.rs".to_owned()).into_iter());
126     let files = files.chain(Some("build.rs".to_owned()).into_iter());
127
128     let (reports, count, fails) = check_files(files);
129     let mut warnings = 0;
130
131     // Display results.
132     println!("Ran {} self tests.", count);
133     assert_eq!(fails, 0, "{} self tests failed", fails);
134
135     for format_report in reports {
136         println!("{}", format_report);
137         warnings += format_report.warning_count();
138     }
139
140     assert_eq!(
141         warnings,
142         0,
143         "Rustfmt's code generated {} warnings",
144         warnings
145     );
146 }
147
148 #[test]
149 fn stdin_formatting_smoke_test() {
150     let input = Input::Text("fn main () {}".to_owned());
151     let config = Config::default();
152     let (error_summary, file_map, _report) =
153         format_input::<io::Stdout>(input, &config, None).unwrap();
154     assert!(error_summary.has_no_errors());
155     for &(ref file_name, ref text) in &file_map {
156         if file_name == "stdin" {
157             assert_eq!(text.to_string(), "fn main() {}\n");
158             return;
159         }
160     }
161     panic!("no stdin");
162 }
163
164 // FIXME(#1990) restore this test
165 // #[test]
166 // fn stdin_disable_all_formatting_test() {
167 //     let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
168 //     let mut child = Command::new("./target/debug/rustfmt")
169 //         .stdin(Stdio::piped())
170 //         .stdout(Stdio::piped())
171 //         .arg("--config-path=./tests/config/disable_all_formatting.toml")
172 //         .spawn()
173 //         .expect("failed to execute child");
174
175 //     {
176 //         let stdin = child.stdin.as_mut().expect("failed to get stdin");
177 //         stdin
178 //             .write_all(input.as_bytes())
179 //             .expect("failed to write stdin");
180 //     }
181 //     let output = child.wait_with_output().expect("failed to wait on child");
182 //     assert!(output.status.success());
183 //     assert!(output.stderr.is_empty());
184 //     assert_eq!(input, String::from_utf8(output.stdout).unwrap());
185 // }
186
187 #[test]
188 fn format_lines_errors_are_reported() {
189     let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
190     let input = Input::Text(format!("fn {}() {{}}", long_identifier));
191     let config = Config::default();
192     let (error_summary, _file_map, _report) =
193         format_input::<io::Stdout>(input, &config, None).unwrap();
194     assert!(error_summary.has_formatting_errors());
195 }
196
197 // For each file, run rustfmt and collect the output.
198 // Returns the number of files checked and the number of failures.
199 fn check_files<I>(files: I) -> (Vec<FormatReport>, u32, u32)
200 where
201     I: Iterator<Item = String>,
202 {
203     let mut count = 0;
204     let mut fails = 0;
205     let mut reports = vec![];
206
207     for file_name in files.filter(|f| f.ends_with(".rs")) {
208         debug!("Testing '{}'...", file_name);
209
210         match idempotent_check(file_name) {
211             Ok(ref report) if report.has_warnings() => {
212                 print!("{}", report);
213                 fails += 1;
214             }
215             Ok(report) => reports.push(report),
216             Err(msg) => {
217                 print_mismatches(msg);
218                 fails += 1;
219             }
220         }
221
222         count += 1;
223     }
224
225     (reports, count, fails)
226 }
227
228 fn print_mismatches(result: HashMap<String, Vec<Mismatch>>) {
229     let mut t = term::stdout().unwrap();
230
231     for (file_name, diff) in result {
232         print_diff(
233             diff,
234             |line_num| format!("\nMismatch at {}:{}:", file_name, line_num),
235             Color::Auto,
236         );
237     }
238
239     t.reset().unwrap();
240 }
241
242 fn read_config(filename: &str) -> Config {
243     let sig_comments = read_significant_comments(filename);
244     // Look for a config file... If there is a 'config' property in the significant comments, use
245     // that. Otherwise, if there are no significant comments at all, look for a config file with
246     // the same name as the test file.
247     let mut config = if !sig_comments.is_empty() {
248         get_config(sig_comments.get("config").map(|x| &(*x)[..]))
249     } else {
250         get_config(
251             Path::new(filename)
252                 .with_extension("toml")
253                 .file_name()
254                 .and_then(std::ffi::OsStr::to_str),
255         )
256     };
257
258     for (key, val) in &sig_comments {
259         if key != "target" && key != "config" {
260             config.override_value(key, val);
261         }
262     }
263
264     // Don't generate warnings for to-do items.
265     config.set().report_todo(ReportTactic::Never);
266
267     config
268 }
269
270 fn format_file<P: Into<PathBuf>>(filepath: P, config: &Config) -> (FileMap, FormatReport) {
271     let filepath = filepath.into();
272     let input = Input::File(filepath);
273     let (_error_summary, file_map, report) =
274         format_input::<io::Stdout>(input, config, None).unwrap();
275     (file_map, report)
276 }
277
278 pub fn idempotent_check(filename: String) -> Result<FormatReport, HashMap<String, Vec<Mismatch>>> {
279     let sig_comments = read_significant_comments(&filename);
280     let config = read_config(&filename);
281     let (file_map, format_report) = format_file(filename, &config);
282
283     let mut write_result = HashMap::new();
284     for &(ref filename, ref text) in &file_map {
285         let mut v = Vec::new();
286         // Won't panic, as we're not doing any IO.
287         write_system_newlines(&mut v, text, &config).unwrap();
288         // Won't panic, we are writing correct utf8.
289         let one_result = String::from_utf8(v).unwrap();
290         write_result.insert(filename.clone(), one_result);
291     }
292
293     let target = sig_comments.get("target").map(|x| &(*x)[..]);
294
295     handle_result(write_result, target).map(|_| format_report)
296 }
297
298 // Reads test config file using the supplied (optional) file name. If there's no file name or the
299 // file doesn't exist, just return the default config. Otherwise, the file must be read
300 // successfully.
301 fn get_config(config_file: Option<&str>) -> Config {
302     let config_file_name = match config_file {
303         None => return Default::default(),
304         Some(file_name) => {
305             let mut full_path = "tests/config/".to_owned();
306             full_path.push_str(file_name);
307             if !Path::new(&full_path).exists() {
308                 return Default::default();
309             };
310             full_path
311         }
312     };
313
314     let mut def_config_file = fs::File::open(config_file_name).expect("Couldn't open config");
315     let mut def_config = String::new();
316     def_config_file
317         .read_to_string(&mut def_config)
318         .expect("Couldn't read config");
319
320     Config::from_toml(&def_config).expect("Invalid toml")
321 }
322
323 // Reads significant comments of the form: // rustfmt-key: value
324 // into a hash map.
325 fn read_significant_comments(file_name: &str) -> HashMap<String, String> {
326     let file = fs::File::open(file_name).expect(&format!("Couldn't read file {}", file_name));
327     let reader = BufReader::new(file);
328     let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
329     let regex = regex::Regex::new(pattern).expect("Failed creating pattern 1");
330
331     // Matches lines containing significant comments or whitespace.
332     let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
333         .expect("Failed creating pattern 2");
334
335     reader
336         .lines()
337         .map(|line| line.expect("Failed getting line"))
338         .take_while(|line| line_regex.is_match(line))
339         .filter_map(|line| {
340             regex.captures_iter(&line).next().map(|capture| {
341                 (
342                     capture
343                         .get(1)
344                         .expect("Couldn't unwrap capture")
345                         .as_str()
346                         .to_owned(),
347                     capture
348                         .get(2)
349                         .expect("Couldn't unwrap capture")
350                         .as_str()
351                         .to_owned(),
352                 )
353             })
354         })
355         .collect()
356 }
357
358 // Compare output to input.
359 // TODO: needs a better name, more explanation.
360 fn handle_result(
361     result: HashMap<String, String>,
362     target: Option<&str>,
363 ) -> Result<(), HashMap<String, Vec<Mismatch>>> {
364     let mut failures = HashMap::new();
365
366     for (file_name, fmt_text) in result {
367         // If file is in tests/source, compare to file with same name in tests/target.
368         let target = get_target(&file_name, target);
369         let open_error = format!("Couldn't open target {:?}", &target);
370         let mut f = fs::File::open(&target).expect(&open_error);
371
372         let mut text = String::new();
373         let read_error = format!("Failed reading target {:?}", &target);
374         f.read_to_string(&mut text).expect(&read_error);
375
376         // Ignore LF and CRLF difference for Windows.
377         if !string_eq_ignore_newline_repr(&fmt_text, &text) {
378             let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
379             assert!(
380                 !diff.is_empty(),
381                 "Empty diff? Maybe due to a missing a newline at the end of a file?"
382             );
383             failures.insert(file_name, diff);
384         }
385     }
386
387     if failures.is_empty() {
388         Ok(())
389     } else {
390         Err(failures)
391     }
392 }
393
394 // Map source file paths to their target paths.
395 fn get_target(file_name: &str, target: Option<&str>) -> String {
396     if file_name.contains("source") {
397         let target_file_name = file_name.replace("source", "target");
398         if let Some(replace_name) = target {
399             Path::new(&target_file_name)
400                 .with_file_name(replace_name)
401                 .into_os_string()
402                 .into_string()
403                 .unwrap()
404         } else {
405             target_file_name
406         }
407     } else {
408         // This is either and idempotence check or a self check
409         file_name.to_owned()
410     }
411 }
412
413 #[test]
414 fn rustfmt_diff_make_diff_tests() {
415     let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
416     assert_eq!(
417         diff,
418         vec![
419             Mismatch {
420                 line_number: 1,
421                 lines: vec![
422                     DiffLine::Context("a".into()),
423                     DiffLine::Resulting("b".into()),
424                     DiffLine::Expected("e".into()),
425                     DiffLine::Context("c".into()),
426                     DiffLine::Context("d".into()),
427                 ],
428             },
429         ]
430     );
431 }
432
433 #[test]
434 fn rustfmt_diff_no_diff_test() {
435     let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
436     assert_eq!(diff, vec![]);
437 }
438
439 // Compare strings without distinguishing between CRLF and LF
440 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
441     let left = CharsIgnoreNewlineRepr(left.chars().peekable());
442     let right = CharsIgnoreNewlineRepr(right.chars().peekable());
443     left.eq(right)
444 }
445
446 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
447
448 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
449     type Item = char;
450     fn next(&mut self) -> Option<char> {
451         self.0.next().map(|c| {
452             if c == '\r' {
453                 if *self.0.peek().unwrap_or(&'\0') == '\n' {
454                     self.0.next();
455                     '\n'
456                 } else {
457                     '\r'
458                 }
459             } else {
460                 c
461             }
462         })
463     }
464 }
465
466 #[test]
467 fn string_eq_ignore_newline_repr_test() {
468     assert!(string_eq_ignore_newline_repr("", ""));
469     assert!(!string_eq_ignore_newline_repr("", "abc"));
470     assert!(!string_eq_ignore_newline_repr("abc", ""));
471     assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
472     assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
473     assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));
474 }