1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
use std::{io, io::prelude::Write};

use super::OutputFormatter;
use crate::{
    bench::fmt_bench_samples,
    console::{ConsoleTestDiscoveryState, ConsoleTestState, OutputLocation},
    term,
    test_result::TestResult,
    time,
    types::NamePadding,
    types::TestDesc,
};

// 当输出在安静模式下达到 100 列时,我们插入一个 '\n'。
// 88 个测试结果字符为 " 11704/12853" 等进度计数留下 12 个字符。
const QUIET_MODE_MAX_COLUMN: usize = 88;

pub(crate) struct TerseFormatter<T> {
    out: OutputLocation<T>,
    use_color: bool,
    is_multithreaded: bool,
    /// 对齐名称时要填充的列数
    max_name_len: usize,

    test_count: usize,
    total_test_count: usize,
}

impl<T: Write> TerseFormatter<T> {
    pub fn new(
        out: OutputLocation<T>,
        use_color: bool,
        max_name_len: usize,
        is_multithreaded: bool,
    ) -> Self {
        TerseFormatter {
            out,
            use_color,
            max_name_len,
            is_multithreaded,
            test_count: 0,
            total_test_count: 0, // 稍后在调用 write_run_start 时初始化
        }
    }

    pub fn write_ok(&mut self) -> io::Result<()> {
        self.write_short_result(".", term::color::GREEN)
    }

    pub fn write_failed(&mut self) -> io::Result<()> {
        self.write_short_result("F", term::color::RED)
    }

    pub fn write_ignored(&mut self) -> io::Result<()> {
        self.write_short_result("i", term::color::YELLOW)
    }

    pub fn write_bench(&mut self) -> io::Result<()> {
        self.write_pretty("bench", term::color::CYAN)
    }

    pub fn write_short_result(
        &mut self,
        result: &str,
        color: term::color::Color,
    ) -> io::Result<()> {
        self.write_pretty(result, color)?;
        if self.test_count % QUIET_MODE_MAX_COLUMN == QUIET_MODE_MAX_COLUMN - 1 {
            // 在处理行缓冲输出 (例如,rust CI 中的 `stamp` 管道) 时,我们会定期插入新行以刷新屏幕。
            //
            //
            let out = format!(" {}/{}\n", self.test_count + 1, self.total_test_count);
            self.write_plain(out)?;
        }

        self.test_count += 1;
        Ok(())
    }

    pub fn write_pretty(&mut self, word: &str, color: term::color::Color) -> io::Result<()> {
        match self.out {
            OutputLocation::Pretty(ref mut term) => {
                if self.use_color {
                    term.fg(color)?;
                }
                term.write_all(word.as_bytes())?;
                if self.use_color {
                    term.reset()?;
                }
                term.flush()
            }
            OutputLocation::Raw(ref mut stdout) => {
                stdout.write_all(word.as_bytes())?;
                stdout.flush()
            }
        }
    }

    pub fn write_plain<S: AsRef<str>>(&mut self, s: S) -> io::Result<()> {
        let s = s.as_ref();
        self.out.write_all(s.as_bytes())?;
        self.out.flush()
    }

    pub fn write_outputs(&mut self, state: &ConsoleTestState) -> io::Result<()> {
        self.write_plain("\nsuccesses:\n")?;
        let mut successes = Vec::new();
        let mut stdouts = String::new();
        for (f, stdout) in &state.not_failures {
            successes.push(f.name.to_string());
            if !stdout.is_empty() {
                stdouts.push_str(&format!("---- {} stdout ----\n", f.name));
                let output = String::from_utf8_lossy(stdout);
                stdouts.push_str(&output);
                stdouts.push('\n');
            }
        }
        if !stdouts.is_empty() {
            self.write_plain("\n")?;
            self.write_plain(&stdouts)?;
        }

        self.write_plain("\nsuccesses:\n")?;
        successes.sort();
        for name in &successes {
            self.write_plain(&format!("    {name}\n"))?;
        }
        Ok(())
    }

    pub fn write_failures(&mut self, state: &ConsoleTestState) -> io::Result<()> {
        self.write_plain("\nfailures:\n")?;
        let mut failures = Vec::new();
        let mut fail_out = String::new();
        for (f, stdout) in &state.failures {
            failures.push(f.name.to_string());
            if !stdout.is_empty() {
                fail_out.push_str(&format!("---- {} stdout ----\n", f.name));
                let output = String::from_utf8_lossy(stdout);
                fail_out.push_str(&output);
                fail_out.push('\n');
            }
        }
        if !fail_out.is_empty() {
            self.write_plain("\n")?;
            self.write_plain(&fail_out)?;
        }

        self.write_plain("\nfailures:\n")?;
        failures.sort();
        for name in &failures {
            self.write_plain(&format!("    {name}\n"))?;
        }
        Ok(())
    }

    fn write_test_name(&mut self, desc: &TestDesc) -> io::Result<()> {
        let name = desc.padded_name(self.max_name_len, desc.name.padding());
        if let Some(test_mode) = desc.test_mode() {
            self.write_plain(format!("test {name} - {test_mode} ... "))?;
        } else {
            self.write_plain(format!("test {name} ... "))?;
        }

        Ok(())
    }
}

impl<T: Write> OutputFormatter for TerseFormatter<T> {
    fn write_discovery_start(&mut self) -> io::Result<()> {
        Ok(())
    }

    fn write_test_discovered(&mut self, desc: &TestDesc, test_type: &str) -> io::Result<()> {
        self.write_plain(format!("{}: {test_type}\n", desc.name))
    }

    fn write_discovery_finish(&mut self, _state: &ConsoleTestDiscoveryState) -> io::Result<()> {
        Ok(())
    }

    fn write_run_start(&mut self, test_count: usize, shuffle_seed: Option<u64>) -> io::Result<()> {
        self.total_test_count = test_count;
        let noun = if test_count != 1 { "tests" } else { "test" };
        let shuffle_seed_msg = if let Some(shuffle_seed) = shuffle_seed {
            format!(" (shuffle seed: {shuffle_seed})")
        } else {
            String::new()
        };
        self.write_plain(format!("\nrunning {test_count} {noun}{shuffle_seed_msg}\n"))
    }

    fn write_test_start(&mut self, desc: &TestDesc) -> io::Result<()> {
        // 旧 libtest 代码的残余部分,这些代码使用填充值来指示基准。
        // 在运行基准测试时,简洁模式仍应打印其名称,就像它是 Pretty 格式化程序一样。
        //
        //
        if !self.is_multithreaded && desc.name.padding() == NamePadding::PadOnRight {
            self.write_test_name(desc)?;
        }

        Ok(())
    }

    fn write_result(
        &mut self,
        desc: &TestDesc,
        result: &TestResult,
        _: Option<&time::TestExecTime>,
        _: &[u8],
        _: &ConsoleTestState,
    ) -> io::Result<()> {
        match *result {
            TestResult::TrOk => self.write_ok(),
            TestResult::TrFailed | TestResult::TrFailedMsg(_) | TestResult::TrTimedFail => {
                self.write_failed()
            }
            TestResult::TrIgnored => self.write_ignored(),
            TestResult::TrBench(ref bs) => {
                if self.is_multithreaded {
                    self.write_test_name(desc)?;
                }
                self.write_bench()?;
                self.write_plain(format!(": {}\n", fmt_bench_samples(bs)))
            }
        }
    }

    fn write_timeout(&mut self, desc: &TestDesc) -> io::Result<()> {
        self.write_plain(format!(
            "test {} has been running for over {} seconds\n",
            desc.name,
            time::TEST_WARN_TIMEOUT_S
        ))
    }

    fn write_run_finish(&mut self, state: &ConsoleTestState) -> io::Result<bool> {
        if state.options.display_output {
            self.write_outputs(state)?;
        }
        let success = state.failed == 0;
        if !success {
            self.write_failures(state)?;
        }

        self.write_plain("\ntest result: ")?;

        if success {
            // 此时没有并行性,因此使用颜色是安全的
            self.write_pretty("ok", term::color::GREEN)?;
        } else {
            self.write_pretty("FAILED", term::color::RED)?;
        }

        let s = format!(
            ". {} passed; {} failed; {} ignored; {} measured; {} filtered out",
            state.passed, state.failed, state.ignored, state.measured, state.filtered_out
        );

        self.write_plain(s)?;

        if let Some(ref exec_time) = state.exec_time {
            let time_str = format!("; finished in {exec_time}");
            self.write_plain(time_str)?;
        }

        self.write_plain("\n\n")?;

        // 自定义处理只有 1 个测试要执行且该测试被忽略的情况。
        // 我们希望显示更详细的 information(为什么这个测试被忽略了) 以供调查之用。
        if self.total_test_count == 1 && state.ignores.len() == 1 {
            let test_desc = &state.ignores[0].0;
            if let Some(im) = test_desc.ignore_message {
                self.write_plain(format!("test: {}, ignore_message: {}\n\n", test_desc.name, im))?;
            }
        }

        Ok(success)
    }
}