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