]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/src/test/mod.rs
Added docs to internal_macro const
[rust.git] / src / tools / rustfmt / src / test / mod.rs
1 use std::collections::HashMap;
2 use std::env;
3 use std::fs;
4 use std::io::{self, BufRead, BufReader, Read, Write};
5 use std::iter::Peekable;
6 use std::mem;
7 use std::path::{Path, PathBuf};
8 use std::process::{Command, Stdio};
9 use std::str::Chars;
10 use std::thread;
11
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};
17
18 mod configuration_snippet;
19 mod mod_resolver;
20 mod parser;
21
22 const DIFF_CONTEXT_SIZE: usize = 3;
23
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
32     "issue-3779/ice.rs",
33     // These files and directory are a part of modules defined inside `cfg_if!`.
34     "cfg_if/mod.rs",
35     "cfg_if/detect",
36     "issue-3253/foo.rs",
37     "issue-3253/bar.rs",
38     "issue-3253/paths",
39     // These files and directory are a part of modules defined inside `cfg_attr(..)`.
40     "cfg_mod/dir",
41     "cfg_mod/bar.rs",
42     "cfg_mod/foo.rs",
43     "cfg_mod/wasm32.rs",
44     "skip/foo.rs",
45 ];
46
47 fn init_log() {
48     let _ = env_logger::builder().is_test(true).try_init();
49 }
50
51 struct TestSetting {
52     /// The size of the stack of the thread that run tests.
53     stack_size: usize,
54 }
55
56 impl Default for TestSetting {
57     fn default() -> Self {
58         TestSetting {
59             stack_size: 8_388_608, // 8MB
60         }
61     }
62 }
63
64 fn run_test_with<F>(test_setting: &TestSetting, f: F)
65 where
66     F: FnOnce(),
67     F: Send + 'static,
68 {
69     thread::Builder::new()
70         .stack_size(test_setting.stack_size)
71         .spawn(f)
72         .expect("Failed to create a test thread")
73         .join()
74         .expect("Failed to join a test thread")
75 }
76
77 fn is_subpath<P>(path: &Path, subpath: &P) -> bool
78 where
79     P: AsRef<Path>,
80 {
81     (0..path.components().count())
82         .map(|i| {
83             path.components()
84                 .skip(i)
85                 .take(subpath.as_ref().components().count())
86         })
87         .any(|c| c.zip(subpath.as_ref().components()).all(|(a, b)| a == b))
88 }
89
90 fn is_file_skip(path: &Path) -> bool {
91     SKIP_FILE_WHITE_LIST
92         .iter()
93         .any(|file_path| is_subpath(path, file_path))
94 }
95
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
98 // are also returned.
99 fn get_test_files(path: &Path, recursive: bool) -> Vec<PathBuf> {
100     let mut files = vec![];
101     if path.is_dir() {
102         for entry in fs::read_dir(path).expect(&format!(
103             "couldn't read directory {}",
104             path.to_str().unwrap()
105         )) {
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) {
111                 files.push(path);
112             }
113         }
114     }
115     files
116 }
117
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()
122     )) {
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())),
130             );
131             assert!(
132                 filebuf
133                     .lines()
134                     .map(Result::unwrap)
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",
138                 path.display()
139             );
140         }
141     }
142 }
143
144 #[test]
145 fn verify_config_test_names() {
146     init_log();
147     for path in &[
148         Path::new("tests/source/configs"),
149         Path::new("tests/target/configs"),
150     ] {
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();
154             if path.is_dir() {
155                 let config_name = path.file_name().unwrap().to_str().unwrap();
156
157                 // Make sure that config name is used in the files in the directory.
158                 verify_config_used(&path, config_name);
159             }
160         }
161     }
162 }
163
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);
171 }
172
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
176 // exactly.
177 #[test]
178 fn system_tests() {
179     init_log();
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);
184
185         // Display results.
186         println!("Ran {} system tests.", count);
187         assert_eq!(fails, 0, "{} system tests failed", fails);
188         assert!(
189             count >= 300,
190             "Expected a minimum of {} system tests to be executed",
191             300
192         )
193     });
194 }
195
196 // Do the same for tests/coverage-source directory.
197 // The only difference is the coverage mode.
198 #[test]
199 fn coverage_tests() {
200     init_log();
201     let files = get_test_files(Path::new("tests/coverage/source"), true);
202     let (_reports, count, fails) = check_files(files, &None);
203
204     println!("Ran {} tests in coverage mode.", count);
205     assert_eq!(fails, 0, "{} tests failed", fails);
206 }
207
208 #[test]
209 fn checkstyle_test() {
210     init_log();
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));
214 }
215
216 #[test]
217 fn json_test() {
218     init_log();
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));
222 }
223
224 #[test]
225 fn modified_test() {
226     init_log();
227     use std::io::BufRead;
228
229     // Test "modified" output
230     let filename = "tests/writemode/source/modified.rs";
231     let mut data = Vec::new();
232     let mut config = Config::default();
233     config
234         .set()
235         .emit_mode(crate::config::EmitMode::ModifiedLines);
236
237     {
238         let mut session = Session::new(config, Some(&mut data));
239         session.format(Input::File(filename.into())).unwrap();
240     }
241
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
247             .split(' ')
248             .map(|s| s.parse::<u32>().unwrap())
249             .collect();
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());
257         }
258         chunks.push(ModifiedChunk {
259             line_number_orig,
260             lines_removed,
261             lines: added_lines,
262         });
263     }
264
265     assert_eq!(
266         chunks,
267         vec![
268             ModifiedChunk {
269                 line_number_orig: 4,
270                 lines_removed: 4,
271                 lines: vec!["fn blah() {}".into()],
272             },
273             ModifiedChunk {
274                 line_number_orig: 9,
275                 lines_removed: 6,
276                 lines: vec!["#[cfg(a, b)]".into(), "fn main() {}".into()],
277             },
278         ],
279     );
280 }
281
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());
287
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();
292
293     let mut expected_file = fs::File::open(&expected_filename).expect("couldn't open target");
294     let mut expected_text = String::new();
295     expected_file
296         .read_to_string(&mut expected_text)
297         .expect("Failed reading target");
298
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");
305     }
306 }
307
308 // Idempotence tests. Files in tests/target are checked to be unaltered by
309 // rustfmt.
310 #[test]
311 fn idempotence_tests() {
312     init_log();
313     run_test_with(&TestSetting::default(), || {
314         // these tests require nightly
315         if !is_nightly_channel!() {
316             return;
317         }
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);
321
322         // Display results.
323         println!("Ran {} idempotent tests.", count);
324         assert_eq!(fails, 0, "{} idempotent tests failed", fails);
325         assert!(
326             count >= 400,
327             "Expected a minimum of {} idempotent tests to be executed",
328             400
329         )
330     });
331 }
332
333 // Run rustfmt on itself. This operation must be idempotent. We also check that
334 // no warnings are emitted.
335 #[test]
336 fn self_tests() {
337     init_log();
338     // Issue-3443: these tests require nightly
339     if !is_nightly_channel!() {
340         return;
341     }
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");
346         path.push(dir);
347         path.push("main.rs");
348         files.push(path);
349     }
350     files.push(PathBuf::from("src/lib.rs"));
351
352     let (reports, count, fails) = check_files(files, &Some(PathBuf::from("rustfmt.toml")));
353     let mut warnings = 0;
354
355     // Display results.
356     println!("Ran {} self tests.", count);
357     assert_eq!(fails, 0, "{} self tests failed", fails);
358
359     for format_report in reports {
360         println!(
361             "{}",
362             FormatReportFormatterBuilder::new(&format_report).build()
363         );
364         warnings += format_report.warning_count();
365     }
366
367     assert_eq!(
368         warnings, 0,
369         "Rustfmt's code generated {} warnings",
370         warnings
371     );
372 }
373
374 #[test]
375 fn format_files_find_new_files_via_cfg_if() {
376     init_log();
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).
380         let files = vec![
381             Path::new("tests/source/issue-4656/lib2.rs"),
382             Path::new("tests/source/issue-4656/lib.rs"),
383         ];
384
385         let config = Config::default();
386         let mut session = Session::<io::Stdout>::new(config, None);
387
388         let mut write_result = HashMap::new();
389         for file in files {
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);
396
397             for (filename, text) in source_file {
398                 if let FileName::Real(ref filename) = filename {
399                     write_result.insert(filename.to_owned(), text);
400                 }
401             }
402         }
403         assert_eq!(
404             3,
405             write_result.len(),
406             "Should have uncovered an extra file (format_me_please.rs) via lib.rs"
407         );
408         assert!(handle_result(write_result, None).is_ok());
409     });
410 }
411
412 #[test]
413 fn stdin_formatting_smoke_test() {
414     init_log();
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![];
419     {
420         let mut session = Session::new(config, Some(&mut buf));
421         session.format(input).unwrap();
422         assert!(session.has_no_errors());
423     }
424
425     #[cfg(not(windows))]
426     assert_eq!(buf, "stdin:\n\nfn main() {}\n".as_bytes());
427     #[cfg(windows)]
428     assert_eq!(buf, "stdin:\n\nfn main() {}\r\n".as_bytes());
429 }
430
431 #[test]
432 fn stdin_parser_panic_caught() {
433     init_log();
434     // See issue #3239.
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));
439
440         assert!(session.has_parsing_errors());
441     }
442 }
443
444 /// Ensures that `EmitMode::ModifiedLines` works with input from `stdin`. Useful
445 /// when embedding Rustfmt (e.g. inside RLS).
446 #[test]
447 fn stdin_works_with_modified_lines() {
448     init_log();
449     let input = "\nfn\n some( )\n{\n}\nfn main () {}\n";
450     let output = "1 6 2\nfn some() {}\nfn main() {}\n";
451
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![];
457     {
458         let mut session = Session::new(config, Some(&mut buf));
459         session.format(input).unwrap();
460         let errors = ReportedErrors {
461             has_diff: true,
462             ..Default::default()
463         };
464         assert_eq!(session.errors, errors);
465     }
466     assert_eq!(buf, output.as_bytes());
467 }
468
469 #[test]
470 fn stdin_disable_all_formatting_test() {
471     init_log();
472     match option_env!("CFG_RELEASE_CHANNEL") {
473         None | Some("nightly") => {}
474         // These tests require nightly.
475         _ => return,
476     }
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")
482         .spawn()
483         .expect("failed to execute child");
484
485     {
486         let stdin = child.stdin.as_mut().expect("failed to get stdin");
487         stdin
488             .write_all(input.as_bytes())
489             .expect("failed to write stdin");
490     }
491
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());
496 }
497
498 #[test]
499 fn format_lines_errors_are_reported() {
500     init_log();
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());
508 }
509
510 #[test]
511 fn format_lines_errors_are_reported_with_tabs() {
512     init_log();
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());
521 }
522
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) {
526     let mut count = 0;
527     let mut fails = 0;
528     let mut reports = vec![];
529
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!() {
533             debug!(
534                 "Skipping '{}' because it requires unstable \
535                  features which are only available on nightly...",
536                 file_name.display()
537             );
538             continue;
539         }
540
541         debug!("Testing '{}'...", file_name.display());
542
543         match idempotent_check(&file_name, &opt_config) {
544             Ok(ref report) if report.has_warnings() => {
545                 print!("{}", FormatReportFormatterBuilder::new(&report).build());
546                 fails += 1;
547             }
548             Ok(report) => reports.push(report),
549             Err(err) => {
550                 if let IdempotentCheckError::Mismatch(msg) = err {
551                     print_mismatches_default_message(msg);
552                 }
553                 fails += 1;
554             }
555         }
556
557         count += 1;
558     }
559
560     (reports, count, fails)
561 }
562
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());
568     }
569
570     if let Some(mut t) = term::stdout() {
571         t.reset().unwrap_or(());
572     }
573 }
574
575 fn print_mismatches<T: Fn(u32) -> String>(
576     result: HashMap<PathBuf, Vec<Mismatch>>,
577     mismatch_msg_formatter: T,
578 ) {
579     for (_file_name, diff) in result {
580         print_diff(diff, &mismatch_msg_formatter, &Default::default());
581     }
582
583     if let Some(mut t) = term::stdout() {
584         t.reset().unwrap_or(());
585     }
586 }
587
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))
595     } else {
596         get_config(filename.with_extension("toml").file_name().map(Path::new))
597     };
598
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);
604             }
605         }
606     }
607
608     // Don't generate warnings for to-do items.
609     config.set().report_todo(ReportTactic::Never);
610
611     config
612 }
613
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)
623 }
624
625 enum IdempotentCheckError {
626     Mismatch(HashMap<PathBuf, Vec<Mismatch>>),
627     Parse,
628 }
629
630 fn idempotent_check(
631     filename: &PathBuf,
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")
637     } else {
638         read_config(filename)
639     };
640     let (parsing_errors, source_file, format_report) = format_file(filename, config);
641     if parsing_errors {
642         return Err(IdempotentCheckError::Parse);
643     }
644
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);
649         }
650     }
651
652     let target = sig_comments.get("target").map(|x| &(*x)[..]);
653
654     handle_result(write_result, target).map(|_| format_report)
655 }
656
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
659 // successfully.
660 fn get_config(config_file: Option<&Path>) -> Config {
661     let config_file_name = match config_file {
662         None => return Default::default(),
663         Some(file_name) => {
664             let mut full_path = PathBuf::from("tests/config/");
665             full_path.push(file_name);
666             if !full_path.exists() {
667                 return Default::default();
668             };
669             full_path
670         }
671     };
672
673     let mut def_config_file = fs::File::open(config_file_name).expect("couldn't open config");
674     let mut def_config = String::new();
675     def_config_file
676         .read_to_string(&mut def_config)
677         .expect("Couldn't read config");
678
679     Config::from_toml(&def_config, Path::new("tests/config/")).expect("invalid TOML")
680 }
681
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");
689
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");
693
694     reader
695         .lines()
696         .map(|line| line.expect("failed getting line"))
697         .take_while(|line| line_regex.is_match(line))
698         .filter_map(|line| {
699             regex.captures_iter(&line).next().map(|capture| {
700                 (
701                     capture
702                         .get(1)
703                         .expect("couldn't unwrap capture")
704                         .as_str()
705                         .to_owned(),
706                     capture
707                         .get(2)
708                         .expect("couldn't unwrap capture")
709                         .as_str()
710                         .to_owned(),
711                 )
712             })
713         })
714         .collect()
715 }
716
717 // Compares output to input.
718 // TODO: needs a better name, more explanation.
719 fn handle_result(
720     result: HashMap<PathBuf, String>,
721     target: Option<&str>,
722 ) -> Result<(), IdempotentCheckError> {
723     let mut failures = HashMap::new();
724
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);
730
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);
734
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);
738             assert!(
739                 !diff.is_empty(),
740                 "Empty diff? Maybe due to a missing a newline at the end of a file?"
741             );
742             failures.insert(file_name, diff);
743         }
744     }
745
746     if failures.is_empty() {
747         Ok(())
748     } else {
749         Err(IdempotentCheckError::Mismatch(failures))
750     }
751 }
752
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
756         .components()
757         .position(|c| c.as_os_str() == "source")
758     {
759         let mut target_file_name = PathBuf::new();
760         for (i, c) in file_name.components().enumerate() {
761             if i == n {
762                 target_file_name.push("target");
763             } else {
764                 target_file_name.push(c.as_os_str());
765             }
766         }
767         if let Some(replace_name) = target {
768             target_file_name.with_file_name(replace_name)
769         } else {
770             target_file_name
771         }
772     } else {
773         // This is either and idempotence check or a self check.
774         file_name.to_owned()
775     }
776 }
777
778 #[test]
779 fn rustfmt_diff_make_diff_tests() {
780     init_log();
781     let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
782     assert_eq!(
783         diff,
784         vec![Mismatch {
785             line_number: 1,
786             line_number_orig: 1,
787             lines: vec![
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()),
793             ],
794         }]
795     );
796 }
797
798 #[test]
799 fn rustfmt_diff_no_diff_test() {
800     init_log();
801     let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
802     assert_eq!(diff, vec![]);
803 }
804
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());
809     left.eq(right)
810 }
811
812 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
813
814 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
815     type Item = char;
816
817     fn next(&mut self) -> Option<char> {
818         self.0.next().map(|c| {
819             if c == '\r' {
820                 if *self.0.peek().unwrap_or(&'\0') == '\n' {
821                     self.0.next();
822                     '\n'
823                 } else {
824                     '\r'
825                 }
826             } else {
827                 c
828             }
829         })
830     }
831 }
832
833 #[test]
834 fn string_eq_ignore_newline_repr_test() {
835     init_log();
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"));
842 }
843
844 struct TempFile {
845     path: PathBuf,
846 }
847
848 fn make_temp_file(file_name: &'static str) -> TempFile {
849     use std::env::var;
850     use std::fs::File;
851
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);
855
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");
860     TempFile { path }
861 }
862
863 impl Drop for TempFile {
864     fn drop(&mut self) {
865         use std::fs::remove_file;
866         remove_file(&self.path).expect("couldn't delete temp file");
867     }
868 }
869
870 fn rustfmt() -> PathBuf {
871     let mut me = env::current_exe().expect("failed to get current executable");
872     // Chop of the test name.
873     me.pop();
874     // Chop off `deps`.
875     me.pop();
876
877     // If we run `cargo test --release`, we might only have a release build.
878     if cfg!(release) {
879         // `../release/`
880         me.pop();
881         me.push("release");
882     }
883     me.push("rustfmt");
884     assert!(
885         me.is_file() || me.with_extension("exe").is_file(),
886         "{}",
887         if cfg!(release) {
888             "no rustfmt bin, try running `cargo build --release` before testing"
889         } else {
890             "no rustfmt bin, try running `cargo build` before testing"
891         }
892     );
893     me
894 }
895
896 #[test]
897 fn verify_check_works() {
898     init_log();
899     let temp_file = make_temp_file("temp_check.rs");
900
901     Command::new(rustfmt().to_str().unwrap())
902         .arg("--check")
903         .arg(temp_file.path.to_str().unwrap())
904         .status()
905         .expect("run with check option failed");
906 }