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::rustfmt_diff::{make_diff, print_diff, DiffLine, Mismatch, ModifiedChunk, OutputWriter};
15 use crate::source_file;
16 use crate::{is_nightly_channel, FormatReport, FormatReportFormatterBuilder, Input, Session};
18 mod configuration_snippet;
22 const DIFF_CONTEXT_SIZE: usize = 3;
24 // A list of files on which we want to skip testing.
25 const SKIP_FILE_WHITE_LIST: &[&str] = &[
26 // We want to make sure that the `skip_children` is correctly working,
27 // so we do not want to test this file directly.
28 "configs/skip_children/foo/mod.rs",
29 "issue-3434/no_entry.rs",
30 "issue-3665/sub_mod.rs",
31 // Testing for issue-3779
33 // These files and directory are a part of modules defined inside `cfg_if!`.
39 // These files and directory are a part of modules defined inside `cfg_attr(..)`.
48 let _ = env_logger::builder().is_test(true).try_init();
52 /// The size of the stack of the thread that run tests.
56 impl Default for TestSetting {
57 fn default() -> Self {
59 stack_size: 8_388_608, // 8MB
64 fn run_test_with<F>(test_setting: &TestSetting, f: F)
69 thread::Builder::new()
70 .stack_size(test_setting.stack_size)
72 .expect("Failed to create a test thread")
74 .expect("Failed to join a test thread")
77 fn is_subpath<P>(path: &Path, subpath: &P) -> bool
81 (0..path.components().count())
85 .take(subpath.as_ref().components().count())
87 .any(|c| c.zip(subpath.as_ref().components()).all(|(a, b)| a == b))
90 fn is_file_skip(path: &Path) -> bool {
93 .any(|file_path| is_subpath(path, file_path))
96 // Returns a `Vec` containing `PathBuf`s of files with an `rs` extension in the
97 // given path. The `recursive` argument controls if files from subdirectories
99 fn get_test_files(path: &Path, recursive: bool) -> Vec<PathBuf> {
100 let mut files = vec![];
102 for entry in fs::read_dir(path).expect(&format!(
103 "couldn't read directory {}",
104 path.to_str().unwrap()
106 let entry = entry.expect("couldn't get `DirEntry`");
107 let path = entry.path();
108 if path.is_dir() && recursive {
109 files.append(&mut get_test_files(&path, recursive));
110 } else if path.extension().map_or(false, |f| f == "rs") && !is_file_skip(&path) {
118 fn verify_config_used(path: &Path, config_name: &str) {
119 for entry in fs::read_dir(path).expect(&format!(
120 "couldn't read {} directory",
121 path.to_str().unwrap()
123 let entry = entry.expect("couldn't get directory entry");
124 let path = entry.path();
125 if path.extension().map_or(false, |f| f == "rs") {
126 // check if "// rustfmt-<config_name>:" appears in the file.
127 let filebuf = BufReader::new(
128 fs::File::open(&path)
129 .unwrap_or_else(|_| panic!("couldn't read file {}", path.display())),
135 .take_while(|l| l.starts_with("//"))
136 .any(|l| l.starts_with(&format!("// rustfmt-{}", config_name))),
137 "config option file {} does not contain expected config name",
145 fn verify_config_test_names() {
148 Path::new("tests/source/configs"),
149 Path::new("tests/target/configs"),
151 for entry in fs::read_dir(path).expect("couldn't read configs directory") {
152 let entry = entry.expect("couldn't get directory entry");
153 let path = entry.path();
155 let config_name = path.file_name().unwrap().to_str().unwrap();
157 // Make sure that config name is used in the files in the directory.
158 verify_config_used(&path, config_name);
164 // This writes to the terminal using the same approach (via `term::stdout` or
165 // `println!`) that is used by `rustfmt::rustfmt_diff::print_diff`. Writing
166 // using only one or the other will cause the output order to differ when
167 // `print_diff` selects the approach not used.
168 fn write_message(msg: &str) {
169 let mut writer = OutputWriter::new(Color::Auto);
170 writer.writeln(msg, None);
173 // Integration tests. The files in `tests/source` are formatted and compared
174 // to their equivalent in `tests/target`. The target file and config can be
175 // overridden by annotations in the source file. The input and output must match
180 run_test_with(&TestSetting::default(), || {
181 // Get all files in the tests/source directory.
182 let files = get_test_files(Path::new("tests/source"), true);
183 let (_reports, count, fails) = check_files(files, &None);
186 println!("Ran {} system tests.", count);
187 assert_eq!(fails, 0, "{} system tests failed", fails);
190 "Expected a minimum of {} system tests to be executed",
196 // Do the same for tests/coverage-source directory.
197 // The only difference is the coverage mode.
199 fn coverage_tests() {
201 let files = get_test_files(Path::new("tests/coverage/source"), true);
202 let (_reports, count, fails) = check_files(files, &None);
204 println!("Ran {} tests in coverage mode.", count);
205 assert_eq!(fails, 0, "{} tests failed", fails);
209 fn checkstyle_test() {
211 let filename = "tests/writemode/source/fn-single-line.rs";
212 let expected_filename = "tests/writemode/target/checkstyle.xml";
213 assert_output(Path::new(filename), Path::new(expected_filename));
219 let filename = "tests/writemode/source/json.rs";
220 let expected_filename = "tests/writemode/target/output.json";
221 assert_output(Path::new(filename), Path::new(expected_filename));
227 use std::io::BufRead;
229 // Test "modified" output
230 let filename = "tests/writemode/source/modified.rs";
231 let mut data = Vec::new();
232 let mut config = Config::default();
235 .emit_mode(crate::config::EmitMode::ModifiedLines);
238 let mut session = Session::new(config, Some(&mut data));
239 session.format(Input::File(filename.into())).unwrap();
242 let mut lines = data.lines();
243 let mut chunks = Vec::new();
244 while let Some(Ok(header)) = lines.next() {
245 // Parse the header line
246 let values: Vec<_> = header
248 .map(|s| s.parse::<u32>().unwrap())
250 assert_eq!(values.len(), 3);
251 let line_number_orig = values[0];
252 let lines_removed = values[1];
253 let num_added = values[2];
254 let mut added_lines = Vec::new();
255 for _ in 0..num_added {
256 added_lines.push(lines.next().unwrap().unwrap());
258 chunks.push(ModifiedChunk {
271 lines: vec!["fn blah() {}".into()],
276 lines: vec!["#[cfg(a, b)]".into(), "fn main() {}".into()],
282 // Helper function for comparing the results of rustfmt
283 // to a known output file generated by one of the write modes.
284 fn assert_output(source: &Path, expected_filename: &Path) {
285 let config = read_config(source);
286 let (_, source_file, _) = format_file(source, config.clone());
288 // Populate output by writing to a vec.
289 let mut out = vec![];
290 let _ = source_file::write_all_files(&source_file, &mut out, &config);
291 let output = String::from_utf8(out).unwrap();
293 let mut expected_file = fs::File::open(&expected_filename).expect("couldn't open target");
294 let mut expected_text = String::new();
296 .read_to_string(&mut expected_text)
297 .expect("Failed reading target");
299 let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
300 if !compare.is_empty() {
301 let mut failures = HashMap::new();
302 failures.insert(source.to_owned(), compare);
303 print_mismatches_default_message(failures);
304 panic!("Text does not match expected output");
308 // Idempotence tests. Files in tests/target are checked to be unaltered by
311 fn idempotence_tests() {
313 run_test_with(&TestSetting::default(), || {
314 // these tests require nightly
315 if !is_nightly_channel!() {
318 // Get all files in the tests/target directory.
319 let files = get_test_files(Path::new("tests/target"), true);
320 let (_reports, count, fails) = check_files(files, &None);
323 println!("Ran {} idempotent tests.", count);
324 assert_eq!(fails, 0, "{} idempotent tests failed", fails);
327 "Expected a minimum of {} idempotent tests to be executed",
333 // Run rustfmt on itself. This operation must be idempotent. We also check that
334 // no warnings are emitted.
338 // Issue-3443: these tests require nightly
339 if !is_nightly_channel!() {
342 let mut files = get_test_files(Path::new("tests"), false);
343 let bin_directories = vec!["cargo-fmt", "git-rustfmt", "bin", "format-diff"];
344 for dir in bin_directories {
345 let mut path = PathBuf::from("src");
347 path.push("main.rs");
350 files.push(PathBuf::from("src/lib.rs"));
352 let (reports, count, fails) = check_files(files, &Some(PathBuf::from("rustfmt.toml")));
353 let mut warnings = 0;
356 println!("Ran {} self tests.", count);
357 assert_eq!(fails, 0, "{} self tests failed", fails);
359 for format_report in reports {
362 FormatReportFormatterBuilder::new(&format_report).build()
364 warnings += format_report.warning_count();
369 "Rustfmt's code generated {} warnings",
375 fn format_files_find_new_files_via_cfg_if() {
377 run_test_with(&TestSetting::default(), || {
378 // To repro issue-4656, it is necessary that these files are parsed
379 // as a part of the same session (hence this separate test runner).
381 Path::new("tests/source/issue-4656/lib2.rs"),
382 Path::new("tests/source/issue-4656/lib.rs"),
385 let config = Config::default();
386 let mut session = Session::<io::Stdout>::new(config, None);
388 let mut write_result = HashMap::new();
390 assert!(file.exists());
391 let result = session.format(Input::File(file.into())).unwrap();
392 assert!(!session.has_formatting_errors());
393 assert!(!result.has_warnings());
394 let mut source_file = SourceFile::new();
395 mem::swap(&mut session.source_file, &mut source_file);
397 for (filename, text) in source_file {
398 if let FileName::Real(ref filename) = filename {
399 write_result.insert(filename.to_owned(), text);
406 "Should have uncovered an extra file (format_me_please.rs) via lib.rs"
408 assert!(handle_result(write_result, None).is_ok());
413 fn stdin_formatting_smoke_test() {
415 let input = Input::Text("fn main () {}".to_owned());
416 let mut config = Config::default();
417 config.set().emit_mode(EmitMode::Stdout);
418 let mut buf: Vec<u8> = vec![];
420 let mut session = Session::new(config, Some(&mut buf));
421 session.format(input).unwrap();
422 assert!(session.has_no_errors());
426 assert_eq!(buf, "stdin:\n\nfn main() {}\n".as_bytes());
428 assert_eq!(buf, "stdin:\n\nfn main() {}\r\n".as_bytes());
432 fn stdin_parser_panic_caught() {
435 for text in ["{", "}"].iter().cloned().map(String::from) {
436 let mut buf = vec![];
437 let mut session = Session::new(Default::default(), Some(&mut buf));
438 let _ = session.format(Input::Text(text));
440 assert!(session.has_parsing_errors());
444 /// Ensures that `EmitMode::ModifiedLines` works with input from `stdin`. Useful
445 /// when embedding Rustfmt (e.g. inside RLS).
447 fn stdin_works_with_modified_lines() {
449 let input = "\nfn\n some( )\n{\n}\nfn main () {}\n";
450 let output = "1 6 2\nfn some() {}\nfn main() {}\n";
452 let input = Input::Text(input.to_owned());
453 let mut config = Config::default();
454 config.set().newline_style(NewlineStyle::Unix);
455 config.set().emit_mode(EmitMode::ModifiedLines);
456 let mut buf: Vec<u8> = vec![];
458 let mut session = Session::new(config, Some(&mut buf));
459 session.format(input).unwrap();
460 let errors = ReportedErrors {
464 assert_eq!(session.errors, errors);
466 assert_eq!(buf, output.as_bytes());
470 fn stdin_disable_all_formatting_test() {
472 match option_env!("CFG_RELEASE_CHANNEL") {
473 None | Some("nightly") => {}
474 // These tests require nightly.
477 let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
478 let mut child = Command::new(rustfmt().to_str().unwrap())
479 .stdin(Stdio::piped())
480 .stdout(Stdio::piped())
481 .arg("--config-path=./tests/config/disable_all_formatting.toml")
483 .expect("failed to execute child");
486 let stdin = child.stdin.as_mut().expect("failed to get stdin");
488 .write_all(input.as_bytes())
489 .expect("failed to write stdin");
492 let output = child.wait_with_output().expect("failed to wait on child");
493 assert!(output.status.success());
494 assert!(output.stderr.is_empty());
495 assert_eq!(input, String::from_utf8(output.stdout).unwrap());
499 fn format_lines_errors_are_reported() {
501 let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
502 let input = Input::Text(format!("fn {}() {{}}", long_identifier));
503 let mut config = Config::default();
504 config.set().error_on_line_overflow(true);
505 let mut session = Session::<io::Stdout>::new(config, None);
506 session.format(input).unwrap();
507 assert!(session.has_formatting_errors());
511 fn format_lines_errors_are_reported_with_tabs() {
513 let long_identifier = String::from_utf8(vec![b'a'; 97]).unwrap();
514 let input = Input::Text(format!("fn a() {{\n\t{}\n}}", long_identifier));
515 let mut config = Config::default();
516 config.set().error_on_line_overflow(true);
517 config.set().hard_tabs(true);
518 let mut session = Session::<io::Stdout>::new(config, None);
519 session.format(input).unwrap();
520 assert!(session.has_formatting_errors());
523 // For each file, run rustfmt and collect the output.
524 // Returns the number of files checked and the number of failures.
525 fn check_files(files: Vec<PathBuf>, opt_config: &Option<PathBuf>) -> (Vec<FormatReport>, u32, u32) {
528 let mut reports = vec![];
530 for file_name in files {
531 let sig_comments = read_significant_comments(&file_name);
532 if sig_comments.contains_key("unstable") && !is_nightly_channel!() {
534 "Skipping '{}' because it requires unstable \
535 features which are only available on nightly...",
541 debug!("Testing '{}'...", file_name.display());
543 match idempotent_check(&file_name, &opt_config) {
544 Ok(ref report) if report.has_warnings() => {
545 print!("{}", FormatReportFormatterBuilder::new(&report).build());
548 Ok(report) => reports.push(report),
550 if let IdempotentCheckError::Mismatch(msg) = err {
551 print_mismatches_default_message(msg);
560 (reports, count, fails)
563 fn print_mismatches_default_message(result: HashMap<PathBuf, Vec<Mismatch>>) {
564 for (file_name, diff) in result {
565 let mismatch_msg_formatter =
566 |line_num| format!("\nMismatch at {}:{}:", file_name.display(), line_num);
567 print_diff(diff, &mismatch_msg_formatter, &Default::default());
570 if let Some(mut t) = term::stdout() {
571 t.reset().unwrap_or(());
575 fn print_mismatches<T: Fn(u32) -> String>(
576 result: HashMap<PathBuf, Vec<Mismatch>>,
577 mismatch_msg_formatter: T,
579 for (_file_name, diff) in result {
580 print_diff(diff, &mismatch_msg_formatter, &Default::default());
583 if let Some(mut t) = term::stdout() {
584 t.reset().unwrap_or(());
588 fn read_config(filename: &Path) -> Config {
589 let sig_comments = read_significant_comments(filename);
590 // Look for a config file. If there is a 'config' property in the significant comments, use
591 // that. Otherwise, if there are no significant comments at all, look for a config file with
592 // the same name as the test file.
593 let mut config = if !sig_comments.is_empty() {
594 get_config(sig_comments.get("config").map(Path::new))
596 get_config(filename.with_extension("toml").file_name().map(Path::new))
599 for (key, val) in &sig_comments {
600 if key != "target" && key != "config" && key != "unstable" {
601 config.override_value(key, val);
602 if config.is_default(key) {
603 warn!("Default value {} used explicitly for {}", val, key);
608 // Don't generate warnings for to-do items.
609 config.set().report_todo(ReportTactic::Never);
614 fn format_file<P: Into<PathBuf>>(filepath: P, config: Config) -> (bool, SourceFile, FormatReport) {
615 let filepath = filepath.into();
616 let input = Input::File(filepath);
617 let mut session = Session::<io::Stdout>::new(config, None);
618 let result = session.format(input).unwrap();
619 let parsing_errors = session.has_parsing_errors();
620 let mut source_file = SourceFile::new();
621 mem::swap(&mut session.source_file, &mut source_file);
622 (parsing_errors, source_file, result)
625 enum IdempotentCheckError {
626 Mismatch(HashMap<PathBuf, Vec<Mismatch>>),
632 opt_config: &Option<PathBuf>,
633 ) -> Result<FormatReport, IdempotentCheckError> {
634 let sig_comments = read_significant_comments(filename);
635 let config = if let Some(ref config_file_path) = opt_config {
636 Config::from_toml_path(config_file_path).expect("`rustfmt.toml` not found")
638 read_config(filename)
640 let (parsing_errors, source_file, format_report) = format_file(filename, config);
642 return Err(IdempotentCheckError::Parse);
645 let mut write_result = HashMap::new();
646 for (filename, text) in source_file {
647 if let FileName::Real(ref filename) = filename {
648 write_result.insert(filename.to_owned(), text);
652 let target = sig_comments.get("target").map(|x| &(*x)[..]);
654 handle_result(write_result, target).map(|_| format_report)
657 // Reads test config file using the supplied (optional) file name. If there's no file name or the
658 // file doesn't exist, just return the default config. Otherwise, the file must be read
660 fn get_config(config_file: Option<&Path>) -> Config {
661 let config_file_name = match config_file {
662 None => return Default::default(),
664 let mut full_path = PathBuf::from("tests/config/");
665 full_path.push(file_name);
666 if !full_path.exists() {
667 return Default::default();
673 let mut def_config_file = fs::File::open(config_file_name).expect("couldn't open config");
674 let mut def_config = String::new();
676 .read_to_string(&mut def_config)
677 .expect("Couldn't read config");
679 Config::from_toml(&def_config, Path::new("tests/config/")).expect("invalid TOML")
682 // Reads significant comments of the form: `// rustfmt-key: value` into a hash map.
683 fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
684 let file = fs::File::open(file_name)
685 .unwrap_or_else(|_| panic!("couldn't read file {}", file_name.display()));
686 let reader = BufReader::new(file);
687 let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
688 let regex = regex::Regex::new(pattern).expect("failed creating pattern 1");
690 // Matches lines containing significant comments or whitespace.
691 let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
692 .expect("failed creating pattern 2");
696 .map(|line| line.expect("failed getting line"))
697 .take_while(|line| line_regex.is_match(line))
699 regex.captures_iter(&line).next().map(|capture| {
703 .expect("couldn't unwrap capture")
708 .expect("couldn't unwrap capture")
717 // Compares output to input.
718 // TODO: needs a better name, more explanation.
720 result: HashMap<PathBuf, String>,
721 target: Option<&str>,
722 ) -> Result<(), IdempotentCheckError> {
723 let mut failures = HashMap::new();
725 for (file_name, fmt_text) in result {
726 // If file is in tests/source, compare to file with same name in tests/target.
727 let target = get_target(&file_name, target);
728 let open_error = format!("couldn't open target {:?}", target);
729 let mut f = fs::File::open(&target).expect(&open_error);
731 let mut text = String::new();
732 let read_error = format!("failed reading target {:?}", target);
733 f.read_to_string(&mut text).expect(&read_error);
735 // Ignore LF and CRLF difference for Windows.
736 if !string_eq_ignore_newline_repr(&fmt_text, &text) {
737 let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
740 "Empty diff? Maybe due to a missing a newline at the end of a file?"
742 failures.insert(file_name, diff);
746 if failures.is_empty() {
749 Err(IdempotentCheckError::Mismatch(failures))
753 // Maps source file paths to their target paths.
754 fn get_target(file_name: &Path, target: Option<&str>) -> PathBuf {
755 if let Some(n) = file_name
757 .position(|c| c.as_os_str() == "source")
759 let mut target_file_name = PathBuf::new();
760 for (i, c) in file_name.components().enumerate() {
762 target_file_name.push("target");
764 target_file_name.push(c.as_os_str());
767 if let Some(replace_name) = target {
768 target_file_name.with_file_name(replace_name)
773 // This is either and idempotence check or a self check.
779 fn rustfmt_diff_make_diff_tests() {
781 let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
788 DiffLine::Context("a".into()),
789 DiffLine::Resulting("b".into()),
790 DiffLine::Expected("e".into()),
791 DiffLine::Context("c".into()),
792 DiffLine::Context("d".into()),
799 fn rustfmt_diff_no_diff_test() {
801 let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
802 assert_eq!(diff, vec![]);
805 // Compare strings without distinguishing between CRLF and LF
806 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
807 let left = CharsIgnoreNewlineRepr(left.chars().peekable());
808 let right = CharsIgnoreNewlineRepr(right.chars().peekable());
812 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
814 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
817 fn next(&mut self) -> Option<char> {
818 self.0.next().map(|c| {
820 if *self.0.peek().unwrap_or(&'\0') == '\n' {
834 fn string_eq_ignore_newline_repr_test() {
836 assert!(string_eq_ignore_newline_repr("", ""));
837 assert!(!string_eq_ignore_newline_repr("", "abc"));
838 assert!(!string_eq_ignore_newline_repr("abc", ""));
839 assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
840 assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
841 assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));
848 fn make_temp_file(file_name: &'static str) -> TempFile {
852 // Used in the Rust build system.
853 let target_dir = var("RUSTFMT_TEST_DIR").unwrap_or_else(|_| ".".to_owned());
854 let path = Path::new(&target_dir).join(file_name);
856 let mut file = File::create(&path).expect("couldn't create temp file");
857 let content = "fn main() {}\n";
858 file.write_all(content.as_bytes())
859 .expect("couldn't write temp file");
863 impl Drop for TempFile {
865 use std::fs::remove_file;
866 remove_file(&self.path).expect("couldn't delete temp file");
870 fn rustfmt() -> PathBuf {
871 let mut me = env::current_exe().expect("failed to get current executable");
872 // Chop of the test name.
877 // If we run `cargo test --release`, we might only have a release build.
885 me.is_file() || me.with_extension("exe").is_file(),
888 "no rustfmt bin, try running `cargo build --release` before testing"
890 "no rustfmt bin, try running `cargo build` before testing"
897 fn verify_check_works() {
899 let temp_file = make_temp_file("temp_check.rs");
901 Command::new(rustfmt().to_str().unwrap())
903 .arg(temp_file.path.to_str().unwrap())
905 .expect("run with check option failed");