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.
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.
11 use std::collections::{HashMap, HashSet};
14 use std::io::{self, BufRead, BufReader, Read, Write};
15 use std::iter::{Enumerate, Peekable};
17 use std::path::{Path, PathBuf};
18 use std::process::{Command, Stdio};
21 use config::{Color, Config, EmitMode, FileName, ReportTactic};
22 use formatting::{ModifiedChunk, SourceFile};
23 use rustfmt_diff::{make_diff, print_diff, DiffLine, Mismatch, OutputWriter};
25 use {FormatReport, Input, Session};
27 const DIFF_CONTEXT_SIZE: usize = 3;
28 const CONFIGURATIONS_FILE_NAME: &str = "Configurations.md";
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
33 fn get_test_files(path: &Path, recursive: bool) -> Vec<PathBuf> {
34 let mut files = vec![];
36 for entry in fs::read_dir(path).expect(&format!(
37 "Couldn't read directory {}",
38 path.to_str().unwrap()
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") {
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()
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())),
68 .take_while(|l| l.starts_with("//"))
69 .any(|l| l.starts_with(&format!("// rustfmt-{}", config_name))),
71 "config option file {} does not contain expected config name",
80 fn verify_config_test_names() {
82 Path::new("tests/source/configs"),
83 Path::new("tests/target/configs"),
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();
89 let config_name = path.file_name().unwrap().to_str().unwrap();
91 // Make sure that config name is used in the files in the directory.
92 verify_config_used(&path, config_name);
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(msg, None);
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
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);
118 println!("Ran {} system tests.", count);
119 assert_eq!(fails, 0, "{} system tests failed", fails);
122 // Do the same for tests/coverage-source directory
123 // the only difference is the coverage mode
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);
129 println!("Ran {} tests in coverage mode.", count);
130 assert_eq!(fails, 0, "{} tests failed", fails);
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));
142 use std::io::BufRead;
144 // Test "modified" output
145 let filename = "tests/writemode/source/modified.rs";
146 let mut data = Vec::new();
147 let mut config = Config::default();
148 config.set().emit_mode(::config::EmitMode::ModifiedLines);
151 let mut session = Session::new(config, Some(&mut data));
152 session.format(Input::File(filename.into())).unwrap();
155 let mut lines = data.lines();
156 let mut chunks = Vec::new();
157 while let Some(Ok(header)) = lines.next() {
158 // Parse the header line
159 let values: Vec<_> = header
161 .map(|s| s.parse::<u32>().unwrap())
163 assert_eq!(values.len(), 3);
164 let line_number_orig = values[0];
165 let lines_removed = values[1];
166 let num_added = values[2];
167 let mut added_lines = Vec::new();
168 for _ in 0..num_added {
169 added_lines.push(lines.next().unwrap().unwrap());
171 chunks.push(ModifiedChunk {
184 lines: vec!["fn blah() {}".into()],
189 lines: vec!["#[cfg(a, b)]".into(), "fn main() {}".into()],
195 // Helper function for comparing the results of rustfmt
196 // to a known output file generated by one of the write modes.
197 fn assert_output(source: &Path, expected_filename: &Path) {
198 let config = read_config(source);
199 let (_, source_file, _) = format_file(source, config.clone());
201 // Populate output by writing to a vec.
202 let mut out = vec![];
203 let _ = source_file::write_all_files(&source_file, &mut out, &config);
204 let output = String::from_utf8(out).unwrap();
206 let mut expected_file = fs::File::open(&expected_filename).expect("Couldn't open target");
207 let mut expected_text = String::new();
209 .read_to_string(&mut expected_text)
210 .expect("Failed reading target");
212 let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
213 if !compare.is_empty() {
214 let mut failures = HashMap::new();
215 failures.insert(source.to_owned(), compare);
216 print_mismatches_default_message(failures);
217 assert!(false, "Text does not match expected output");
221 // Idempotence tests. Files in tests/target are checked to be unaltered by
224 fn idempotence_tests() {
225 match option_env!("CFG_RELEASE_CHANNEL") {
226 None | Some("nightly") => {}
227 _ => return, // these tests require nightly
229 // Get all files in the tests/target directory.
230 let files = get_test_files(Path::new("tests/target"), true);
231 let (_reports, count, fails) = check_files(files, &None);
234 println!("Ran {} idempotent tests.", count);
235 assert_eq!(fails, 0, "{} idempotent tests failed", fails);
238 // Run rustfmt on itself. This operation must be idempotent. We also check that
239 // no warnings are emitted.
242 let mut files = get_test_files(Path::new("tests"), false);
243 let bin_directories = vec!["cargo-fmt", "git-rustfmt", "bin", "format-diff"];
244 for dir in bin_directories {
245 let mut path = PathBuf::from("src");
247 path.push("main.rs");
250 files.push(PathBuf::from("src/lib.rs"));
252 let (reports, count, fails) = check_files(files, &Some(PathBuf::from("rustfmt.toml")));
253 let mut warnings = 0;
256 println!("Ran {} self tests.", count);
257 assert_eq!(fails, 0, "{} self tests failed", fails);
259 for format_report in reports {
260 println!("{}", format_report);
261 warnings += format_report.warning_count();
266 "Rustfmt's code generated {} warnings",
272 fn stdin_formatting_smoke_test() {
273 let input = Input::Text("fn main () {}".to_owned());
274 let mut config = Config::default();
275 config.set().emit_mode(EmitMode::Stdout);
276 let mut buf: Vec<u8> = vec![];
278 let mut session = Session::new(config, Some(&mut buf));
279 session.format(input).unwrap();
280 assert!(session.has_no_errors());
284 assert_eq!(buf, "fn main() {}\n".as_bytes());
286 assert_eq!(buf, "fn main() {}\r\n".as_bytes());
290 fn stdin_disable_all_formatting_test() {
291 match option_env!("CFG_RELEASE_CHANNEL") {
292 None | Some("nightly") => {}
293 _ => return, // these tests require nightly
295 let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
296 let mut child = Command::new(rustfmt().to_str().unwrap())
297 .stdin(Stdio::piped())
298 .stdout(Stdio::piped())
299 .arg("--config-path=./tests/config/disable_all_formatting.toml")
301 .expect("failed to execute child");
304 let stdin = child.stdin.as_mut().expect("failed to get stdin");
306 .write_all(input.as_bytes())
307 .expect("failed to write stdin");
310 let output = child.wait_with_output().expect("failed to wait on child");
311 assert!(output.status.success());
312 assert!(output.stderr.is_empty());
313 assert_eq!(input, String::from_utf8(output.stdout).unwrap());
317 fn format_lines_errors_are_reported() {
318 let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
319 let input = Input::Text(format!("fn {}() {{}}", long_identifier));
320 let mut config = Config::default();
321 config.set().error_on_line_overflow(true);
322 let mut session = Session::<io::Stdout>::new(config, None);
323 session.format(input).unwrap();
324 assert!(session.has_formatting_errors());
328 fn format_lines_errors_are_reported_with_tabs() {
329 let long_identifier = String::from_utf8(vec![b'a'; 97]).unwrap();
330 let input = Input::Text(format!("fn a() {{\n\t{}\n}}", long_identifier));
331 let mut config = Config::default();
332 config.set().error_on_line_overflow(true);
333 config.set().hard_tabs(true);
334 let mut session = Session::<io::Stdout>::new(config, None);
335 session.format(input).unwrap();
336 assert!(session.has_formatting_errors());
339 // For each file, run rustfmt and collect the output.
340 // Returns the number of files checked and the number of failures.
341 fn check_files(files: Vec<PathBuf>, opt_config: &Option<PathBuf>) -> (Vec<FormatReport>, u32, u32) {
344 let mut reports = vec![];
346 for file_name in files {
347 debug!("Testing '{}'...", file_name.display());
349 match idempotent_check(&file_name, &opt_config) {
350 Ok(ref report) if report.has_warnings() => {
351 print!("{}", report);
354 Ok(report) => reports.push(report),
356 if let IdempotentCheckError::Mismatch(msg) = err {
357 print_mismatches_default_message(msg);
366 (reports, count, fails)
369 fn print_mismatches_default_message(result: HashMap<PathBuf, Vec<Mismatch>>) {
370 for (file_name, diff) in result {
371 let mismatch_msg_formatter =
372 |line_num| format!("\nMismatch at {}:{}:", file_name.display(), line_num);
373 print_diff(diff, &mismatch_msg_formatter, &Default::default());
376 if let Some(mut t) = term::stdout() {
377 t.reset().unwrap_or(());
381 fn print_mismatches<T: Fn(u32) -> String>(
382 result: HashMap<PathBuf, Vec<Mismatch>>,
383 mismatch_msg_formatter: T,
385 for (_file_name, diff) in result {
386 print_diff(diff, &mismatch_msg_formatter, &Default::default());
389 if let Some(mut t) = term::stdout() {
390 t.reset().unwrap_or(());
394 fn read_config(filename: &Path) -> Config {
395 let sig_comments = read_significant_comments(filename);
396 // Look for a config file... If there is a 'config' property in the significant comments, use
397 // that. Otherwise, if there are no significant comments at all, look for a config file with
398 // the same name as the test file.
399 let mut config = if !sig_comments.is_empty() {
400 get_config(sig_comments.get("config").map(Path::new))
402 get_config(filename.with_extension("toml").file_name().map(Path::new))
405 for (key, val) in &sig_comments {
406 if key != "target" && key != "config" {
407 config.override_value(key, val);
408 if config.is_default(key) {
409 warn!("Default value {} used explicitly for {}", val, key);
414 // Don't generate warnings for to-do items.
415 config.set().report_todo(ReportTactic::Never);
420 fn format_file<P: Into<PathBuf>>(filepath: P, config: Config) -> (bool, SourceFile, FormatReport) {
421 let filepath = filepath.into();
422 let input = Input::File(filepath);
423 let mut session = Session::<io::Stdout>::new(config, None);
424 let result = session.format(input).unwrap();
425 let parsing_errors = session.has_parsing_errors();
426 let mut source_file = SourceFile::new();
427 mem::swap(&mut session.source_file, &mut source_file);
428 (parsing_errors, source_file, result)
431 enum IdempotentCheckError {
432 Mismatch(HashMap<PathBuf, Vec<Mismatch>>),
438 opt_config: &Option<PathBuf>,
439 ) -> Result<FormatReport, IdempotentCheckError> {
440 let sig_comments = read_significant_comments(filename);
441 let config = if let Some(ref config_file_path) = opt_config {
442 Config::from_toml_path(config_file_path).expect("rustfmt.toml not found")
444 read_config(filename)
446 let (parsing_errors, source_file, format_report) = format_file(filename, config);
448 return Err(IdempotentCheckError::Parse);
451 let mut write_result = HashMap::new();
452 for (filename, text) in source_file {
453 if let FileName::Real(ref filename) = filename {
454 write_result.insert(filename.to_owned(), text);
458 let target = sig_comments.get("target").map(|x| &(*x)[..]);
460 handle_result(write_result, target).map(|_| format_report)
463 // Reads test config file using the supplied (optional) file name. If there's no file name or the
464 // file doesn't exist, just return the default config. Otherwise, the file must be read
466 fn get_config(config_file: Option<&Path>) -> Config {
467 let config_file_name = match config_file {
468 None => return Default::default(),
470 let mut full_path = PathBuf::from("tests/config/");
471 full_path.push(file_name);
472 if !full_path.exists() {
473 return Default::default();
479 let mut def_config_file = fs::File::open(config_file_name).expect("Couldn't open config");
480 let mut def_config = String::new();
482 .read_to_string(&mut def_config)
483 .expect("Couldn't read config");
485 Config::from_toml(&def_config, Path::new("tests/config/")).expect("Invalid toml")
488 // Reads significant comments of the form: // rustfmt-key: value
490 fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
492 fs::File::open(file_name).expect(&format!("Couldn't read file {}", file_name.display()));
493 let reader = BufReader::new(file);
494 let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
495 let regex = regex::Regex::new(pattern).expect("Failed creating pattern 1");
497 // Matches lines containing significant comments or whitespace.
498 let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
499 .expect("Failed creating pattern 2");
503 .map(|line| line.expect("Failed getting line"))
504 .take_while(|line| line_regex.is_match(line))
506 regex.captures_iter(&line).next().map(|capture| {
510 .expect("Couldn't unwrap capture")
515 .expect("Couldn't unwrap capture")
524 // Compare output to input.
525 // TODO: needs a better name, more explanation.
527 result: HashMap<PathBuf, String>,
528 target: Option<&str>,
529 ) -> Result<(), IdempotentCheckError> {
530 let mut failures = HashMap::new();
532 for (file_name, fmt_text) in result {
533 // If file is in tests/source, compare to file with same name in tests/target.
534 let target = get_target(&file_name, target);
535 let open_error = format!("Couldn't open target {:?}", &target);
536 let mut f = fs::File::open(&target).expect(&open_error);
538 let mut text = String::new();
539 let read_error = format!("Failed reading target {:?}", &target);
540 f.read_to_string(&mut text).expect(&read_error);
542 // Ignore LF and CRLF difference for Windows.
543 if !string_eq_ignore_newline_repr(&fmt_text, &text) {
544 let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
547 "Empty diff? Maybe due to a missing a newline at the end of a file?"
549 failures.insert(file_name, diff);
553 if failures.is_empty() {
556 Err(IdempotentCheckError::Mismatch(failures))
560 // Map source file paths to their target paths.
561 fn get_target(file_name: &Path, target: Option<&str>) -> PathBuf {
562 if let Some(n) = file_name
564 .position(|c| c.as_os_str() == "source")
566 let mut target_file_name = PathBuf::new();
567 for (i, c) in file_name.components().enumerate() {
569 target_file_name.push("target");
571 target_file_name.push(c.as_os_str());
574 if let Some(replace_name) = target {
575 target_file_name.with_file_name(replace_name)
580 // This is either and idempotence check or a self check
586 fn rustfmt_diff_make_diff_tests() {
587 let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
594 DiffLine::Context("a".into()),
595 DiffLine::Resulting("b".into()),
596 DiffLine::Expected("e".into()),
597 DiffLine::Context("c".into()),
598 DiffLine::Context("d".into()),
605 fn rustfmt_diff_no_diff_test() {
606 let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
607 assert_eq!(diff, vec![]);
610 // Compare strings without distinguishing between CRLF and LF
611 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
612 let left = CharsIgnoreNewlineRepr(left.chars().peekable());
613 let right = CharsIgnoreNewlineRepr(right.chars().peekable());
617 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
619 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
622 fn next(&mut self) -> Option<char> {
623 self.0.next().map(|c| {
625 if *self.0.peek().unwrap_or(&'\0') == '\n' {
639 fn string_eq_ignore_newline_repr_test() {
640 assert!(string_eq_ignore_newline_repr("", ""));
641 assert!(!string_eq_ignore_newline_repr("", "abc"));
642 assert!(!string_eq_ignore_newline_repr("abc", ""));
643 assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
644 assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
645 assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));
648 // This enum is used to represent one of three text features in Configurations.md: a block of code
649 // with its starting line number, the name of a rustfmt configuration option, or the value of a
650 // rustfmt configuration option.
651 enum ConfigurationSection {
652 CodeBlock((String, u32)), // (String: block of code, u32: line number of code block start)
657 impl ConfigurationSection {
658 fn get_section<I: Iterator<Item = String>>(
659 file: &mut Enumerate<I>,
660 ) -> Option<ConfigurationSection> {
662 static ref CONFIG_NAME_REGEX: regex::Regex =
663 regex::Regex::new(r"^## `([^`]+)`").expect("Failed creating configuration pattern");
664 static ref CONFIG_VALUE_REGEX: regex::Regex =
665 regex::Regex::new(r#"^#### `"?([^`"]+)"?`"#)
666 .expect("Failed creating configuration value pattern");
672 if line.starts_with("```rust") {
673 // Get the lines of the code block.
674 let lines: Vec<String> = file
676 .take_while(|l| !l.starts_with("```"))
678 let block = format!("{}\n", lines.join("\n"));
680 // +1 to translate to one-based indexing
681 // +1 to get to first line of code (line after "```")
682 let start_line = (i + 2) as u32;
684 return Some(ConfigurationSection::CodeBlock((block, start_line)));
685 } else if let Some(c) = CONFIG_NAME_REGEX.captures(&line) {
686 return Some(ConfigurationSection::ConfigName(String::from(&c[1])));
687 } else if let Some(c) = CONFIG_VALUE_REGEX.captures(&line) {
688 return Some(ConfigurationSection::ConfigValue(String::from(&c[1])));
691 None => return None, // reached the end of the file
697 // This struct stores the information about code blocks in the configurations
698 // file, formats the code blocks, and prints formatting errors.
699 struct ConfigCodeBlock {
700 config_name: Option<String>,
701 config_value: Option<String>,
702 code_block: Option<String>,
703 code_block_start: Option<u32>,
706 impl ConfigCodeBlock {
707 fn new() -> ConfigCodeBlock {
712 code_block_start: None,
716 fn set_config_name(&mut self, name: Option<String>) {
717 self.config_name = name;
718 self.config_value = None;
721 fn set_config_value(&mut self, value: Option<String>) {
722 self.config_value = value;
725 fn set_code_block(&mut self, code_block: String, code_block_start: u32) {
726 self.code_block = Some(code_block);
727 self.code_block_start = Some(code_block_start);
730 fn get_block_config(&self) -> Config {
731 let mut config = Config::default();
732 if self.config_value.is_some() && self.config_value.is_some() {
733 config.override_value(
734 self.config_name.as_ref().unwrap(),
735 self.config_value.as_ref().unwrap(),
741 fn code_block_valid(&self) -> bool {
742 // We never expect to not have a code block.
743 assert!(self.code_block.is_some() && self.code_block_start.is_some());
745 // See if code block begins with #![rustfmt::skip].
753 == "#![rustfmt::skip]";
755 if self.config_name.is_none() && !fmt_skip {
756 write_message(&format!(
757 "No configuration name for {}:{}",
758 CONFIGURATIONS_FILE_NAME,
759 self.code_block_start.unwrap()
763 if self.config_value.is_none() && !fmt_skip {
764 write_message(&format!(
765 "No configuration value for {}:{}",
766 CONFIGURATIONS_FILE_NAME,
767 self.code_block_start.unwrap()
774 fn has_parsing_errors<T: Write>(&self, session: &Session<T>) -> bool {
775 if session.has_parsing_errors() {
776 write_message(&format!(
777 "\u{261d}\u{1f3fd} Cannot format {}:{}",
778 CONFIGURATIONS_FILE_NAME,
779 self.code_block_start.unwrap()
787 fn print_diff(&self, compare: Vec<Mismatch>) {
788 let mut mismatches = HashMap::new();
789 mismatches.insert(PathBuf::from(CONFIGURATIONS_FILE_NAME), compare);
790 print_mismatches(mismatches, |line_num| {
792 "\nMismatch at {}:{}:",
793 CONFIGURATIONS_FILE_NAME,
794 line_num + self.code_block_start.unwrap() - 1
799 fn formatted_has_diff(&self, text: &str) -> bool {
800 let compare = make_diff(self.code_block.as_ref().unwrap(), text, DIFF_CONTEXT_SIZE);
801 if !compare.is_empty() {
802 self.print_diff(compare);
809 // Return a bool indicating if formatting this code block is an idempotent
810 // operation. This function also triggers printing any formatting failure
812 fn formatted_is_idempotent(&self) -> bool {
813 // Verify that we have all of the expected information.
814 if !self.code_block_valid() {
818 let input = Input::Text(self.code_block.as_ref().unwrap().to_owned());
819 let mut config = self.get_block_config();
820 config.set().emit_mode(EmitMode::Stdout);
821 let mut buf: Vec<u8> = vec![];
824 let mut session = Session::new(config, Some(&mut buf));
825 session.format(input).unwrap();
826 if self.has_parsing_errors(&session) {
831 !self.formatted_has_diff(&String::from_utf8(buf).unwrap())
834 // Extract a code block from the iterator. Behavior:
835 // - Rust code blocks are identifed by lines beginning with "```rust".
836 // - One explicit configuration setting is supported per code block.
837 // - Rust code blocks with no configuration setting are illegal and cause an
838 // assertion failure, unless the snippet begins with #![rustfmt::skip].
839 // - Configuration names in Configurations.md must be in the form of
841 // - Configuration values in Configurations.md must be in the form of
843 fn extract<I: Iterator<Item = String>>(
844 file: &mut Enumerate<I>,
845 prev: Option<&ConfigCodeBlock>,
846 hash_set: &mut HashSet<String>,
847 ) -> Option<ConfigCodeBlock> {
848 let mut code_block = ConfigCodeBlock::new();
849 code_block.config_name = prev.and_then(|cb| cb.config_name.clone());
852 match ConfigurationSection::get_section(file) {
853 Some(ConfigurationSection::CodeBlock((block, start_line))) => {
854 code_block.set_code_block(block, start_line);
857 Some(ConfigurationSection::ConfigName(name)) => {
859 Config::is_valid_name(&name),
860 "an unknown configuration option was found: {}",
864 hash_set.remove(&name),
865 "multiple configuration guides found for option {}",
868 code_block.set_config_name(Some(name));
870 Some(ConfigurationSection::ConfigValue(value)) => {
871 code_block.set_config_value(Some(value));
873 None => return None, // end of file was reached
882 fn configuration_snippet_tests() {
883 // Read Configurations.md and build a `Vec` of `ConfigCodeBlock` structs with one
884 // entry for each Rust code block found.
885 fn get_code_blocks() -> Vec<ConfigCodeBlock> {
886 let mut file_iter = BufReader::new(
887 fs::File::open(Path::new(CONFIGURATIONS_FILE_NAME))
888 .expect(&format!("Couldn't read file {}", CONFIGURATIONS_FILE_NAME)),
893 let mut code_blocks: Vec<ConfigCodeBlock> = Vec::new();
894 let mut hash_set = Config::hash_set();
897 ConfigCodeBlock::extract(&mut file_iter, code_blocks.last(), &mut hash_set)
899 code_blocks.push(cb);
902 for name in hash_set {
903 if !Config::is_hidden_option(&name) {
904 panic!("{} does not have a configuration guide", name);
911 let blocks = get_code_blocks();
912 let failures = blocks
914 .map(|b| b.formatted_is_idempotent())
915 .fold(0, |acc, r| acc + (!r as u32));
918 println!("Ran {} configurations tests.", blocks.len());
919 assert_eq!(failures, 0, "{} configurations tests failed", failures);
926 fn make_temp_file(file_name: &'static str) -> TempFile {
930 // Used in the Rust build system.
931 let target_dir = var("RUSTFMT_TEST_DIR").unwrap_or_else(|_| ".".to_owned());
932 let path = Path::new(&target_dir).join(file_name);
934 let mut file = File::create(&path).expect("Couldn't create temp file");
935 let content = "fn main() {}\n";
936 file.write_all(content.as_bytes())
937 .expect("Couldn't write temp file");
941 impl Drop for TempFile {
943 use std::fs::remove_file;
944 remove_file(&self.path).expect("Couldn't delete temp file");
948 fn rustfmt() -> PathBuf {
949 let mut me = env::current_exe().expect("failed to get current executable");
950 me.pop(); // chop of the test name
951 me.pop(); // chop off `deps`
953 // if we run `cargo test --release` we might only have a release build
961 me.is_file() || me.with_extension("exe").is_file(),
963 "no rustfmt bin, try running `cargo build --release` before testing"
965 "no rustfmt bin, try running `cargo build` before testing"
972 fn verify_check_works() {
973 let temp_file = make_temp_file("temp_check.rs");
975 Command::new(rustfmt().to_str().unwrap())
977 .arg(temp_file.path.to_str().unwrap())
979 .expect("run with check option failed");