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.
14 extern crate rustfmt_nightly as rustfmt;
17 use std::collections::HashMap;
19 use std::io::{self, BufRead, BufReader, Read};
20 use std::iter::Peekable;
21 use std::path::{Path, PathBuf};
25 use rustfmt::filemap::{write_system_newlines, FileMap};
26 use rustfmt::config::{Color, Config, ReportTactic};
27 use rustfmt::rustfmt_diff::*;
29 const DIFF_CONTEXT_SIZE: usize = 3;
31 fn get_path_string(dir_entry: io::Result<fs::DirEntry>) -> String {
32 let path = dir_entry.expect("Couldn't get DirEntry").path();
34 path.to_str().expect("Couldn't stringify path").to_owned()
37 // Integration tests. The files in the tests/source are formatted and compared
38 // to their equivalent in tests/target. The target file and config can be
39 // overridden by annotations in the source file. The input and output must match
43 // Get all files in the tests/source directory.
44 let files = fs::read_dir("tests/source").expect("Couldn't read source dir");
45 // Turn a DirEntry into a String that represents the relative path to the
47 let files = files.map(get_path_string);
48 let (_reports, count, fails) = check_files(files);
51 println!("Ran {} system tests.", count);
52 assert_eq!(fails, 0, "{} system tests failed", fails);
55 // Do the same for tests/coverage-source directory
56 // the only difference is the coverage mode
59 let files = fs::read_dir("tests/coverage/source").expect("Couldn't read source dir");
60 let files = files.map(get_path_string);
61 let (_reports, count, fails) = check_files(files);
63 println!("Ran {} tests in coverage mode.", count);
64 assert_eq!(fails, 0, "{} tests failed", fails);
68 fn checkstyle_test() {
69 let filename = "tests/writemode/source/fn-single-line.rs";
70 let expected_filename = "tests/writemode/target/checkstyle.xml";
71 assert_output(filename, expected_filename);
75 // Helper function for comparing the results of rustfmt
76 // to a known output file generated by one of the write modes.
77 fn assert_output(source: &str, expected_filename: &str) {
78 let config = read_config(source);
79 let (file_map, _report) = format_file(source, &config);
81 // Populate output by writing to a vec.
83 let _ = filemap::write_all_files(&file_map, &mut out, &config);
84 let output = String::from_utf8(out).unwrap();
86 let mut expected_file = fs::File::open(&expected_filename).expect("Couldn't open target");
87 let mut expected_text = String::new();
89 .read_to_string(&mut expected_text)
90 .expect("Failed reading target");
92 let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
93 if !compare.is_empty() {
94 let mut failures = HashMap::new();
95 failures.insert(source.to_string(), compare);
96 print_mismatches(failures);
97 assert!(false, "Text does not match expected output");
101 // Idempotence tests. Files in tests/target are checked to be unaltered by
104 fn idempotence_tests() {
105 // Get all files in the tests/target directory.
106 let files = fs::read_dir("tests/target")
107 .expect("Couldn't read target dir")
108 .map(get_path_string);
109 let (_reports, count, fails) = check_files(files);
112 println!("Ran {} idempotent tests.", count);
113 assert_eq!(fails, 0, "{} idempotent tests failed", fails);
116 // Run rustfmt on itself. This operation must be idempotent. We also check that
117 // no warnings are emitted.
120 let files = fs::read_dir("src/bin")
121 .expect("Couldn't read src dir")
122 .chain(fs::read_dir("tests").expect("Couldn't read tests dir"))
123 .map(get_path_string);
124 // Hack because there's no `IntoIterator` impl for `[T; N]`.
125 let files = files.chain(Some("src/lib.rs".to_owned()).into_iter());
126 let files = files.chain(Some("build.rs".to_owned()).into_iter());
128 let (reports, count, fails) = check_files(files);
129 let mut warnings = 0;
132 println!("Ran {} self tests.", count);
133 assert_eq!(fails, 0, "{} self tests failed", fails);
135 for format_report in reports {
136 println!("{}", format_report);
137 warnings += format_report.warning_count();
143 "Rustfmt's code generated {} warnings",
149 fn stdin_formatting_smoke_test() {
150 let input = Input::Text("fn main () {}".to_owned());
151 let config = Config::default();
152 let (error_summary, file_map, _report) =
153 format_input::<io::Stdout>(input, &config, None).unwrap();
154 assert!(error_summary.has_no_errors());
155 for &(ref file_name, ref text) in &file_map {
156 if file_name == "stdin" {
157 assert_eq!(text.to_string(), "fn main() {}\n");
164 // FIXME(#1990) restore this test
166 // fn stdin_disable_all_formatting_test() {
167 // let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
168 // let mut child = Command::new("./target/debug/rustfmt")
169 // .stdin(Stdio::piped())
170 // .stdout(Stdio::piped())
171 // .arg("--config-path=./tests/config/disable_all_formatting.toml")
173 // .expect("failed to execute child");
176 // let stdin = child.stdin.as_mut().expect("failed to get stdin");
178 // .write_all(input.as_bytes())
179 // .expect("failed to write stdin");
181 // let output = child.wait_with_output().expect("failed to wait on child");
182 // assert!(output.status.success());
183 // assert!(output.stderr.is_empty());
184 // assert_eq!(input, String::from_utf8(output.stdout).unwrap());
188 fn format_lines_errors_are_reported() {
189 let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
190 let input = Input::Text(format!("fn {}() {{}}", long_identifier));
191 let config = Config::default();
192 let (error_summary, _file_map, _report) =
193 format_input::<io::Stdout>(input, &config, None).unwrap();
194 assert!(error_summary.has_formatting_errors());
197 // For each file, run rustfmt and collect the output.
198 // Returns the number of files checked and the number of failures.
199 fn check_files<I>(files: I) -> (Vec<FormatReport>, u32, u32)
201 I: Iterator<Item = String>,
205 let mut reports = vec![];
207 for file_name in files.filter(|f| f.ends_with(".rs")) {
208 debug!("Testing '{}'...", file_name);
210 match idempotent_check(file_name) {
211 Ok(ref report) if report.has_warnings() => {
212 print!("{}", report);
215 Ok(report) => reports.push(report),
217 print_mismatches(msg);
225 (reports, count, fails)
228 fn print_mismatches(result: HashMap<String, Vec<Mismatch>>) {
229 let mut t = term::stdout().unwrap();
231 for (file_name, diff) in result {
234 |line_num| format!("\nMismatch at {}:{}:", file_name, line_num),
242 fn read_config(filename: &str) -> Config {
243 let sig_comments = read_significant_comments(filename);
244 // Look for a config file... If there is a 'config' property in the significant comments, use
245 // that. Otherwise, if there are no significant comments at all, look for a config file with
246 // the same name as the test file.
247 let mut config = if !sig_comments.is_empty() {
248 get_config(sig_comments.get("config").map(|x| &(*x)[..]))
252 .with_extension("toml")
254 .and_then(std::ffi::OsStr::to_str),
258 for (key, val) in &sig_comments {
259 if key != "target" && key != "config" {
260 config.override_value(key, val);
264 // Don't generate warnings for to-do items.
265 config.set().report_todo(ReportTactic::Never);
270 fn format_file<P: Into<PathBuf>>(filepath: P, config: &Config) -> (FileMap, FormatReport) {
271 let filepath = filepath.into();
272 let input = Input::File(filepath);
273 let (_error_summary, file_map, report) =
274 format_input::<io::Stdout>(input, config, None).unwrap();
278 pub fn idempotent_check(filename: String) -> Result<FormatReport, HashMap<String, Vec<Mismatch>>> {
279 let sig_comments = read_significant_comments(&filename);
280 let config = read_config(&filename);
281 let (file_map, format_report) = format_file(filename, &config);
283 let mut write_result = HashMap::new();
284 for &(ref filename, ref text) in &file_map {
285 let mut v = Vec::new();
286 // Won't panic, as we're not doing any IO.
287 write_system_newlines(&mut v, text, &config).unwrap();
288 // Won't panic, we are writing correct utf8.
289 let one_result = String::from_utf8(v).unwrap();
290 write_result.insert(filename.clone(), one_result);
293 let target = sig_comments.get("target").map(|x| &(*x)[..]);
295 handle_result(write_result, target).map(|_| format_report)
298 // Reads test config file using the supplied (optional) file name. If there's no file name or the
299 // file doesn't exist, just return the default config. Otherwise, the file must be read
301 fn get_config(config_file: Option<&str>) -> Config {
302 let config_file_name = match config_file {
303 None => return Default::default(),
305 let mut full_path = "tests/config/".to_owned();
306 full_path.push_str(file_name);
307 if !Path::new(&full_path).exists() {
308 return Default::default();
314 let mut def_config_file = fs::File::open(config_file_name).expect("Couldn't open config");
315 let mut def_config = String::new();
317 .read_to_string(&mut def_config)
318 .expect("Couldn't read config");
320 Config::from_toml(&def_config).expect("Invalid toml")
323 // Reads significant comments of the form: // rustfmt-key: value
325 fn read_significant_comments(file_name: &str) -> HashMap<String, String> {
326 let file = fs::File::open(file_name).expect(&format!("Couldn't read file {}", file_name));
327 let reader = BufReader::new(file);
328 let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
329 let regex = regex::Regex::new(pattern).expect("Failed creating pattern 1");
331 // Matches lines containing significant comments or whitespace.
332 let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
333 .expect("Failed creating pattern 2");
337 .map(|line| line.expect("Failed getting line"))
338 .take_while(|line| line_regex.is_match(line))
340 regex.captures_iter(&line).next().map(|capture| {
344 .expect("Couldn't unwrap capture")
349 .expect("Couldn't unwrap capture")
358 // Compare output to input.
359 // TODO: needs a better name, more explanation.
361 result: HashMap<String, String>,
362 target: Option<&str>,
363 ) -> Result<(), HashMap<String, Vec<Mismatch>>> {
364 let mut failures = HashMap::new();
366 for (file_name, fmt_text) in result {
367 // If file is in tests/source, compare to file with same name in tests/target.
368 let target = get_target(&file_name, target);
369 let open_error = format!("Couldn't open target {:?}", &target);
370 let mut f = fs::File::open(&target).expect(&open_error);
372 let mut text = String::new();
373 let read_error = format!("Failed reading target {:?}", &target);
374 f.read_to_string(&mut text).expect(&read_error);
376 // Ignore LF and CRLF difference for Windows.
377 if !string_eq_ignore_newline_repr(&fmt_text, &text) {
378 let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
381 "Empty diff? Maybe due to a missing a newline at the end of a file?"
383 failures.insert(file_name, diff);
387 if failures.is_empty() {
394 // Map source file paths to their target paths.
395 fn get_target(file_name: &str, target: Option<&str>) -> String {
396 if file_name.contains("source") {
397 let target_file_name = file_name.replace("source", "target");
398 if let Some(replace_name) = target {
399 Path::new(&target_file_name)
400 .with_file_name(replace_name)
408 // This is either and idempotence check or a self check
414 fn rustfmt_diff_make_diff_tests() {
415 let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
422 DiffLine::Context("a".into()),
423 DiffLine::Resulting("b".into()),
424 DiffLine::Expected("e".into()),
425 DiffLine::Context("c".into()),
426 DiffLine::Context("d".into()),
434 fn rustfmt_diff_no_diff_test() {
435 let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
436 assert_eq!(diff, vec![]);
439 // Compare strings without distinguishing between CRLF and LF
440 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
441 let left = CharsIgnoreNewlineRepr(left.chars().peekable());
442 let right = CharsIgnoreNewlineRepr(right.chars().peekable());
446 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
448 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
450 fn next(&mut self) -> Option<char> {
451 self.0.next().map(|c| {
453 if *self.0.peek().unwrap_or(&'\0') == '\n' {
467 fn string_eq_ignore_newline_repr_test() {
468 assert!(string_eq_ignore_newline_repr("", ""));
469 assert!(!string_eq_ignore_newline_repr("", "abc"));
470 assert!(!string_eq_ignore_newline_repr("abc", ""));
471 assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
472 assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
473 assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));