1 use std::collections::HashMap;
4 use std::io::{self, BufRead, BufReader, Read, Write};
5 use std::iter::Peekable;
7 use std::path::{Path, PathBuf};
8 use std::process::{Command, Stdio};
12 use crate::config::{Color, Config, EmitMode, FileName, NewlineStyle, ReportTactic};
13 use crate::formatting::{ReportedErrors, SourceFile};
14 use crate::is_nightly_channel;
15 use crate::rustfmt_diff::{make_diff, print_diff, DiffLine, Mismatch, ModifiedChunk, OutputWriter};
16 use crate::source_file;
17 use crate::{FormatReport, FormatReportFormatterBuilder, Input, Session};
19 mod configuration_snippet;
21 const DIFF_CONTEXT_SIZE: usize = 3;
23 // A list of files on which we want to skip testing.
24 const SKIP_FILE_WHITE_LIST: &[&str] = &[
25 // We want to make sure that the `skip_children` is correctly working,
26 // so we do not want to test this file directly.
27 "configs/skip_children/foo/mod.rs",
28 "issue-3434/no_entry.rs",
29 "issue-3665/sub_mod.rs",
30 // These files and directory are a part of modules defined inside `cfg_if!`.
36 // These files and directory are a part of modules defined inside `cfg_attr(..)`.
44 /// The size of the stack of the thread that run tests.
48 impl Default for TestSetting {
49 fn default() -> Self {
51 stack_size: 8_388_608, // 8MB
56 fn run_test_with<F>(test_setting: &TestSetting, f: F)
61 thread::Builder::new()
62 .stack_size(test_setting.stack_size)
64 .expect("Failed to create a test thread")
66 .expect("Failed to join a test thread")
69 fn is_subpath<P>(path: &Path, subpath: &P) -> bool
73 (0..path.components().count())
77 .take(subpath.as_ref().components().count())
79 .any(|c| c.zip(subpath.as_ref().components()).all(|(a, b)| a == b))
82 fn is_file_skip(path: &Path) -> bool {
85 .any(|file_path| is_subpath(path, file_path))
88 // Returns a `Vec` containing `PathBuf`s of files with an `rs` extension in the
89 // given path. The `recursive` argument controls if files from subdirectories
91 fn get_test_files(path: &Path, recursive: bool) -> Vec<PathBuf> {
92 let mut files = vec![];
94 for entry in fs::read_dir(path).expect(&format!(
95 "couldn't read directory {}",
96 path.to_str().unwrap()
98 let entry = entry.expect("couldn't get `DirEntry`");
99 let path = entry.path();
100 if path.is_dir() && recursive {
101 files.append(&mut get_test_files(&path, recursive));
102 } else if path.extension().map_or(false, |f| f == "rs") && !is_file_skip(&path) {
110 fn verify_config_used(path: &Path, config_name: &str) {
111 for entry in fs::read_dir(path).expect(&format!(
112 "couldn't read {} directory",
113 path.to_str().unwrap()
115 let entry = entry.expect("couldn't get directory entry");
116 let path = entry.path();
117 if path.extension().map_or(false, |f| f == "rs") {
118 // check if "// rustfmt-<config_name>:" appears in the file.
119 let filebuf = BufReader::new(
120 fs::File::open(&path)
121 .unwrap_or_else(|_| panic!("couldn't read file {}", path.display())),
127 .take_while(|l| l.starts_with("//"))
128 .any(|l| l.starts_with(&format!("// rustfmt-{}", config_name))),
130 "config option file {} does not contain expected config name",
139 fn verify_config_test_names() {
141 Path::new("tests/source/configs"),
142 Path::new("tests/target/configs"),
144 for entry in fs::read_dir(path).expect("couldn't read configs directory") {
145 let entry = entry.expect("couldn't get directory entry");
146 let path = entry.path();
148 let config_name = path.file_name().unwrap().to_str().unwrap();
150 // Make sure that config name is used in the files in the directory.
151 verify_config_used(&path, config_name);
157 // This writes to the terminal using the same approach (via `term::stdout` or
158 // `println!`) that is used by `rustfmt::rustfmt_diff::print_diff`. Writing
159 // using only one or the other will cause the output order to differ when
160 // `print_diff` selects the approach not used.
161 fn write_message(msg: &str) {
162 let mut writer = OutputWriter::new(Color::Auto);
163 writer.writeln(msg, None);
166 // Integration tests. The files in `tests/source` are formatted and compared
167 // to their equivalent in `tests/target`. The target file and config can be
168 // overridden by annotations in the source file. The input and output must match
172 run_test_with(&TestSetting::default(), || {
173 // Get all files in the tests/source directory.
174 let files = get_test_files(Path::new("tests/source"), true);
175 let (_reports, count, fails) = check_files(files, &None);
178 println!("Ran {} system tests.", count);
179 assert_eq!(fails, 0, "{} system tests failed", fails);
182 "Expected a minimum of {} system tests to be executed",
188 // Do the same for tests/coverage-source directory.
189 // The only difference is the coverage mode.
191 fn coverage_tests() {
192 let files = get_test_files(Path::new("tests/coverage/source"), true);
193 let (_reports, count, fails) = check_files(files, &None);
195 println!("Ran {} tests in coverage mode.", count);
196 assert_eq!(fails, 0, "{} tests failed", fails);
200 fn checkstyle_test() {
201 let filename = "tests/writemode/source/fn-single-line.rs";
202 let expected_filename = "tests/writemode/target/checkstyle.xml";
203 assert_output(Path::new(filename), Path::new(expected_filename));
208 let filename = "tests/writemode/source/json.rs";
209 let expected_filename = "tests/writemode/target/output.json";
210 assert_output(Path::new(filename), Path::new(expected_filename));
215 use std::io::BufRead;
217 // Test "modified" output
218 let filename = "tests/writemode/source/modified.rs";
219 let mut data = Vec::new();
220 let mut config = Config::default();
223 .emit_mode(crate::config::EmitMode::ModifiedLines);
226 let mut session = Session::new(config, Some(&mut data));
227 session.format(Input::File(filename.into())).unwrap();
230 let mut lines = data.lines();
231 let mut chunks = Vec::new();
232 while let Some(Ok(header)) = lines.next() {
233 // Parse the header line
234 let values: Vec<_> = header
236 .map(|s| s.parse::<u32>().unwrap())
238 assert_eq!(values.len(), 3);
239 let line_number_orig = values[0];
240 let lines_removed = values[1];
241 let num_added = values[2];
242 let mut added_lines = Vec::new();
243 for _ in 0..num_added {
244 added_lines.push(lines.next().unwrap().unwrap());
246 chunks.push(ModifiedChunk {
259 lines: vec!["fn blah() {}".into()],
264 lines: vec!["#[cfg(a, b)]".into(), "fn main() {}".into()],
270 // Helper function for comparing the results of rustfmt
271 // to a known output file generated by one of the write modes.
272 fn assert_output(source: &Path, expected_filename: &Path) {
273 let config = read_config(source);
274 let (_, source_file, _) = format_file(source, config.clone());
276 // Populate output by writing to a vec.
277 let mut out = vec![];
278 let _ = source_file::write_all_files(&source_file, &mut out, &config);
279 let output = String::from_utf8(out).unwrap();
281 let mut expected_file = fs::File::open(&expected_filename).expect("couldn't open target");
282 let mut expected_text = String::new();
284 .read_to_string(&mut expected_text)
285 .expect("Failed reading target");
287 let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
288 if !compare.is_empty() {
289 let mut failures = HashMap::new();
290 failures.insert(source.to_owned(), compare);
291 print_mismatches_default_message(failures);
292 panic!("Text does not match expected output");
296 // Idempotence tests. Files in tests/target are checked to be unaltered by
299 fn idempotence_tests() {
300 run_test_with(&TestSetting::default(), || {
301 // these tests require nightly
302 if !is_nightly_channel!() {
305 // Get all files in the tests/target directory.
306 let files = get_test_files(Path::new("tests/target"), true);
307 let (_reports, count, fails) = check_files(files, &None);
310 println!("Ran {} idempotent tests.", count);
311 assert_eq!(fails, 0, "{} idempotent tests failed", fails);
314 "Expected a minimum of {} idempotent tests to be executed",
320 // Run rustfmt on itself. This operation must be idempotent. We also check that
321 // no warnings are emitted.
324 // Issue-3443: these tests require nightly
325 if !is_nightly_channel!() {
328 let mut files = get_test_files(Path::new("tests"), false);
329 let bin_directories = vec!["cargo-fmt", "git-rustfmt", "bin", "format-diff"];
330 for dir in bin_directories {
331 let mut path = PathBuf::from("src");
333 path.push("main.rs");
336 files.push(PathBuf::from("src/lib.rs"));
338 let (reports, count, fails) = check_files(files, &Some(PathBuf::from("rustfmt.toml")));
339 let mut warnings = 0;
342 println!("Ran {} self tests.", count);
343 assert_eq!(fails, 0, "{} self tests failed", fails);
345 for format_report in reports {
348 FormatReportFormatterBuilder::new(&format_report).build()
350 warnings += format_report.warning_count();
355 "Rustfmt's code generated {} warnings",
361 fn stdin_formatting_smoke_test() {
362 let input = Input::Text("fn main () {}".to_owned());
363 let mut config = Config::default();
364 config.set().emit_mode(EmitMode::Stdout);
365 let mut buf: Vec<u8> = vec![];
367 let mut session = Session::new(config, Some(&mut buf));
368 session.format(input).unwrap();
369 assert!(session.has_no_errors());
373 assert_eq!(buf, "stdin:\n\nfn main() {}\n".as_bytes());
375 assert_eq!(buf, "stdin:\n\nfn main() {}\r\n".as_bytes());
379 fn stdin_parser_panic_caught() {
381 for text in ["{", "}"].iter().cloned().map(String::from) {
382 let mut buf = vec![];
383 let mut session = Session::new(Default::default(), Some(&mut buf));
384 let _ = session.format(Input::Text(text));
386 assert!(session.has_parsing_errors());
390 /// Ensures that `EmitMode::ModifiedLines` works with input from `stdin`. Useful
391 /// when embedding Rustfmt (e.g. inside RLS).
393 fn stdin_works_with_modified_lines() {
394 let input = "\nfn\n some( )\n{\n}\nfn main () {}\n";
395 let output = "1 6 2\nfn some() {}\nfn main() {}\n";
397 let input = Input::Text(input.to_owned());
398 let mut config = Config::default();
399 config.set().newline_style(NewlineStyle::Unix);
400 config.set().emit_mode(EmitMode::ModifiedLines);
401 let mut buf: Vec<u8> = vec![];
403 let mut session = Session::new(config, Some(&mut buf));
404 session.format(input).unwrap();
405 let errors = ReportedErrors {
409 assert_eq!(session.errors, errors);
411 assert_eq!(buf, output.as_bytes());
415 fn stdin_disable_all_formatting_test() {
416 match option_env!("CFG_RELEASE_CHANNEL") {
417 None | Some("nightly") => {}
418 // These tests require nightly.
421 let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
422 let mut child = Command::new(rustfmt().to_str().unwrap())
423 .stdin(Stdio::piped())
424 .stdout(Stdio::piped())
425 .arg("--config-path=./tests/config/disable_all_formatting.toml")
427 .expect("failed to execute child");
430 let stdin = child.stdin.as_mut().expect("failed to get stdin");
432 .write_all(input.as_bytes())
433 .expect("failed to write stdin");
436 let output = child.wait_with_output().expect("failed to wait on child");
437 assert!(output.status.success());
438 assert!(output.stderr.is_empty());
439 assert_eq!(input, String::from_utf8(output.stdout).unwrap());
443 fn format_lines_errors_are_reported() {
444 let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
445 let input = Input::Text(format!("fn {}() {{}}", long_identifier));
446 let mut config = Config::default();
447 config.set().error_on_line_overflow(true);
448 let mut session = Session::<io::Stdout>::new(config, None);
449 session.format(input).unwrap();
450 assert!(session.has_formatting_errors());
454 fn format_lines_errors_are_reported_with_tabs() {
455 let long_identifier = String::from_utf8(vec![b'a'; 97]).unwrap();
456 let input = Input::Text(format!("fn a() {{\n\t{}\n}}", long_identifier));
457 let mut config = Config::default();
458 config.set().error_on_line_overflow(true);
459 config.set().hard_tabs(true);
460 let mut session = Session::<io::Stdout>::new(config, None);
461 session.format(input).unwrap();
462 assert!(session.has_formatting_errors());
465 // For each file, run rustfmt and collect the output.
466 // Returns the number of files checked and the number of failures.
467 fn check_files(files: Vec<PathBuf>, opt_config: &Option<PathBuf>) -> (Vec<FormatReport>, u32, u32) {
470 let mut reports = vec![];
472 for file_name in files {
473 let sig_comments = read_significant_comments(&file_name);
474 if sig_comments.contains_key("unstable") && !is_nightly_channel!() {
476 "Skipping '{}' because it requires unstable \
477 features which are only available on nightly...",
483 debug!("Testing '{}'...", file_name.display());
485 match idempotent_check(&file_name, &opt_config) {
486 Ok(ref report) if report.has_warnings() => {
487 print!("{}", FormatReportFormatterBuilder::new(&report).build());
490 Ok(report) => reports.push(report),
492 if let IdempotentCheckError::Mismatch(msg) = err {
493 print_mismatches_default_message(msg);
502 (reports, count, fails)
505 fn print_mismatches_default_message(result: HashMap<PathBuf, Vec<Mismatch>>) {
506 for (file_name, diff) in result {
507 let mismatch_msg_formatter =
508 |line_num| format!("\nMismatch at {}:{}:", file_name.display(), line_num);
509 print_diff(diff, &mismatch_msg_formatter, &Default::default());
512 if let Some(mut t) = term::stdout() {
513 t.reset().unwrap_or(());
517 fn print_mismatches<T: Fn(u32) -> String>(
518 result: HashMap<PathBuf, Vec<Mismatch>>,
519 mismatch_msg_formatter: T,
521 for (_file_name, diff) in result {
522 print_diff(diff, &mismatch_msg_formatter, &Default::default());
525 if let Some(mut t) = term::stdout() {
526 t.reset().unwrap_or(());
530 fn read_config(filename: &Path) -> Config {
531 let sig_comments = read_significant_comments(filename);
532 // Look for a config file. If there is a 'config' property in the significant comments, use
533 // that. Otherwise, if there are no significant comments at all, look for a config file with
534 // the same name as the test file.
535 let mut config = if !sig_comments.is_empty() {
536 get_config(sig_comments.get("config").map(Path::new))
538 get_config(filename.with_extension("toml").file_name().map(Path::new))
541 for (key, val) in &sig_comments {
542 if key != "target" && key != "config" && key != "unstable" {
543 config.override_value(key, val);
544 if config.is_default(key) {
545 warn!("Default value {} used explicitly for {}", val, key);
550 // Don't generate warnings for to-do items.
551 config.set().report_todo(ReportTactic::Never);
556 fn format_file<P: Into<PathBuf>>(filepath: P, config: Config) -> (bool, SourceFile, FormatReport) {
557 let filepath = filepath.into();
558 let input = Input::File(filepath);
559 let mut session = Session::<io::Stdout>::new(config, None);
560 let result = session.format(input).unwrap();
561 let parsing_errors = session.has_parsing_errors();
562 let mut source_file = SourceFile::new();
563 mem::swap(&mut session.source_file, &mut source_file);
564 (parsing_errors, source_file, result)
567 enum IdempotentCheckError {
568 Mismatch(HashMap<PathBuf, Vec<Mismatch>>),
574 opt_config: &Option<PathBuf>,
575 ) -> Result<FormatReport, IdempotentCheckError> {
576 let sig_comments = read_significant_comments(filename);
577 let config = if let Some(ref config_file_path) = opt_config {
578 Config::from_toml_path(config_file_path).expect("`rustfmt.toml` not found")
580 read_config(filename)
582 let (parsing_errors, source_file, format_report) = format_file(filename, config);
584 return Err(IdempotentCheckError::Parse);
587 let mut write_result = HashMap::new();
588 for (filename, text) in source_file {
589 if let FileName::Real(ref filename) = filename {
590 write_result.insert(filename.to_owned(), text);
594 let target = sig_comments.get("target").map(|x| &(*x)[..]);
596 handle_result(write_result, target).map(|_| format_report)
599 // Reads test config file using the supplied (optional) file name. If there's no file name or the
600 // file doesn't exist, just return the default config. Otherwise, the file must be read
602 fn get_config(config_file: Option<&Path>) -> Config {
603 let config_file_name = match config_file {
604 None => return Default::default(),
606 let mut full_path = PathBuf::from("tests/config/");
607 full_path.push(file_name);
608 if !full_path.exists() {
609 return Default::default();
615 let mut def_config_file = fs::File::open(config_file_name).expect("couldn't open config");
616 let mut def_config = String::new();
618 .read_to_string(&mut def_config)
619 .expect("Couldn't read config");
621 Config::from_toml(&def_config, Path::new("tests/config/")).expect("invalid TOML")
624 // Reads significant comments of the form: `// rustfmt-key: value` into a hash map.
625 fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
626 let file = fs::File::open(file_name)
627 .unwrap_or_else(|_| panic!("couldn't read file {}", file_name.display()));
628 let reader = BufReader::new(file);
629 let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
630 let regex = regex::Regex::new(pattern).expect("failed creating pattern 1");
632 // Matches lines containing significant comments or whitespace.
633 let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
634 .expect("failed creating pattern 2");
638 .map(|line| line.expect("failed getting line"))
639 .take_while(|line| line_regex.is_match(line))
641 regex.captures_iter(&line).next().map(|capture| {
645 .expect("couldn't unwrap capture")
650 .expect("couldn't unwrap capture")
659 // Compares output to input.
660 // TODO: needs a better name, more explanation.
662 result: HashMap<PathBuf, String>,
663 target: Option<&str>,
664 ) -> Result<(), IdempotentCheckError> {
665 let mut failures = HashMap::new();
667 for (file_name, fmt_text) in result {
668 // If file is in tests/source, compare to file with same name in tests/target.
669 let target = get_target(&file_name, target);
670 let open_error = format!("couldn't open target {:?}", target);
671 let mut f = fs::File::open(&target).expect(&open_error);
673 let mut text = String::new();
674 let read_error = format!("failed reading target {:?}", target);
675 f.read_to_string(&mut text).expect(&read_error);
677 // Ignore LF and CRLF difference for Windows.
678 if !string_eq_ignore_newline_repr(&fmt_text, &text) {
679 let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
682 "Empty diff? Maybe due to a missing a newline at the end of a file?"
684 failures.insert(file_name, diff);
688 if failures.is_empty() {
691 Err(IdempotentCheckError::Mismatch(failures))
695 // Maps source file paths to their target paths.
696 fn get_target(file_name: &Path, target: Option<&str>) -> PathBuf {
697 if let Some(n) = file_name
699 .position(|c| c.as_os_str() == "source")
701 let mut target_file_name = PathBuf::new();
702 for (i, c) in file_name.components().enumerate() {
704 target_file_name.push("target");
706 target_file_name.push(c.as_os_str());
709 if let Some(replace_name) = target {
710 target_file_name.with_file_name(replace_name)
715 // This is either and idempotence check or a self check.
721 fn rustfmt_diff_make_diff_tests() {
722 let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
729 DiffLine::Context("a".into()),
730 DiffLine::Resulting("b".into()),
731 DiffLine::Expected("e".into()),
732 DiffLine::Context("c".into()),
733 DiffLine::Context("d".into()),
740 fn rustfmt_diff_no_diff_test() {
741 let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
742 assert_eq!(diff, vec![]);
745 // Compare strings without distinguishing between CRLF and LF
746 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
747 let left = CharsIgnoreNewlineRepr(left.chars().peekable());
748 let right = CharsIgnoreNewlineRepr(right.chars().peekable());
752 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
754 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
757 fn next(&mut self) -> Option<char> {
758 self.0.next().map(|c| {
760 if *self.0.peek().unwrap_or(&'\0') == '\n' {
774 fn string_eq_ignore_newline_repr_test() {
775 assert!(string_eq_ignore_newline_repr("", ""));
776 assert!(!string_eq_ignore_newline_repr("", "abc"));
777 assert!(!string_eq_ignore_newline_repr("abc", ""));
778 assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
779 assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
780 assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));
787 fn make_temp_file(file_name: &'static str) -> TempFile {
791 // Used in the Rust build system.
792 let target_dir = var("RUSTFMT_TEST_DIR").unwrap_or_else(|_| ".".to_owned());
793 let path = Path::new(&target_dir).join(file_name);
795 let mut file = File::create(&path).expect("couldn't create temp file");
796 let content = "fn main() {}\n";
797 file.write_all(content.as_bytes())
798 .expect("couldn't write temp file");
802 impl Drop for TempFile {
804 use std::fs::remove_file;
805 remove_file(&self.path).expect("couldn't delete temp file");
809 fn rustfmt() -> PathBuf {
810 let mut me = env::current_exe().expect("failed to get current executable");
811 // Chop of the test name.
816 // If we run `cargo test --release`, we might only have a release build.
824 me.is_file() || me.with_extension("exe").is_file(),
826 "no rustfmt bin, try running `cargo build --release` before testing"
828 "no rustfmt bin, try running `cargo build` before testing"
835 fn verify_check_works() {
836 let temp_file = make_temp_file("temp_check.rs");
838 Command::new(rustfmt().to_str().unwrap())
840 .arg(temp_file.path.to_str().unwrap())
842 .expect("run with check option failed");