]> git.lizzy.rs Git - rust.git/blob - src/test/mod.rs
fix formatting mods inside cfg_if macro (#3763)
[rust.git] / 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::is_nightly_channel;
15 use crate::rustfmt_diff::{make_diff, print_diff, DiffLine, Mismatch, ModifiedChunk, OutputWriter};
16 use crate::source_file;
17 use crate::{FormatReport, FormatReportFormatterBuilder, Input, Session};
18
19 mod configuration_snippet;
20
21 const DIFF_CONTEXT_SIZE: usize = 3;
22
23 // A list of files on which we want to skip testing.
24 const SKIP_FILE_WHITE_LIST: &[&str] = &[
25     // We want to make sure that the `skip_children` is correctly working,
26     // so we do not want to test this file directly.
27     "configs/skip_children/foo/mod.rs",
28     "issue-3434/no_entry.rs",
29     "issue-3665/sub_mod.rs",
30     // These files and directory are a part of modules defined inside `cfg_if!`.
31     "cfg_if/mod.rs",
32     "cfg_if/detect",
33     "issue-3253/foo.rs",
34     "issue-3253/bar.rs",
35     "issue-3253/paths",
36     // These files and directory are a part of modules defined inside `cfg_attr(..)`.
37     "cfg_mod/dir",
38     "cfg_mod/bar.rs",
39     "cfg_mod/foo.rs",
40     "cfg_mod/wasm32.rs",
41 ];
42
43 struct TestSetting {
44     /// The size of the stack of the thread that run tests.
45     stack_size: usize,
46 }
47
48 impl Default for TestSetting {
49     fn default() -> Self {
50         TestSetting {
51             stack_size: 8_388_608, // 8MB
52         }
53     }
54 }
55
56 fn run_test_with<F>(test_setting: &TestSetting, f: F)
57 where
58     F: FnOnce(),
59     F: Send + 'static,
60 {
61     thread::Builder::new()
62         .stack_size(test_setting.stack_size)
63         .spawn(f)
64         .expect("Failed to create a test thread")
65         .join()
66         .expect("Failed to join a test thread")
67 }
68
69 fn is_subpath<P>(path: &Path, subpath: &P) -> bool
70 where
71     P: AsRef<Path>,
72 {
73     (0..path.components().count())
74         .map(|i| {
75             path.components()
76                 .skip(i)
77                 .take(subpath.as_ref().components().count())
78         })
79         .any(|c| c.zip(subpath.as_ref().components()).all(|(a, b)| a == b))
80 }
81
82 fn is_file_skip(path: &Path) -> bool {
83     SKIP_FILE_WHITE_LIST
84         .iter()
85         .any(|file_path| is_subpath(path, file_path))
86 }
87
88 // Returns a `Vec` containing `PathBuf`s of files with an  `rs` extension in the
89 // given path. The `recursive` argument controls if files from subdirectories
90 // are also returned.
91 fn get_test_files(path: &Path, recursive: bool) -> Vec<PathBuf> {
92     let mut files = vec![];
93     if path.is_dir() {
94         for entry in fs::read_dir(path).expect(&format!(
95             "couldn't read directory {}",
96             path.to_str().unwrap()
97         )) {
98             let entry = entry.expect("couldn't get `DirEntry`");
99             let path = entry.path();
100             if path.is_dir() && recursive {
101                 files.append(&mut get_test_files(&path, recursive));
102             } else if path.extension().map_or(false, |f| f == "rs") && !is_file_skip(&path) {
103                 files.push(path);
104             }
105         }
106     }
107     files
108 }
109
110 fn verify_config_used(path: &Path, config_name: &str) {
111     for entry in fs::read_dir(path).expect(&format!(
112         "couldn't read {} directory",
113         path.to_str().unwrap()
114     )) {
115         let entry = entry.expect("couldn't get directory entry");
116         let path = entry.path();
117         if path.extension().map_or(false, |f| f == "rs") {
118             // check if "// rustfmt-<config_name>:" appears in the file.
119             let filebuf = BufReader::new(
120                 fs::File::open(&path)
121                     .unwrap_or_else(|_| panic!("couldn't read file {}", path.display())),
122             );
123             assert!(
124                 filebuf
125                     .lines()
126                     .map(Result::unwrap)
127                     .take_while(|l| l.starts_with("//"))
128                     .any(|l| l.starts_with(&format!("// rustfmt-{}", config_name))),
129                 format!(
130                     "config option file {} does not contain expected config name",
131                     path.display()
132                 )
133             );
134         }
135     }
136 }
137
138 #[test]
139 fn verify_config_test_names() {
140     for path in &[
141         Path::new("tests/source/configs"),
142         Path::new("tests/target/configs"),
143     ] {
144         for entry in fs::read_dir(path).expect("couldn't read configs directory") {
145             let entry = entry.expect("couldn't get directory entry");
146             let path = entry.path();
147             if path.is_dir() {
148                 let config_name = path.file_name().unwrap().to_str().unwrap();
149
150                 // Make sure that config name is used in the files in the directory.
151                 verify_config_used(&path, config_name);
152             }
153         }
154     }
155 }
156
157 // This writes to the terminal using the same approach (via `term::stdout` or
158 // `println!`) that is used by `rustfmt::rustfmt_diff::print_diff`. Writing
159 // using only one or the other will cause the output order to differ when
160 // `print_diff` selects the approach not used.
161 fn write_message(msg: &str) {
162     let mut writer = OutputWriter::new(Color::Auto);
163     writer.writeln(msg, None);
164 }
165
166 // Integration tests. The files in `tests/source` are formatted and compared
167 // to their equivalent in `tests/target`. The target file and config can be
168 // overridden by annotations in the source file. The input and output must match
169 // exactly.
170 #[test]
171 fn system_tests() {
172     run_test_with(&TestSetting::default(), || {
173         // Get all files in the tests/source directory.
174         let files = get_test_files(Path::new("tests/source"), true);
175         let (_reports, count, fails) = check_files(files, &None);
176
177         // Display results.
178         println!("Ran {} system tests.", count);
179         assert_eq!(fails, 0, "{} system tests failed", fails);
180         assert!(
181             count >= 300,
182             "Expected a minimum of {} system tests to be executed",
183             300
184         )
185     });
186 }
187
188 // Do the same for tests/coverage-source directory.
189 // The only difference is the coverage mode.
190 #[test]
191 fn coverage_tests() {
192     let files = get_test_files(Path::new("tests/coverage/source"), true);
193     let (_reports, count, fails) = check_files(files, &None);
194
195     println!("Ran {} tests in coverage mode.", count);
196     assert_eq!(fails, 0, "{} tests failed", fails);
197 }
198
199 #[test]
200 fn checkstyle_test() {
201     let filename = "tests/writemode/source/fn-single-line.rs";
202     let expected_filename = "tests/writemode/target/checkstyle.xml";
203     assert_output(Path::new(filename), Path::new(expected_filename));
204 }
205
206 #[test]
207 fn json_test() {
208     let filename = "tests/writemode/source/json.rs";
209     let expected_filename = "tests/writemode/target/output.json";
210     assert_output(Path::new(filename), Path::new(expected_filename));
211 }
212
213 #[test]
214 fn modified_test() {
215     use std::io::BufRead;
216
217     // Test "modified" output
218     let filename = "tests/writemode/source/modified.rs";
219     let mut data = Vec::new();
220     let mut config = Config::default();
221     config
222         .set()
223         .emit_mode(crate::config::EmitMode::ModifiedLines);
224
225     {
226         let mut session = Session::new(config, Some(&mut data));
227         session.format(Input::File(filename.into())).unwrap();
228     }
229
230     let mut lines = data.lines();
231     let mut chunks = Vec::new();
232     while let Some(Ok(header)) = lines.next() {
233         // Parse the header line
234         let values: Vec<_> = header
235             .split(' ')
236             .map(|s| s.parse::<u32>().unwrap())
237             .collect();
238         assert_eq!(values.len(), 3);
239         let line_number_orig = values[0];
240         let lines_removed = values[1];
241         let num_added = values[2];
242         let mut added_lines = Vec::new();
243         for _ in 0..num_added {
244             added_lines.push(lines.next().unwrap().unwrap());
245         }
246         chunks.push(ModifiedChunk {
247             line_number_orig,
248             lines_removed,
249             lines: added_lines,
250         });
251     }
252
253     assert_eq!(
254         chunks,
255         vec![
256             ModifiedChunk {
257                 line_number_orig: 4,
258                 lines_removed: 4,
259                 lines: vec!["fn blah() {}".into()],
260             },
261             ModifiedChunk {
262                 line_number_orig: 9,
263                 lines_removed: 6,
264                 lines: vec!["#[cfg(a, b)]".into(), "fn main() {}".into()],
265             },
266         ],
267     );
268 }
269
270 // Helper function for comparing the results of rustfmt
271 // to a known output file generated by one of the write modes.
272 fn assert_output(source: &Path, expected_filename: &Path) {
273     let config = read_config(source);
274     let (_, source_file, _) = format_file(source, config.clone());
275
276     // Populate output by writing to a vec.
277     let mut out = vec![];
278     let _ = source_file::write_all_files(&source_file, &mut out, &config);
279     let output = String::from_utf8(out).unwrap();
280
281     let mut expected_file = fs::File::open(&expected_filename).expect("couldn't open target");
282     let mut expected_text = String::new();
283     expected_file
284         .read_to_string(&mut expected_text)
285         .expect("Failed reading target");
286
287     let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
288     if !compare.is_empty() {
289         let mut failures = HashMap::new();
290         failures.insert(source.to_owned(), compare);
291         print_mismatches_default_message(failures);
292         panic!("Text does not match expected output");
293     }
294 }
295
296 // Idempotence tests. Files in tests/target are checked to be unaltered by
297 // rustfmt.
298 #[test]
299 fn idempotence_tests() {
300     run_test_with(&TestSetting::default(), || {
301         // these tests require nightly
302         if !is_nightly_channel!() {
303             return;
304         }
305         // Get all files in the tests/target directory.
306         let files = get_test_files(Path::new("tests/target"), true);
307         let (_reports, count, fails) = check_files(files, &None);
308
309         // Display results.
310         println!("Ran {} idempotent tests.", count);
311         assert_eq!(fails, 0, "{} idempotent tests failed", fails);
312         assert!(
313             count >= 400,
314             "Expected a minimum of {} idempotent tests to be executed",
315             400
316         )
317     });
318 }
319
320 // Run rustfmt on itself. This operation must be idempotent. We also check that
321 // no warnings are emitted.
322 #[test]
323 fn self_tests() {
324     // Issue-3443: these tests require nightly
325     if !is_nightly_channel!() {
326         return;
327     }
328     let mut files = get_test_files(Path::new("tests"), false);
329     let bin_directories = vec!["cargo-fmt", "git-rustfmt", "bin", "format-diff"];
330     for dir in bin_directories {
331         let mut path = PathBuf::from("src");
332         path.push(dir);
333         path.push("main.rs");
334         files.push(path);
335     }
336     files.push(PathBuf::from("src/lib.rs"));
337
338     let (reports, count, fails) = check_files(files, &Some(PathBuf::from("rustfmt.toml")));
339     let mut warnings = 0;
340
341     // Display results.
342     println!("Ran {} self tests.", count);
343     assert_eq!(fails, 0, "{} self tests failed", fails);
344
345     for format_report in reports {
346         println!(
347             "{}",
348             FormatReportFormatterBuilder::new(&format_report).build()
349         );
350         warnings += format_report.warning_count();
351     }
352
353     assert_eq!(
354         warnings, 0,
355         "Rustfmt's code generated {} warnings",
356         warnings
357     );
358 }
359
360 #[test]
361 fn stdin_formatting_smoke_test() {
362     let input = Input::Text("fn main () {}".to_owned());
363     let mut config = Config::default();
364     config.set().emit_mode(EmitMode::Stdout);
365     let mut buf: Vec<u8> = vec![];
366     {
367         let mut session = Session::new(config, Some(&mut buf));
368         session.format(input).unwrap();
369         assert!(session.has_no_errors());
370     }
371
372     #[cfg(not(windows))]
373     assert_eq!(buf, "stdin:\n\nfn main() {}\n".as_bytes());
374     #[cfg(windows)]
375     assert_eq!(buf, "stdin:\n\nfn main() {}\r\n".as_bytes());
376 }
377
378 #[test]
379 fn stdin_parser_panic_caught() {
380     // See issue #3239.
381     for text in ["{", "}"].iter().cloned().map(String::from) {
382         let mut buf = vec![];
383         let mut session = Session::new(Default::default(), Some(&mut buf));
384         let _ = session.format(Input::Text(text));
385
386         assert!(session.has_parsing_errors());
387     }
388 }
389
390 /// Ensures that `EmitMode::ModifiedLines` works with input from `stdin`. Useful
391 /// when embedding Rustfmt (e.g. inside RLS).
392 #[test]
393 fn stdin_works_with_modified_lines() {
394     let input = "\nfn\n some( )\n{\n}\nfn main () {}\n";
395     let output = "1 6 2\nfn some() {}\nfn main() {}\n";
396
397     let input = Input::Text(input.to_owned());
398     let mut config = Config::default();
399     config.set().newline_style(NewlineStyle::Unix);
400     config.set().emit_mode(EmitMode::ModifiedLines);
401     let mut buf: Vec<u8> = vec![];
402     {
403         let mut session = Session::new(config, Some(&mut buf));
404         session.format(input).unwrap();
405         let errors = ReportedErrors {
406             has_diff: true,
407             ..Default::default()
408         };
409         assert_eq!(session.errors, errors);
410     }
411     assert_eq!(buf, output.as_bytes());
412 }
413
414 #[test]
415 fn stdin_disable_all_formatting_test() {
416     match option_env!("CFG_RELEASE_CHANNEL") {
417         None | Some("nightly") => {}
418         // These tests require nightly.
419         _ => return,
420     }
421     let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
422     let mut child = Command::new(rustfmt().to_str().unwrap())
423         .stdin(Stdio::piped())
424         .stdout(Stdio::piped())
425         .arg("--config-path=./tests/config/disable_all_formatting.toml")
426         .spawn()
427         .expect("failed to execute child");
428
429     {
430         let stdin = child.stdin.as_mut().expect("failed to get stdin");
431         stdin
432             .write_all(input.as_bytes())
433             .expect("failed to write stdin");
434     }
435
436     let output = child.wait_with_output().expect("failed to wait on child");
437     assert!(output.status.success());
438     assert!(output.stderr.is_empty());
439     assert_eq!(input, String::from_utf8(output.stdout).unwrap());
440 }
441
442 #[test]
443 fn format_lines_errors_are_reported() {
444     let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
445     let input = Input::Text(format!("fn {}() {{}}", long_identifier));
446     let mut config = Config::default();
447     config.set().error_on_line_overflow(true);
448     let mut session = Session::<io::Stdout>::new(config, None);
449     session.format(input).unwrap();
450     assert!(session.has_formatting_errors());
451 }
452
453 #[test]
454 fn format_lines_errors_are_reported_with_tabs() {
455     let long_identifier = String::from_utf8(vec![b'a'; 97]).unwrap();
456     let input = Input::Text(format!("fn a() {{\n\t{}\n}}", long_identifier));
457     let mut config = Config::default();
458     config.set().error_on_line_overflow(true);
459     config.set().hard_tabs(true);
460     let mut session = Session::<io::Stdout>::new(config, None);
461     session.format(input).unwrap();
462     assert!(session.has_formatting_errors());
463 }
464
465 // For each file, run rustfmt and collect the output.
466 // Returns the number of files checked and the number of failures.
467 fn check_files(files: Vec<PathBuf>, opt_config: &Option<PathBuf>) -> (Vec<FormatReport>, u32, u32) {
468     let mut count = 0;
469     let mut fails = 0;
470     let mut reports = vec![];
471
472     for file_name in files {
473         let sig_comments = read_significant_comments(&file_name);
474         if sig_comments.contains_key("unstable") && !is_nightly_channel!() {
475             debug!(
476                 "Skipping '{}' because it requires unstable \
477                  features which are only available on nightly...",
478                 file_name.display()
479             );
480             continue;
481         }
482
483         debug!("Testing '{}'...", file_name.display());
484
485         match idempotent_check(&file_name, &opt_config) {
486             Ok(ref report) if report.has_warnings() => {
487                 print!("{}", FormatReportFormatterBuilder::new(&report).build());
488                 fails += 1;
489             }
490             Ok(report) => reports.push(report),
491             Err(err) => {
492                 if let IdempotentCheckError::Mismatch(msg) = err {
493                     print_mismatches_default_message(msg);
494                 }
495                 fails += 1;
496             }
497         }
498
499         count += 1;
500     }
501
502     (reports, count, fails)
503 }
504
505 fn print_mismatches_default_message(result: HashMap<PathBuf, Vec<Mismatch>>) {
506     for (file_name, diff) in result {
507         let mismatch_msg_formatter =
508             |line_num| format!("\nMismatch at {}:{}:", file_name.display(), line_num);
509         print_diff(diff, &mismatch_msg_formatter, &Default::default());
510     }
511
512     if let Some(mut t) = term::stdout() {
513         t.reset().unwrap_or(());
514     }
515 }
516
517 fn print_mismatches<T: Fn(u32) -> String>(
518     result: HashMap<PathBuf, Vec<Mismatch>>,
519     mismatch_msg_formatter: T,
520 ) {
521     for (_file_name, diff) in result {
522         print_diff(diff, &mismatch_msg_formatter, &Default::default());
523     }
524
525     if let Some(mut t) = term::stdout() {
526         t.reset().unwrap_or(());
527     }
528 }
529
530 fn read_config(filename: &Path) -> Config {
531     let sig_comments = read_significant_comments(filename);
532     // Look for a config file. If there is a 'config' property in the significant comments, use
533     // that. Otherwise, if there are no significant comments at all, look for a config file with
534     // the same name as the test file.
535     let mut config = if !sig_comments.is_empty() {
536         get_config(sig_comments.get("config").map(Path::new))
537     } else {
538         get_config(filename.with_extension("toml").file_name().map(Path::new))
539     };
540
541     for (key, val) in &sig_comments {
542         if key != "target" && key != "config" && key != "unstable" {
543             config.override_value(key, val);
544             if config.is_default(key) {
545                 warn!("Default value {} used explicitly for {}", val, key);
546             }
547         }
548     }
549
550     // Don't generate warnings for to-do items.
551     config.set().report_todo(ReportTactic::Never);
552
553     config
554 }
555
556 fn format_file<P: Into<PathBuf>>(filepath: P, config: Config) -> (bool, SourceFile, FormatReport) {
557     let filepath = filepath.into();
558     let input = Input::File(filepath);
559     let mut session = Session::<io::Stdout>::new(config, None);
560     let result = session.format(input).unwrap();
561     let parsing_errors = session.has_parsing_errors();
562     let mut source_file = SourceFile::new();
563     mem::swap(&mut session.source_file, &mut source_file);
564     (parsing_errors, source_file, result)
565 }
566
567 enum IdempotentCheckError {
568     Mismatch(HashMap<PathBuf, Vec<Mismatch>>),
569     Parse,
570 }
571
572 fn idempotent_check(
573     filename: &PathBuf,
574     opt_config: &Option<PathBuf>,
575 ) -> Result<FormatReport, IdempotentCheckError> {
576     let sig_comments = read_significant_comments(filename);
577     let config = if let Some(ref config_file_path) = opt_config {
578         Config::from_toml_path(config_file_path).expect("`rustfmt.toml` not found")
579     } else {
580         read_config(filename)
581     };
582     let (parsing_errors, source_file, format_report) = format_file(filename, config);
583     if parsing_errors {
584         return Err(IdempotentCheckError::Parse);
585     }
586
587     let mut write_result = HashMap::new();
588     for (filename, text) in source_file {
589         if let FileName::Real(ref filename) = filename {
590             write_result.insert(filename.to_owned(), text);
591         }
592     }
593
594     let target = sig_comments.get("target").map(|x| &(*x)[..]);
595
596     handle_result(write_result, target).map(|_| format_report)
597 }
598
599 // Reads test config file using the supplied (optional) file name. If there's no file name or the
600 // file doesn't exist, just return the default config. Otherwise, the file must be read
601 // successfully.
602 fn get_config(config_file: Option<&Path>) -> Config {
603     let config_file_name = match config_file {
604         None => return Default::default(),
605         Some(file_name) => {
606             let mut full_path = PathBuf::from("tests/config/");
607             full_path.push(file_name);
608             if !full_path.exists() {
609                 return Default::default();
610             };
611             full_path
612         }
613     };
614
615     let mut def_config_file = fs::File::open(config_file_name).expect("couldn't open config");
616     let mut def_config = String::new();
617     def_config_file
618         .read_to_string(&mut def_config)
619         .expect("Couldn't read config");
620
621     Config::from_toml(&def_config, Path::new("tests/config/")).expect("invalid TOML")
622 }
623
624 // Reads significant comments of the form: `// rustfmt-key: value` into a hash map.
625 fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
626     let file = fs::File::open(file_name)
627         .unwrap_or_else(|_| panic!("couldn't read file {}", file_name.display()));
628     let reader = BufReader::new(file);
629     let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
630     let regex = regex::Regex::new(pattern).expect("failed creating pattern 1");
631
632     // Matches lines containing significant comments or whitespace.
633     let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
634         .expect("failed creating pattern 2");
635
636     reader
637         .lines()
638         .map(|line| line.expect("failed getting line"))
639         .take_while(|line| line_regex.is_match(line))
640         .filter_map(|line| {
641             regex.captures_iter(&line).next().map(|capture| {
642                 (
643                     capture
644                         .get(1)
645                         .expect("couldn't unwrap capture")
646                         .as_str()
647                         .to_owned(),
648                     capture
649                         .get(2)
650                         .expect("couldn't unwrap capture")
651                         .as_str()
652                         .to_owned(),
653                 )
654             })
655         })
656         .collect()
657 }
658
659 // Compares output to input.
660 // TODO: needs a better name, more explanation.
661 fn handle_result(
662     result: HashMap<PathBuf, String>,
663     target: Option<&str>,
664 ) -> Result<(), IdempotentCheckError> {
665     let mut failures = HashMap::new();
666
667     for (file_name, fmt_text) in result {
668         // If file is in tests/source, compare to file with same name in tests/target.
669         let target = get_target(&file_name, target);
670         let open_error = format!("couldn't open target {:?}", target);
671         let mut f = fs::File::open(&target).expect(&open_error);
672
673         let mut text = String::new();
674         let read_error = format!("failed reading target {:?}", target);
675         f.read_to_string(&mut text).expect(&read_error);
676
677         // Ignore LF and CRLF difference for Windows.
678         if !string_eq_ignore_newline_repr(&fmt_text, &text) {
679             let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
680             assert!(
681                 !diff.is_empty(),
682                 "Empty diff? Maybe due to a missing a newline at the end of a file?"
683             );
684             failures.insert(file_name, diff);
685         }
686     }
687
688     if failures.is_empty() {
689         Ok(())
690     } else {
691         Err(IdempotentCheckError::Mismatch(failures))
692     }
693 }
694
695 // Maps source file paths to their target paths.
696 fn get_target(file_name: &Path, target: Option<&str>) -> PathBuf {
697     if let Some(n) = file_name
698         .components()
699         .position(|c| c.as_os_str() == "source")
700     {
701         let mut target_file_name = PathBuf::new();
702         for (i, c) in file_name.components().enumerate() {
703             if i == n {
704                 target_file_name.push("target");
705             } else {
706                 target_file_name.push(c.as_os_str());
707             }
708         }
709         if let Some(replace_name) = target {
710             target_file_name.with_file_name(replace_name)
711         } else {
712             target_file_name
713         }
714     } else {
715         // This is either and idempotence check or a self check.
716         file_name.to_owned()
717     }
718 }
719
720 #[test]
721 fn rustfmt_diff_make_diff_tests() {
722     let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
723     assert_eq!(
724         diff,
725         vec![Mismatch {
726             line_number: 1,
727             line_number_orig: 1,
728             lines: vec![
729                 DiffLine::Context("a".into()),
730                 DiffLine::Resulting("b".into()),
731                 DiffLine::Expected("e".into()),
732                 DiffLine::Context("c".into()),
733                 DiffLine::Context("d".into()),
734             ],
735         }]
736     );
737 }
738
739 #[test]
740 fn rustfmt_diff_no_diff_test() {
741     let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
742     assert_eq!(diff, vec![]);
743 }
744
745 // Compare strings without distinguishing between CRLF and LF
746 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
747     let left = CharsIgnoreNewlineRepr(left.chars().peekable());
748     let right = CharsIgnoreNewlineRepr(right.chars().peekable());
749     left.eq(right)
750 }
751
752 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
753
754 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
755     type Item = char;
756
757     fn next(&mut self) -> Option<char> {
758         self.0.next().map(|c| {
759             if c == '\r' {
760                 if *self.0.peek().unwrap_or(&'\0') == '\n' {
761                     self.0.next();
762                     '\n'
763                 } else {
764                     '\r'
765                 }
766             } else {
767                 c
768             }
769         })
770     }
771 }
772
773 #[test]
774 fn string_eq_ignore_newline_repr_test() {
775     assert!(string_eq_ignore_newline_repr("", ""));
776     assert!(!string_eq_ignore_newline_repr("", "abc"));
777     assert!(!string_eq_ignore_newline_repr("abc", ""));
778     assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
779     assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
780     assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));
781 }
782
783 struct TempFile {
784     path: PathBuf,
785 }
786
787 fn make_temp_file(file_name: &'static str) -> TempFile {
788     use std::env::var;
789     use std::fs::File;
790
791     // Used in the Rust build system.
792     let target_dir = var("RUSTFMT_TEST_DIR").unwrap_or_else(|_| ".".to_owned());
793     let path = Path::new(&target_dir).join(file_name);
794
795     let mut file = File::create(&path).expect("couldn't create temp file");
796     let content = "fn main() {}\n";
797     file.write_all(content.as_bytes())
798         .expect("couldn't write temp file");
799     TempFile { path }
800 }
801
802 impl Drop for TempFile {
803     fn drop(&mut self) {
804         use std::fs::remove_file;
805         remove_file(&self.path).expect("couldn't delete temp file");
806     }
807 }
808
809 fn rustfmt() -> PathBuf {
810     let mut me = env::current_exe().expect("failed to get current executable");
811     // Chop of the test name.
812     me.pop();
813     // Chop off `deps`.
814     me.pop();
815
816     // If we run `cargo test --release`, we might only have a release build.
817     if cfg!(release) {
818         // `../release/`
819         me.pop();
820         me.push("release");
821     }
822     me.push("rustfmt");
823     assert!(
824         me.is_file() || me.with_extension("exe").is_file(),
825         if cfg!(release) {
826             "no rustfmt bin, try running `cargo build --release` before testing"
827         } else {
828             "no rustfmt bin, try running `cargo build` before testing"
829         }
830     );
831     me
832 }
833
834 #[test]
835 fn verify_check_works() {
836     let temp_file = make_temp_file("temp_check.rs");
837
838     Command::new(rustfmt().to_str().unwrap())
839         .arg("--check")
840         .arg(temp_file.path.to_str().unwrap())
841         .status()
842         .expect("run with check option failed");
843 }