]> git.lizzy.rs Git - rust.git/blobdiff - tests/system.rs
Merge pull request #966 from MicahChalmer/skip-children-in-plain-write-mode
[rust.git] / tests / system.rs
index bc5298ae22db1de3744e55b0fad6545c38540754..1af9c0f3462f8c13d00d416f3e4396ef87363fd6 100644 (file)
 use std::collections::HashMap;
 use std::fs;
 use std::io::{self, Read, BufRead, BufReader};
-use std::path::Path;
+use std::path::{Path, PathBuf};
 
 use rustfmt::*;
 use rustfmt::filemap::{write_system_newlines, FileMap};
-use rustfmt::config::{Config, ReportTactic, WriteMode};
+use rustfmt::config::{Config, ReportTactic};
 use rustfmt::rustfmt_diff::*;
 
 const DIFF_CONTEXT_SIZE: usize = 3;
@@ -44,7 +44,7 @@ fn system_tests() {
     // Turn a DirEntry into a String that represents the relative path to the
     // file.
     let files = files.map(get_path_string);
-    let (_reports, count, fails) = check_files(files, None);
+    let (_reports, count, fails) = check_files(files);
 
     // Display results.
     println!("Ran {} system tests.", count);
@@ -55,9 +55,9 @@ fn system_tests() {
 // the only difference is the coverage mode
 #[test]
 fn coverage_tests() {
-    let files = fs::read_dir("tests/coverage-source").expect("Couldn't read source dir");
+    let files = fs::read_dir("tests/coverage/source").expect("Couldn't read source dir");
     let files = files.map(get_path_string);
-    let (_reports, count, fails) = check_files(files, Some(WriteMode::Coverage));
+    let (_reports, count, fails) = check_files(files);
 
     println!("Ran {} tests in coverage mode.", count);
     assert!(fails == 0, "{} tests failed", fails);
@@ -65,21 +65,17 @@ fn coverage_tests() {
 
 #[test]
 fn checkstyle_test() {
-    let filename = "tests/source/fn-single-line.rs";
-    let expected_filename = "tests/writemode/checkstyle.xml";
-    assert_output(filename, expected_filename, Some(WriteMode::Checkstyle));
+    let filename = "tests/writemode/source/fn-single-line.rs";
+    let expected_filename = "tests/writemode/target/checkstyle.xml";
+    assert_output(filename, expected_filename);
 }
 
 
 // Helper function for comparing the results of rustfmt
 // to a known output file generated by one of the write modes.
-fn assert_output(source: &str, expected_filename: &str, write_mode: Option<WriteMode>) {
-    let file_map = run_rustfmt(source.to_string(), write_mode);
-
-    let mut config = read_config(&source);
-    if let Some(write_mode) = write_mode {
-        config.write_mode = write_mode;
-    }
+fn assert_output(source: &str, expected_filename: &str) {
+    let config = read_config(&source);
+    let (file_map, _report) = format_file(source, &config);
 
     // Populate output by writing to a vec.
     let mut out = vec![];
@@ -89,7 +85,7 @@ fn assert_output(source: &str, expected_filename: &str, write_mode: Option<Write
     let mut expected_file = fs::File::open(&expected_filename).expect("Couldn't open target");
     let mut expected_text = String::new();
     expected_file.read_to_string(&mut expected_text)
-                 .expect("Failed reading target");
+        .expect("Failed reading target");
 
     let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE);
     if compare.len() > 0 {
@@ -106,9 +102,9 @@ fn assert_output(source: &str, expected_filename: &str, write_mode: Option<Write
 fn idempotence_tests() {
     // Get all files in the tests/target directory.
     let files = fs::read_dir("tests/target")
-                    .expect("Couldn't read target dir")
-                    .map(get_path_string);
-    let (_reports, count, fails) = check_files(files, None);
+        .expect("Couldn't read target dir")
+        .map(get_path_string);
+    let (_reports, count, fails) = check_files(files);
 
     // Display results.
     println!("Ran {} idempotent tests.", count);
@@ -120,13 +116,13 @@ fn idempotence_tests() {
 #[test]
 fn self_tests() {
     let files = fs::read_dir("src/bin")
-                    .expect("Couldn't read src dir")
-                    .chain(fs::read_dir("tests").expect("Couldn't read tests dir"))
-                    .map(get_path_string);
+        .expect("Couldn't read src dir")
+        .chain(fs::read_dir("tests").expect("Couldn't read tests dir"))
+        .map(get_path_string);
     // Hack because there's no `IntoIterator` impl for `[T; N]`.
     let files = files.chain(Some("src/lib.rs".to_owned()).into_iter());
 
-    let (reports, count, fails) = check_files(files, None);
+    let (reports, count, fails) = check_files(files);
     let mut warnings = 0;
 
     // Display results.
@@ -143,9 +139,27 @@ fn self_tests() {
             warnings);
 }
 
+#[test]
+fn stdin_formatting_smoke_test() {
+    let input = Input::Text("fn main () {}".to_owned());
+    let config = Config::default();
+    let (error_summary, file_map, _report) = format_input(input, &config);
+    assert!(error_summary.has_no_errors());
+    assert_eq!(file_map["stdin"].to_string(), "fn main() {}\n")
+}
+
+#[test]
+fn format_lines_errors_are_reported() {
+    let long_identifier = String::from_utf8(vec![b'a'; 239]).unwrap();
+    let input = Input::Text(format!("fn {}() {{}}", long_identifier));
+    let config = Config::default();
+    let (error_summary, _file_map, _report) = format_input(input, &config);
+    assert!(error_summary.has_formatting_errors());
+}
+
 // For each file, run rustfmt and collect the output.
 // Returns the number of files checked and the number of failures.
-fn check_files<I>(files: I, write_mode: Option<WriteMode>) -> (Vec<FormatReport>, u32, u32)
+fn check_files<I>(files: I) -> (Vec<FormatReport>, u32, u32)
     where I: Iterator<Item = String>
 {
     let mut count = 0;
@@ -155,7 +169,7 @@ fn check_files<I>(files: I, write_mode: Option<WriteMode>) -> (Vec<FormatReport>
     for file_name in files.filter(|f| f.ends_with(".rs")) {
         println!("Testing '{}'...", file_name);
 
-        match idempotent_check(file_name, write_mode) {
+        match idempotent_check(file_name) {
             Ok(report) => reports.push(report),
             Err(msg) => {
                 print_mismatches(msg);
@@ -177,7 +191,7 @@ fn print_mismatches(result: HashMap<String, Vec<Mismatch>>) {
                    |line_num| format!("\nMismatch at {}:{}:", file_name, line_num));
     }
 
-    assert!(t.reset().unwrap());
+    t.reset().unwrap();
 }
 
 fn read_config(filename: &str) -> Config {
@@ -192,25 +206,20 @@ fn read_config(filename: &str) -> Config {
 
     // Don't generate warnings for to-do items.
     config.report_todo = ReportTactic::Never;
+
     config
 }
 
-// Simulate run()
-fn run_rustfmt(filename: String, write_mode: Option<WriteMode>) -> FileMap {
-    let mut config = read_config(&filename);
-    if let Some(write_mode) = write_mode {
-        config.write_mode = write_mode;
-    }
-    format(Path::new(&filename), &config)
+fn format_file<P: Into<PathBuf>>(filename: P, config: &Config) -> (FileMap, FormatReport) {
+    let input = Input::File(filename.into());
+    let (_error_summary, file_map, report) = format_input(input, &config);
+    return (file_map, report);
 }
 
-pub fn idempotent_check(filename: String,
-                        write_mode: Option<WriteMode>)
-                        -> Result<FormatReport, HashMap<String, Vec<Mismatch>>> {
+pub fn idempotent_check(filename: String) -> Result<FormatReport, HashMap<String, Vec<Mismatch>>> {
     let sig_comments = read_significant_comments(&filename);
     let config = read_config(&filename);
-    let mut file_map = run_rustfmt(filename, write_mode);
-    let format_report = fmt_lines(&mut file_map, &config);
+    let (file_map, format_report) = format_file(filename, &config);
 
     let mut write_result = HashMap::new();
     for (filename, text) in file_map.iter() {
@@ -224,7 +233,7 @@ pub fn idempotent_check(filename: String,
 
     let target = sig_comments.get("target").map(|x| &(*x)[..]);
 
-    handle_result(write_result, target, write_mode).map(|_| format_report)
+    handle_result(write_result, target).map(|_| format_report)
 }
 
 // Reads test config file from comments and reads its contents.
@@ -255,31 +264,30 @@ fn read_significant_comments(file_name: &str) -> HashMap<String, String> {
 
     // Matches lines containing significant comments or whitespace.
     let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
-                         .expect("Failed creating pattern 2");
+        .expect("Failed creating pattern 2");
 
     reader.lines()
-          .map(|line| line.expect("Failed getting line"))
-          .take_while(|line| line_regex.is_match(&line))
-          .filter_map(|line| {
-              regex.captures_iter(&line).next().map(|capture| {
-                  (capture.at(1).expect("Couldn't unwrap capture").to_owned(),
-                   capture.at(2).expect("Couldn't unwrap capture").to_owned())
-              })
-          })
-          .collect()
+        .map(|line| line.expect("Failed getting line"))
+        .take_while(|line| line_regex.is_match(&line))
+        .filter_map(|line| {
+            regex.captures_iter(&line).next().map(|capture| {
+                (capture.at(1).expect("Couldn't unwrap capture").to_owned(),
+                 capture.at(2).expect("Couldn't unwrap capture").to_owned())
+            })
+        })
+        .collect()
 }
 
 // Compare output to input.
 // TODO: needs a better name, more explanation.
 fn handle_result(result: HashMap<String, String>,
-                 target: Option<&str>,
-                 write_mode: Option<WriteMode>)
+                 target: Option<&str>)
                  -> Result<(), HashMap<String, Vec<Mismatch>>> {
     let mut failures = HashMap::new();
 
     for (file_name, fmt_text) in result {
         // If file is in tests/source, compare to file with same name in tests/target.
-        let target = get_target(&file_name, target, write_mode);
+        let target = get_target(&file_name, target);
         let mut f = fs::File::open(&target).expect("Couldn't open target");
 
         let mut text = String::new();
@@ -301,30 +309,20 @@ fn handle_result(result: HashMap<String, String>,
 }
 
 // Map source file paths to their target paths.
-fn get_target(file_name: &str, target: Option<&str>, write_mode: Option<WriteMode>) -> String {
-    let file_path = Path::new(file_name);
-    let (source_path_prefix, target_path_prefix) = match write_mode {
-        Some(WriteMode::Coverage) => {
-            (Path::new("tests/coverage-source/"),
-             "tests/coverage-target/")
+fn get_target(file_name: &str, target: Option<&str>) -> String {
+    if file_name.contains("source") {
+        let target_file_name = file_name.replace("source", "target");
+        if let Some(replace_name) = target {
+            Path::new(&target_file_name)
+                .with_file_name(replace_name)
+                .into_os_string()
+                .into_string()
+                .unwrap()
+        } else {
+            target_file_name
         }
-        _ => (Path::new("tests/source/"), "tests/target/"),
-    };
-
-    if file_path.starts_with(source_path_prefix) {
-        let mut components = file_path.components();
-        // Can't skip(2) as the resulting iterator can't as_path()
-        components.next();
-        components.next();
-
-        let new_target = match components.as_path().to_str() {
-            Some(string) => string,
-            None => file_name,
-        };
-        let base = target.unwrap_or(new_target);
-
-        format!("{}{}", target_path_prefix, base)
     } else {
+        // This is either and idempotence check or a self check
         file_name.to_owned()
     }
 }