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.
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.
16 use std::collections::HashMap;
18 use std::io::{self, Read, BufRead, BufReader};
22 use rustfmt::filemap::{write_system_newlines, FileMap};
23 use rustfmt::config::{Config, ReportTactic, WriteMode};
24 use rustfmt::rustfmt_diff::*;
26 static DIFF_CONTEXT_SIZE: usize = 3;
28 fn get_path_string(dir_entry: io::Result<fs::DirEntry>) -> String {
29 let path = dir_entry.ok().expect("Couldn't get DirEntry.").path();
31 path.to_str().expect("Couldn't stringify path.").to_owned()
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
38 // FIXME(#28) would be good to check for error messages and fail on them, or at
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
46 let files = files.map(get_path_string);
47 let (_reports, count, fails) = check_files(files, WriteMode::Default);
50 println!("Ran {} system tests.", count);
51 assert!(fails == 0, "{} system tests failed", fails);
54 // Do the same for tests/coverage-source directory
55 // the only difference is the coverage mode
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);
62 println!("Ran {} tests in coverage mode.", count);
63 assert!(fails == 0, "{} tests failed", fails);
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, WriteMode::Checkstyle);
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: WriteMode) {
77 let config = read_config(&source);
78 let file_map = run_rustfmt(source.to_string(), write_mode);
80 // Populate output by writing to a vec.
82 let _ = filemap::write_all_files(&file_map, &mut out, write_mode, &config);
83 let output = String::from_utf8(out).unwrap();
85 let mut expected_file = fs::File::open(&expected_filename)
87 .expect("Couldn't open target.");
88 let mut expected_text = String::new();
89 expected_file.read_to_string(&mut expected_text)
91 .expect("Failed reading target.");
93 let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
94 if compare.len() > 0 {
95 let mut failures = HashMap::new();
96 failures.insert(source.to_string(), compare);
97 print_mismatches(failures);
98 assert!(false, "Text does not match expected output");
102 // Idempotence tests. Files in tests/target are checked to be unaltered by
105 fn idempotence_tests() {
106 // Get all files in the tests/target directory.
107 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, WriteMode::Default);
114 println!("Ran {} idempotent tests.", count);
115 assert!(fails == 0, "{} idempotent tests failed", fails);
118 // Run rustfmt on itself. This operation must be idempotent. We also check that
119 // no warnings are emitted.
122 let files = fs::read_dir("src/bin")
124 .expect("Couldn't read src dir.")
125 .chain(fs::read_dir("tests").ok().expect("Couldn't read tests dir."))
126 .map(get_path_string);
127 // Hack because there's no `IntoIterator` impl for `[T; N]`.
128 let files = files.chain(Some("src/lib.rs".to_owned()).into_iter());
130 let (reports, count, fails) = check_files(files, WriteMode::Default);
131 let mut warnings = 0;
134 println!("Ran {} self tests.", count);
135 assert!(fails == 0, "{} self tests failed", fails);
137 for format_report in reports {
138 println!("{}", format_report);
139 warnings += format_report.warning_count();
142 assert!(warnings == 0,
143 "Rustfmt's code generated {} warnings",
147 // For each file, run rustfmt and collect the output.
148 // Returns the number of files checked and the number of failures.
149 fn check_files<I>(files: I, write_mode: WriteMode) -> (Vec<FormatReport>, u32, u32)
150 where I: Iterator<Item = String>
154 let mut reports = vec![];
156 for file_name in files.filter(|f| f.ends_with(".rs")) {
157 println!("Testing '{}'...", file_name);
159 match idempotent_check(file_name, write_mode) {
160 Ok(report) => reports.push(report),
162 print_mismatches(msg);
170 (reports, count, fails)
173 fn print_mismatches(result: HashMap<String, Vec<Mismatch>>) {
174 let mut t = term::stdout().unwrap();
176 for (file_name, diff) in result {
178 |line_num| format!("\nMismatch at {}:{}:", file_name, line_num));
181 assert!(t.reset().unwrap());
184 fn read_config(filename: &str) -> Config {
185 let sig_comments = read_significant_comments(&filename);
186 let mut config = get_config(sig_comments.get("config").map(|x| &(*x)[..]));
188 for (key, val) in &sig_comments {
189 if key != "target" && key != "config" {
190 config.override_value(key, val);
194 // Don't generate warnings for to-do items.
195 config.report_todo = ReportTactic::Never;
200 fn run_rustfmt(filename: String, write_mode: WriteMode) -> FileMap {
201 let config = read_config(&filename);
202 format(Path::new(&filename), &config, write_mode)
205 pub fn idempotent_check(filename: String,
206 write_mode: WriteMode)
207 -> Result<FormatReport, HashMap<String, Vec<Mismatch>>> {
208 let sig_comments = read_significant_comments(&filename);
209 let config = read_config(&filename);
210 let mut file_map = run_rustfmt(filename, write_mode);
211 let format_report = fmt_lines(&mut file_map, &config);
213 let mut write_result = HashMap::new();
214 for (filename, text) in file_map.iter() {
215 let mut v = Vec::new();
216 // Won't panic, as we're not doing any IO.
217 write_system_newlines(&mut v, text, &config).unwrap();
218 // Won't panic, we are writing correct utf8.
219 let one_result = String::from_utf8(v).unwrap();
220 write_result.insert(filename.clone(), one_result);
223 let target = sig_comments.get("target").map(|x| &(*x)[..]);
225 handle_result(write_result, target, write_mode).map(|_| format_report)
228 // Reads test config file from comments and reads its contents.
229 fn get_config(config_file: Option<&str>) -> Config {
230 let config_file_name = match config_file {
231 None => return Default::default(),
233 let mut full_path = "tests/config/".to_owned();
234 full_path.push_str(&file_name);
239 let mut def_config_file = fs::File::open(config_file_name)
241 .expect("Couldn't open config.");
242 let mut def_config = String::new();
243 def_config_file.read_to_string(&mut def_config).ok().expect("Couldn't read config.");
245 Config::from_toml(&def_config)
248 // Reads significant comments of the form: // rustfmt-key: value
250 fn read_significant_comments(file_name: &str) -> HashMap<String, String> {
251 let file = fs::File::open(file_name)
253 .expect(&format!("Couldn't read file {}.", file_name));
254 let reader = BufReader::new(file);
255 let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
256 let regex = regex::Regex::new(&pattern).ok().expect("Failed creating pattern 1.");
258 // Matches lines containing significant comments or whitespace.
259 let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
261 .expect("Failed creating pattern 2.");
264 .map(|line| line.ok().expect("Failed getting line."))
265 .take_while(|line| line_regex.is_match(&line))
267 regex.captures_iter(&line).next().map(|capture| {
268 (capture.at(1).expect("Couldn't unwrap capture.").to_owned(),
269 capture.at(2).expect("Couldn't unwrap capture.").to_owned())
275 // Compare output to input.
276 // TODO: needs a better name, more explanation.
277 fn handle_result(result: HashMap<String, String>,
278 target: Option<&str>,
279 write_mode: WriteMode)
280 -> Result<(), HashMap<String, Vec<Mismatch>>> {
281 let mut failures = HashMap::new();
283 for (file_name, fmt_text) in result {
284 // If file is in tests/source, compare to file with same name in tests/target.
285 let target = get_target(&file_name, target, write_mode);
286 let mut f = fs::File::open(&target).ok().expect("Couldn't open target.");
288 let mut text = String::new();
289 f.read_to_string(&mut text).ok().expect("Failed reading target.");
291 if fmt_text != text {
292 let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
293 failures.insert(file_name, diff);
297 if failures.is_empty() {
304 // Map source file paths to their target paths.
305 fn get_target(file_name: &str, target: Option<&str>, write_mode: WriteMode) -> String {
306 let file_path = Path::new(file_name);
307 let (source_path_prefix, target_path_prefix) = match write_mode {
308 WriteMode::Coverage => {
309 (Path::new("tests/coverage-source/"),
310 "tests/coverage-target/")
312 _ => (Path::new("tests/source/"), "tests/target/"),
315 if file_path.starts_with(source_path_prefix) {
316 let mut components = file_path.components();
317 // Can't skip(2) as the resulting iterator can't as_path()
321 let new_target = match components.as_path().to_str() {
322 Some(string) => string,
325 let base = target.unwrap_or(new_target);
327 format!("{}{}", target_path_prefix, base)
334 fn rustfmt_diff_make_diff_tests() {
335 let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
339 lines: vec![DiffLine::Context("a".into()),
340 DiffLine::Resulting("b".into()),
341 DiffLine::Expected("e".into()),
342 DiffLine::Context("c".into()),
343 DiffLine::Context("d".into())],