]> git.lizzy.rs Git - rust.git/blob - library/test/src/formatters/terse.rs
Rollup merge of #90621 - adamgemmell:dev/stabilise-target-feature, r=Amanieu
[rust.git] / library / test / src / formatters / terse.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::NamePadding,
11     types::TestDesc,
12 };
13
14 // insert a '\n' after 100 tests in quiet mode
15 const QUIET_MODE_MAX_COLUMN: usize = 100;
16
17 pub(crate) struct TerseFormatter<T> {
18     out: OutputLocation<T>,
19     use_color: bool,
20     is_multithreaded: bool,
21     /// Number of columns to fill when aligning names
22     max_name_len: usize,
23
24     test_count: usize,
25     total_test_count: usize,
26 }
27
28 impl<T: Write> TerseFormatter<T> {
29     pub fn new(
30         out: OutputLocation<T>,
31         use_color: bool,
32         max_name_len: usize,
33         is_multithreaded: bool,
34     ) -> Self {
35         TerseFormatter {
36             out,
37             use_color,
38             max_name_len,
39             is_multithreaded,
40             test_count: 0,
41             total_test_count: 0, // initialized later, when write_run_start is called
42         }
43     }
44
45     pub fn write_ok(&mut self) -> io::Result<()> {
46         self.write_short_result(".", term::color::GREEN)
47     }
48
49     pub fn write_failed(&mut self) -> io::Result<()> {
50         self.write_short_result("F", term::color::RED)
51     }
52
53     pub fn write_ignored(&mut self) -> io::Result<()> {
54         self.write_short_result("i", term::color::YELLOW)
55     }
56
57     pub fn write_bench(&mut self) -> io::Result<()> {
58         self.write_pretty("bench", term::color::CYAN)
59     }
60
61     pub fn write_short_result(
62         &mut self,
63         result: &str,
64         color: term::color::Color,
65     ) -> io::Result<()> {
66         self.write_pretty(result, color)?;
67         if self.test_count % QUIET_MODE_MAX_COLUMN == QUIET_MODE_MAX_COLUMN - 1 {
68             // we insert a new line every 100 dots in order to flush the
69             // screen when dealing with line-buffered output (e.g., piping to
70             // `stamp` in the rust CI).
71             let out = format!(" {}/{}\n", self.test_count + 1, self.total_test_count);
72             self.write_plain(&out)?;
73         }
74
75         self.test_count += 1;
76         Ok(())
77     }
78
79     pub fn write_pretty(&mut self, word: &str, color: term::color::Color) -> io::Result<()> {
80         match self.out {
81             OutputLocation::Pretty(ref mut term) => {
82                 if self.use_color {
83                     term.fg(color)?;
84                 }
85                 term.write_all(word.as_bytes())?;
86                 if self.use_color {
87                     term.reset()?;
88                 }
89                 term.flush()
90             }
91             OutputLocation::Raw(ref mut stdout) => {
92                 stdout.write_all(word.as_bytes())?;
93                 stdout.flush()
94             }
95         }
96     }
97
98     pub fn write_plain<S: AsRef<str>>(&mut self, s: S) -> io::Result<()> {
99         let s = s.as_ref();
100         self.out.write_all(s.as_bytes())?;
101         self.out.flush()
102     }
103
104     pub fn write_outputs(&mut self, state: &ConsoleTestState) -> io::Result<()> {
105         self.write_plain("\nsuccesses:\n")?;
106         let mut successes = Vec::new();
107         let mut stdouts = String::new();
108         for &(ref f, ref stdout) in &state.not_failures {
109             successes.push(f.name.to_string());
110             if !stdout.is_empty() {
111                 stdouts.push_str(&format!("---- {} stdout ----\n", f.name));
112                 let output = String::from_utf8_lossy(stdout);
113                 stdouts.push_str(&output);
114                 stdouts.push('\n');
115             }
116         }
117         if !stdouts.is_empty() {
118             self.write_plain("\n")?;
119             self.write_plain(&stdouts)?;
120         }
121
122         self.write_plain("\nsuccesses:\n")?;
123         successes.sort();
124         for name in &successes {
125             self.write_plain(&format!("    {name}\n"))?;
126         }
127         Ok(())
128     }
129
130     pub fn write_failures(&mut self, state: &ConsoleTestState) -> io::Result<()> {
131         self.write_plain("\nfailures:\n")?;
132         let mut failures = Vec::new();
133         let mut fail_out = String::new();
134         for &(ref f, ref stdout) in &state.failures {
135             failures.push(f.name.to_string());
136             if !stdout.is_empty() {
137                 fail_out.push_str(&format!("---- {} stdout ----\n", f.name));
138                 let output = String::from_utf8_lossy(stdout);
139                 fail_out.push_str(&output);
140                 fail_out.push('\n');
141             }
142         }
143         if !fail_out.is_empty() {
144             self.write_plain("\n")?;
145             self.write_plain(&fail_out)?;
146         }
147
148         self.write_plain("\nfailures:\n")?;
149         failures.sort();
150         for name in &failures {
151             self.write_plain(&format!("    {name}\n"))?;
152         }
153         Ok(())
154     }
155
156     fn write_test_name(&mut self, desc: &TestDesc) -> io::Result<()> {
157         let name = desc.padded_name(self.max_name_len, desc.name.padding());
158         if let Some(test_mode) = desc.test_mode() {
159             self.write_plain(&format!("test {name} - {test_mode} ... "))?;
160         } else {
161             self.write_plain(&format!("test {name} ... "))?;
162         }
163
164         Ok(())
165     }
166 }
167
168 impl<T: Write> OutputFormatter for TerseFormatter<T> {
169     fn write_run_start(&mut self, test_count: usize, shuffle_seed: Option<u64>) -> io::Result<()> {
170         self.total_test_count = test_count;
171         let noun = if test_count != 1 { "tests" } else { "test" };
172         let shuffle_seed_msg = if let Some(shuffle_seed) = shuffle_seed {
173             format!(" (shuffle seed: {shuffle_seed})")
174         } else {
175             String::new()
176         };
177         self.write_plain(&format!("\nrunning {test_count} {noun}{shuffle_seed_msg}\n"))
178     }
179
180     fn write_test_start(&mut self, desc: &TestDesc) -> io::Result<()> {
181         // Remnants from old libtest code that used the padding value
182         // in order to indicate benchmarks.
183         // When running benchmarks, terse-mode should still print their name as if
184         // it is the Pretty formatter.
185         if !self.is_multithreaded && desc.name.padding() == NamePadding::PadOnRight {
186             self.write_test_name(desc)?;
187         }
188
189         Ok(())
190     }
191
192     fn write_result(
193         &mut self,
194         desc: &TestDesc,
195         result: &TestResult,
196         _: Option<&time::TestExecTime>,
197         _: &[u8],
198         _: &ConsoleTestState,
199     ) -> io::Result<()> {
200         match *result {
201             TestResult::TrOk => self.write_ok(),
202             TestResult::TrFailed | TestResult::TrFailedMsg(_) | TestResult::TrTimedFail => {
203                 self.write_failed()
204             }
205             TestResult::TrIgnored => self.write_ignored(),
206             TestResult::TrBench(ref bs) => {
207                 if self.is_multithreaded {
208                     self.write_test_name(desc)?;
209                 }
210                 self.write_bench()?;
211                 self.write_plain(&format!(": {}\n", fmt_bench_samples(bs)))
212             }
213         }
214     }
215
216     fn write_timeout(&mut self, desc: &TestDesc) -> io::Result<()> {
217         self.write_plain(&format!(
218             "test {} has been running for over {} seconds\n",
219             desc.name,
220             time::TEST_WARN_TIMEOUT_S
221         ))
222     }
223
224     fn write_run_finish(&mut self, state: &ConsoleTestState) -> io::Result<bool> {
225         if state.options.display_output {
226             self.write_outputs(state)?;
227         }
228         let success = state.failed == 0;
229         if !success {
230             self.write_failures(state)?;
231         }
232
233         self.write_plain("\ntest result: ")?;
234
235         if success {
236             // There's no parallelism at this point so it's safe to use color
237             self.write_pretty("ok", term::color::GREEN)?;
238         } else {
239             self.write_pretty("FAILED", term::color::RED)?;
240         }
241
242         let s = format!(
243             ". {} passed; {} failed; {} ignored; {} measured; {} filtered out",
244             state.passed, state.failed, state.ignored, state.measured, state.filtered_out
245         );
246
247         self.write_plain(&s)?;
248
249         if let Some(ref exec_time) = state.exec_time {
250             let time_str = format!("; finished in {exec_time}");
251             self.write_plain(&time_str)?;
252         }
253
254         self.write_plain("\n\n")?;
255
256         Ok(success)
257     }
258 }