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