]> git.lizzy.rs Git - rust.git/blob - tests/system.rs
Add a test for soft wrapping for comments
[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::{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(diff, |line_num| {
233             format!("\nMismatch at {}:{}:", file_name, line_num)
234         });
235     }
236
237     t.reset().unwrap();
238 }
239
240 fn read_config(filename: &str) -> Config {
241     let sig_comments = read_significant_comments(filename);
242     // Look for a config file... If there is a 'config' property in the significant comments, use
243     // that. Otherwise, if there are no significant comments at all, look for a config file with
244     // the same name as the test file.
245     let mut config = if !sig_comments.is_empty() {
246         get_config(sig_comments.get("config").map(|x| &(*x)[..]))
247     } else {
248         get_config(
249             Path::new(filename)
250                 .with_extension("toml")
251                 .file_name()
252                 .and_then(std::ffi::OsStr::to_str),
253         )
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) -> (FileMap, FormatReport) {
269     let filepath = filepath.into();
270     let input = Input::File(filepath);
271     let (_error_summary, file_map, report) =
272         format_input::<io::Stdout>(input, config, None).unwrap();
273     (file_map, report)
274 }
275
276 pub fn idempotent_check(filename: String) -> Result<FormatReport, HashMap<String, Vec<Mismatch>>> {
277     let sig_comments = read_significant_comments(&filename);
278     let config = read_config(&filename);
279     let (file_map, format_report) = format_file(filename, &config);
280
281     let mut write_result = HashMap::new();
282     for &(ref filename, ref text) in &file_map {
283         let mut v = Vec::new();
284         // Won't panic, as we're not doing any IO.
285         write_system_newlines(&mut v, text, &config).unwrap();
286         // Won't panic, we are writing correct utf8.
287         let one_result = String::from_utf8(v).unwrap();
288         write_result.insert(filename.clone(), one_result);
289     }
290
291     let target = sig_comments.get("target").map(|x| &(*x)[..]);
292
293     handle_result(write_result, target).map(|_| format_report)
294 }
295
296 // Reads test config file using the supplied (optional) file name. If there's no file name or the
297 // file doesn't exist, just return the default config. Otherwise, the file must be read
298 // successfully.
299 fn get_config(config_file: Option<&str>) -> Config {
300     let config_file_name = match config_file {
301         None => return Default::default(),
302         Some(file_name) => {
303             let mut full_path = "tests/config/".to_owned();
304             full_path.push_str(file_name);
305             if !Path::new(&full_path).exists() {
306                 return Default::default();
307             };
308             full_path
309         }
310     };
311
312     let mut def_config_file = fs::File::open(config_file_name).expect("Couldn't open config");
313     let mut def_config = String::new();
314     def_config_file
315         .read_to_string(&mut def_config)
316         .expect("Couldn't read config");
317
318     Config::from_toml(&def_config).expect("Invalid toml")
319 }
320
321 // Reads significant comments of the form: // rustfmt-key: value
322 // into a hash map.
323 fn read_significant_comments(file_name: &str) -> HashMap<String, String> {
324     let file = fs::File::open(file_name).expect(&format!("Couldn't read file {}", file_name));
325     let reader = BufReader::new(file);
326     let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
327     let regex = regex::Regex::new(pattern).expect("Failed creating pattern 1");
328
329     // Matches lines containing significant comments or whitespace.
330     let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
331         .expect("Failed creating pattern 2");
332
333     reader
334         .lines()
335         .map(|line| line.expect("Failed getting line"))
336         .take_while(|line| line_regex.is_match(line))
337         .filter_map(|line| {
338             regex.captures_iter(&line).next().map(|capture| {
339                 (
340                     capture
341                         .get(1)
342                         .expect("Couldn't unwrap capture")
343                         .as_str()
344                         .to_owned(),
345                     capture
346                         .get(2)
347                         .expect("Couldn't unwrap capture")
348                         .as_str()
349                         .to_owned(),
350                 )
351             })
352         })
353         .collect()
354 }
355
356 // Compare output to input.
357 // TODO: needs a better name, more explanation.
358 fn handle_result(
359     result: HashMap<String, String>,
360     target: Option<&str>,
361 ) -> Result<(), HashMap<String, Vec<Mismatch>>> {
362     let mut failures = HashMap::new();
363
364     for (file_name, fmt_text) in result {
365         // If file is in tests/source, compare to file with same name in tests/target.
366         let target = get_target(&file_name, target);
367         let open_error = format!("Couldn't open target {:?}", &target);
368         let mut f = fs::File::open(&target).expect(&open_error);
369
370         let mut text = String::new();
371         let read_error = format!("Failed reading target {:?}", &target);
372         f.read_to_string(&mut text).expect(&read_error);
373
374         // Ignore LF and CRLF difference for Windows.
375         if !string_eq_ignore_newline_repr(&fmt_text, &text) {
376             let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
377             assert!(
378                 !diff.is_empty(),
379                 "Empty diff? Maybe due to a missing a newline at the end of a file?"
380             );
381             failures.insert(file_name, diff);
382         }
383     }
384
385     if failures.is_empty() {
386         Ok(())
387     } else {
388         Err(failures)
389     }
390 }
391
392 // Map source file paths to their target paths.
393 fn get_target(file_name: &str, target: Option<&str>) -> String {
394     if file_name.contains("source") {
395         let target_file_name = file_name.replace("source", "target");
396         if let Some(replace_name) = target {
397             Path::new(&target_file_name)
398                 .with_file_name(replace_name)
399                 .into_os_string()
400                 .into_string()
401                 .unwrap()
402         } else {
403             target_file_name
404         }
405     } else {
406         // This is either and idempotence check or a self check
407         file_name.to_owned()
408     }
409 }
410
411 #[test]
412 fn rustfmt_diff_make_diff_tests() {
413     let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
414     assert_eq!(
415         diff,
416         vec![
417             Mismatch {
418                 line_number: 1,
419                 lines: vec![
420                     DiffLine::Context("a".into()),
421                     DiffLine::Resulting("b".into()),
422                     DiffLine::Expected("e".into()),
423                     DiffLine::Context("c".into()),
424                     DiffLine::Context("d".into()),
425                 ],
426             },
427         ]
428     );
429 }
430
431 #[test]
432 fn rustfmt_diff_no_diff_test() {
433     let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
434     assert_eq!(diff, vec![]);
435 }
436
437 // Compare strings without distinguishing between CRLF and LF
438 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
439     let left = CharsIgnoreNewlineRepr(left.chars().peekable());
440     let right = CharsIgnoreNewlineRepr(right.chars().peekable());
441     left.eq(right)
442 }
443
444 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
445
446 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
447     type Item = char;
448     fn next(&mut self) -> Option<char> {
449         self.0.next().map(|c| if c == '\r' {
450             if *self.0.peek().unwrap_or(&'\0') == '\n' {
451                 self.0.next();
452                 '\n'
453             } else {
454                 '\r'
455             }
456         } else {
457             c
458         })
459     }
460 }
461
462 #[test]
463 fn string_eq_ignore_newline_repr_test() {
464     assert!(string_eq_ignore_newline_repr("", ""));
465     assert!(!string_eq_ignore_newline_repr("", "abc"));
466     assert!(!string_eq_ignore_newline_repr("abc", ""));
467     assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
468     assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
469     assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));
470 }