1 use std::collections::{HashMap, HashSet};
4 use std::io::{self, BufRead, BufReader, Read, Write};
5 use std::iter::{Enumerate, Peekable};
7 use std::path::{Path, PathBuf};
8 use std::process::{Command, Stdio};
12 use crate::config::{Color, Config, EmitMode, FileName, NewlineStyle, ReportTactic};
13 use crate::formatting::{ReportedErrors, SourceFile};
14 use crate::rustfmt_diff::{make_diff, print_diff, DiffLine, Mismatch, ModifiedChunk, OutputWriter};
15 use crate::source_file;
16 use crate::{FormatReport, FormatReportFormatterBuilder, Input, Session};
18 const DIFF_CONTEXT_SIZE: usize = 3;
19 const CONFIGURATIONS_FILE_NAME: &str = "Configurations.md";
21 // A list of files on which we want to skip testing.
22 const SKIP_FILE_WHITE_LIST: &[&str] = &[
23 // We want to make sure that the `skip_children` is correctly working,
24 // so we do not want to test this file directly.
25 "configs/skip_children/foo/mod.rs",
26 "issue-3434/no_entry.rs",
30 /// The size of the stack of the thread that run tests.
34 impl Default for TestSetting {
35 fn default() -> Self {
37 stack_size: 8_388_608, // 8MB
42 fn run_test_with<F>(test_setting: &TestSetting, f: F)
47 thread::Builder::new()
48 .stack_size(test_setting.stack_size)
50 .expect("Failed to create a test thread")
52 .expect("Failed to join a test thread")
55 fn is_file_skip(path: &Path) -> bool {
58 .any(|file_path| path.ends_with(file_path))
61 // Returns a `Vec` containing `PathBuf`s of files with an `rs` extension in the
62 // given path. The `recursive` argument controls if files from subdirectories
64 fn get_test_files(path: &Path, recursive: bool) -> Vec<PathBuf> {
65 let mut files = vec![];
67 for entry in fs::read_dir(path).expect(&format!(
68 "couldn't read directory {}",
69 path.to_str().unwrap()
71 let entry = entry.expect("couldn't get `DirEntry`");
72 let path = entry.path();
73 if path.is_dir() && recursive {
74 files.append(&mut get_test_files(&path, recursive));
75 } else if path.extension().map_or(false, |f| f == "rs") && !is_file_skip(&path) {
83 fn verify_config_used(path: &Path, config_name: &str) {
84 for entry in fs::read_dir(path).expect(&format!(
85 "couldn't read {} directory",
86 path.to_str().unwrap()
88 let entry = entry.expect("couldn't get directory entry");
89 let path = entry.path();
90 if path.extension().map_or(false, |f| f == "rs") {
91 // check if "// rustfmt-<config_name>:" appears in the file.
92 let filebuf = BufReader::new(
94 .unwrap_or_else(|_| panic!("couldn't read file {}", path.display())),
100 .take_while(|l| l.starts_with("//"))
101 .any(|l| l.starts_with(&format!("// rustfmt-{}", config_name))),
103 "config option file {} does not contain expected config name",
112 fn verify_config_test_names() {
114 Path::new("tests/source/configs"),
115 Path::new("tests/target/configs"),
117 for entry in fs::read_dir(path).expect("couldn't read configs directory") {
118 let entry = entry.expect("couldn't get directory entry");
119 let path = entry.path();
121 let config_name = path.file_name().unwrap().to_str().unwrap();
123 // Make sure that config name is used in the files in the directory.
124 verify_config_used(&path, config_name);
130 // This writes to the terminal using the same approach (via `term::stdout` or
131 // `println!`) that is used by `rustfmt::rustfmt_diff::print_diff`. Writing
132 // using only one or the other will cause the output order to differ when
133 // `print_diff` selects the approach not used.
134 fn write_message(msg: &str) {
135 let mut writer = OutputWriter::new(Color::Auto);
136 writer.writeln(msg, None);
139 // Integration tests. The files in `tests/source` are formatted and compared
140 // to their equivalent in `tests/target`. The target file and config can be
141 // overridden by annotations in the source file. The input and output must match
145 run_test_with(&TestSetting::default(), || {
146 // Get all files in the tests/source directory.
147 let files = get_test_files(Path::new("tests/source"), true);
148 let (_reports, count, fails) = check_files(files, &None);
151 println!("Ran {} system tests.", count);
152 assert_eq!(fails, 0, "{} system tests failed", fails);
156 // Do the same for tests/coverage-source directory.
157 // The only difference is the coverage mode.
159 fn coverage_tests() {
160 let files = get_test_files(Path::new("tests/coverage/source"), true);
161 let (_reports, count, fails) = check_files(files, &None);
163 println!("Ran {} tests in coverage mode.", count);
164 assert_eq!(fails, 0, "{} tests failed", fails);
168 fn checkstyle_test() {
169 let filename = "tests/writemode/source/fn-single-line.rs";
170 let expected_filename = "tests/writemode/target/checkstyle.xml";
171 assert_output(Path::new(filename), Path::new(expected_filename));
176 use std::io::BufRead;
178 // Test "modified" output
179 let filename = "tests/writemode/source/modified.rs";
180 let mut data = Vec::new();
181 let mut config = Config::default();
184 .emit_mode(crate::config::EmitMode::ModifiedLines);
187 let mut session = Session::new(config, Some(&mut data));
188 session.format(Input::File(filename.into())).unwrap();
191 let mut lines = data.lines();
192 let mut chunks = Vec::new();
193 while let Some(Ok(header)) = lines.next() {
194 // Parse the header line
195 let values: Vec<_> = header
197 .map(|s| s.parse::<u32>().unwrap())
199 assert_eq!(values.len(), 3);
200 let line_number_orig = values[0];
201 let lines_removed = values[1];
202 let num_added = values[2];
203 let mut added_lines = Vec::new();
204 for _ in 0..num_added {
205 added_lines.push(lines.next().unwrap().unwrap());
207 chunks.push(ModifiedChunk {
220 lines: vec!["fn blah() {}".into()],
225 lines: vec!["#[cfg(a, b)]".into(), "fn main() {}".into()],
231 // Helper function for comparing the results of rustfmt
232 // to a known output file generated by one of the write modes.
233 fn assert_output(source: &Path, expected_filename: &Path) {
234 let config = read_config(source);
235 let (_, source_file, _) = format_file(source, config.clone());
237 // Populate output by writing to a vec.
238 let mut out = vec![];
239 let _ = source_file::write_all_files(&source_file, &mut out, &config);
240 let output = String::from_utf8(out).unwrap();
242 let mut expected_file = fs::File::open(&expected_filename).expect("couldn't open target");
243 let mut expected_text = String::new();
245 .read_to_string(&mut expected_text)
246 .expect("Failed reading target");
248 let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
249 if !compare.is_empty() {
250 let mut failures = HashMap::new();
251 failures.insert(source.to_owned(), compare);
252 print_mismatches_default_message(failures);
253 panic!("Text does not match expected output");
257 // Idempotence tests. Files in tests/target are checked to be unaltered by
260 fn idempotence_tests() {
261 run_test_with(&TestSetting::default(), || {
262 match option_env!("CFG_RELEASE_CHANNEL") {
263 None | Some("nightly") => {}
264 _ => return, // these tests require nightly
266 // Get all files in the tests/target directory.
267 let files = get_test_files(Path::new("tests/target"), true);
268 let (_reports, count, fails) = check_files(files, &None);
271 println!("Ran {} idempotent tests.", count);
272 assert_eq!(fails, 0, "{} idempotent tests failed", fails);
276 // Run rustfmt on itself. This operation must be idempotent. We also check that
277 // no warnings are emitted.
280 match option_env!("CFG_RELEASE_CHANNEL") {
281 None | Some("nightly") => {}
282 _ => return, // Issue-3443: these tests require nightly
284 let mut files = get_test_files(Path::new("tests"), false);
285 let bin_directories = vec!["cargo-fmt", "git-rustfmt", "bin", "format-diff"];
286 for dir in bin_directories {
287 let mut path = PathBuf::from("src");
289 path.push("main.rs");
292 files.push(PathBuf::from("src/lib.rs"));
294 let (reports, count, fails) = check_files(files, &Some(PathBuf::from("rustfmt.toml")));
295 let mut warnings = 0;
298 println!("Ran {} self tests.", count);
299 assert_eq!(fails, 0, "{} self tests failed", fails);
301 for format_report in reports {
304 FormatReportFormatterBuilder::new(&format_report).build()
306 warnings += format_report.warning_count();
311 "Rustfmt's code generated {} warnings",
317 fn stdin_formatting_smoke_test() {
318 let input = Input::Text("fn main () {}".to_owned());
319 let mut config = Config::default();
320 config.set().emit_mode(EmitMode::Stdout);
321 let mut buf: Vec<u8> = vec![];
323 let mut session = Session::new(config, Some(&mut buf));
324 session.format(input).unwrap();
325 assert!(session.has_no_errors());
329 assert_eq!(buf, "fn main() {}\n".as_bytes());
331 assert_eq!(buf, "fn main() {}\r\n".as_bytes());
335 fn stdin_parser_panic_caught() {
337 for text in ["{", "}"].iter().cloned().map(String::from) {
338 let mut buf = vec![];
339 let mut session = Session::new(Default::default(), Some(&mut buf));
340 let _ = session.format(Input::Text(text));
342 assert!(session.has_parsing_errors());
346 /// Ensures that `EmitMode::ModifiedLines` works with input from `stdin`. Useful
347 /// when embedding Rustfmt (e.g. inside RLS).
349 fn stdin_works_with_modified_lines() {
350 let input = "\nfn\n some( )\n{\n}\nfn main () {}\n";
351 let output = "1 6 2\nfn some() {}\nfn main() {}\n";
353 let input = Input::Text(input.to_owned());
354 let mut config = Config::default();
355 config.set().newline_style(NewlineStyle::Unix);
356 config.set().emit_mode(EmitMode::ModifiedLines);
357 let mut buf: Vec<u8> = vec![];
359 let mut session = Session::new(config, Some(&mut buf));
360 session.format(input).unwrap();
361 let errors = ReportedErrors {
365 assert_eq!(session.errors, errors);
367 assert_eq!(buf, output.as_bytes());
371 fn stdin_disable_all_formatting_test() {
372 match option_env!("CFG_RELEASE_CHANNEL") {
373 None | Some("nightly") => {}
374 // These tests require nightly.
377 let input = String::from("fn main() { println!(\"This should not be formatted.\"); }");
378 let mut child = Command::new(rustfmt().to_str().unwrap())
379 .stdin(Stdio::piped())
380 .stdout(Stdio::piped())
381 .arg("--config-path=./tests/config/disable_all_formatting.toml")
383 .expect("failed to execute child");
386 let stdin = child.stdin.as_mut().expect("failed to get stdin");
388 .write_all(input.as_bytes())
389 .expect("failed to write stdin");
392 let output = child.wait_with_output().expect("failed to wait on child");
393 assert!(output.status.success());
394 assert!(output.stderr.is_empty());
395 assert_eq!(input, String::from_utf8(output.stdout).unwrap());
399 fn format_lines_errors_are_reported() {
400 let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
401 let input = Input::Text(format!("fn {}() {{}}", long_identifier));
402 let mut config = Config::default();
403 config.set().error_on_line_overflow(true);
404 let mut session = Session::<io::Stdout>::new(config, None);
405 session.format(input).unwrap();
406 assert!(session.has_formatting_errors());
410 fn format_lines_errors_are_reported_with_tabs() {
411 let long_identifier = String::from_utf8(vec![b'a'; 97]).unwrap();
412 let input = Input::Text(format!("fn a() {{\n\t{}\n}}", long_identifier));
413 let mut config = Config::default();
414 config.set().error_on_line_overflow(true);
415 config.set().hard_tabs(true);
416 let mut session = Session::<io::Stdout>::new(config, None);
417 session.format(input).unwrap();
418 assert!(session.has_formatting_errors());
421 // For each file, run rustfmt and collect the output.
422 // Returns the number of files checked and the number of failures.
423 fn check_files(files: Vec<PathBuf>, opt_config: &Option<PathBuf>) -> (Vec<FormatReport>, u32, u32) {
426 let mut reports = vec![];
428 for file_name in files {
429 debug!("Testing '{}'...", file_name.display());
431 match idempotent_check(&file_name, &opt_config) {
432 Ok(ref report) if report.has_warnings() => {
433 print!("{}", FormatReportFormatterBuilder::new(&report).build());
436 Ok(report) => reports.push(report),
438 if let IdempotentCheckError::Mismatch(msg) = err {
439 print_mismatches_default_message(msg);
448 (reports, count, fails)
451 fn print_mismatches_default_message(result: HashMap<PathBuf, Vec<Mismatch>>) {
452 for (file_name, diff) in result {
453 let mismatch_msg_formatter =
454 |line_num| format!("\nMismatch at {}:{}:", file_name.display(), line_num);
455 print_diff(diff, &mismatch_msg_formatter, &Default::default());
458 if let Some(mut t) = term::stdout() {
459 t.reset().unwrap_or(());
463 fn print_mismatches<T: Fn(u32) -> String>(
464 result: HashMap<PathBuf, Vec<Mismatch>>,
465 mismatch_msg_formatter: T,
467 for (_file_name, diff) in result {
468 print_diff(diff, &mismatch_msg_formatter, &Default::default());
471 if let Some(mut t) = term::stdout() {
472 t.reset().unwrap_or(());
476 fn read_config(filename: &Path) -> Config {
477 let sig_comments = read_significant_comments(filename);
478 // Look for a config file. If there is a 'config' property in the significant comments, use
479 // that. Otherwise, if there are no significant comments at all, look for a config file with
480 // the same name as the test file.
481 let mut config = if !sig_comments.is_empty() {
482 get_config(sig_comments.get("config").map(Path::new))
484 get_config(filename.with_extension("toml").file_name().map(Path::new))
487 for (key, val) in &sig_comments {
488 if key != "target" && key != "config" {
489 config.override_value(key, val);
490 if config.is_default(key) {
491 warn!("Default value {} used explicitly for {}", val, key);
496 // Don't generate warnings for to-do items.
497 config.set().report_todo(ReportTactic::Never);
502 fn format_file<P: Into<PathBuf>>(filepath: P, config: Config) -> (bool, SourceFile, FormatReport) {
503 let filepath = filepath.into();
504 let input = Input::File(filepath);
505 let mut session = Session::<io::Stdout>::new(config, None);
506 let result = session.format(input).unwrap();
507 let parsing_errors = session.has_parsing_errors();
508 let mut source_file = SourceFile::new();
509 mem::swap(&mut session.source_file, &mut source_file);
510 (parsing_errors, source_file, result)
513 enum IdempotentCheckError {
514 Mismatch(HashMap<PathBuf, Vec<Mismatch>>),
520 opt_config: &Option<PathBuf>,
521 ) -> Result<FormatReport, IdempotentCheckError> {
522 let sig_comments = read_significant_comments(filename);
523 let config = if let Some(ref config_file_path) = opt_config {
524 Config::from_toml_path(config_file_path).expect("`rustfmt.toml` not found")
526 read_config(filename)
528 let (parsing_errors, source_file, format_report) = format_file(filename, config);
530 return Err(IdempotentCheckError::Parse);
533 let mut write_result = HashMap::new();
534 for (filename, text) in source_file {
535 if let FileName::Real(ref filename) = filename {
536 write_result.insert(filename.to_owned(), text);
540 let target = sig_comments.get("target").map(|x| &(*x)[..]);
542 handle_result(write_result, target).map(|_| format_report)
545 // Reads test config file using the supplied (optional) file name. If there's no file name or the
546 // file doesn't exist, just return the default config. Otherwise, the file must be read
548 fn get_config(config_file: Option<&Path>) -> Config {
549 let config_file_name = match config_file {
550 None => return Default::default(),
552 let mut full_path = PathBuf::from("tests/config/");
553 full_path.push(file_name);
554 if !full_path.exists() {
555 return Default::default();
561 let mut def_config_file = fs::File::open(config_file_name).expect("couldn't open config");
562 let mut def_config = String::new();
564 .read_to_string(&mut def_config)
565 .expect("Couldn't read config");
567 Config::from_toml(&def_config).expect("invalid TOML")
570 // Reads significant comments of the form: `// rustfmt-key: value` into a hash map.
571 fn read_significant_comments(file_name: &Path) -> HashMap<String, String> {
572 let file = fs::File::open(file_name)
573 .unwrap_or_else(|_| panic!("couldn't read file {}", file_name.display()));
574 let reader = BufReader::new(file);
575 let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
576 let regex = regex::Regex::new(pattern).expect("failed creating pattern 1");
578 // Matches lines containing significant comments or whitespace.
579 let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
580 .expect("failed creating pattern 2");
584 .map(|line| line.expect("failed getting line"))
585 .take_while(|line| line_regex.is_match(line))
587 regex.captures_iter(&line).next().map(|capture| {
591 .expect("couldn't unwrap capture")
596 .expect("couldn't unwrap capture")
605 // Compares output to input.
606 // TODO: needs a better name, more explanation.
608 result: HashMap<PathBuf, String>,
609 target: Option<&str>,
610 ) -> Result<(), IdempotentCheckError> {
611 let mut failures = HashMap::new();
613 for (file_name, fmt_text) in result {
614 // If file is in tests/source, compare to file with same name in tests/target.
615 let target = get_target(&file_name, target);
616 let open_error = format!("couldn't open target {:?}", target);
617 let mut f = fs::File::open(&target).expect(&open_error);
619 let mut text = String::new();
620 let read_error = format!("failed reading target {:?}", target);
621 f.read_to_string(&mut text).expect(&read_error);
623 // Ignore LF and CRLF difference for Windows.
624 if !string_eq_ignore_newline_repr(&fmt_text, &text) {
625 let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
628 "Empty diff? Maybe due to a missing a newline at the end of a file?"
630 failures.insert(file_name, diff);
634 if failures.is_empty() {
637 Err(IdempotentCheckError::Mismatch(failures))
641 // Maps source file paths to their target paths.
642 fn get_target(file_name: &Path, target: Option<&str>) -> PathBuf {
643 if let Some(n) = file_name
645 .position(|c| c.as_os_str() == "source")
647 let mut target_file_name = PathBuf::new();
648 for (i, c) in file_name.components().enumerate() {
650 target_file_name.push("target");
652 target_file_name.push(c.as_os_str());
655 if let Some(replace_name) = target {
656 target_file_name.with_file_name(replace_name)
661 // This is either and idempotence check or a self check.
667 fn rustfmt_diff_make_diff_tests() {
668 let diff = make_diff("a\nb\nc\nd", "a\ne\nc\nd", 3);
675 DiffLine::Context("a".into()),
676 DiffLine::Resulting("b".into()),
677 DiffLine::Expected("e".into()),
678 DiffLine::Context("c".into()),
679 DiffLine::Context("d".into()),
686 fn rustfmt_diff_no_diff_test() {
687 let diff = make_diff("a\nb\nc\nd", "a\nb\nc\nd", 3);
688 assert_eq!(diff, vec![]);
691 // Compare strings without distinguishing between CRLF and LF
692 fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool {
693 let left = CharsIgnoreNewlineRepr(left.chars().peekable());
694 let right = CharsIgnoreNewlineRepr(right.chars().peekable());
698 struct CharsIgnoreNewlineRepr<'a>(Peekable<Chars<'a>>);
700 impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> {
703 fn next(&mut self) -> Option<char> {
704 self.0.next().map(|c| {
706 if *self.0.peek().unwrap_or(&'\0') == '\n' {
720 fn string_eq_ignore_newline_repr_test() {
721 assert!(string_eq_ignore_newline_repr("", ""));
722 assert!(!string_eq_ignore_newline_repr("", "abc"));
723 assert!(!string_eq_ignore_newline_repr("abc", ""));
724 assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd"));
725 assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb"));
726 assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk"));
729 // This enum is used to represent one of three text features in Configurations.md: a block of code
730 // with its starting line number, the name of a rustfmt configuration option, or the value of a
731 // rustfmt configuration option.
732 enum ConfigurationSection {
733 CodeBlock((String, u32)), // (String: block of code, u32: line number of code block start)
738 impl ConfigurationSection {
739 fn get_section<I: Iterator<Item = String>>(
740 file: &mut Enumerate<I>,
741 ) -> Option<ConfigurationSection> {
743 static ref CONFIG_NAME_REGEX: regex::Regex =
744 regex::Regex::new(r"^## `([^`]+)`").expect("failed creating configuration pattern");
745 static ref CONFIG_VALUE_REGEX: regex::Regex =
746 regex::Regex::new(r#"^#### `"?([^`"]+)"?`"#)
747 .expect("failed creating configuration value pattern");
753 if line.starts_with("```rust") {
754 // Get the lines of the code block.
755 let lines: Vec<String> = file
757 .take_while(|l| !l.starts_with("```"))
759 let block = format!("{}\n", lines.join("\n"));
761 // +1 to translate to one-based indexing
762 // +1 to get to first line of code (line after "```")
763 let start_line = (i + 2) as u32;
765 return Some(ConfigurationSection::CodeBlock((block, start_line)));
766 } else if let Some(c) = CONFIG_NAME_REGEX.captures(&line) {
767 return Some(ConfigurationSection::ConfigName(String::from(&c[1])));
768 } else if let Some(c) = CONFIG_VALUE_REGEX.captures(&line) {
769 return Some(ConfigurationSection::ConfigValue(String::from(&c[1])));
772 None => return None, // reached the end of the file
778 // This struct stores the information about code blocks in the configurations
779 // file, formats the code blocks, and prints formatting errors.
780 struct ConfigCodeBlock {
781 config_name: Option<String>,
782 config_value: Option<String>,
783 code_block: Option<String>,
784 code_block_start: Option<u32>,
787 impl ConfigCodeBlock {
788 fn new() -> ConfigCodeBlock {
793 code_block_start: None,
797 fn set_config_name(&mut self, name: Option<String>) {
798 self.config_name = name;
799 self.config_value = None;
802 fn set_config_value(&mut self, value: Option<String>) {
803 self.config_value = value;
806 fn set_code_block(&mut self, code_block: String, code_block_start: u32) {
807 self.code_block = Some(code_block);
808 self.code_block_start = Some(code_block_start);
811 fn get_block_config(&self) -> Config {
812 let mut config = Config::default();
813 if self.config_value.is_some() && self.config_value.is_some() {
814 config.override_value(
815 self.config_name.as_ref().unwrap(),
816 self.config_value.as_ref().unwrap(),
822 fn code_block_valid(&self) -> bool {
823 // We never expect to not have a code block.
824 assert!(self.code_block.is_some() && self.code_block_start.is_some());
826 // See if code block begins with #![rustfmt::skip].
834 == "#![rustfmt::skip]";
836 if self.config_name.is_none() && !fmt_skip {
837 write_message(&format!(
838 "No configuration name for {}:{}",
839 CONFIGURATIONS_FILE_NAME,
840 self.code_block_start.unwrap()
844 if self.config_value.is_none() && !fmt_skip {
845 write_message(&format!(
846 "No configuration value for {}:{}",
847 CONFIGURATIONS_FILE_NAME,
848 self.code_block_start.unwrap()
855 fn has_parsing_errors<T: Write>(&self, session: &Session<'_, T>) -> bool {
856 if session.has_parsing_errors() {
857 write_message(&format!(
858 "\u{261d}\u{1f3fd} Cannot format {}:{}",
859 CONFIGURATIONS_FILE_NAME,
860 self.code_block_start.unwrap()
868 fn print_diff(&self, compare: Vec<Mismatch>) {
869 let mut mismatches = HashMap::new();
870 mismatches.insert(PathBuf::from(CONFIGURATIONS_FILE_NAME), compare);
871 print_mismatches(mismatches, |line_num| {
873 "\nMismatch at {}:{}:",
874 CONFIGURATIONS_FILE_NAME,
875 line_num + self.code_block_start.unwrap() - 1
880 fn formatted_has_diff(&self, text: &str) -> bool {
881 let compare = make_diff(self.code_block.as_ref().unwrap(), text, DIFF_CONTEXT_SIZE);
882 if !compare.is_empty() {
883 self.print_diff(compare);
890 // Return a bool indicating if formatting this code block is an idempotent
891 // operation. This function also triggers printing any formatting failure
893 fn formatted_is_idempotent(&self) -> bool {
894 // Verify that we have all of the expected information.
895 if !self.code_block_valid() {
899 let input = Input::Text(self.code_block.as_ref().unwrap().to_owned());
900 let mut config = self.get_block_config();
901 config.set().emit_mode(EmitMode::Stdout);
902 let mut buf: Vec<u8> = vec![];
905 let mut session = Session::new(config, Some(&mut buf));
906 session.format(input).unwrap();
907 if self.has_parsing_errors(&session) {
912 !self.formatted_has_diff(&String::from_utf8(buf).unwrap())
915 // Extract a code block from the iterator. Behavior:
916 // - Rust code blocks are identifed by lines beginning with "```rust".
917 // - One explicit configuration setting is supported per code block.
918 // - Rust code blocks with no configuration setting are illegal and cause an
919 // assertion failure, unless the snippet begins with #![rustfmt::skip].
920 // - Configuration names in Configurations.md must be in the form of
922 // - Configuration values in Configurations.md must be in the form of
924 fn extract<I: Iterator<Item = String>>(
925 file: &mut Enumerate<I>,
926 prev: Option<&ConfigCodeBlock>,
927 hash_set: &mut HashSet<String>,
928 ) -> Option<ConfigCodeBlock> {
929 let mut code_block = ConfigCodeBlock::new();
930 code_block.config_name = prev.and_then(|cb| cb.config_name.clone());
933 match ConfigurationSection::get_section(file) {
934 Some(ConfigurationSection::CodeBlock((block, start_line))) => {
935 code_block.set_code_block(block, start_line);
938 Some(ConfigurationSection::ConfigName(name)) => {
940 Config::is_valid_name(&name),
941 "an unknown configuration option was found: {}",
945 hash_set.remove(&name),
946 "multiple configuration guides found for option {}",
949 code_block.set_config_name(Some(name));
951 Some(ConfigurationSection::ConfigValue(value)) => {
952 code_block.set_config_value(Some(value));
954 None => return None, // end of file was reached
963 fn configuration_snippet_tests() {
964 // Read Configurations.md and build a `Vec` of `ConfigCodeBlock` structs with one
965 // entry for each Rust code block found.
966 fn get_code_blocks() -> Vec<ConfigCodeBlock> {
967 let mut file_iter = BufReader::new(
968 fs::File::open(Path::new(CONFIGURATIONS_FILE_NAME))
969 .unwrap_or_else(|_| panic!("couldn't read file {}", CONFIGURATIONS_FILE_NAME)),
974 let mut code_blocks: Vec<ConfigCodeBlock> = Vec::new();
975 let mut hash_set = Config::hash_set();
978 ConfigCodeBlock::extract(&mut file_iter, code_blocks.last(), &mut hash_set)
980 code_blocks.push(cb);
983 for name in hash_set {
984 if !Config::is_hidden_option(&name) {
985 panic!("{} does not have a configuration guide", name);
992 let blocks = get_code_blocks();
993 let failures = blocks
995 .map(ConfigCodeBlock::formatted_is_idempotent)
996 .fold(0, |acc, r| acc + (!r as u32));
999 println!("Ran {} configurations tests.", blocks.len());
1000 assert_eq!(failures, 0, "{} configurations tests failed", failures);
1007 fn make_temp_file(file_name: &'static str) -> TempFile {
1011 // Used in the Rust build system.
1012 let target_dir = var("RUSTFMT_TEST_DIR").unwrap_or_else(|_| ".".to_owned());
1013 let path = Path::new(&target_dir).join(file_name);
1015 let mut file = File::create(&path).expect("couldn't create temp file");
1016 let content = "fn main() {}\n";
1017 file.write_all(content.as_bytes())
1018 .expect("couldn't write temp file");
1022 impl Drop for TempFile {
1023 fn drop(&mut self) {
1024 use std::fs::remove_file;
1025 remove_file(&self.path).expect("couldn't delete temp file");
1029 fn rustfmt() -> PathBuf {
1030 let mut me = env::current_exe().expect("failed to get current executable");
1031 // Chop of the test name.
1036 // If we run `cargo test --release`, we might only have a release build.
1044 me.is_file() || me.with_extension("exe").is_file(),
1046 "no rustfmt bin, try running `cargo build --release` before testing"
1048 "no rustfmt bin, try running `cargo build` before testing"
1055 fn verify_check_works() {
1056 let temp_file = make_temp_file("temp_check.rs");
1058 Command::new(rustfmt().to_str().unwrap())
1060 .arg(temp_file.path.to_str().unwrap())
1062 .expect("run with check option failed");