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 stdin_generated_files_issue_5172() {
563 let input = Input::Text("//@generated\nfn main() {}".to_owned());
564 let mut config = Config::default();
565 config.set().emit_mode(EmitMode::Stdout);
566 config.set().format_generated_files(false);
567 config.set().newline_style(NewlineStyle::Unix);
568 let mut buf: Vec<u8> = vec![];
570 let mut session = Session::new(config, Some(&mut buf));
571 session.format(input).unwrap();
572 assert!(session.has_no_errors());
574 // N.B. this should be changed once `format_generated_files` is supported with stdin
576 String::from_utf8(buf).unwrap(),
577 "<stdin>:\n\n//@generated\nfn main() {}\n",
582 fn format_lines_errors_are_reported() {
584 let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
585 let input = Input::Text(format!("fn {}() {{}}", long_identifier));
586 let mut config = Config::default();
587 config.set().error_on_line_overflow(true);
588 let mut session = Session::<io::Stdout>::new(config, None);
589 session.format(input).unwrap();
590 assert!(session.has_formatting_errors());
594 fn format_lines_errors_are_reported_with_tabs() {
596 let long_identifier = String::from_utf8(vec![b'a'; 97]).unwrap();
597 let input = Input::Text(format!("fn a() {{\n\t{}\n}}", long_identifier));
598 let mut config = Config::default();
599 config.set().error_on_line_overflow(true);
600 config.set().hard_tabs(true);
601 let mut session = Session::<io::Stdout>::new(config, None);
602 session.format(input).unwrap();
603 assert!(session.has_formatting_errors());
606 // For each file, run rustfmt and collect the output.
607 // Returns the number of files checked and the number of failures.
608 fn check_files(files: Vec<PathBuf>, opt_config: &Option<PathBuf>) -> (Vec<FormatReport>, u32, u32) {
611 let mut reports = vec![];
613 for file_name in files {
614 let sig_comments = read_significant_comments(&file_name);
615 if sig_comments.contains_key("unstable") && !is_nightly_channel!() {
617 "Skipping '{}' because it requires unstable \
618 features which are only available on nightly...",
624 debug!("Testing '{}'...", file_name.display());
626 match idempotent_check(&file_name, opt_config) {
627 Ok(ref report) if report.has_warnings() => {
628 print!("{}", FormatReportFormatterBuilder::new(report).build());
631 Ok(report) => reports.push(report),
633 if let IdempotentCheckError::Mismatch(msg) = err {
634 print_mismatches_default_message(msg);
643 (reports, count, fails)
646 fn print_mismatches_default_message(result: HashMap<PathBuf, Vec<Mismatch>>) {
647 for (file_name, diff) in result {
648 let mismatch_msg_formatter =
649 |line_num| format!("\nMismatch at {}:{}:", file_name.display(), line_num);
650 print_diff(diff, &mismatch_msg_formatter, &Default::default());
653 if let Some(mut t) = term::stdout() {
654 t.reset().unwrap_or(());
658 fn print_mismatches<T: Fn(u32) -> String>(
659 result: HashMap<PathBuf, Vec<Mismatch>>,
660 mismatch_msg_formatter: T,
662 for (_file_name, diff) in result {
663 print_diff(diff, &mismatch_msg_formatter, &Default::default());
666 if let Some(mut t) = term::stdout() {
667 t.reset().unwrap_or(());
671 fn read_config(filename: &Path) -> Config {
672 let sig_comments = read_significant_comments(filename);
673 // Look for a config file. If there is a 'config' property in the significant comments, use
674 // that. Otherwise, if there are no significant comments at all, look for a config file with
675 // the same name as the test file.
676 let mut config = if !sig_comments.is_empty() {
677 get_config(sig_comments.get("config").map(Path::new))
679 get_config(filename.with_extension("toml").file_name().map(Path::new))
682 for (key, val) in &sig_comments {
683 if key != "target" && key != "config" && key != "unstable" {
684 config.override_value(key, val);
685 if config.is_default(key) {
686 warn!("Default value {} used explicitly for {}", val, key);
691 // Don't generate warnings for to-do items.
692 config.set().report_todo(ReportTactic::Never);
697 fn format_file<P: Into<PathBuf>>(filepath: P, config: Config) -> (bool, SourceFile, FormatReport) {
698 let filepath = filepath.into();
699 let input = Input::File(filepath);
700 let mut session = Session::<io::Stdout>::new(config, None);
701 let result = session.format(input).unwrap();
702 let parsing_errors = session.has_parsing_errors();
703 let mut source_file = SourceFile::new();
704 mem::swap(&mut session.source_file, &mut source_file);
705 (parsing_errors, source_file, result)
708 enum IdempotentCheckError {
709 Mismatch(HashMap<PathBuf, Vec<Mismatch>>),
715 opt_config: &Option<PathBuf>,
716 ) -> Result<FormatReport, IdempotentCheckError> {
717 let sig_comments = read_significant_comments(filename);
718 let config = if let Some(ref config_file_path) = opt_config {
719 Config::from_toml_path(config_file_path).expect("`rustfmt.toml` not found")
721 read_config(filename)
723 let (parsing_errors, source_file, format_report) = format_file(filename, config);
725 return Err(IdempotentCheckError::Parse);
728 let mut write_result = HashMap::new();
729 for (filename, text) in source_file {
730 if let FileName::Real(ref filename) = filename {
731 write_result.insert(filename.to_owned(), text);
735 let target = sig_comments.get("target").map(|x| &(*x)[..]);
737 handle_result(write_result, target).map(|_| format_report)
740 // Reads test config file using the supplied (optional) file name. If there's no file name or the
741 // file doesn't exist, just return the default config. Otherwise, the file must be read
743 fn get_config(config_file: Option<&Path>) -> Config {
744 let config_file_name = match config_file {
745 None => return Default::default(),
747 let mut full_path = PathBuf::from("tests/config/");
748 full_path.push(file_name);
749 if !full_path.exists() {
750 return Default::default();
756 let mut def_config_file = fs::File::open(config_file_name).expect("couldn't open config");
757 let mut def_config = String::new();
759 .read_to_string(&mut def_config)
760 .expect("Couldn't read config");
762 Config::from_toml(&def_config, Path::new("tests/config/")).expect("invalid TOML")
765 // Reads significant comments of the form: `// rustfmt-key: value` into a hash map.
766 fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
767 let file = fs::File::open(file_name)
768 .unwrap_or_else(|_| panic!("couldn't read file {}", file_name.display()));
769 let reader = BufReader::new(file);
770 let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
771 let regex = regex::Regex::new(pattern).expect("failed creating pattern 1");
773 // Matches lines containing significant comments or whitespace.
774 let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
775 .expect("failed creating pattern 2");
779 .map(|line| line.expect("failed getting line"))
780 .filter(|line| line_regex.is_match(line))
782 regex.captures_iter(&line).next().map(|capture| {
786 .expect("couldn't unwrap capture")
791 .expect("couldn't unwrap capture")
800 // Compares output to input.
801 // TODO: needs a better name, more explanation.
803 result: HashMap<PathBuf, String>,
804 target: Option<&str>,
805 ) -> Result<(), IdempotentCheckError> {
806 let mut failures = HashMap::new();
808 for (file_name, fmt_text) in result {
809 // If file is in tests/source, compare to file with same name in tests/target.
810 let target = get_target(&file_name, target);
811 let open_error = format!("couldn't open target {:?}", target);
812 let mut f = fs::File::open(&target).expect(&open_error);
814 let mut text = String::new();
815 let read_error = format!("failed reading target {:?}", target);
816 f.read_to_string(&mut text).expect(&read_error);
818 // Ignore LF and CRLF difference for Windows.
819 if !string_eq_ignore_newline_repr(&fmt_text, &text) {
820 let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
823 "Empty diff? Maybe due to a missing a newline at the end of a file?"
825 failures.insert(file_name, diff);
829 if failures.is_empty() {
832 Err(IdempotentCheckError::Mismatch(failures))
836 // Maps source file paths to their target paths.
837 fn get_target(file_name: &Path, target: Option<&str>) -> PathBuf {
838 if let Some(n) = file_name
840 .position(|c| c.as_os_str() == "source")
842 let mut target_file_name = PathBuf::new();
843 for (i, c) in file_name.components().enumerate() {
845 target_file_name.push("target");
847 target_file_name.push(c.as_os_str());
850 if let Some(replace_name) = target {
851 target_file_name.with_file_name(replace_name)
856 // This is either and idempotence check or a self check.
862 fn rustfmt_diff_make_diff_tests() {
864 let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
871 DiffLine::Context("a".into()),
872 DiffLine::Resulting("b".into()),
873 DiffLine::Expected("e".into()),
874 DiffLine::Context("c".into()),
875 DiffLine::Context("d".into()),
882 fn rustfmt_diff_no_diff_test() {
884 let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
885 assert_eq!(diff, vec![]);
888 // Compare strings without distinguishing between CRLF and LF
889 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
890 let left = CharsIgnoreNewlineRepr(left.chars().peekable());
891 let right = CharsIgnoreNewlineRepr(right.chars().peekable());
895 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
897 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
900 fn next(&mut self) -> Option<char> {
901 self.0.next().map(|c| {
903 if *self.0.peek().unwrap_or(&'\0') == '\n' {
917 fn string_eq_ignore_newline_repr_test() {
919 assert!(string_eq_ignore_newline_repr("", ""));
920 assert!(!string_eq_ignore_newline_repr("", "abc"));
921 assert!(!string_eq_ignore_newline_repr("abc", ""));
922 assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
923 assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
924 assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));
931 fn make_temp_file(file_name: &'static str) -> TempFile {
935 // Used in the Rust build system.
936 let target_dir = var("RUSTFMT_TEST_DIR").unwrap_or_else(|_| ".".to_owned());
937 let path = Path::new(&target_dir).join(file_name);
939 let mut file = File::create(&path).expect("couldn't create temp file");
940 let content = "fn main() {}\n";
941 file.write_all(content.as_bytes())
942 .expect("couldn't write temp file");
946 impl Drop for TempFile {
948 use std::fs::remove_file;
949 remove_file(&self.path).expect("couldn't delete temp file");
953 fn rustfmt() -> PathBuf {
954 let mut me = env::current_exe().expect("failed to get current executable");
955 // Chop of the test name.
960 // If we run `cargo test --release`, we might only have a release build.
968 me.is_file() || me.with_extension("exe").is_file(),
971 "no rustfmt bin, try running `cargo build --release` before testing"
973 "no rustfmt bin, try running `cargo build` before testing"
980 fn verify_check_works() {
982 let temp_file = make_temp_file("temp_check.rs");
984 Command::new(rustfmt().to_str().unwrap())
986 .arg(temp_file.path.to_str().unwrap())
988 .expect("run with check option failed");
992 fn verify_check_works_with_stdin() {
995 let mut child = Command::new(rustfmt().to_str().unwrap())
997 .stdin(Stdio::piped())
998 .stderr(Stdio::piped())
1000 .expect("run with check option failed");
1003 let stdin = child.stdin.as_mut().expect("Failed to open stdin");
1005 .write_all("fn main() {}\n".as_bytes())
1006 .expect("Failed to write to rustfmt --check");
1010 .expect("Failed to wait on rustfmt child");
1011 assert!(output.status.success());
1015 fn verify_check_l_works_with_stdin() {
1018 let mut child = Command::new(rustfmt().to_str().unwrap())
1021 .stdin(Stdio::piped())
1022 .stdout(Stdio::piped())
1023 .stderr(Stdio::piped())
1025 .expect("run with check option failed");
1028 let stdin = child.stdin.as_mut().expect("Failed to open stdin");
1030 .write_all("fn main()\n{}\n".as_bytes())
1031 .expect("Failed to write to rustfmt --check");
1035 .expect("Failed to wait on rustfmt child");
1036 assert!(output.status.success());
1037 assert_eq!(std::str::from_utf8(&output.stdout).unwrap(), "<stdin>\n");