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