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.
11 #![feature(catch_panic)]
17 use std::collections::HashMap;
19 use std::io::{self, Read, BufRead, BufReader};
23 fn get_path_string(dir_entry: io::Result<fs::DirEntry>) -> String {
24 let path = dir_entry.ok().expect("Couldn't get DirEntry.").path();
26 path.to_str().expect("Couldn't stringify path.").to_owned()
29 // Integration tests. The files in the tests/source are formatted and compared
30 // to their equivalent in tests/target. The target file and config can be
31 // overriden by annotations in the source file. The input and output must match
33 // FIXME(#28) would be good to check for error messages and fail on them, or at
37 // Get all files in the tests/source directory
38 let files = fs::read_dir("tests/source").ok().expect("Couldn't read source dir.");
39 // turn a DirEntry into a String that represents the relative path to the file
40 let files = files.map(get_path_string);
42 let (count, fails) = check_files(files);
45 println!("Ran {} system tests.", count);
46 assert!(fails == 0, "{} system tests failed", fails);
49 // Idempotence tests. Files in tests/target are checked to be unaltered by
52 fn idempotence_tests() {
53 // Get all files in the tests/target directory
54 let files = fs::read_dir("tests/target").ok().expect("Couldn't read target dir.");
55 let files = files.chain(fs::read_dir("tests").ok().expect("Couldn't read tests dir."));
56 let files = files.chain(fs::read_dir("src/bin").ok().expect("Couldn't read src dir."));
57 // turn a DirEntry into a String that represents the relative path to the file
58 let files = files.map(get_path_string);
59 // hack because there's no `IntoIterator` impl for `[T; N]`
60 let files = files.chain(Some("src/lib.rs".to_owned()).into_iter());
62 let (count, fails) = check_files(files);
65 println!("Ran {} idempotent tests.", count);
66 assert!(fails == 0, "{} idempotent tests failed", fails);
69 // For each file, run rustfmt and collect the output.
70 // Returns the number of files checked and the number of failures.
71 fn check_files<I>(files: I) -> (u32, u32)
72 where I: Iterator<Item = String>
77 for file_name in files.filter(|f| f.ends_with(".rs")) {
78 println!("Testing '{}'...", file_name);
79 if let Err(msg) = idempotent_check(file_name) {
80 print_mismatches(msg);
89 fn print_mismatches(result: HashMap<String, String>) {
90 for (_, fmt_text) in result {
91 println!("{}", fmt_text);
95 // Ick, just needed to get a &'static to handle_result.
96 static HANDLE_RESULT: &'static Fn(HashMap<String, String>) = &handle_result;
98 pub fn idempotent_check(filename: String) -> Result<(), HashMap<String, String>> {
99 let config = get_config(&filename);
100 let args = vec!["rustfmt".to_owned(), filename];
101 // this thread is not used for concurrency, but rather to workaround the issue that the passed
102 // function handle needs to have static lifetime. Instead of using a global RefCell, we use
103 // panic to return a result in case of failure. This has the advantage of smoothing the road to
104 // multithreaded rustfmt
105 thread::catch_panic(move || {
106 run(args, WriteMode::Return(HANDLE_RESULT), &config);
108 *any.downcast().ok().expect("Downcast failed.")
112 // Reads test config file from comments and loads it
113 fn get_config(file_name: &str) -> String {
114 let config_file_name = read_significant_comment(file_name, "config")
116 let mut full_path = "tests/config/".to_owned();
117 full_path.push_str(&file_name);
120 .unwrap_or("default.toml".to_owned());
122 let mut def_config_file = fs::File::open(config_file_name).ok().expect("Couldn't open config.");
123 let mut def_config = String::new();
124 def_config_file.read_to_string(&mut def_config).ok().expect("Couldn't read config.");
129 fn read_significant_comment(file_name: &str, option: &str) -> Option<String> {
130 let file = fs::File::open(file_name).ok().expect("Couldn't read file for comment.");
131 let reader = BufReader::new(file);
132 let pattern = format!("^\\s*//\\s*rustfmt-{}:\\s*(\\S+)", option);
133 let regex = regex::Regex::new(&pattern).ok().expect("Failed creating pattern 1.");
135 // matches exactly the lines containing significant comments or whitespace
136 let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[:alpha:]+:\s*\S+)")
137 .ok().expect("Failed creating pattern 2.");
140 .map(|line| line.ok().expect("Failed getting line."))
141 .take_while(|line| line_regex.is_match(&line))
143 regex.captures_iter(&line).next().map(|capture| {
144 capture.at(1).expect("Couldn't unwrap capture.").to_owned()
150 // Compare output to input.
151 fn handle_result(result: HashMap<String, String>) {
152 let mut failures = HashMap::new();
154 for (file_name, fmt_text) in result {
155 // If file is in tests/source, compare to file with same name in tests/target
156 let target_file_name = get_target(&file_name);
157 let mut f = fs::File::open(&target_file_name).ok().expect("Couldn't open target.");
159 let mut text = String::new();
160 // TODO: speedup by running through bytes iterator
161 f.read_to_string(&mut text).ok().expect("Failed reading target.");
162 if fmt_text != text {
163 let diff_str = make_diff(&file_name, &fmt_text, &text);
164 failures.insert(file_name, diff_str);
167 if !failures.is_empty() {
172 // Map source file paths to their target paths.
173 fn get_target(file_name: &str) -> String {
174 if file_name.starts_with("tests/source/") {
175 let target = read_significant_comment(file_name, "target");
176 let base = target.unwrap_or(file_name.trim_left_matches("tests/source/").to_owned());
178 let mut target_file = "tests/target/".to_owned();
179 target_file.push_str(&base);
187 // Produces a diff string between the expected output and actual output of
188 // rustfmt on a given file
189 fn make_diff(file_name: &str, expected: &str, actual: &str) -> String {
190 let mut line_number = 1;
191 let mut prev_both = true;
192 let mut text = String::new();
194 for result in diff::lines(expected, actual) {
196 diff::Result::Left(str) => {
198 text.push_str(&format!("Mismatch @ {}:{}\n", file_name, line_number));
200 text.push_str(&format!("-{}⏎\n", str));
203 diff::Result::Right(str) => {
205 text.push_str(&format!("Mismatch @ {}:{}\n", file_name, line_number));
207 text.push_str(&format!("+{}⏎\n", str));
211 diff::Result::Both(..) => {