]> git.lizzy.rs Git - rust.git/blob - src/libtest/formatters/pretty.rs
Rollup merge of #65307 - Phosphorus15:master, r=varkor
[rust.git] / src / libtest / formatters / pretty.rs
1 use super::*;
2
3 pub(crate) struct PrettyFormatter<T> {
4     out: OutputLocation<T>,
5     use_color: bool,
6     time_options: Option<TestTimeOptions>,
7
8     /// Number of columns to fill when aligning names
9     max_name_len: usize,
10
11     is_multithreaded: bool,
12 }
13
14 impl<T: Write> PrettyFormatter<T> {
15     pub fn new(
16         out: OutputLocation<T>,
17         use_color: bool,
18         max_name_len: usize,
19         is_multithreaded: bool,
20         time_options: Option<TestTimeOptions>,
21     ) -> Self {
22         PrettyFormatter {
23             out,
24             use_color,
25             max_name_len,
26             is_multithreaded,
27             time_options
28         }
29     }
30
31     #[cfg(test)]
32     pub fn output_location(&self) -> &OutputLocation<T> {
33         &self.out
34     }
35
36     pub fn write_ok(&mut self) -> io::Result<()> {
37         self.write_short_result("ok", term::color::GREEN)
38     }
39
40     pub fn write_failed(&mut self) -> io::Result<()> {
41         self.write_short_result("FAILED", term::color::RED)
42     }
43
44     pub fn write_ignored(&mut self) -> io::Result<()> {
45         self.write_short_result("ignored", term::color::YELLOW)
46     }
47
48     pub fn write_allowed_fail(&mut self) -> io::Result<()> {
49         self.write_short_result("FAILED (allowed)", term::color::YELLOW)
50     }
51
52     pub fn write_time_failed(&mut self) -> io::Result<()> {
53         self.write_short_result("FAILED (time limit exceeded)", term::color::RED)
54     }
55
56     pub fn write_bench(&mut self) -> io::Result<()> {
57         self.write_pretty("bench", term::color::CYAN)
58     }
59
60     pub fn write_short_result(
61         &mut self,
62         result: &str,
63         color: term::color::Color,
64     ) -> io::Result<()> {
65         self.write_pretty(result, color)
66     }
67
68     pub fn write_pretty(&mut self, word: &str, color: term::color::Color) -> io::Result<()> {
69         match self.out {
70             Pretty(ref mut term) => {
71                 if self.use_color {
72                     term.fg(color)?;
73                 }
74                 term.write_all(word.as_bytes())?;
75                 if self.use_color {
76                     term.reset()?;
77                 }
78                 term.flush()
79             }
80             Raw(ref mut stdout) => {
81                 stdout.write_all(word.as_bytes())?;
82                 stdout.flush()
83             }
84         }
85     }
86
87     pub fn write_plain<S: AsRef<str>>(&mut self, s: S) -> io::Result<()> {
88         let s = s.as_ref();
89         self.out.write_all(s.as_bytes())?;
90         self.out.flush()
91     }
92
93     fn write_time(
94         &mut self,
95         desc: &TestDesc,
96         exec_time: Option<&TestExecTime>
97     ) -> io::Result<()> {
98         if let (Some(opts), Some(time)) = (self.time_options, exec_time) {
99             let time_str = format!(" <{}>", time);
100
101             let color = if opts.colored {
102                 if opts.is_critical(desc, time) {
103                     Some(term::color::RED)
104                 } else if opts.is_warn(desc, time) {
105                     Some(term::color::YELLOW)
106                 } else {
107                     None
108                 }
109             } else {
110                 None
111             };
112
113             match color {
114                 Some(color) => self.write_pretty(&time_str, color)?,
115                 None => self.write_plain(&time_str)?
116             }
117         }
118
119         Ok(())
120     }
121
122     fn write_results(
123         &mut self,
124         inputs: &Vec<(TestDesc, Vec<u8>)>,
125         results_type: &str
126     ) -> io::Result<()> {
127         let results_out_str = format!("\n{}:\n", results_type);
128
129         self.write_plain(&results_out_str)?;
130
131         let mut results = Vec::new();
132         let mut stdouts = String::new();
133         for &(ref f, ref stdout) in inputs {
134             results.push(f.name.to_string());
135             if !stdout.is_empty() {
136                 stdouts.push_str(&format!("---- {} stdout ----\n", f.name));
137                 let output = String::from_utf8_lossy(stdout);
138                 stdouts.push_str(&output);
139                 stdouts.push_str("\n");
140             }
141         }
142         if !stdouts.is_empty() {
143             self.write_plain("\n")?;
144             self.write_plain(&stdouts)?;
145         }
146
147         self.write_plain(&results_out_str)?;
148         results.sort();
149         for name in &results {
150             self.write_plain(&format!("    {}\n", name))?;
151         }
152         Ok(())
153     }
154
155     pub fn write_successes(&mut self, state: &ConsoleTestState) -> io::Result<()> {
156         self.write_results(&state.not_failures, "successes")
157     }
158
159     pub fn write_failures(&mut self, state: &ConsoleTestState) -> io::Result<()> {
160         self.write_results(&state.failures, "failures")
161     }
162
163     pub fn write_time_failures(&mut self, state: &ConsoleTestState) -> io::Result<()> {
164         self.write_results(&state.time_failures, "failures (time limit exceeded)")
165     }
166
167     fn write_test_name(&mut self, desc: &TestDesc) -> io::Result<()> {
168         let name = desc.padded_name(self.max_name_len, desc.name.padding());
169         self.write_plain(&format!("test {} ... ", name))?;
170
171         Ok(())
172     }
173 }
174
175 impl<T: Write> OutputFormatter for PrettyFormatter<T> {
176     fn write_run_start(&mut self, test_count: usize) -> io::Result<()> {
177         let noun = if test_count != 1 { "tests" } else { "test" };
178         self.write_plain(&format!("\nrunning {} {}\n", test_count, noun))
179     }
180
181     fn write_test_start(&mut self, desc: &TestDesc) -> io::Result<()> {
182         // When running tests concurrently, we should not print
183         // the test's name as the result will be mis-aligned.
184         // When running the tests serially, we print the name here so
185         // that the user can see which test hangs.
186         if !self.is_multithreaded {
187             self.write_test_name(desc)?;
188         }
189
190         Ok(())
191     }
192
193     fn write_result(
194         &mut self,
195         desc: &TestDesc,
196         result: &TestResult,
197         exec_time: Option<&TestExecTime>,
198         _: &[u8],
199         _: &ConsoleTestState,
200     ) -> io::Result<()> {
201         if self.is_multithreaded {
202             self.write_test_name(desc)?;
203         }
204
205         match *result {
206             TrOk => self.write_ok()?,
207             TrFailed | TrFailedMsg(_) => self.write_failed()?,
208             TrIgnored => self.write_ignored()?,
209             TrAllowedFail => self.write_allowed_fail()?,
210             TrBench(ref bs) => {
211                 self.write_bench()?;
212                 self.write_plain(&format!(": {}", fmt_bench_samples(bs)))?;
213             }
214             TrTimedFail => self.write_time_failed()?,
215         }
216
217         self.write_time(desc, exec_time)?;
218         self.write_plain("\n")
219     }
220
221     fn write_timeout(&mut self, desc: &TestDesc) -> io::Result<()> {
222         if self.is_multithreaded {
223             self.write_test_name(desc)?;
224         }
225
226         self.write_plain(&format!(
227             "test {} has been running for over {} seconds\n",
228             desc.name, TEST_WARN_TIMEOUT_S
229         ))
230     }
231
232     fn write_run_finish(&mut self, state: &ConsoleTestState) -> io::Result<bool> {
233         if state.options.display_output {
234             self.write_successes(state)?;
235         }
236         let success = state.failed == 0;
237         if !success {
238             if !state.failures.is_empty() {
239                 self.write_failures(state)?;
240             }
241
242             if !state.time_failures.is_empty() {
243                 self.write_time_failures(state)?;
244             }
245         }
246
247         self.write_plain("\ntest result: ")?;
248
249         if success {
250             // There's no parallelism at this point so it's safe to use color
251             self.write_pretty("ok", term::color::GREEN)?;
252         } else {
253             self.write_pretty("FAILED", term::color::RED)?;
254         }
255
256         let s = if state.allowed_fail > 0 {
257             format!(
258                 ". {} passed; {} failed ({} allowed); {} ignored; {} measured; {} filtered out\n\n",
259                 state.passed,
260                 state.failed + state.allowed_fail,
261                 state.allowed_fail,
262                 state.ignored,
263                 state.measured,
264                 state.filtered_out
265             )
266         } else {
267             format!(
268                 ". {} passed; {} failed; {} ignored; {} measured; {} filtered out\n\n",
269                 state.passed, state.failed, state.ignored, state.measured, state.filtered_out
270             )
271         };
272
273         self.write_plain(&s)?;
274
275         Ok(success)
276     }
277 }