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