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::{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 {
232 print_diff(diff, |line_num| {
233 format!("\nMismatch at {}:{}:", file_name, line_num)
240 fn read_config(filename: &str) -> Config {
241 let sig_comments = read_significant_comments(filename);
242 // Look for a config file... If there is a 'config' property in the significant comments, use
243 // that. Otherwise, if there are no significant comments at all, look for a config file with
244 // the same name as the test file.
245 let mut config = if !sig_comments.is_empty() {
246 get_config(sig_comments.get("config").map(|x| &(*x)[..]))
250 .with_extension("toml")
252 .and_then(std::ffi::OsStr::to_str),
256 for (key, val) in &sig_comments {
257 if key != "target" && key != "config" {
258 config.override_value(key, val);
262 // Don't generate warnings for to-do items.
263 config.set().report_todo(ReportTactic::Never);
268 fn format_file<P: Into<PathBuf>>(filepath: P, config: &Config) -> (FileMap, FormatReport) {
269 let filepath = filepath.into();
270 let input = Input::File(filepath);
271 let (_error_summary, file_map, report) =
272 format_input::<io::Stdout>(input, config, None).unwrap();
276 pub fn idempotent_check(filename: String) -> Result<FormatReport, HashMap<String, Vec<Mismatch>>> {
277 let sig_comments = read_significant_comments(&filename);
278 let config = read_config(&filename);
279 let (file_map, format_report) = format_file(filename, &config);
281 let mut write_result = HashMap::new();
282 for &(ref filename, ref text) in &file_map {
283 let mut v = Vec::new();
284 // Won't panic, as we're not doing any IO.
285 write_system_newlines(&mut v, text, &config).unwrap();
286 // Won't panic, we are writing correct utf8.
287 let one_result = String::from_utf8(v).unwrap();
288 write_result.insert(filename.clone(), one_result);
291 let target = sig_comments.get("target").map(|x| &(*x)[..]);
293 handle_result(write_result, target).map(|_| format_report)
296 // Reads test config file using the supplied (optional) file name. If there's no file name or the
297 // file doesn't exist, just return the default config. Otherwise, the file must be read
299 fn get_config(config_file: Option<&str>) -> Config {
300 let config_file_name = match config_file {
301 None => return Default::default(),
303 let mut full_path = "tests/config/".to_owned();
304 full_path.push_str(file_name);
305 if !Path::new(&full_path).exists() {
306 return Default::default();
312 let mut def_config_file = fs::File::open(config_file_name).expect("Couldn't open config");
313 let mut def_config = String::new();
315 .read_to_string(&mut def_config)
316 .expect("Couldn't read config");
318 Config::from_toml(&def_config).expect("Invalid toml")
321 // Reads significant comments of the form: // rustfmt-key: value
323 fn read_significant_comments(file_name: &str) -> HashMap<String, String> {
324 let file = fs::File::open(file_name).expect(&format!("Couldn't read file {}", file_name));
325 let reader = BufReader::new(file);
326 let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
327 let regex = regex::Regex::new(pattern).expect("Failed creating pattern 1");
329 // Matches lines containing significant comments or whitespace.
330 let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
331 .expect("Failed creating pattern 2");
335 .map(|line| line.expect("Failed getting line"))
336 .take_while(|line| line_regex.is_match(line))
338 regex.captures_iter(&line).next().map(|capture| {
342 .expect("Couldn't unwrap capture")
347 .expect("Couldn't unwrap capture")
356 // Compare output to input.
357 // TODO: needs a better name, more explanation.
359 result: HashMap<String, String>,
360 target: Option<&str>,
361 ) -> Result<(), HashMap<String, Vec<Mismatch>>> {
362 let mut failures = HashMap::new();
364 for (file_name, fmt_text) in result {
365 // If file is in tests/source, compare to file with same name in tests/target.
366 let target = get_target(&file_name, target);
367 let open_error = format!("Couldn't open target {:?}", &target);
368 let mut f = fs::File::open(&target).expect(&open_error);
370 let mut text = String::new();
371 let read_error = format!("Failed reading target {:?}", &target);
372 f.read_to_string(&mut text).expect(&read_error);
374 // Ignore LF and CRLF difference for Windows.
375 if !string_eq_ignore_newline_repr(&fmt_text, &text) {
376 let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
379 "Empty diff? Maybe due to a missing a newline at the end of a file?"
381 failures.insert(file_name, diff);
385 if failures.is_empty() {
392 // Map source file paths to their target paths.
393 fn get_target(file_name: &str, target: Option<&str>) -> String {
394 if file_name.contains("source") {
395 let target_file_name = file_name.replace("source", "target");
396 if let Some(replace_name) = target {
397 Path::new(&target_file_name)
398 .with_file_name(replace_name)
406 // This is either and idempotence check or a self check
412 fn rustfmt_diff_make_diff_tests() {
413 let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
420 DiffLine::Context("a".into()),
421 DiffLine::Resulting("b".into()),
422 DiffLine::Expected("e".into()),
423 DiffLine::Context("c".into()),
424 DiffLine::Context("d".into()),
432 fn rustfmt_diff_no_diff_test() {
433 let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
434 assert_eq!(diff, vec![]);
437 // Compare strings without distinguishing between CRLF and LF
438 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
439 let left = CharsIgnoreNewlineRepr(left.chars().peekable());
440 let right = CharsIgnoreNewlineRepr(right.chars().peekable());
444 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
446 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
448 fn next(&mut self) -> Option<char> {
449 self.0.next().map(|c| if c == '\r' {
450 if *self.0.peek().unwrap_or(&'\0') == '\n' {
463 fn string_eq_ignore_newline_repr_test() {
464 assert!(string_eq_ignore_newline_repr("", ""));
465 assert!(!string_eq_ignore_newline_repr("", "abc"));
466 assert!(!string_eq_ignore_newline_repr("abc", ""));
467 assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
468 assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
469 assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));