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};
19 use std::path::{Path, PathBuf};
22 use rustfmt::filemap::{write_system_newlines, FileMap};
23 use rustfmt::config::{Config, ReportTactic};
24 use rustfmt::rustfmt_diff::*;
26 const DIFF_CONTEXT_SIZE: usize = 3;
28 fn get_path_string(dir_entry: io::Result<fs::DirEntry>) -> String {
29 let path = dir_entry.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").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);
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").expect("Couldn't read source dir");
59 let files = files.map(get_path_string);
60 let (_reports, count, fails) = check_files(files);
62 println!("Ran {} tests in coverage mode.", count);
63 assert!(fails == 0, "{} tests failed", fails);
67 fn checkstyle_test() {
68 let filename = "tests/writemode/source/fn-single-line.rs";
69 let expected_filename = "tests/writemode/target/checkstyle.xml";
70 assert_output(filename, expected_filename);
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) {
77 let config = read_config(&source);
78 let (file_map, _report) = format_file(source, &config);
80 // Populate output by writing to a vec.
82 let _ = filemap::write_all_files(&file_map, &mut out, &config);
83 let output = String::from_utf8(out).unwrap();
85 let mut expected_file = fs::File::open(&expected_filename).expect("Couldn't open target");
86 let mut expected_text = String::new();
87 expected_file.read_to_string(&mut expected_text)
88 .expect("Failed reading target");
90 let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
91 if compare.len() > 0 {
92 let mut failures = HashMap::new();
93 failures.insert(source.to_string(), compare);
94 print_mismatches(failures);
95 assert!(false, "Text does not match expected output");
99 // Idempotence tests. Files in tests/target are checked to be unaltered by
102 fn idempotence_tests() {
103 // Get all files in the tests/target directory.
104 let files = fs::read_dir("tests/target")
105 .expect("Couldn't read target dir")
106 .map(get_path_string);
107 let (_reports, count, fails) = check_files(files);
110 println!("Ran {} idempotent tests.", count);
111 assert!(fails == 0, "{} idempotent tests failed", fails);
114 // Run rustfmt on itself. This operation must be idempotent. We also check that
115 // no warnings are emitted.
118 let files = fs::read_dir("src/bin")
119 .expect("Couldn't read src dir")
120 .chain(fs::read_dir("tests").expect("Couldn't read tests dir"))
121 .map(get_path_string);
122 // Hack because there's no `IntoIterator` impl for `[T; N]`.
123 let files = files.chain(Some("src/lib.rs".to_owned()).into_iter());
125 let (reports, count, fails) = check_files(files);
126 let mut warnings = 0;
129 println!("Ran {} self tests.", count);
130 assert!(fails == 0, "{} self tests failed", fails);
132 for format_report in reports {
133 println!("{}", format_report);
134 warnings += format_report.warning_count();
137 assert!(warnings == 0,
138 "Rustfmt's code generated {} warnings",
143 fn stdin_formatting_smoke_test() {
144 let input = Input::Text("fn main () {}".to_owned());
145 let config = Config::default();
146 let (error_summary, file_map, _report) = format_input(input, &config);
147 assert!(error_summary.has_no_errors());
148 assert_eq!(file_map["stdin"].to_string(), "fn main() {}\n")
152 fn format_lines_errors_are_reported() {
153 let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
154 let input = Input::Text(format!("fn {}() {{}}", long_identifier));
155 let config = Config::default();
156 let (error_summary, _file_map, _report) = format_input(input, &config);
157 assert!(error_summary.has_formatting_errors());
160 // For each file, run rustfmt and collect the output.
161 // Returns the number of files checked and the number of failures.
162 fn check_files<I>(files: I) -> (Vec<FormatReport>, u32, u32)
163 where I: Iterator<Item = String>
167 let mut reports = vec![];
169 for file_name in files.filter(|f| f.ends_with(".rs")) {
170 println!("Testing '{}'...", file_name);
172 match idempotent_check(file_name) {
173 Ok(report) => reports.push(report),
175 print_mismatches(msg);
183 (reports, count, fails)
186 fn print_mismatches(result: HashMap<String, Vec<Mismatch>>) {
187 let mut t = term::stdout().unwrap();
189 for (file_name, diff) in result {
191 |line_num| format!("\nMismatch at {}:{}:", file_name, line_num));
197 fn read_config(filename: &str) -> Config {
198 let sig_comments = read_significant_comments(&filename);
199 let mut config = get_config(sig_comments.get("config").map(|x| &(*x)[..]));
201 for (key, val) in &sig_comments {
202 if key != "target" && key != "config" {
203 config.override_value(key, val);
207 // Don't generate warnings for to-do items.
208 config.report_todo = ReportTactic::Never;
213 fn format_file<P: Into<PathBuf>>(filename: P, config: &Config) -> (FileMap, FormatReport) {
214 let input = Input::File(filename.into());
215 let (_error_summary, file_map, report) = format_input(input, &config);
216 return (file_map, report);
219 pub fn idempotent_check(filename: String) -> Result<FormatReport, HashMap<String, Vec<Mismatch>>> {
220 let sig_comments = read_significant_comments(&filename);
221 let config = read_config(&filename);
222 let (file_map, format_report) = format_file(filename, &config);
224 let mut write_result = HashMap::new();
225 for (filename, text) in file_map.iter() {
226 let mut v = Vec::new();
227 // Won't panic, as we're not doing any IO.
228 write_system_newlines(&mut v, text, &config).unwrap();
229 // Won't panic, we are writing correct utf8.
230 let one_result = String::from_utf8(v).unwrap();
231 write_result.insert(filename.clone(), one_result);
234 let target = sig_comments.get("target").map(|x| &(*x)[..]);
236 handle_result(write_result, target).map(|_| format_report)
239 // Reads test config file from comments and reads its contents.
240 fn get_config(config_file: Option<&str>) -> Config {
241 let config_file_name = match config_file {
242 None => return Default::default(),
244 let mut full_path = "tests/config/".to_owned();
245 full_path.push_str(&file_name);
250 let mut def_config_file = fs::File::open(config_file_name).expect("Couldn't open config");
251 let mut def_config = String::new();
252 def_config_file.read_to_string(&mut def_config).expect("Couldn't read config");
254 Config::from_toml(&def_config)
257 // Reads significant comments of the form: // rustfmt-key: value
259 fn read_significant_comments(file_name: &str) -> HashMap<String, String> {
260 let file = fs::File::open(file_name).expect(&format!("Couldn't read file {}", file_name));
261 let reader = BufReader::new(file);
262 let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
263 let regex = regex::Regex::new(&pattern).expect("Failed creating pattern 1");
265 // Matches lines containing significant comments or whitespace.
266 let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
267 .expect("Failed creating pattern 2");
270 .map(|line| line.expect("Failed getting line"))
271 .take_while(|line| line_regex.is_match(&line))
273 regex.captures_iter(&line).next().map(|capture| {
274 (capture.at(1).expect("Couldn't unwrap capture").to_owned(),
275 capture.at(2).expect("Couldn't unwrap capture").to_owned())
281 // Compare output to input.
282 // TODO: needs a better name, more explanation.
283 fn handle_result(result: HashMap<String, String>,
284 target: Option<&str>)
285 -> Result<(), HashMap<String, Vec<Mismatch>>> {
286 let mut failures = HashMap::new();
288 for (file_name, fmt_text) in result {
289 // If file is in tests/source, compare to file with same name in tests/target.
290 let target = get_target(&file_name, target);
291 let mut f = fs::File::open(&target).expect("Couldn't open target");
293 let mut text = String::new();
294 f.read_to_string(&mut text).expect("Failed reading target");
296 if fmt_text != text {
297 let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
298 assert!(!diff.is_empty(),
299 "Empty diff? Maybe due to a missing a newline at the end of a file?");
300 failures.insert(file_name, diff);
304 if failures.is_empty() {
311 // Map source file paths to their target paths.
312 fn get_target(file_name: &str, target: Option<&str>) -> String {
313 if file_name.contains("source") {
314 let target_file_name = file_name.replace("source", "target");
315 if let Some(replace_name) = target {
316 Path::new(&target_file_name)
317 .with_file_name(replace_name)
325 // This is either and idempotence check or a self check
331 fn rustfmt_diff_make_diff_tests() {
332 let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
336 lines: vec![DiffLine::Context("a".into()),
337 DiffLine::Resulting("b".into()),
338 DiffLine::Expected("e".into()),
339 DiffLine::Context("c".into()),
340 DiffLine::Context("d".into())],