]> git.lizzy.rs Git - rust.git/blob - library/test/src/formatters/pretty.rs
Rollup merge of #91950 - estebank:point-at-type-of-non-allocator, r=matthewjasper
[rust.git] / library / test / src / formatters / pretty.rs
1 use std::{io, io::prelude::Write};
2
3 use super::OutputFormatter;
4 use crate::{
5     bench::fmt_bench_samples,
6     console::{ConsoleTestState, OutputLocation},
7     term,
8     test_result::TestResult,
9     time,
10     types::TestDesc,
11 };
12
13 pub(crate) struct PrettyFormatter<T> {
14     out: OutputLocation<T>,
15     use_color: bool,
16     time_options: Option<time::TestTimeOptions>,
17
18     /// Number of columns to fill when aligning names
19     max_name_len: usize,
20
21     is_multithreaded: bool,
22 }
23
24 impl<T: Write> PrettyFormatter<T> {
25     pub fn new(
26         out: OutputLocation<T>,
27         use_color: bool,
28         max_name_len: usize,
29         is_multithreaded: bool,
30         time_options: Option<time::TestTimeOptions>,
31     ) -> Self {
32         PrettyFormatter { out, use_color, max_name_len, is_multithreaded, time_options }
33     }
34
35     #[cfg(test)]
36     pub fn output_location(&self) -> &OutputLocation<T> {
37         &self.out
38     }
39
40     pub fn write_ok(&mut self) -> io::Result<()> {
41         self.write_short_result("ok", term::color::GREEN)
42     }
43
44     pub fn write_failed(&mut self) -> io::Result<()> {
45         self.write_short_result("FAILED", term::color::RED)
46     }
47
48     pub fn write_ignored(&mut self) -> io::Result<()> {
49         self.write_short_result("ignored", 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             OutputLocation::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             OutputLocation::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<&time::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('\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         if let Some(test_mode) = desc.test_mode() {
170             self.write_plain(&format!("test {} - {} ... ", name, test_mode))?;
171         } else {
172             self.write_plain(&format!("test {} ... ", name))?;
173         }
174
175         Ok(())
176     }
177 }
178
179 impl<T: Write> OutputFormatter for PrettyFormatter<T> {
180     fn write_run_start(&mut self, test_count: usize, shuffle_seed: Option<u64>) -> io::Result<()> {
181         let noun = if test_count != 1 { "tests" } else { "test" };
182         let shuffle_seed_msg = if let Some(shuffle_seed) = shuffle_seed {
183             format!(" (shuffle seed: {})", shuffle_seed)
184         } else {
185             String::new()
186         };
187         self.write_plain(&format!("\nrunning {} {}{}\n", test_count, noun, shuffle_seed_msg))
188     }
189
190     fn write_test_start(&mut self, desc: &TestDesc) -> io::Result<()> {
191         // When running tests concurrently, we should not print
192         // the test's name as the result will be mis-aligned.
193         // When running the tests serially, we print the name here so
194         // that the user can see which test hangs.
195         if !self.is_multithreaded {
196             self.write_test_name(desc)?;
197         }
198
199         Ok(())
200     }
201
202     fn write_result(
203         &mut self,
204         desc: &TestDesc,
205         result: &TestResult,
206         exec_time: Option<&time::TestExecTime>,
207         _: &[u8],
208         _: &ConsoleTestState,
209     ) -> io::Result<()> {
210         if self.is_multithreaded {
211             self.write_test_name(desc)?;
212         }
213
214         match *result {
215             TestResult::TrOk => self.write_ok()?,
216             TestResult::TrFailed | TestResult::TrFailedMsg(_) => self.write_failed()?,
217             TestResult::TrIgnored => self.write_ignored()?,
218             TestResult::TrBench(ref bs) => {
219                 self.write_bench()?;
220                 self.write_plain(&format!(": {}", fmt_bench_samples(bs)))?;
221             }
222             TestResult::TrTimedFail => self.write_time_failed()?,
223         }
224
225         self.write_time(desc, exec_time)?;
226         self.write_plain("\n")
227     }
228
229     fn write_timeout(&mut self, desc: &TestDesc) -> io::Result<()> {
230         self.write_plain(&format!(
231             "test {} has been running for over {} seconds\n",
232             desc.name,
233             time::TEST_WARN_TIMEOUT_S
234         ))
235     }
236
237     fn write_run_finish(&mut self, state: &ConsoleTestState) -> io::Result<bool> {
238         if state.options.display_output {
239             self.write_successes(state)?;
240         }
241         let success = state.failed == 0;
242         if !success {
243             if !state.failures.is_empty() {
244                 self.write_failures(state)?;
245             }
246
247             if !state.time_failures.is_empty() {
248                 self.write_time_failures(state)?;
249             }
250         }
251
252         self.write_plain("\ntest result: ")?;
253
254         if success {
255             // There's no parallelism at this point so it's safe to use color
256             self.write_pretty("ok", term::color::GREEN)?;
257         } else {
258             self.write_pretty("FAILED", term::color::RED)?;
259         }
260
261         let s = format!(
262             ". {} passed; {} failed; {} ignored; {} measured; {} filtered out",
263             state.passed, state.failed, state.ignored, state.measured, state.filtered_out
264         );
265
266         self.write_plain(&s)?;
267
268         if let Some(ref exec_time) = state.exec_time {
269             let time_str = format!("; finished in {}", exec_time);
270             self.write_plain(&time_str)?;
271         }
272
273         self.write_plain("\n\n")?;
274
275         Ok(success)
276     }
277 }