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