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 use rustfmt_config_proc_macro::nightly_only_test;
20 mod configuration_snippet;
24 const DIFF_CONTEXT_SIZE: usize = 3;
26 // A list of files on which we want to skip testing.
27 const SKIP_FILE_WHITE_LIST: &[&str] = &[
28 // We want to make sure that the `skip_children` is correctly working,
29 // so we do not want to test this file directly.
30 "configs/skip_children/foo/mod.rs",
31 "issue-3434/no_entry.rs",
32 "issue-3665/sub_mod.rs",
33 // Testing for issue-3779
35 // These files and directory are a part of modules defined inside `cfg_if!`.
41 // These files and directory are a part of modules defined inside `cfg_attr(..)`.
50 let _ = env_logger::builder().is_test(true).try_init();
54 /// The size of the stack of the thread that run tests.
58 impl Default for TestSetting {
59 fn default() -> Self {
61 stack_size: 8_388_608, // 8MB
66 fn run_test_with<F>(test_setting: &TestSetting, f: F)
71 thread::Builder::new()
72 .stack_size(test_setting.stack_size)
74 .expect("Failed to create a test thread")
76 .expect("Failed to join a test thread")
79 fn is_subpath<P>(path: &Path, subpath: &P) -> bool
83 (0..path.components().count())
87 .take(subpath.as_ref().components().count())
89 .any(|c| c.zip(subpath.as_ref().components()).all(|(a, b)| a == b))
92 fn is_file_skip(path: &Path) -> bool {
95 .any(|file_path| is_subpath(path, file_path))
98 // Returns a `Vec` containing `PathBuf`s of files with an `rs` extension in the
99 // given path. The `recursive` argument controls if files from subdirectories
100 // are also returned.
101 fn get_test_files(path: &Path, recursive: bool) -> Vec<PathBuf> {
102 let mut files = vec![];
104 for entry in fs::read_dir(path).expect(&format!(
105 "couldn't read directory {}",
106 path.to_str().unwrap()
108 let entry = entry.expect("couldn't get `DirEntry`");
109 let path = entry.path();
110 if path.is_dir() && recursive {
111 files.append(&mut get_test_files(&path, recursive));
112 } else if path.extension().map_or(false, |f| f == "rs") && !is_file_skip(&path) {
120 fn verify_config_used(path: &Path, config_name: &str) {
121 for entry in fs::read_dir(path).expect(&format!(
122 "couldn't read {} directory",
123 path.to_str().unwrap()
125 let entry = entry.expect("couldn't get directory entry");
126 let path = entry.path();
127 if path.extension().map_or(false, |f| f == "rs") {
128 // check if "// rustfmt-<config_name>:" appears in the file.
129 let filebuf = BufReader::new(
130 fs::File::open(&path)
131 .unwrap_or_else(|_| panic!("couldn't read file {}", path.display())),
137 .take_while(|l| l.starts_with("//"))
138 .any(|l| l.starts_with(&format!("// rustfmt-{}", config_name))),
139 "config option file {} does not contain expected config name",
147 fn verify_config_test_names() {
150 Path::new("tests/source/configs"),
151 Path::new("tests/target/configs"),
153 for entry in fs::read_dir(path).expect("couldn't read configs directory") {
154 let entry = entry.expect("couldn't get directory entry");
155 let path = entry.path();
157 let config_name = path.file_name().unwrap().to_str().unwrap();
159 // Make sure that config name is used in the files in the directory.
160 verify_config_used(&path, config_name);
166 // This writes to the terminal using the same approach (via `term::stdout` or
167 // `println!`) that is used by `rustfmt::rustfmt_diff::print_diff`. Writing
168 // using only one or the other will cause the output order to differ when
169 // `print_diff` selects the approach not used.
170 fn write_message(msg: &str) {
171 let mut writer = OutputWriter::new(Color::Auto);
172 writer.writeln(msg, None);
175 // Integration tests. The files in `tests/source` are formatted and compared
176 // to their equivalent in `tests/target`. The target file and config can be
177 // overridden by annotations in the source file. The input and output must match
182 run_test_with(&TestSetting::default(), || {
183 // Get all files in the tests/source directory.
184 let files = get_test_files(Path::new("tests/source"), true);
185 let (_reports, count, fails) = check_files(files, &None);
188 println!("Ran {} system tests.", count);
189 assert_eq!(fails, 0, "{} system tests failed", fails);
192 "Expected a minimum of {} system tests to be executed",
198 // Do the same for tests/coverage-source directory.
199 // The only difference is the coverage mode.
201 fn coverage_tests() {
203 let files = get_test_files(Path::new("tests/coverage/source"), true);
204 let (_reports, count, fails) = check_files(files, &None);
206 println!("Ran {} tests in coverage mode.", count);
207 assert_eq!(fails, 0, "{} tests failed", fails);
211 fn checkstyle_test() {
213 let filename = "tests/writemode/source/fn-single-line.rs";
214 let expected_filename = "tests/writemode/target/checkstyle.xml";
215 assert_output(Path::new(filename), Path::new(expected_filename));
221 let filename = "tests/writemode/source/json.rs";
222 let expected_filename = "tests/writemode/target/output.json";
223 assert_output(Path::new(filename), Path::new(expected_filename));
229 use std::io::BufRead;
231 // Test "modified" output
232 let filename = "tests/writemode/source/modified.rs";
233 let mut data = Vec::new();
234 let mut config = Config::default();
237 .emit_mode(crate::config::EmitMode::ModifiedLines);
240 let mut session = Session::new(config, Some(&mut data));
241 session.format(Input::File(filename.into())).unwrap();
244 let mut lines = data.lines();
245 let mut chunks = Vec::new();
246 while let Some(Ok(header)) = lines.next() {
247 // Parse the header line
248 let values: Vec<_> = header
250 .map(|s| s.parse::<u32>().unwrap())
252 assert_eq!(values.len(), 3);
253 let line_number_orig = values[0];
254 let lines_removed = values[1];
255 let num_added = values[2];
256 let mut added_lines = Vec::new();
257 for _ in 0..num_added {
258 added_lines.push(lines.next().unwrap().unwrap());
260 chunks.push(ModifiedChunk {
273 lines: vec!["fn blah() {}".into()],
278 lines: vec!["#[cfg(a, b)]".into(), "fn main() {}".into()],
284 // Helper function for comparing the results of rustfmt
285 // to a known output file generated by one of the write modes.
286 fn assert_output(source: &Path, expected_filename: &Path) {
287 let config = read_config(source);
288 let (_, source_file, _) = format_file(source, config.clone());
290 // Populate output by writing to a vec.
291 let mut out = vec![];
292 let _ = source_file::write_all_files(&source_file, &mut out, &config);
293 let output = String::from_utf8(out).unwrap();
295 let mut expected_file = fs::File::open(&expected_filename).expect("couldn't open target");
296 let mut expected_text = String::new();
298 .read_to_string(&mut expected_text)
299 .expect("Failed reading target");
301 let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
302 if !compare.is_empty() {
303 let mut failures = HashMap::new();
304 failures.insert(source.to_owned(), compare);
305 print_mismatches_default_message(failures);
306 panic!("Text does not match expected output");
310 // Helper function for comparing the results of rustfmt
311 // to a known output generated by one of the write modes.
312 fn assert_stdin_output(
314 expected_filename: &Path,
318 let mut config = Config::default();
319 config.set().newline_style(NewlineStyle::Unix);
320 config.set().emit_mode(emit_mode);
322 let mut source_file = fs::File::open(&source).expect("couldn't open source");
323 let mut source_text = String::new();
325 .read_to_string(&mut source_text)
326 .expect("Failed reading target");
327 let input = Input::Text(source_text);
329 // Populate output by writing to a vec.
330 let mut buf: Vec<u8> = vec![];
332 let mut session = Session::new(config, Some(&mut buf));
333 session.format(input).unwrap();
334 let errors = ReportedErrors {
338 assert_eq!(session.errors, errors);
341 let mut expected_file = fs::File::open(&expected_filename).expect("couldn't open target");
342 let mut expected_text = String::new();
344 .read_to_string(&mut expected_text)
345 .expect("Failed reading target");
347 let output = String::from_utf8(buf).unwrap();
348 let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
349 if !compare.is_empty() {
350 let mut failures = HashMap::new();
351 failures.insert(source.to_owned(), compare);
352 print_mismatches_default_message(failures);
353 panic!("Text does not match expected output");
356 // Idempotence tests. Files in tests/target are checked to be unaltered by
360 fn idempotence_tests() {
362 run_test_with(&TestSetting::default(), || {
363 // Get all files in the tests/target directory.
364 let files = get_test_files(Path::new("tests/target"), true);
365 let (_reports, count, fails) = check_files(files, &None);
368 println!("Ran {} idempotent tests.", count);
369 assert_eq!(fails, 0, "{} idempotent tests failed", fails);
372 "Expected a minimum of {} idempotent tests to be executed",
378 // Run rustfmt on itself. This operation must be idempotent. We also check that
379 // no warnings are emitted.
380 // Issue-3443: these tests require nightly
385 let mut files = get_test_files(Path::new("tests"), false);
386 let bin_directories = vec!["cargo-fmt", "git-rustfmt", "bin", "format-diff"];
387 for dir in bin_directories {
388 let mut path = PathBuf::from("src");
390 path.push("main.rs");
393 files.push(PathBuf::from("src/lib.rs"));
395 let (reports, count, fails) = check_files(files, &Some(PathBuf::from("rustfmt.toml")));
396 let mut warnings = 0;
399 println!("Ran {} self tests.", count);
400 assert_eq!(fails, 0, "{} self tests failed", fails);
402 for format_report in reports {
405 FormatReportFormatterBuilder::new(&format_report).build()
407 warnings += format_report.warning_count();
412 "Rustfmt's code generated {} warnings",
418 fn format_files_find_new_files_via_cfg_if() {
420 run_test_with(&TestSetting::default(), || {
421 // To repro issue-4656, it is necessary that these files are parsed
422 // as a part of the same session (hence this separate test runner).
424 Path::new("tests/source/issue-4656/lib2.rs"),
425 Path::new("tests/source/issue-4656/lib.rs"),
428 let config = Config::default();
429 let mut session = Session::<io::Stdout>::new(config, None);
431 let mut write_result = HashMap::new();
433 assert!(file.exists());
434 let result = session.format(Input::File(file.into())).unwrap();
435 assert!(!session.has_formatting_errors());
436 assert!(!result.has_warnings());
437 let mut source_file = SourceFile::new();
438 mem::swap(&mut session.source_file, &mut source_file);
440 for (filename, text) in source_file {
441 if let FileName::Real(ref filename) = filename {
442 write_result.insert(filename.to_owned(), text);
449 "Should have uncovered an extra file (format_me_please.rs) via lib.rs"
451 assert!(handle_result(write_result, None).is_ok());
456 fn stdin_formatting_smoke_test() {
458 let input = Input::Text("fn main () {}".to_owned());
459 let mut config = Config::default();
460 config.set().emit_mode(EmitMode::Stdout);
461 let mut buf: Vec<u8> = vec![];
463 let mut session = Session::new(config, Some(&mut buf));
464 session.format(input).unwrap();
465 assert!(session.has_no_errors());
469 assert_eq!(buf, "stdin:\n\nfn main() {}\n".as_bytes());
471 assert_eq!(buf, "stdin:\n\nfn main() {}\r\n".as_bytes());
475 fn stdin_parser_panic_caught() {
478 for text in ["{", "}"].iter().cloned().map(String::from) {
479 let mut buf = vec![];
480 let mut session = Session::new(Default::default(), Some(&mut buf));
481 let _ = session.format(Input::Text(text));
483 assert!(session.has_parsing_errors());
487 /// Ensures that `EmitMode::ModifiedLines` works with input from `stdin`. Useful
488 /// when embedding Rustfmt (e.g. inside RLS).
490 fn stdin_works_with_modified_lines() {
492 let input = "\nfn\n some( )\n{\n}\nfn main () {}\n";
493 let output = "1 6 2\nfn some() {}\nfn main() {}\n";
495 let input = Input::Text(input.to_owned());
496 let mut config = Config::default();
497 config.set().newline_style(NewlineStyle::Unix);
498 config.set().emit_mode(EmitMode::ModifiedLines);
499 let mut buf: Vec<u8> = vec![];
501 let mut session = Session::new(config, Some(&mut buf));
502 session.format(input).unwrap();
503 let errors = ReportedErrors {
507 assert_eq!(session.errors, errors);
509 assert_eq!(buf, output.as_bytes());
512 /// Ensures that `EmitMode::Json` works with input from `stdin`.
514 fn stdin_works_with_json() {
517 Path::new("tests/writemode/source/stdin.rs"),
518 Path::new("tests/writemode/target/stdin.json"),
524 /// Ensures that `EmitMode::Checkstyle` works with input from `stdin`.
526 fn stdin_works_with_checkstyle() {
529 Path::new("tests/writemode/source/stdin.rs"),
530 Path::new("tests/writemode/target/stdin.xml"),
531 EmitMode::Checkstyle,
537 fn stdin_disable_all_formatting_test() {
539 let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
540 let mut child = Command::new(rustfmt().to_str().unwrap())
541 .stdin(Stdio::piped())
542 .stdout(Stdio::piped())
543 .arg("--config-path=./tests/config/disable_all_formatting.toml")
545 .expect("failed to execute child");
548 let stdin = child.stdin.as_mut().expect("failed to get stdin");
550 .write_all(input.as_bytes())
551 .expect("failed to write stdin");
554 let output = child.wait_with_output().expect("failed to wait on child");
555 assert!(output.status.success());
556 assert!(output.stderr.is_empty());
557 assert_eq!(input, String::from_utf8(output.stdout).unwrap());
561 fn format_lines_errors_are_reported() {
563 let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
564 let input = Input::Text(format!("fn {}() {{}}", long_identifier));
565 let mut config = Config::default();
566 config.set().error_on_line_overflow(true);
567 let mut session = Session::<io::Stdout>::new(config, None);
568 session.format(input).unwrap();
569 assert!(session.has_formatting_errors());
573 fn format_lines_errors_are_reported_with_tabs() {
575 let long_identifier = String::from_utf8(vec![b'a'; 97]).unwrap();
576 let input = Input::Text(format!("fn a() {{\n\t{}\n}}", long_identifier));
577 let mut config = Config::default();
578 config.set().error_on_line_overflow(true);
579 config.set().hard_tabs(true);
580 let mut session = Session::<io::Stdout>::new(config, None);
581 session.format(input).unwrap();
582 assert!(session.has_formatting_errors());
585 // For each file, run rustfmt and collect the output.
586 // Returns the number of files checked and the number of failures.
587 fn check_files(files: Vec<PathBuf>, opt_config: &Option<PathBuf>) -> (Vec<FormatReport>, u32, u32) {
590 let mut reports = vec![];
592 for file_name in files {
593 let sig_comments = read_significant_comments(&file_name);
594 if sig_comments.contains_key("unstable") && !is_nightly_channel!() {
596 "Skipping '{}' because it requires unstable \
597 features which are only available on nightly...",
603 debug!("Testing '{}'...", file_name.display());
605 match idempotent_check(&file_name, opt_config) {
606 Ok(ref report) if report.has_warnings() => {
607 print!("{}", FormatReportFormatterBuilder::new(report).build());
610 Ok(report) => reports.push(report),
612 if let IdempotentCheckError::Mismatch(msg) = err {
613 print_mismatches_default_message(msg);
622 (reports, count, fails)
625 fn print_mismatches_default_message(result: HashMap<PathBuf, Vec<Mismatch>>) {
626 for (file_name, diff) in result {
627 let mismatch_msg_formatter =
628 |line_num| format!("\nMismatch at {}:{}:", file_name.display(), line_num);
629 print_diff(diff, &mismatch_msg_formatter, &Default::default());
632 if let Some(mut t) = term::stdout() {
633 t.reset().unwrap_or(());
637 fn print_mismatches<T: Fn(u32) -> String>(
638 result: HashMap<PathBuf, Vec<Mismatch>>,
639 mismatch_msg_formatter: T,
641 for (_file_name, diff) in result {
642 print_diff(diff, &mismatch_msg_formatter, &Default::default());
645 if let Some(mut t) = term::stdout() {
646 t.reset().unwrap_or(());
650 fn read_config(filename: &Path) -> Config {
651 let sig_comments = read_significant_comments(filename);
652 // Look for a config file. If there is a 'config' property in the significant comments, use
653 // that. Otherwise, if there are no significant comments at all, look for a config file with
654 // the same name as the test file.
655 let mut config = if !sig_comments.is_empty() {
656 get_config(sig_comments.get("config").map(Path::new))
658 get_config(filename.with_extension("toml").file_name().map(Path::new))
661 for (key, val) in &sig_comments {
662 if key != "target" && key != "config" && key != "unstable" {
663 config.override_value(key, val);
664 if config.is_default(key) {
665 warn!("Default value {} used explicitly for {}", val, key);
670 // Don't generate warnings for to-do items.
671 config.set().report_todo(ReportTactic::Never);
676 fn format_file<P: Into<PathBuf>>(filepath: P, config: Config) -> (bool, SourceFile, FormatReport) {
677 let filepath = filepath.into();
678 let input = Input::File(filepath);
679 let mut session = Session::<io::Stdout>::new(config, None);
680 let result = session.format(input).unwrap();
681 let parsing_errors = session.has_parsing_errors();
682 let mut source_file = SourceFile::new();
683 mem::swap(&mut session.source_file, &mut source_file);
684 (parsing_errors, source_file, result)
687 enum IdempotentCheckError {
688 Mismatch(HashMap<PathBuf, Vec<Mismatch>>),
694 opt_config: &Option<PathBuf>,
695 ) -> Result<FormatReport, IdempotentCheckError> {
696 let sig_comments = read_significant_comments(filename);
697 let config = if let Some(ref config_file_path) = opt_config {
698 Config::from_toml_path(config_file_path).expect("`rustfmt.toml` not found")
700 read_config(filename)
702 let (parsing_errors, source_file, format_report) = format_file(filename, config);
704 return Err(IdempotentCheckError::Parse);
707 let mut write_result = HashMap::new();
708 for (filename, text) in source_file {
709 if let FileName::Real(ref filename) = filename {
710 write_result.insert(filename.to_owned(), text);
714 let target = sig_comments.get("target").map(|x| &(*x)[..]);
716 handle_result(write_result, target).map(|_| format_report)
719 // Reads test config file using the supplied (optional) file name. If there's no file name or the
720 // file doesn't exist, just return the default config. Otherwise, the file must be read
722 fn get_config(config_file: Option<&Path>) -> Config {
723 let config_file_name = match config_file {
724 None => return Default::default(),
726 let mut full_path = PathBuf::from("tests/config/");
727 full_path.push(file_name);
728 if !full_path.exists() {
729 return Default::default();
735 let mut def_config_file = fs::File::open(config_file_name).expect("couldn't open config");
736 let mut def_config = String::new();
738 .read_to_string(&mut def_config)
739 .expect("Couldn't read config");
741 Config::from_toml(&def_config, Path::new("tests/config/")).expect("invalid TOML")
744 // Reads significant comments of the form: `// rustfmt-key: value` into a hash map.
745 fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
746 let file = fs::File::open(file_name)
747 .unwrap_or_else(|_| panic!("couldn't read file {}", file_name.display()));
748 let reader = BufReader::new(file);
749 let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
750 let regex = regex::Regex::new(pattern).expect("failed creating pattern 1");
752 // Matches lines containing significant comments or whitespace.
753 let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
754 .expect("failed creating pattern 2");
758 .map(|line| line.expect("failed getting line"))
759 .filter(|line| line_regex.is_match(line))
761 regex.captures_iter(&line).next().map(|capture| {
765 .expect("couldn't unwrap capture")
770 .expect("couldn't unwrap capture")
779 // Compares output to input.
780 // TODO: needs a better name, more explanation.
782 result: HashMap<PathBuf, String>,
783 target: Option<&str>,
784 ) -> Result<(), IdempotentCheckError> {
785 let mut failures = HashMap::new();
787 for (file_name, fmt_text) in result {
788 // If file is in tests/source, compare to file with same name in tests/target.
789 let target = get_target(&file_name, target);
790 let open_error = format!("couldn't open target {:?}", target);
791 let mut f = fs::File::open(&target).expect(&open_error);
793 let mut text = String::new();
794 let read_error = format!("failed reading target {:?}", target);
795 f.read_to_string(&mut text).expect(&read_error);
797 // Ignore LF and CRLF difference for Windows.
798 if !string_eq_ignore_newline_repr(&fmt_text, &text) {
799 let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
802 "Empty diff? Maybe due to a missing a newline at the end of a file?"
804 failures.insert(file_name, diff);
808 if failures.is_empty() {
811 Err(IdempotentCheckError::Mismatch(failures))
815 // Maps source file paths to their target paths.
816 fn get_target(file_name: &Path, target: Option<&str>) -> PathBuf {
817 if let Some(n) = file_name
819 .position(|c| c.as_os_str() == "source")
821 let mut target_file_name = PathBuf::new();
822 for (i, c) in file_name.components().enumerate() {
824 target_file_name.push("target");
826 target_file_name.push(c.as_os_str());
829 if let Some(replace_name) = target {
830 target_file_name.with_file_name(replace_name)
835 // This is either and idempotence check or a self check.
841 fn rustfmt_diff_make_diff_tests() {
843 let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
850 DiffLine::Context("a".into()),
851 DiffLine::Resulting("b".into()),
852 DiffLine::Expected("e".into()),
853 DiffLine::Context("c".into()),
854 DiffLine::Context("d".into()),
861 fn rustfmt_diff_no_diff_test() {
863 let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
864 assert_eq!(diff, vec![]);
867 // Compare strings without distinguishing between CRLF and LF
868 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
869 let left = CharsIgnoreNewlineRepr(left.chars().peekable());
870 let right = CharsIgnoreNewlineRepr(right.chars().peekable());
874 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
876 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
879 fn next(&mut self) -> Option<char> {
880 self.0.next().map(|c| {
882 if *self.0.peek().unwrap_or(&'\0') == '\n' {
896 fn string_eq_ignore_newline_repr_test() {
898 assert!(string_eq_ignore_newline_repr("", ""));
899 assert!(!string_eq_ignore_newline_repr("", "abc"));
900 assert!(!string_eq_ignore_newline_repr("abc", ""));
901 assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
902 assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
903 assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));
910 fn make_temp_file(file_name: &'static str) -> TempFile {
914 // Used in the Rust build system.
915 let target_dir = var("RUSTFMT_TEST_DIR").unwrap_or_else(|_| ".".to_owned());
916 let path = Path::new(&target_dir).join(file_name);
918 let mut file = File::create(&path).expect("couldn't create temp file");
919 let content = "fn main() {}\n";
920 file.write_all(content.as_bytes())
921 .expect("couldn't write temp file");
925 impl Drop for TempFile {
927 use std::fs::remove_file;
928 remove_file(&self.path).expect("couldn't delete temp file");
932 fn rustfmt() -> PathBuf {
933 let mut me = env::current_exe().expect("failed to get current executable");
934 // Chop of the test name.
939 // If we run `cargo test --release`, we might only have a release build.
947 me.is_file() || me.with_extension("exe").is_file(),
950 "no rustfmt bin, try running `cargo build --release` before testing"
952 "no rustfmt bin, try running `cargo build` before testing"
959 fn verify_check_works() {
961 let temp_file = make_temp_file("temp_check.rs");
963 Command::new(rustfmt().to_str().unwrap())
965 .arg(temp_file.path.to_str().unwrap())
967 .expect("run with check option failed");
971 fn verify_check_works_with_stdin() {
974 let mut child = Command::new(rustfmt().to_str().unwrap())
976 .stdin(Stdio::piped())
977 .stderr(Stdio::piped())
979 .expect("run with check option failed");
982 let stdin = child.stdin.as_mut().expect("Failed to open stdin");
984 .write_all("fn main() {}\n".as_bytes())
985 .expect("Failed to write to rustfmt --check");
989 .expect("Failed to wait on rustfmt child");
990 assert!(output.status.success());