]> git.lizzy.rs Git - rust.git/blob - tests/system.rs
Merge pull request #897 from matklad/refactor-run
[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 rustfmt;
12 extern crate diff;
13 extern crate regex;
14 extern crate term;
15
16 use std::collections::HashMap;
17 use std::fs;
18 use std::io::{self, Read, BufRead, BufReader};
19 use std::path::{Path, PathBuf};
20
21 use rustfmt::*;
22 use rustfmt::filemap::{write_system_newlines, FileMap};
23 use rustfmt::config::{Config, ReportTactic, WriteMode};
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 // overriden by annotations in the source file. The input and output must match
37 // exactly.
38 // FIXME(#28) would be good to check for error messages and fail on them, or at
39 // least report.
40 #[test]
41 fn system_tests() {
42     // Get all files in the tests/source directory.
43     let files = fs::read_dir("tests/source").expect("Couldn't read source dir");
44     // Turn a DirEntry into a String that represents the relative path to the
45     // file.
46     let files = files.map(get_path_string);
47     let (_reports, count, fails) = check_files(files, None);
48
49     // Display results.
50     println!("Ran {} system tests.", count);
51     assert!(fails == 0, "{} system tests failed", fails);
52 }
53
54 // Do the same for tests/coverage-source directory
55 // the only difference is the coverage mode
56 #[test]
57 fn coverage_tests() {
58     let files = fs::read_dir("tests/coverage-source").expect("Couldn't read source dir");
59     let files = files.map(get_path_string);
60     let (_reports, count, fails) = check_files(files, Some(WriteMode::Coverage));
61
62     println!("Ran {} tests in coverage mode.", count);
63     assert!(fails == 0, "{} tests failed", fails);
64 }
65
66 #[test]
67 fn checkstyle_test() {
68     let filename = "tests/source/fn-single-line.rs";
69     let expected_filename = "tests/writemode/checkstyle.xml";
70     assert_output(filename, expected_filename, Some(WriteMode::Checkstyle));
71 }
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: &str, expected_filename: &str, write_mode: Option<WriteMode>) {
77     let config = read_config(&source, write_mode);
78     let (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.read_to_string(&mut expected_text)
88                  .expect("Failed reading target");
89
90     let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
91     if compare.len() > 0 {
92         let mut failures = HashMap::new();
93         failures.insert(source.to_string(), compare);
94         print_mismatches(failures);
95         assert!(false, "Text does not match expected output");
96     }
97 }
98
99 // Idempotence tests. Files in tests/target are checked to be unaltered by
100 // rustfmt.
101 #[test]
102 fn idempotence_tests() {
103     // Get all files in the tests/target directory.
104     let files = fs::read_dir("tests/target")
105                     .expect("Couldn't read target dir")
106                     .map(get_path_string);
107     let (_reports, count, fails) = check_files(files, None);
108
109     // Display results.
110     println!("Ran {} idempotent tests.", count);
111     assert!(fails == 0, "{} idempotent tests failed", fails);
112 }
113
114 // Run rustfmt on itself. This operation must be idempotent. We also check that
115 // no warnings are emitted.
116 #[test]
117 fn self_tests() {
118     let files = fs::read_dir("src/bin")
119                     .expect("Couldn't read src dir")
120                     .chain(fs::read_dir("tests").expect("Couldn't read tests dir"))
121                     .map(get_path_string);
122     // Hack because there's no `IntoIterator` impl for `[T; N]`.
123     let files = files.chain(Some("src/lib.rs".to_owned()).into_iter());
124
125     let (reports, count, fails) = check_files(files, None);
126     let mut warnings = 0;
127
128     // Display results.
129     println!("Ran {} self tests.", count);
130     assert!(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!(warnings == 0,
138             "Rustfmt's code generated {} warnings",
139             warnings);
140 }
141
142 // For each file, run rustfmt and collect the output.
143 // Returns the number of files checked and the number of failures.
144 fn check_files<I>(files: I, write_mode: Option<WriteMode>) -> (Vec<FormatReport>, u32, u32)
145     where I: Iterator<Item = String>
146 {
147     let mut count = 0;
148     let mut fails = 0;
149     let mut reports = vec![];
150
151     for file_name in files.filter(|f| f.ends_with(".rs")) {
152         println!("Testing '{}'...", file_name);
153
154         match idempotent_check(file_name, write_mode) {
155             Ok(report) => reports.push(report),
156             Err(msg) => {
157                 print_mismatches(msg);
158                 fails += 1;
159             }
160         }
161
162         count += 1;
163     }
164
165     (reports, count, fails)
166 }
167
168 fn print_mismatches(result: HashMap<String, Vec<Mismatch>>) {
169     let mut t = term::stdout().unwrap();
170
171     for (file_name, diff) in result {
172         print_diff(diff,
173                    |line_num| format!("\nMismatch at {}:{}:", file_name, line_num));
174     }
175
176     assert!(t.reset().unwrap());
177 }
178
179 fn read_config(filename: &str, write_mode: Option<WriteMode>) -> Config {
180     let sig_comments = read_significant_comments(&filename);
181     let mut config = get_config(sig_comments.get("config").map(|x| &(*x)[..]));
182
183     for (key, val) in &sig_comments {
184         if key != "target" && key != "config" {
185             config.override_value(key, val);
186         }
187     }
188
189     // Don't generate warnings for to-do items.
190     config.report_todo = ReportTactic::Never;
191
192     if let Some(mode) = write_mode {
193         config.write_mode = mode
194     }
195
196     config
197 }
198
199 fn format_file<P: Into<PathBuf>>(filename: P, config: &Config) -> (FileMap, FormatReport) {
200     let input = Input::File(filename.into());
201     format_input(input, &config)
202 }
203
204 pub fn idempotent_check(filename: String,
205                         write_mode: Option<WriteMode>)
206                         -> Result<FormatReport, HashMap<String, Vec<Mismatch>>> {
207     let sig_comments = read_significant_comments(&filename);
208     let config = read_config(&filename, write_mode);
209     let (file_map, format_report) = format_file(filename, &config);
210
211     let mut write_result = HashMap::new();
212     for (filename, text) in file_map.iter() {
213         let mut v = Vec::new();
214         // Won't panic, as we're not doing any IO.
215         write_system_newlines(&mut v, text, &config).unwrap();
216         // Won't panic, we are writing correct utf8.
217         let one_result = String::from_utf8(v).unwrap();
218         write_result.insert(filename.clone(), one_result);
219     }
220
221     let target = sig_comments.get("target").map(|x| &(*x)[..]);
222
223     handle_result(write_result, target, write_mode).map(|_| format_report)
224 }
225
226 // Reads test config file from comments and reads its contents.
227 fn get_config(config_file: Option<&str>) -> Config {
228     let config_file_name = match config_file {
229         None => return Default::default(),
230         Some(file_name) => {
231             let mut full_path = "tests/config/".to_owned();
232             full_path.push_str(&file_name);
233             full_path
234         }
235     };
236
237     let mut def_config_file = fs::File::open(config_file_name).expect("Couldn't open config");
238     let mut def_config = String::new();
239     def_config_file.read_to_string(&mut def_config).expect("Couldn't read config");
240
241     Config::from_toml(&def_config)
242 }
243
244 // Reads significant comments of the form: // rustfmt-key: value
245 // into a hash map.
246 fn read_significant_comments(file_name: &str) -> HashMap<String, String> {
247     let file = fs::File::open(file_name).expect(&format!("Couldn't read file {}", file_name));
248     let reader = BufReader::new(file);
249     let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
250     let regex = regex::Regex::new(&pattern).expect("Failed creating pattern 1");
251
252     // Matches lines containing significant comments or whitespace.
253     let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
254                          .expect("Failed creating pattern 2");
255
256     reader.lines()
257           .map(|line| line.expect("Failed getting line"))
258           .take_while(|line| line_regex.is_match(&line))
259           .filter_map(|line| {
260               regex.captures_iter(&line).next().map(|capture| {
261                   (capture.at(1).expect("Couldn't unwrap capture").to_owned(),
262                    capture.at(2).expect("Couldn't unwrap capture").to_owned())
263               })
264           })
265           .collect()
266 }
267
268 // Compare output to input.
269 // TODO: needs a better name, more explanation.
270 fn handle_result(result: HashMap<String, String>,
271                  target: Option<&str>,
272                  write_mode: Option<WriteMode>)
273                  -> Result<(), HashMap<String, Vec<Mismatch>>> {
274     let mut failures = HashMap::new();
275
276     for (file_name, fmt_text) in result {
277         // If file is in tests/source, compare to file with same name in tests/target.
278         let target = get_target(&file_name, target, write_mode);
279         let mut f = fs::File::open(&target).expect("Couldn't open target");
280
281         let mut text = String::new();
282         f.read_to_string(&mut text).expect("Failed reading target");
283
284         if fmt_text != text {
285             let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
286             assert!(!diff.is_empty(),
287                     "Empty diff? Maybe due to a missing a newline at the end of a file?");
288             failures.insert(file_name, diff);
289         }
290     }
291
292     if failures.is_empty() {
293         Ok(())
294     } else {
295         Err(failures)
296     }
297 }
298
299 // Map source file paths to their target paths.
300 fn get_target(file_name: &str, target: Option<&str>, write_mode: Option<WriteMode>) -> String {
301     let file_path = Path::new(file_name);
302     let (source_path_prefix, target_path_prefix) = match write_mode {
303         Some(WriteMode::Coverage) => {
304             (Path::new("tests/coverage-source/"), "tests/coverage-target/")
305         }
306         _ => (Path::new("tests/source/"), "tests/target/"),
307     };
308
309     if file_path.starts_with(source_path_prefix) {
310         let mut components = file_path.components();
311         // Can't skip(2) as the resulting iterator can't as_path()
312         components.next();
313         components.next();
314
315         let new_target = match components.as_path().to_str() {
316             Some(string) => string,
317             None => file_name,
318         };
319         let base = target.unwrap_or(new_target);
320
321         format!("{}{}", target_path_prefix, base)
322     } else {
323         file_name.to_owned()
324     }
325 }
326
327 #[test]
328 fn rustfmt_diff_make_diff_tests() {
329     let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
330     assert_eq!(diff,
331                vec![Mismatch {
332                         line_number: 1,
333                         lines: vec![DiffLine::Context("a".into()),
334                                     DiffLine::Resulting("b".into()),
335                                     DiffLine::Expected("e".into()),
336                                     DiffLine::Context("c".into()),
337                                     DiffLine::Context("d".into())],
338                     }]);
339 }