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;
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/target/fn-single-line.rs".to_string();
69 let expected = "tests/writemode/checkstyle.xml";
71 let output = run_rustfmt(filename.clone(), WriteMode::Checkstyle);
73 let mut expected_file = fs::File::open(&expected)
75 .expect("Couldn't open target.");
76 let mut expected_text = String::new();
77 expected_file.read_to_string(&mut expected_text)
79 .expect("Failed reading target.");
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");
90 // Idempotence tests. Files in tests/target are checked to be unaltered by
93 fn idempotence_tests() {
94 // Get all files in the tests/target directory.
95 let files = fs::read_dir("tests/target")
97 .expect("Couldn't read target dir.")
98 .map(get_path_string);
99 let (_reports, count, fails) = check_files(files, WriteMode::Default);
102 println!("Ran {} idempotent tests.", count);
103 assert!(fails == 0, "{} idempotent tests failed", fails);
106 // Run rustfmt on itself. This operation must be idempotent. We also check that
107 // no warnings are emitted.
110 let files = fs::read_dir("src/bin")
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());
118 let (reports, count, fails) = check_files(files, WriteMode::Default);
119 let mut warnings = 0;
122 println!("Ran {} self tests.", count);
123 assert!(fails == 0, "{} self tests failed", fails);
125 for format_report in reports {
126 println!("{}", format_report);
127 warnings += format_report.warning_count();
130 assert!(warnings == 0,
131 "Rustfmt's code generated {} warnings",
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>
142 let mut reports = vec![];
144 for file_name in files.filter(|f| f.ends_with(".rs")) {
145 println!("Testing '{}'...", file_name);
147 match idempotent_check(file_name, write_mode) {
148 Ok(report) => reports.push(report),
150 print_mismatches(msg);
158 (reports, count, fails)
161 fn print_mismatches(result: HashMap<String, Vec<Mismatch>>) {
162 let mut t = term::stdout().unwrap();
164 for (file_name, diff) in result {
166 |line_num| format!("\nMismatch at {}:{}:", file_name, line_num));
169 assert!(t.reset().unwrap());
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)[..]));
176 for (key, val) in &sig_comments {
177 if key != "target" && key != "config" {
178 config.override_value(key, val);
182 // Don't generate warnings for to-do items.
183 config.report_todo = ReportTactic::Never;
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();
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);
200 // write_result.remove(&filename).unwrap().to_owned()
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)[..]));
209 for (key, val) in &sig_comments {
210 if key != "target" && key != "config" {
211 config.override_value(key, val);
215 // Don't generate warnings for to-do items.
216 config.report_todo = ReportTactic::Never;
218 let mut file_map = format(Path::new(&filename), &config, write_mode);
219 let format_report = fmt_lines(&mut file_map, &config);
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);
231 let target = sig_comments.get("target").map(|x| &(*x)[..]);
233 handle_result(write_result, target, write_mode).map(|_| format_report)
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(),
241 let mut full_path = "tests/config/".to_owned();
242 full_path.push_str(&file_name);
247 let mut def_config_file = fs::File::open(config_file_name)
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.");
253 Config::from_toml(&def_config)
256 // Reads significant comments of the form: // rustfmt-key: value
258 fn read_significant_comments(file_name: &str) -> HashMap<String, String> {
259 let file = fs::File::open(file_name)
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.");
266 // Matches lines containing significant comments or whitespace.
267 let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
269 .expect("Failed creating pattern 2.");
272 .map(|line| line.ok().expect("Failed getting line."))
273 .take_while(|line| line_regex.is_match(&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())
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();
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.");
296 let mut text = String::new();
297 f.read_to_string(&mut text).ok().expect("Failed reading target.");
299 if fmt_text != text {
300 let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
301 failures.insert(file_name, diff);
305 if failures.is_empty() {
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/")
320 _ => (Path::new("tests/source/"), "tests/target/"),
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()
329 let new_target = match components.as_path().to_str() {
330 Some(string) => string,
333 let base = target.unwrap_or(new_target);
335 format!("{}{}", target_path_prefix, base)
342 fn rustfmt_diff_make_diff_tests() {
343 let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
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())],