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