]> git.lizzy.rs Git - rust.git/blob - tests/system.rs
6d3c817256cae7443c0260d4c1ffa212ff0165eb
[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::config::{Config, ReportTactic};
23 use rustfmt::rustfmt_diff::*;
24
25 static DIFF_CONTEXT_SIZE: usize = 3;
26
27 fn get_path_string(dir_entry: io::Result<fs::DirEntry>) -> String {
28     let path = dir_entry.ok().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 // overriden by annotations in the source file. The input and output must match
36 // exactly.
37 // FIXME(#28) would be good to check for error messages and fail on them, or at
38 // least report.
39 #[test]
40 fn system_tests() {
41     // Get all files in the tests/source directory.
42     let files = fs::read_dir("tests/source").ok().expect("Couldn't read source dir.");
43     // Turn a DirEntry into a String that represents the relative path to the
44     // file.
45     let files = files.map(get_path_string);
46     let (_reports, count, fails) = check_files(files, WriteMode::Return);
47
48     // Display results.
49     println!("Ran {} system tests.", count);
50     assert!(fails == 0, "{} system tests failed", fails);
51 }
52
53 // Do the same for tests/coverage-source directory
54 // the only difference is the coverage mode
55 #[test]
56 fn coverage_tests() {
57     let files = fs::read_dir("tests/coverage-source").ok().expect("Couldn't read source dir.");
58     let files = files.map(get_path_string);
59     let (_reports, count, fails) = check_files(files, WriteMode::Coverage);
60
61     println!("Ran {} tests in coverage mode.", count);
62     assert!(fails == 0, "{} tests failed", fails);
63 }
64
65 // Idempotence tests. Files in tests/target are checked to be unaltered by
66 // rustfmt.
67 #[test]
68 fn idempotence_tests() {
69     // Get all files in the tests/target directory.
70     let files = fs::read_dir("tests/target")
71                     .ok()
72                     .expect("Couldn't read target dir.")
73                     .map(get_path_string);
74     let (_reports, count, fails) = check_files(files, WriteMode::Return);
75
76     // Display results.
77     println!("Ran {} idempotent tests.", count);
78     assert!(fails == 0, "{} idempotent tests failed", fails);
79 }
80
81 // Run rustfmt on itself. This operation must be idempotent. We also check that
82 // no warnings are emitted.
83 #[test]
84 fn self_tests() {
85     let files = fs::read_dir("src/bin")
86                     .ok()
87                     .expect("Couldn't read src dir.")
88                     .chain(fs::read_dir("tests").ok().expect("Couldn't read tests dir."))
89                     .map(get_path_string);
90     // Hack because there's no `IntoIterator` impl for `[T; N]`.
91     let files = files.chain(Some("src/lib.rs".to_owned()).into_iter());
92
93     let (reports, count, fails) = check_files(files, WriteMode::Return);
94     let mut warnings = 0;
95
96     // Display results.
97     println!("Ran {} self tests.", count);
98     assert!(fails == 0, "{} self tests failed", fails);
99
100     for format_report in reports {
101         println!("{}", format_report);
102         warnings += format_report.warning_count();
103     }
104
105     assert!(warnings == 0,
106             "Rustfmt's code generated {} warnings",
107             warnings);
108 }
109
110 // For each file, run rustfmt and collect the output.
111 // Returns the number of files checked and the number of failures.
112 fn check_files<I>(files: I, write_mode: WriteMode) -> (Vec<FormatReport>, u32, u32)
113     where I: Iterator<Item = String>
114 {
115     let mut count = 0;
116     let mut fails = 0;
117     let mut reports = vec![];
118
119     for file_name in files.filter(|f| f.ends_with(".rs")) {
120         println!("Testing '{}'...", file_name);
121
122         match idempotent_check(file_name, write_mode) {
123             Ok(report) => reports.push(report),
124             Err(msg) => {
125                 print_mismatches(msg);
126                 fails += 1;
127             }
128         }
129
130         count += 1;
131     }
132
133     (reports, count, fails)
134 }
135
136 fn print_mismatches(result: HashMap<String, Vec<Mismatch>>) {
137     let mut t = term::stdout().unwrap();
138
139     for (file_name, diff) in result {
140         print_diff(diff,
141                    |line_num| format!("\nMismatch at {}:{}:", file_name, line_num));
142     }
143
144     assert!(t.reset().unwrap());
145 }
146
147 pub fn idempotent_check(filename: String,
148                         write_mode: WriteMode)
149                         -> Result<FormatReport, HashMap<String, Vec<Mismatch>>> {
150     let sig_comments = read_significant_comments(&filename);
151     let mut config = get_config(sig_comments.get("config").map(|x| &(*x)[..]));
152
153     for (key, val) in &sig_comments {
154         if key != "target" && key != "config" {
155             config.override_value(key, val);
156         }
157     }
158
159     // Don't generate warnings for to-do items.
160     config.report_todo = ReportTactic::Never;
161
162     let mut file_map = format(Path::new(&filename), &config, write_mode);
163     let format_report = fmt_lines(&mut file_map, &config);
164
165     // Won't panic, as we're not doing any IO.
166     let write_result = filemap::write_all_files(&file_map, WriteMode::Return, &config).unwrap();
167     let target = sig_comments.get("target").map(|x| &(*x)[..]);
168
169     handle_result(write_result, target, write_mode).map(|_| format_report)
170 }
171
172 // Reads test config file from comments and reads its contents.
173 fn get_config(config_file: Option<&str>) -> Config {
174     let config_file_name = match config_file {
175         None => return Default::default(),
176         Some(file_name) => {
177             let mut full_path = "tests/config/".to_owned();
178             full_path.push_str(&file_name);
179             full_path
180         }
181     };
182
183     let mut def_config_file = fs::File::open(config_file_name)
184                                   .ok()
185                                   .expect("Couldn't open config.");
186     let mut def_config = String::new();
187     def_config_file.read_to_string(&mut def_config).ok().expect("Couldn't read config.");
188
189     Config::from_toml(&def_config)
190 }
191
192 // Reads significant comments of the form: // rustfmt-key: value
193 // into a hash map.
194 fn read_significant_comments(file_name: &str) -> HashMap<String, String> {
195     let file = fs::File::open(file_name)
196                    .ok()
197                    .expect(&format!("Couldn't read file {}.", file_name));
198     let reader = BufReader::new(file);
199     let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
200     let regex = regex::Regex::new(&pattern).ok().expect("Failed creating pattern 1.");
201
202     // Matches lines containing significant comments or whitespace.
203     let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
204                          .ok()
205                          .expect("Failed creating pattern 2.");
206
207     reader.lines()
208           .map(|line| line.ok().expect("Failed getting line."))
209           .take_while(|line| line_regex.is_match(&line))
210           .filter_map(|line| {
211               regex.captures_iter(&line).next().map(|capture| {
212                   (capture.at(1).expect("Couldn't unwrap capture.").to_owned(),
213                    capture.at(2).expect("Couldn't unwrap capture.").to_owned())
214               })
215           })
216           .collect()
217 }
218
219 // Compare output to input.
220 // TODO: needs a better name, more explanation.
221 fn handle_result(result: HashMap<String, String>,
222                  target: Option<&str>,
223                  write_mode: WriteMode)
224                  -> Result<(), HashMap<String, Vec<Mismatch>>> {
225     let mut failures = HashMap::new();
226
227     for (file_name, fmt_text) in result {
228         // If file is in tests/source, compare to file with same name in tests/target.
229         let target = get_target(&file_name, target, write_mode);
230         let mut f = fs::File::open(&target).ok().expect("Couldn't open target.");
231
232         let mut text = String::new();
233         f.read_to_string(&mut text).ok().expect("Failed reading target.");
234
235         if fmt_text != text {
236             let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
237             failures.insert(file_name, diff);
238         }
239     }
240
241     if failures.is_empty() {
242         Ok(())
243     } else {
244         Err(failures)
245     }
246 }
247
248 // Map source file paths to their target paths.
249 fn get_target(file_name: &str, target: Option<&str>, write_mode: WriteMode) -> String {
250     let file_path = Path::new(file_name);
251     let (source_path_prefix, target_path_prefix) = match write_mode {
252         WriteMode::Coverage => {
253             (Path::new("tests/coverage-source/"),
254              "tests/coverage-target/")
255         }
256         _ => (Path::new("tests/source/"), "tests/target/"),
257     };
258
259     if file_path.starts_with(source_path_prefix) {
260         let mut components = file_path.components();
261         // Can't skip(2) as the resulting iterator can't as_path()
262         components.next();
263         components.next();
264
265         let new_target = match components.as_path().to_str() {
266             Some(string) => string,
267             None => file_name,
268         };
269         let base = target.unwrap_or(new_target);
270
271         format!("{}{}", target_path_prefix, base)
272     } else {
273         file_name.to_owned()
274     }
275 }