]> git.lizzy.rs Git - rust.git/blob - tests/system.rs
Merge pull request #98 from cassiersg/misc
[rust.git] / tests / system.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 #![feature(catch_panic)]
12
13 extern crate rustfmt;
14 extern crate diff;
15 extern crate regex;
16
17 use std::collections::HashMap;
18 use std::fs;
19 use std::io::{self, Read, BufRead, BufReader};
20 use std::thread;
21 use rustfmt::*;
22
23 fn get_path_string(dir_entry: io::Result<fs::DirEntry>) -> String {
24     let path = dir_entry.ok().expect("Couldn't get DirEntry.").path();
25
26     path.to_str().expect("Couldn't stringify path.").to_owned()
27 }
28
29 // Integration tests and idempotence tests. The files in the tests/source are
30 // formatted and compared to their equivalent in tests/target. The target file
31 // and config can be overriden by annotations in the source file. The input and
32 // output must match exactly.
33 // Files in tests/target are checked to be unaltered by rustfmt.
34 // FIXME(#28) would be good to check for error messages and fail on them, or at least report.
35 #[test]
36 fn system_tests() {
37     // Get all files in the tests/target directory
38     let files = fs::read_dir("tests/target").ok().expect("Couldn't read dir 1.");
39     let files = files.chain(fs::read_dir("tests").ok().expect("Couldn't read dir 2."));
40     let files = files.chain(fs::read_dir("src/bin").ok().expect("Couldn't read dir 3."));
41     // turn a DirEntry into a String that represents the relative path to the file
42     let files = files.map(get_path_string);
43     // hack because there's no `IntoIterator` impl for `[T; N]`
44     let files = files.chain(Some("src/lib.rs".to_owned()).into_iter());
45
46     let (count, fails) = check_files(files);
47
48     // Display results
49     println!("Ran {} idempotent tests.", count);
50     assert!(fails == 0, "{} idempotent tests failed", fails);
51
52     // Get all files in the tests/source directory
53     let files = fs::read_dir("tests/source").ok().expect("Couldn't read dir 4.");
54     // turn a DirEntry into a String that represents the relative path to the file
55     let files = files.map(get_path_string);
56
57     let (count, fails) = check_files(files);
58
59     // Display results
60     println!("Ran {} system tests.", count);
61     assert!(fails == 0, "{} system tests failed", fails);
62 }
63
64 // For each file, run rustfmt and collect the output.
65 // Returns the number of files checked and the number of failures.
66 fn check_files<I>(files: I) -> (u32, u32)
67     where I: Iterator<Item = String>
68 {
69     let mut count = 0;
70     let mut fails = 0;
71
72     for file_name in files.filter(|f| f.ends_with(".rs")) {
73         println!("Testing '{}'...", file_name);
74         match idempotent_check(file_name) {
75             Ok(()) => {},
76             Err(m) => {
77                 print_mismatches(m);
78                 fails += 1;
79             },
80         }
81         count += 1;
82     }
83
84     (count, fails)
85 }
86
87 fn print_mismatches(result: HashMap<String, String>) {
88     for (_, fmt_text) in result {
89         println!("{}", fmt_text);
90     }
91 }
92
93 // Ick, just needed to get a &'static to handle_result.
94 static HANDLE_RESULT: &'static Fn(HashMap<String, String>) = &handle_result;
95
96 pub fn idempotent_check(filename: String) -> Result<(), HashMap<String, String>> {
97     let config = get_config(&filename);
98     let args = vec!["rustfmt".to_owned(), filename];
99     // this thread is not used for concurrency, but rather to workaround the issue that the passed
100     // function handle needs to have static lifetime. Instead of using a global RefCell, we use
101     // panic to return a result in case of failure. This has the advantage of smoothing the road to
102     // multithreaded rustfmt
103     thread::catch_panic(move || {
104         run(args, WriteMode::Return(HANDLE_RESULT), &config);
105     }).map_err(|any|
106         *any.downcast().ok().expect("Downcast failed.")
107     )
108 }
109
110 // Reads test config file from comments and loads it
111 fn get_config(file_name: &str) -> String {
112     let config_file_name = read_significant_comment(file_name, "config")
113         .map(|file_name| {
114             let mut full_path = "tests/config/".to_owned();
115             full_path.push_str(&file_name);
116             full_path
117         })
118         .unwrap_or("default.toml".to_owned());
119
120     let mut def_config_file = fs::File::open(config_file_name).ok().expect("Couldn't open config.");
121     let mut def_config = String::new();
122     def_config_file.read_to_string(&mut def_config).ok().expect("Couldn't read config.");
123
124     def_config
125 }
126
127 fn read_significant_comment(file_name: &str, option: &str) -> Option<String> {
128     let file = fs::File::open(file_name).ok().expect("Couldn't read file for comment.");
129     let reader = BufReader::new(file);
130     let pattern = format!("^\\s*//\\s*rustfmt-{}:\\s*(\\S+)", option);
131     let regex = regex::Regex::new(&pattern).ok().expect("Failed creating pattern 1.");
132
133     // matches exactly the lines containing significant comments or whitespace
134     let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[:alpha:]+:\s*\S+)")
135         .ok().expect("Failed creating pattern 2.");
136
137     reader.lines()
138           .map(|line| line.ok().expect("Failed getting line."))
139           .take_while(|line| line_regex.is_match(&line))
140           .filter_map(|line| {
141               regex.captures_iter(&line).next().map(|capture| {
142                   capture.at(1).expect("Couldn't unwrap capture.").to_owned()
143               })
144           })
145           .next()
146 }
147
148 // Compare output to input.
149 fn handle_result(result: HashMap<String, String>) {
150     let mut failures = HashMap::new();
151
152     for (file_name, fmt_text) in result {
153         // If file is in tests/source, compare to file with same name in tests/target
154         let target_file_name = get_target(&file_name);
155         let mut f = fs::File::open(&target_file_name).ok().expect("Couldn't open target.");
156
157         let mut text = String::new();
158         // TODO: speedup by running through bytes iterator
159         f.read_to_string(&mut text).ok().expect("Failed reading target.");
160         if fmt_text != text {
161             let diff_str = make_diff(&file_name, &fmt_text, &text);
162             failures.insert(file_name, diff_str);
163         }
164     }
165     if !failures.is_empty() {
166         panic!(failures);
167     }
168 }
169
170 // Map source file paths to their target paths.
171 fn get_target(file_name: &str) -> String {
172     if file_name.starts_with("tests/source/") {
173         let target = read_significant_comment(file_name, "target");
174         let base = target.unwrap_or(file_name.trim_left_matches("tests/source/").to_owned());
175
176         let mut target_file = "tests/target/".to_owned();
177         target_file.push_str(&base);
178
179         target_file
180     } else {
181         file_name.to_owned()
182     }
183 }
184
185 // Produces a diff string between the expected output and actual output of
186 // rustfmt on a given file
187 fn make_diff(file_name: &str, expected: &str, actual: &str) -> String {
188     let mut line_number = 1;
189     let mut prev_both = true;
190     let mut text = String::new();
191
192     for result in diff::lines(expected, actual) {
193         match result {
194             diff::Result::Left(str) => {
195                 if prev_both {
196                     text.push_str(&format!("Mismatch @ {}:{}\n", file_name, line_number));
197                 }
198                 text.push_str(&format!("-{}⏎\n", str));
199                 prev_both = false;
200             }
201             diff::Result::Right(str) => {
202                 if prev_both {
203                     text.push_str(&format!("Mismatch @ {}:{}\n", file_name, line_number));
204                 }
205                 text.push_str(&format!("+{}⏎\n", str));
206                 prev_both = false;
207                 line_number += 1;
208             }
209             diff::Result::Both(..) => {
210                 line_number += 1;
211                 prev_both = true;
212             }
213         }
214     }
215
216     text
217 }