]> git.lizzy.rs Git - rust.git/blob - src/test/mod.rs
Merge pull request #2687 from Marwes/issue_2641
[rust.git] / src / test / mod.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 extern crate assert_cli;
12
13 use std::collections::{HashMap, HashSet};
14 use std::env;
15 use std::fs;
16 use std::io::{self, BufRead, BufReader, Read};
17 use std::iter::{Enumerate, Peekable};
18 use std::path::{Path, PathBuf};
19 use std::str::Chars;
20
21 use config::summary::Summary;
22 use config::{Color, Config, ReportTactic};
23 use filemap::write_system_newlines;
24 use rustfmt_diff::*;
25 use *;
26
27 const DIFF_CONTEXT_SIZE: usize = 3;
28 const CONFIGURATIONS_FILE_NAME: &str = "Configurations.md";
29
30 // Returns a `Vec` containing `PathBuf`s of files with a rs extension in the
31 // given path. The `recursive` argument controls if files from subdirectories
32 // are also returned.
33 fn get_test_files(path: &Path, recursive: bool) -> Vec<PathBuf> {
34     let mut files = vec![];
35     if path.is_dir() {
36         for entry in fs::read_dir(path).expect(&format!(
37             "Couldn't read directory {}",
38             path.to_str().unwrap()
39         )) {
40             let entry = entry.expect("Couldn't get DirEntry");
41             let path = entry.path();
42             if path.is_dir() && recursive {
43                 files.append(&mut get_test_files(&path, recursive));
44             } else if path.extension().map_or(false, |f| f == "rs") {
45                 files.push(path);
46             }
47         }
48     }
49     files
50 }
51
52 fn verify_config_used(path: &Path, config_name: &str) {
53     for entry in fs::read_dir(path).expect(&format!(
54         "Couldn't read {} directory",
55         path.to_str().unwrap()
56     )) {
57         let entry = entry.expect("Couldn't get directory entry");
58         let path = entry.path();
59         if path.extension().map_or(false, |f| f == "rs") {
60             // check if "// rustfmt-<config_name>:" appears in the file.
61             let filebuf = BufReader::new(
62                 fs::File::open(&path).expect(&format!("Couldn't read file {}", path.display())),
63             );
64             assert!(
65                 filebuf
66                     .lines()
67                     .map(|l| l.unwrap())
68                     .take_while(|l| l.starts_with("//"))
69                     .any(|l| l.starts_with(&format!("// rustfmt-{}", config_name))),
70                 format!(
71                     "config option file {} does not contain expected config name",
72                     path.display()
73                 )
74             );
75         }
76     }
77 }
78
79 #[test]
80 fn verify_config_test_names() {
81     for path in &[
82         Path::new("tests/source/configs"),
83         Path::new("tests/target/configs"),
84     ] {
85         for entry in fs::read_dir(path).expect("Couldn't read configs directory") {
86             let entry = entry.expect("Couldn't get directory entry");
87             let path = entry.path();
88             if path.is_dir() {
89                 let config_name = path.file_name().unwrap().to_str().unwrap();
90
91                 // Make sure that config name is used in the files in the directory.
92                 verify_config_used(&path, config_name);
93             }
94         }
95     }
96 }
97
98 // This writes to the terminal using the same approach (via term::stdout or
99 // println!) that is used by `rustfmt::rustfmt_diff::print_diff`. Writing
100 // using only one or the other will cause the output order to differ when
101 // `print_diff` selects the approach not used.
102 fn write_message(msg: &str) {
103     let mut writer = OutputWriter::new(Color::Auto);
104     writer.writeln(&format!("{}", msg), None);
105 }
106
107 // Integration tests. The files in the tests/source are formatted and compared
108 // to their equivalent in tests/target. The target file and config can be
109 // overridden by annotations in the source file. The input and output must match
110 // exactly.
111 #[test]
112 fn system_tests() {
113     // Get all files in the tests/source directory.
114     let files = get_test_files(Path::new("tests/source"), true);
115     let (_reports, count, fails) = check_files(files, None);
116
117     // Display results.
118     println!("Ran {} system tests.", count);
119     assert_eq!(fails, 0, "{} system tests failed", fails);
120 }
121
122 // Do the same for tests/coverage-source directory
123 // the only difference is the coverage mode
124 #[test]
125 fn coverage_tests() {
126     let files = get_test_files(Path::new("tests/coverage/source"), true);
127     let (_reports, count, fails) = check_files(files, None);
128
129     println!("Ran {} tests in coverage mode.", count);
130     assert_eq!(fails, 0, "{} tests failed", fails);
131 }
132
133 #[test]
134 fn checkstyle_test() {
135     let filename = "tests/writemode/source/fn-single-line.rs";
136     let expected_filename = "tests/writemode/target/checkstyle.xml";
137     assert_output(Path::new(filename), Path::new(expected_filename));
138 }
139
140 #[test]
141 fn modified_test() {
142     // Test "modified" output
143     let filename = "tests/writemode/source/modified.rs";
144     let result = get_modified_lines(Input::File(filename.into()), &Config::default()).unwrap();
145     assert_eq!(
146         result.modified_lines,
147         ModifiedLines {
148             chunks: vec![
149                 ModifiedChunk {
150                     line_number_orig: 4,
151                     lines_removed: 4,
152                     lines: vec!["fn blah() {}".into()],
153                 },
154                 ModifiedChunk {
155                     line_number_orig: 9,
156                     lines_removed: 6,
157                     lines: vec!["#[cfg(a, b)]".into(), "fn main() {}".into()],
158                 },
159             ],
160         }
161     );
162 }
163
164 // Helper function for comparing the results of rustfmt
165 // to a known output file generated by one of the write modes.
166 fn assert_output(source: &Path, expected_filename: &Path) {
167     let config = read_config(source);
168     let (_error_summary, file_map, _report) = format_file(source, &config);
169
170     // Populate output by writing to a vec.
171     let mut out = vec![];
172     let _ = filemap::write_all_files(&file_map, &mut out, &config);
173     let output = String::from_utf8(out).unwrap();
174
175     let mut expected_file = fs::File::open(&expected_filename).expect("Couldn't open target");
176     let mut expected_text = String::new();
177     expected_file
178         .read_to_string(&mut expected_text)
179         .expect("Failed reading target");
180
181     let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
182     if !compare.is_empty() {
183         let mut failures = HashMap::new();
184         failures.insert(source.to_owned(), compare);
185         print_mismatches_default_message(failures);
186         assert!(false, "Text does not match expected output");
187     }
188 }
189
190 // Idempotence tests. Files in tests/target are checked to be unaltered by
191 // rustfmt.
192 #[test]
193 fn idempotence_tests() {
194     match option_env!("CFG_RELEASE_CHANNEL") {
195         None | Some("nightly") => {}
196         _ => return, // these tests require nightly
197     }
198     // Get all files in the tests/target directory.
199     let files = get_test_files(Path::new("tests/target"), true);
200     let (_reports, count, fails) = check_files(files, None);
201
202     // Display results.
203     println!("Ran {} idempotent tests.", count);
204     assert_eq!(fails, 0, "{} idempotent tests failed", fails);
205 }
206
207 // Run rustfmt on itself. This operation must be idempotent. We also check that
208 // no warnings are emitted.
209 #[test]
210 fn self_tests() {
211     let mut files = get_test_files(Path::new("tests"), false);
212     let bin_directories = vec!["cargo-fmt", "git-rustfmt", "bin", "format-diff"];
213     for dir in bin_directories {
214         let mut path = PathBuf::from("src");
215         path.push(dir);
216         path.push("main.rs");
217         files.push(path);
218     }
219     files.push(PathBuf::from("src/lib.rs"));
220
221     let (reports, count, fails) = check_files(files, Some(PathBuf::from("rustfmt.toml")));
222     let mut warnings = 0;
223
224     // Display results.
225     println!("Ran {} self tests.", count);
226     assert_eq!(fails, 0, "{} self tests failed", fails);
227
228     for format_report in reports {
229         println!("{}", format_report);
230         warnings += format_report.warning_count();
231     }
232
233     assert_eq!(
234         warnings, 0,
235         "Rustfmt's code generated {} warnings",
236         warnings
237     );
238 }
239
240 #[test]
241 fn stdin_formatting_smoke_test() {
242     let input = Input::Text("fn main () {}".to_owned());
243     let config = Config::default();
244     let (error_summary, file_map, _report) =
245         format_input::<io::Stdout>(input, &config, None).unwrap();
246     assert!(error_summary.has_no_errors());
247     for &(ref file_name, ref text) in &file_map {
248         if let FileName::Custom(ref file_name) = *file_name {
249             if file_name == "stdin" {
250                 assert_eq!(text.to_string(), "fn main() {}\n");
251                 return;
252             }
253         }
254     }
255     panic!("no stdin");
256 }
257
258 // FIXME(#1990) restore this test
259 // #[test]
260 // fn stdin_disable_all_formatting_test() {
261 //     let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
262 //     let mut child = Command::new("./target/debug/rustfmt")
263 //         .stdin(Stdio::piped())
264 //         .stdout(Stdio::piped())
265 //         .arg("--config-path=./tests/config/disable_all_formatting.toml")
266 //         .spawn()
267 //         .expect("failed to execute child");
268
269 //     {
270 //         let stdin = child.stdin.as_mut().expect("failed to get stdin");
271 //         stdin
272 //             .write_all(input.as_bytes())
273 //             .expect("failed to write stdin");
274 //     }
275 //     let output = child.wait_with_output().expect("failed to wait on child");
276 //     assert!(output.status.success());
277 //     assert!(output.stderr.is_empty());
278 //     assert_eq!(input, String::from_utf8(output.stdout).unwrap());
279 // }
280
281 #[test]
282 fn format_lines_errors_are_reported() {
283     let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
284     let input = Input::Text(format!("fn {}() {{}}", long_identifier));
285     let mut config = Config::default();
286     config.set().error_on_line_overflow(true);
287     let (error_summary, _file_map, _report) =
288         format_input::<io::Stdout>(input, &config, None).unwrap();
289     assert!(error_summary.has_formatting_errors());
290 }
291
292 #[test]
293 fn format_lines_errors_are_reported_with_tabs() {
294     let long_identifier = String::from_utf8(vec![b'a'; 97]).unwrap();
295     let input = Input::Text(format!("fn a() {{\n\t{}\n}}", long_identifier));
296     let mut config = Config::default();
297     config.set().error_on_line_overflow(true);
298     config.set().hard_tabs(true);
299     let (error_summary, _file_map, _report) =
300         format_input::<io::Stdout>(input, &config, None).unwrap();
301     assert!(error_summary.has_formatting_errors());
302 }
303
304 // For each file, run rustfmt and collect the output.
305 // Returns the number of files checked and the number of failures.
306 fn check_files(files: Vec<PathBuf>, opt_config: Option<PathBuf>) -> (Vec<FormatReport>, u32, u32) {
307     let mut count = 0;
308     let mut fails = 0;
309     let mut reports = vec![];
310
311     for file_name in files {
312         debug!("Testing '{}'...", file_name.display());
313
314         match idempotent_check(&file_name, &opt_config) {
315             Ok(ref report) if report.has_warnings() => {
316                 print!("{}", report);
317                 fails += 1;
318             }
319             Ok(report) => reports.push(report),
320             Err(err) => {
321                 if let IdempotentCheckError::Mismatch(msg) = err {
322                     print_mismatches_default_message(msg);
323                 }
324                 fails += 1;
325             }
326         }
327
328         count += 1;
329     }
330
331     (reports, count, fails)
332 }
333
334 fn print_mismatches_default_message(result: HashMap<PathBuf, Vec<Mismatch>>) {
335     for (file_name, diff) in result {
336         let mismatch_msg_formatter =
337             |line_num| format!("\nMismatch at {}:{}:", file_name.display(), line_num);
338         print_diff(diff, &mismatch_msg_formatter, &Default::default());
339     }
340
341     if let Some(mut t) = term::stdout() {
342         t.reset().unwrap_or(());
343     }
344 }
345
346 fn print_mismatches<T: Fn(u32) -> String>(
347     result: HashMap<PathBuf, Vec<Mismatch>>,
348     mismatch_msg_formatter: T,
349 ) {
350     for (_file_name, diff) in result {
351         print_diff(diff, &mismatch_msg_formatter, &Default::default());
352     }
353
354     if let Some(mut t) = term::stdout() {
355         t.reset().unwrap_or(());
356     }
357 }
358
359 fn read_config(filename: &Path) -> Config {
360     let sig_comments = read_significant_comments(filename);
361     // Look for a config file... If there is a 'config' property in the significant comments, use
362     // that. Otherwise, if there are no significant comments at all, look for a config file with
363     // the same name as the test file.
364     let mut config = if !sig_comments.is_empty() {
365         get_config(sig_comments.get("config").map(Path::new))
366     } else {
367         get_config(filename.with_extension("toml").file_name().map(Path::new))
368     };
369
370     for (key, val) in &sig_comments {
371         if key != "target" && key != "config" {
372             config.override_value(key, val);
373         }
374     }
375
376     // Don't generate warnings for to-do items.
377     config.set().report_todo(ReportTactic::Never);
378
379     config
380 }
381
382 fn format_file<P: Into<PathBuf>>(filepath: P, config: &Config) -> (Summary, FileMap, FormatReport) {
383     let filepath = filepath.into();
384     let input = Input::File(filepath);
385     format_input::<io::Stdout>(input, config, None).unwrap()
386 }
387
388 pub enum IdempotentCheckError {
389     Mismatch(HashMap<PathBuf, Vec<Mismatch>>),
390     Parse,
391 }
392
393 pub fn idempotent_check(
394     filename: &PathBuf,
395     opt_config: &Option<PathBuf>,
396 ) -> Result<FormatReport, IdempotentCheckError> {
397     let sig_comments = read_significant_comments(filename);
398     let config = if let Some(ref config_file_path) = opt_config {
399         Config::from_toml_path(config_file_path).expect("rustfmt.toml not found")
400     } else {
401         read_config(filename)
402     };
403     let (error_summary, file_map, format_report) = format_file(filename, &config);
404     if error_summary.has_parsing_errors() {
405         return Err(IdempotentCheckError::Parse);
406     }
407
408     let mut write_result = HashMap::new();
409     for &(ref filename, ref text) in &file_map {
410         let mut v = Vec::new();
411         // Won't panic, as we're not doing any IO.
412         write_system_newlines(&mut v, text, &config).unwrap();
413         // Won't panic, we are writing correct utf8.
414         let one_result = String::from_utf8(v).unwrap();
415         if let FileName::Real(ref filename) = *filename {
416             write_result.insert(filename.to_owned(), one_result);
417         }
418     }
419
420     let target = sig_comments.get("target").map(|x| &(*x)[..]);
421
422     handle_result(write_result, target).map(|_| format_report)
423 }
424
425 // Reads test config file using the supplied (optional) file name. If there's no file name or the
426 // file doesn't exist, just return the default config. Otherwise, the file must be read
427 // successfully.
428 fn get_config(config_file: Option<&Path>) -> Config {
429     let config_file_name = match config_file {
430         None => return Default::default(),
431         Some(file_name) => {
432             let mut full_path = PathBuf::from("tests/config/");
433             full_path.push(file_name);
434             if !full_path.exists() {
435                 return Default::default();
436             };
437             full_path
438         }
439     };
440
441     let mut def_config_file = fs::File::open(config_file_name).expect("Couldn't open config");
442     let mut def_config = String::new();
443     def_config_file
444         .read_to_string(&mut def_config)
445         .expect("Couldn't read config");
446
447     Config::from_toml(&def_config, Path::new("tests/config/")).expect("Invalid toml")
448 }
449
450 // Reads significant comments of the form: // rustfmt-key: value
451 // into a hash map.
452 fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
453     let file =
454         fs::File::open(file_name).expect(&format!("Couldn't read file {}", file_name.display()));
455     let reader = BufReader::new(file);
456     let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
457     let regex = regex::Regex::new(pattern).expect("Failed creating pattern 1");
458
459     // Matches lines containing significant comments or whitespace.
460     let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
461         .expect("Failed creating pattern 2");
462
463     reader
464         .lines()
465         .map(|line| line.expect("Failed getting line"))
466         .take_while(|line| line_regex.is_match(line))
467         .filter_map(|line| {
468             regex.captures_iter(&line).next().map(|capture| {
469                 (
470                     capture
471                         .get(1)
472                         .expect("Couldn't unwrap capture")
473                         .as_str()
474                         .to_owned(),
475                     capture
476                         .get(2)
477                         .expect("Couldn't unwrap capture")
478                         .as_str()
479                         .to_owned(),
480                 )
481             })
482         })
483         .collect()
484 }
485
486 // Compare output to input.
487 // TODO: needs a better name, more explanation.
488 fn handle_result(
489     result: HashMap<PathBuf, String>,
490     target: Option<&str>,
491 ) -> Result<(), IdempotentCheckError> {
492     let mut failures = HashMap::new();
493
494     for (file_name, fmt_text) in result {
495         // If file is in tests/source, compare to file with same name in tests/target.
496         let target = get_target(&file_name, target);
497         let open_error = format!("Couldn't open target {:?}", &target);
498         let mut f = fs::File::open(&target).expect(&open_error);
499
500         let mut text = String::new();
501         let read_error = format!("Failed reading target {:?}", &target);
502         f.read_to_string(&mut text).expect(&read_error);
503
504         // Ignore LF and CRLF difference for Windows.
505         if !string_eq_ignore_newline_repr(&fmt_text, &text) {
506             let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
507             assert!(
508                 !diff.is_empty(),
509                 "Empty diff? Maybe due to a missing a newline at the end of a file?"
510             );
511             failures.insert(file_name, diff);
512         }
513     }
514
515     if failures.is_empty() {
516         Ok(())
517     } else {
518         Err(IdempotentCheckError::Mismatch(failures))
519     }
520 }
521
522 // Map source file paths to their target paths.
523 fn get_target(file_name: &Path, target: Option<&str>) -> PathBuf {
524     if let Some(n) = file_name
525         .components()
526         .position(|c| c.as_os_str() == "source")
527     {
528         let mut target_file_name = PathBuf::new();
529         for (i, c) in file_name.components().enumerate() {
530             if i == n {
531                 target_file_name.push("target");
532             } else {
533                 target_file_name.push(c.as_os_str());
534             }
535         }
536         if let Some(replace_name) = target {
537             target_file_name.with_file_name(replace_name)
538         } else {
539             target_file_name
540         }
541     } else {
542         // This is either and idempotence check or a self check
543         file_name.to_owned()
544     }
545 }
546
547 #[test]
548 fn rustfmt_diff_make_diff_tests() {
549     let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
550     assert_eq!(
551         diff,
552         vec![Mismatch {
553             line_number: 1,
554             line_number_orig: 1,
555             lines: vec![
556                 DiffLine::Context("a".into()),
557                 DiffLine::Resulting("b".into()),
558                 DiffLine::Expected("e".into()),
559                 DiffLine::Context("c".into()),
560                 DiffLine::Context("d".into()),
561             ],
562         }]
563     );
564 }
565
566 #[test]
567 fn rustfmt_diff_no_diff_test() {
568     let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
569     assert_eq!(diff, vec![]);
570 }
571
572 // Compare strings without distinguishing between CRLF and LF
573 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
574     let left = CharsIgnoreNewlineRepr(left.chars().peekable());
575     let right = CharsIgnoreNewlineRepr(right.chars().peekable());
576     left.eq(right)
577 }
578
579 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
580
581 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
582     type Item = char;
583
584     fn next(&mut self) -> Option<char> {
585         self.0.next().map(|c| {
586             if c == '\r' {
587                 if *self.0.peek().unwrap_or(&'\0') == '\n' {
588                     self.0.next();
589                     '\n'
590                 } else {
591                     '\r'
592                 }
593             } else {
594                 c
595             }
596         })
597     }
598 }
599
600 #[test]
601 fn string_eq_ignore_newline_repr_test() {
602     assert!(string_eq_ignore_newline_repr("", ""));
603     assert!(!string_eq_ignore_newline_repr("", "abc"));
604     assert!(!string_eq_ignore_newline_repr("abc", ""));
605     assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
606     assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
607     assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));
608 }
609
610 // This enum is used to represent one of three text features in Configurations.md: a block of code
611 // with its starting line number, the name of a rustfmt configuration option, or the value of a
612 // rustfmt configuration option.
613 enum ConfigurationSection {
614     CodeBlock((String, u32)), // (String: block of code, u32: line number of code block start)
615     ConfigName(String),
616     ConfigValue(String),
617 }
618
619 impl ConfigurationSection {
620     fn get_section<I: Iterator<Item = String>>(
621         file: &mut Enumerate<I>,
622     ) -> Option<ConfigurationSection> {
623         lazy_static! {
624             static ref CONFIG_NAME_REGEX: regex::Regex =
625                 regex::Regex::new(r"^## `([^`]+)`").expect("Failed creating configuration pattern");
626             static ref CONFIG_VALUE_REGEX: regex::Regex =
627                 regex::Regex::new(r#"^#### `"?([^`"]+)"?`"#)
628                     .expect("Failed creating configuration value pattern");
629         }
630
631         loop {
632             match file.next() {
633                 Some((i, line)) => {
634                     if line.starts_with("```rust") {
635                         // Get the lines of the code block.
636                         let lines: Vec<String> = file
637                             .map(|(_i, l)| l)
638                             .take_while(|l| !l.starts_with("```"))
639                             .collect();
640                         let block = format!("{}\n", lines.join("\n"));
641
642                         // +1 to translate to one-based indexing
643                         // +1 to get to first line of code (line after "```")
644                         let start_line = (i + 2) as u32;
645
646                         return Some(ConfigurationSection::CodeBlock((block, start_line)));
647                     } else if let Some(c) = CONFIG_NAME_REGEX.captures(&line) {
648                         return Some(ConfigurationSection::ConfigName(String::from(&c[1])));
649                     } else if let Some(c) = CONFIG_VALUE_REGEX.captures(&line) {
650                         return Some(ConfigurationSection::ConfigValue(String::from(&c[1])));
651                     }
652                 }
653                 None => return None, // reached the end of the file
654             }
655         }
656     }
657 }
658
659 // This struct stores the information about code blocks in the configurations
660 // file, formats the code blocks, and prints formatting errors.
661 struct ConfigCodeBlock {
662     config_name: Option<String>,
663     config_value: Option<String>,
664     code_block: Option<String>,
665     code_block_start: Option<u32>,
666 }
667
668 impl ConfigCodeBlock {
669     fn new() -> ConfigCodeBlock {
670         ConfigCodeBlock {
671             config_name: None,
672             config_value: None,
673             code_block: None,
674             code_block_start: None,
675         }
676     }
677
678     fn set_config_name(&mut self, name: Option<String>) {
679         self.config_name = name;
680         self.config_value = None;
681     }
682
683     fn set_config_value(&mut self, value: Option<String>) {
684         self.config_value = value;
685     }
686
687     fn set_code_block(&mut self, code_block: String, code_block_start: u32) {
688         self.code_block = Some(code_block);
689         self.code_block_start = Some(code_block_start);
690     }
691
692     fn get_block_config(&self) -> Config {
693         let mut config = Config::default();
694         if self.config_value.is_some() && self.config_value.is_some() {
695             config.override_value(
696                 self.config_name.as_ref().unwrap(),
697                 self.config_value.as_ref().unwrap(),
698             );
699         }
700         config
701     }
702
703     fn code_block_valid(&self) -> bool {
704         // We never expect to not have a code block.
705         assert!(self.code_block.is_some() && self.code_block_start.is_some());
706
707         // See if code block begins with #![rustfmt_skip].
708         let fmt_skip = self
709             .code_block
710             .as_ref()
711             .unwrap()
712             .split('\n')
713             .nth(0)
714             .unwrap_or("") == "#![rustfmt_skip]";
715
716         if self.config_name.is_none() && !fmt_skip {
717             write_message(&format!(
718                 "No configuration name for {}:{}",
719                 CONFIGURATIONS_FILE_NAME,
720                 self.code_block_start.unwrap()
721             ));
722             return false;
723         }
724         if self.config_value.is_none() && !fmt_skip {
725             write_message(&format!(
726                 "No configuration value for {}:{}",
727                 CONFIGURATIONS_FILE_NAME,
728                 self.code_block_start.unwrap()
729             ));
730             return false;
731         }
732         true
733     }
734
735     fn has_parsing_errors(&self, error_summary: Summary) -> bool {
736         if error_summary.has_parsing_errors() {
737             write_message(&format!(
738                 "\u{261d}\u{1f3fd} Cannot format {}:{}",
739                 CONFIGURATIONS_FILE_NAME,
740                 self.code_block_start.unwrap()
741             ));
742             return true;
743         }
744
745         false
746     }
747
748     fn print_diff(&self, compare: Vec<Mismatch>) {
749         let mut mismatches = HashMap::new();
750         mismatches.insert(PathBuf::from(CONFIGURATIONS_FILE_NAME), compare);
751         print_mismatches(mismatches, |line_num| {
752             format!(
753                 "\nMismatch at {}:{}:",
754                 CONFIGURATIONS_FILE_NAME,
755                 line_num + self.code_block_start.unwrap() - 1
756             )
757         });
758     }
759
760     fn formatted_has_diff(&self, file_map: &FileMap) -> bool {
761         let &(ref _file_name, ref text) = file_map.first().unwrap();
762         let compare = make_diff(self.code_block.as_ref().unwrap(), text, DIFF_CONTEXT_SIZE);
763         if !compare.is_empty() {
764             self.print_diff(compare);
765             return true;
766         }
767
768         false
769     }
770
771     // Return a bool indicating if formatting this code block is an idempotent
772     // operation. This function also triggers printing any formatting failure
773     // messages.
774     fn formatted_is_idempotent(&self) -> bool {
775         // Verify that we have all of the expected information.
776         if !self.code_block_valid() {
777             return false;
778         }
779
780         let input = Input::Text(self.code_block.as_ref().unwrap().to_owned());
781         let config = self.get_block_config();
782
783         let (error_summary, file_map, _report) =
784             format_input::<io::Stdout>(input, &config, None).unwrap();
785
786         !self.has_parsing_errors(error_summary) && !self.formatted_has_diff(&file_map)
787     }
788
789     // Extract a code block from the iterator. Behavior:
790     // - Rust code blocks are identifed by lines beginning with "```rust".
791     // - One explicit configuration setting is supported per code block.
792     // - Rust code blocks with no configuration setting are illegal and cause an
793     //   assertion failure, unless the snippet begins with #![rustfmt_skip].
794     // - Configuration names in Configurations.md must be in the form of
795     //   "## `NAME`".
796     // - Configuration values in Configurations.md must be in the form of
797     //   "#### `VALUE`".
798     fn extract<I: Iterator<Item = String>>(
799         file: &mut Enumerate<I>,
800         prev: Option<&ConfigCodeBlock>,
801         hash_set: &mut HashSet<String>,
802     ) -> Option<ConfigCodeBlock> {
803         let mut code_block = ConfigCodeBlock::new();
804         code_block.config_name = prev.and_then(|cb| cb.config_name.clone());
805
806         loop {
807             match ConfigurationSection::get_section(file) {
808                 Some(ConfigurationSection::CodeBlock((block, start_line))) => {
809                     code_block.set_code_block(block, start_line);
810                     break;
811                 }
812                 Some(ConfigurationSection::ConfigName(name)) => {
813                     assert!(
814                         Config::is_valid_name(&name),
815                         "an unknown configuration option was found: {}",
816                         name
817                     );
818                     assert!(
819                         hash_set.remove(&name),
820                         "multiple configuration guides found for option {}",
821                         name
822                     );
823                     code_block.set_config_name(Some(name));
824                 }
825                 Some(ConfigurationSection::ConfigValue(value)) => {
826                     code_block.set_config_value(Some(value));
827                 }
828                 None => return None, // end of file was reached
829             }
830         }
831
832         Some(code_block)
833     }
834 }
835
836 #[test]
837 fn configuration_snippet_tests() {
838     // Read Configurations.md and build a `Vec` of `ConfigCodeBlock` structs with one
839     // entry for each Rust code block found.
840     fn get_code_blocks() -> Vec<ConfigCodeBlock> {
841         let mut file_iter = BufReader::new(
842             fs::File::open(Path::new(CONFIGURATIONS_FILE_NAME))
843                 .expect(&format!("Couldn't read file {}", CONFIGURATIONS_FILE_NAME)),
844         ).lines()
845             .map(|l| l.unwrap())
846             .enumerate();
847         let mut code_blocks: Vec<ConfigCodeBlock> = Vec::new();
848         let mut hash_set = Config::hash_set();
849
850         while let Some(cb) =
851             ConfigCodeBlock::extract(&mut file_iter, code_blocks.last(), &mut hash_set)
852         {
853             code_blocks.push(cb);
854         }
855
856         for name in hash_set {
857             if !Config::is_hidden_option(&name) {
858                 panic!("{} does not have a configuration guide", name);
859             }
860         }
861
862         code_blocks
863     }
864
865     let blocks = get_code_blocks();
866     let failures = blocks
867         .iter()
868         .map(|b| b.formatted_is_idempotent())
869         .fold(0, |acc, r| acc + (!r as u32));
870
871     // Display results.
872     println!("Ran {} configurations tests.", blocks.len());
873     assert_eq!(failures, 0, "{} configurations tests failed", failures);
874 }
875
876 struct TempFile {
877     path: PathBuf,
878 }
879
880 fn make_temp_file(file_name: &'static str) -> TempFile {
881     use std::env::var;
882     use std::fs::File;
883
884     // Used in the Rust build system.
885     let target_dir = var("RUSTFMT_TEST_DIR").unwrap_or_else(|_| ".".to_owned());
886     let path = Path::new(&target_dir).join(file_name);
887
888     let mut file = File::create(&path).expect("Couldn't create temp file");
889     let content = "fn main() {}\n";
890     file.write_all(content.as_bytes())
891         .expect("Couldn't write temp file");
892     TempFile { path }
893 }
894
895 impl Drop for TempFile {
896     fn drop(&mut self) {
897         use std::fs::remove_file;
898         remove_file(&self.path).expect("Couldn't delete temp file");
899     }
900 }
901
902 fn rustfmt() -> PathBuf {
903     let mut me = env::current_exe().expect("failed to get current executable");
904     me.pop(); // chop of the test name
905     me.pop(); // chop off `deps`
906     me.push("rustfmt");
907     return me;
908 }
909
910 #[test]
911 fn verify_check_works() {
912     let temp_file = make_temp_file("temp_check.rs");
913     assert_cli::Assert::command(&[
914         rustfmt().to_str().unwrap(),
915         "--write-mode=check",
916         temp_file.path.to_str().unwrap(),
917     ]).succeeds()
918         .unwrap();
919 }
920
921 #[test]
922 fn verify_diff_works() {
923     let temp_file = make_temp_file("temp_diff.rs");
924     assert_cli::Assert::command(&[
925         rustfmt().to_str().unwrap(),
926         "--write-mode=diff",
927         temp_file.path.to_str().unwrap(),
928     ]).succeeds()
929         .unwrap();
930 }