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