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::path::{Path, PathBuf};
23 use rustfmt::filemap::{write_system_newlines, FileMap};
24 use rustfmt::config::{Config, ReportTactic};
25 use rustfmt::rustfmt_diff::*;
27 const DIFF_CONTEXT_SIZE: usize = 3;
29 fn get_path_string(dir_entry: io::Result<fs::DirEntry>) -> String {
30 let path = dir_entry.expect("Couldn't get DirEntry").path();
32 path.to_str().expect("Couldn't stringify path").to_owned()
35 // Integration tests. The files in the tests/source are formatted and compared
36 // to their equivalent in tests/target. The target file and config can be
37 // overridden by annotations in the source file. The input and output must match
41 // Get all files in the tests/source directory.
42 let files = fs::read_dir("tests/source").expect("Couldn't read source dir");
43 // Turn a DirEntry into a String that represents the relative path to the
45 let files = files.map(get_path_string);
46 let (_reports, count, fails) = check_files(files);
49 println!("Ran {} system tests.", count);
50 assert_eq!(fails, 0, "{} system tests failed", fails);
53 // Do the same for tests/coverage-source directory
54 // the only difference is the coverage mode
57 let files = fs::read_dir("tests/coverage/source").expect("Couldn't read source dir");
58 let files = files.map(get_path_string);
59 let (_reports, count, fails) = check_files(files);
61 println!("Ran {} tests in coverage mode.", count);
62 assert_eq!(fails, 0, "{} tests failed", fails);
66 fn checkstyle_test() {
67 let filename = "tests/writemode/source/fn-single-line.rs";
68 let expected_filename = "tests/writemode/target/checkstyle.xml";
69 assert_output(filename, expected_filename);
73 // Helper function for comparing the results of rustfmt
74 // to a known output file generated by one of the write modes.
75 fn assert_output(source: &str, expected_filename: &str) {
76 let config = read_config(source);
77 let (file_map, _report) = format_file(source, &config);
79 // Populate output by writing to a vec.
81 let _ = filemap::write_all_files(&file_map, &mut out, &config);
82 let output = String::from_utf8(out).unwrap();
84 let mut expected_file = fs::File::open(&expected_filename).expect("Couldn't open target");
85 let mut expected_text = String::new();
87 .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.is_empty() {
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_eq!(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());
124 let files = files.chain(Some("build.rs".to_owned()).into_iter());
126 let (reports, count, fails) = check_files(files);
127 let mut warnings = 0;
130 println!("Ran {} self tests.", count);
131 assert_eq!(fails, 0, "{} self tests failed", fails);
133 for format_report in reports {
134 println!("{}", format_report);
135 warnings += format_report.warning_count();
141 "Rustfmt's code generated {} warnings",
147 fn stdin_formatting_smoke_test() {
148 let input = Input::Text("fn main () {}".to_owned());
149 let config = Config::default();
150 let (error_summary, file_map, _report) =
151 format_input::<io::Stdout>(input, &config, None).unwrap();
152 assert!(error_summary.has_no_errors());
153 for &(ref file_name, ref text) in &file_map {
154 if file_name == "stdin" {
155 assert_eq!(text.to_string(), "fn main() {}\n");
162 // FIXME(#1990) restore this test
164 // fn stdin_disable_all_formatting_test() {
165 // let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
166 // let mut child = Command::new("./target/debug/rustfmt")
167 // .stdin(Stdio::piped())
168 // .stdout(Stdio::piped())
169 // .arg("--config-path=./tests/config/disable_all_formatting.toml")
171 // .expect("failed to execute child");
174 // let stdin = child.stdin.as_mut().expect("failed to get stdin");
176 // .write_all(input.as_bytes())
177 // .expect("failed to write stdin");
179 // let output = child.wait_with_output().expect("failed to wait on child");
180 // assert!(output.status.success());
181 // assert!(output.stderr.is_empty());
182 // assert_eq!(input, String::from_utf8(output.stdout).unwrap());
186 fn format_lines_errors_are_reported() {
187 let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
188 let input = Input::Text(format!("fn {}() {{}}", long_identifier));
189 let config = Config::default();
190 let (error_summary, _file_map, _report) =
191 format_input::<io::Stdout>(input, &config, None).unwrap();
192 assert!(error_summary.has_formatting_errors());
195 // For each file, run rustfmt and collect the output.
196 // Returns the number of files checked and the number of failures.
197 fn check_files<I>(files: I) -> (Vec<FormatReport>, u32, u32)
199 I: Iterator<Item = String>,
203 let mut reports = vec![];
205 for file_name in files.filter(|f| f.ends_with(".rs")) {
206 debug!("Testing '{}'...", file_name);
208 match idempotent_check(file_name) {
209 Ok(ref report) if report.has_warnings() => {
210 print!("{}", report);
213 Ok(report) => reports.push(report),
215 print_mismatches(msg);
223 (reports, count, fails)
226 fn print_mismatches(result: HashMap<String, Vec<Mismatch>>) {
227 let mut t = term::stdout().unwrap();
229 for (file_name, diff) in result {
230 print_diff(diff, |line_num| {
231 format!("\nMismatch at {}:{}:", file_name, line_num)
238 fn read_config(filename: &str) -> Config {
239 let sig_comments = read_significant_comments(filename);
240 // Look for a config file... If there is a 'config' property in the significant comments, use
241 // that. Otherwise, if there are no significant comments at all, look for a config file with
242 // the same name as the test file.
243 let mut config = if !sig_comments.is_empty() {
244 get_config(sig_comments.get("config").map(|x| &(*x)[..]))
248 .with_extension("toml")
250 .and_then(std::ffi::OsStr::to_str),
254 for (key, val) in &sig_comments {
255 if key != "target" && key != "config" {
256 config.override_value(key, val);
260 // Don't generate warnings for to-do items.
261 config.set().report_todo(ReportTactic::Never);
266 fn format_file<P: Into<PathBuf>>(filepath: P, config: &Config) -> (FileMap, FormatReport) {
267 let filepath = filepath.into();
268 let input = Input::File(filepath);
269 let (_error_summary, file_map, report) =
270 format_input::<io::Stdout>(input, config, None).unwrap();
274 pub fn idempotent_check(filename: String) -> Result<FormatReport, HashMap<String, Vec<Mismatch>>> {
275 let sig_comments = read_significant_comments(&filename);
276 let config = read_config(&filename);
277 let (file_map, format_report) = format_file(filename, &config);
279 let mut write_result = HashMap::new();
280 for &(ref filename, ref text) in &file_map {
281 let mut v = Vec::new();
282 // Won't panic, as we're not doing any IO.
283 write_system_newlines(&mut v, text, &config).unwrap();
284 // Won't panic, we are writing correct utf8.
285 let one_result = String::from_utf8(v).unwrap();
286 write_result.insert(filename.clone(), one_result);
289 let target = sig_comments.get("target").map(|x| &(*x)[..]);
291 handle_result(write_result, target).map(|_| format_report)
294 // Reads test config file using the supplied (optional) file name. If there's no file name or the
295 // file doesn't exist, just return the default config. Otherwise, the file must be read
297 fn get_config(config_file: Option<&str>) -> Config {
298 let config_file_name = match config_file {
299 None => return Default::default(),
301 let mut full_path = "tests/config/".to_owned();
302 full_path.push_str(file_name);
303 if !Path::new(&full_path).exists() {
304 return Default::default();
310 let mut def_config_file = fs::File::open(config_file_name).expect("Couldn't open config");
311 let mut def_config = String::new();
313 .read_to_string(&mut def_config)
314 .expect("Couldn't read config");
316 Config::from_toml(&def_config).expect("Invalid toml")
319 // Reads significant comments of the form: // rustfmt-key: value
321 fn read_significant_comments(file_name: &str) -> HashMap<String, String> {
322 let file = fs::File::open(file_name).expect(&format!("Couldn't read file {}", file_name));
323 let reader = BufReader::new(file);
324 let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
325 let regex = regex::Regex::new(pattern).expect("Failed creating pattern 1");
327 // Matches lines containing significant comments or whitespace.
328 let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
329 .expect("Failed creating pattern 2");
333 .map(|line| line.expect("Failed getting line"))
334 .take_while(|line| line_regex.is_match(line))
336 regex.captures_iter(&line).next().map(|capture| {
340 .expect("Couldn't unwrap capture")
345 .expect("Couldn't unwrap capture")
354 // Compare output to input.
355 // TODO: needs a better name, more explanation.
357 result: HashMap<String, String>,
358 target: Option<&str>,
359 ) -> Result<(), HashMap<String, Vec<Mismatch>>> {
360 let mut failures = HashMap::new();
362 for (file_name, fmt_text) in result {
363 // If file is in tests/source, compare to file with same name in tests/target.
364 let target = get_target(&file_name, target);
365 let open_error = format!("Couldn't open target {:?}", &target);
366 let mut f = fs::File::open(&target).expect(&open_error);
368 let mut text = String::new();
369 let read_error = format!("Failed reading target {:?}", &target);
370 f.read_to_string(&mut text).expect(&read_error);
372 if fmt_text != text {
373 let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
376 "Empty diff? Maybe due to a missing a newline at the end of a file?"
378 failures.insert(file_name, diff);
382 if failures.is_empty() {
389 // Map source file paths to their target paths.
390 fn get_target(file_name: &str, target: Option<&str>) -> String {
391 if file_name.contains("source") {
392 let target_file_name = file_name.replace("source", "target");
393 if let Some(replace_name) = target {
394 Path::new(&target_file_name)
395 .with_file_name(replace_name)
403 // This is either and idempotence check or a self check
409 fn rustfmt_diff_make_diff_tests() {
410 let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
417 DiffLine::Context("a".into()),
418 DiffLine::Resulting("b".into()),
419 DiffLine::Expected("e".into()),
420 DiffLine::Context("c".into()),
421 DiffLine::Context("d".into()),
429 fn rustfmt_diff_no_diff_test() {
430 let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
431 assert_eq!(diff, vec![]);