]> git.lizzy.rs Git - rust.git/blob - tests/system.rs
Use max width for function decls, etc.
[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 extern crate rustfmt;
12 extern crate diff;
13 extern crate regex;
14 extern crate term;
15
16 use std::collections::HashMap;
17 use std::fs;
18 use std::io::{self, Read, BufRead, BufReader};
19
20 use rustfmt::*;
21 use rustfmt::config::{Config, ReportTactic};
22 use rustfmt::rustfmt_diff::*;
23
24 static DIFF_CONTEXT_SIZE: usize = 3;
25
26 fn get_path_string(dir_entry: io::Result<fs::DirEntry>) -> String {
27     let path = dir_entry.ok().expect("Couldn't get DirEntry.").path();
28
29     path.to_str().expect("Couldn't stringify path.").to_owned()
30 }
31
32 // Integration tests. The files in the tests/source are formatted and compared
33 // to their equivalent in tests/target. The target file and config can be
34 // overriden by annotations in the source file. The input and output must match
35 // exactly.
36 // FIXME(#28) would be good to check for error messages and fail on them, or at
37 // least report.
38 #[test]
39 fn system_tests() {
40     // Get all files in the tests/source directory.
41     let files = fs::read_dir("tests/source").ok().expect("Couldn't read source dir.");
42     // Turn a DirEntry into a String that represents the relative path to the
43     // file.
44     let files = files.map(get_path_string);
45     let (_reports, count, fails) = check_files(files);
46
47     // Display results.
48     println!("Ran {} system tests.", count);
49     assert!(fails == 0, "{} system tests failed", fails);
50 }
51
52 // Idempotence tests. Files in tests/target are checked to be unaltered by
53 // rustfmt.
54 #[test]
55 fn idempotence_tests() {
56     // Get all files in the tests/target directory.
57     let files = fs::read_dir("tests/target")
58                     .ok()
59                     .expect("Couldn't read target dir.")
60                     .map(get_path_string);
61     let (_reports, count, fails) = check_files(files);
62
63     // Display results.
64     println!("Ran {} idempotent tests.", count);
65     assert!(fails == 0, "{} idempotent tests failed", fails);
66 }
67
68 // Run rustfmt on itself. This operation must be idempotent. We also check that
69 // no warnings are emitted.
70 #[test]
71 fn self_tests() {
72     let files = fs::read_dir("src/bin")
73                     .ok()
74                     .expect("Couldn't read src dir.")
75                     .chain(fs::read_dir("tests").ok().expect("Couldn't read tests dir."))
76                     .map(get_path_string);
77     // Hack because there's no `IntoIterator` impl for `[T; N]`.
78     let files = files.chain(Some("src/lib.rs".to_owned()).into_iter());
79
80     let (reports, count, fails) = check_files(files);
81     let mut warnings = 0;
82
83     // Display results.
84     println!("Ran {} self tests.", count);
85     assert!(fails == 0, "{} self tests failed", fails);
86
87     for format_report in reports {
88         println!("{}", format_report);
89         warnings += format_report.warning_count();
90     }
91
92     assert!(warnings == 0,
93             "Rustfmt's code generated {} warnings",
94             warnings);
95 }
96
97 // For each file, run rustfmt and collect the output.
98 // Returns the number of files checked and the number of failures.
99 fn check_files<I>(files: I) -> (Vec<FormatReport>, u32, u32)
100     where I: Iterator<Item = String>
101 {
102     let mut count = 0;
103     let mut fails = 0;
104     let mut reports = vec![];
105
106     for file_name in files.filter(|f| f.ends_with(".rs")) {
107         println!("Testing '{}'...", file_name);
108
109         match idempotent_check(file_name) {
110             Ok(report) => reports.push(report),
111             Err(msg) => {
112                 print_mismatches(msg);
113                 fails += 1;
114             }
115         }
116
117         count += 1;
118     }
119
120     (reports, count, fails)
121 }
122
123 fn print_mismatches(result: HashMap<String, Vec<Mismatch>>) {
124     let mut t = term::stdout().unwrap();
125
126     for (file_name, diff) in result {
127         print_diff(diff,
128                    |line_num| format!("\nMismatch at {}:{}:", file_name, line_num));
129     }
130
131     assert!(t.reset().unwrap());
132 }
133
134 pub fn idempotent_check(filename: String) -> Result<FormatReport, HashMap<String, Vec<Mismatch>>> {
135     let sig_comments = read_significant_comments(&filename);
136     let mut config = get_config(sig_comments.get("config").map(|x| &(*x)[..]));
137     let args = vec!["rustfmt".to_owned(), filename];
138
139     for (key, val) in &sig_comments {
140         if key != "target" && key != "config" {
141             config.override_value(key, val);
142         }
143     }
144
145     // Don't generate warnings for to-do items.
146     config.report_todo = ReportTactic::Never;
147
148     let mut file_map = format(args, &config);
149     let format_report = fmt_lines(&mut file_map, &config);
150
151     // Won't panic, as we're not doing any IO.
152     let write_result = filemap::write_all_files(&file_map, WriteMode::Return, &config).unwrap();
153     let target = sig_comments.get("target").map(|x| &(*x)[..]);
154
155     handle_result(write_result, target).map(|_| format_report)
156 }
157
158 // Reads test config file from comments and reads its contents.
159 fn get_config(config_file: Option<&str>) -> Config {
160     let config_file_name = match config_file {
161         None => return Default::default(),
162         Some(file_name) => {
163             let mut full_path = "tests/config/".to_owned();
164             full_path.push_str(&file_name);
165             full_path
166         }
167     };
168
169     let mut def_config_file = fs::File::open(config_file_name)
170                                   .ok()
171                                   .expect("Couldn't open config.");
172     let mut def_config = String::new();
173     def_config_file.read_to_string(&mut def_config).ok().expect("Couldn't read config.");
174
175     Config::from_toml(&def_config)
176 }
177
178 // Reads significant comments of the form: // rustfmt-key: value
179 // into a hash map.
180 fn read_significant_comments(file_name: &str) -> HashMap<String, String> {
181     let file = fs::File::open(file_name)
182                    .ok()
183                    .expect(&format!("Couldn't read file {}.", file_name));
184     let reader = BufReader::new(file);
185     let pattern = r"^\s*//\s*rustfmt-([^:]+):\s*(\S+)";
186     let regex = regex::Regex::new(&pattern).ok().expect("Failed creating pattern 1.");
187
188     // Matches lines containing significant comments or whitespace.
189     let line_regex = regex::Regex::new(r"(^\s*$)|(^\s*//\s*rustfmt-[^:]+:\s*\S+)")
190                          .ok()
191                          .expect("Failed creating pattern 2.");
192
193     reader.lines()
194           .map(|line| line.ok().expect("Failed getting line."))
195           .take_while(|line| line_regex.is_match(&line))
196           .filter_map(|line| {
197               regex.captures_iter(&line).next().map(|capture| {
198                   (capture.at(1).expect("Couldn't unwrap capture.").to_owned(),
199                    capture.at(2).expect("Couldn't unwrap capture.").to_owned())
200               })
201           })
202           .collect()
203 }
204
205 // Compare output to input.
206 // TODO: needs a better name, more explanation.
207 fn handle_result(result: HashMap<String, String>,
208                  target: Option<&str>)
209                  -> Result<(), HashMap<String, Vec<Mismatch>>> {
210     let mut failures = HashMap::new();
211
212     for (file_name, fmt_text) in result {
213         // If file is in tests/source, compare to file with same name in tests/target.
214         let target = get_target(&file_name, target);
215         let mut f = fs::File::open(&target).ok().expect("Couldn't open target.");
216
217         let mut text = String::new();
218         f.read_to_string(&mut text).ok().expect("Failed reading target.");
219
220         if fmt_text != text {
221             let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE);
222             failures.insert(file_name, diff);
223         }
224     }
225
226     if failures.is_empty() {
227         Ok(())
228     } else {
229         Err(failures)
230     }
231 }
232
233 // Map source file paths to their target paths.
234 fn get_target(file_name: &str, target: Option<&str>) -> String {
235     if file_name.starts_with("tests/source/") {
236         let base = target.unwrap_or(file_name.trim_left_matches("tests/source/"));
237
238         format!("tests/target/{}", base)
239     } else {
240         file_name.to_owned()
241     }
242 }