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