1 use std::{borrow::Cow, io, io::prelude::Write};
3 use super::OutputFormatter;
5 console::{ConsoleTestState, OutputLocation},
6 test_result::TestResult,
11 pub(crate) struct JsonFormatter<T> {
12 out: OutputLocation<T>,
15 impl<T: Write> JsonFormatter<T> {
16 pub fn new(out: OutputLocation<T>) -> Self {
20 fn writeln_message(&mut self, s: &str) -> io::Result<()> {
21 assert!(!s.contains('\n'));
23 self.out.write_all(s.as_ref())?;
24 self.out.write_all(b"\n")
27 fn write_message(&mut self, s: &str) -> io::Result<()> {
28 assert!(!s.contains('\n'));
30 self.out.write_all(s.as_ref())
38 exec_time: Option<&time::TestExecTime>,
39 stdout: Option<Cow<'_, str>>,
42 // A doc test's name includes a filename which must be escaped for correct json.
43 self.write_message(&*format!(
44 r#"{{ "type": "{}", "name": "{}", "event": "{}""#,
49 if let Some(exec_time) = exec_time {
50 self.write_message(&*format!(r#", "exec_time": {}"#, exec_time.0.as_secs_f64()))?;
52 if let Some(stdout) = stdout {
53 self.write_message(&*format!(r#", "stdout": "{}""#, EscapedString(stdout)))?;
55 if let Some(extra) = extra {
56 self.write_message(&*format!(r#", {}"#, extra))?;
58 self.writeln_message(" }")
62 impl<T: Write> OutputFormatter for JsonFormatter<T> {
63 fn write_run_start(&mut self, test_count: usize, shuffle_seed: Option<u64>) -> io::Result<()> {
64 let shuffle_seed_json = if let Some(shuffle_seed) = shuffle_seed {
65 format!(r#", "shuffle_seed": {}"#, shuffle_seed)
69 self.writeln_message(&*format!(
70 r#"{{ "type": "suite", "event": "started", "test_count": {}{} }}"#,
71 test_count, shuffle_seed_json
75 fn write_test_start(&mut self, desc: &TestDesc) -> io::Result<()> {
76 self.writeln_message(&*format!(
77 r#"{{ "type": "test", "event": "started", "name": "{}" }}"#,
78 EscapedString(desc.name.as_slice())
86 exec_time: Option<&time::TestExecTime>,
88 state: &ConsoleTestState,
90 let display_stdout = state.options.display_output || *result != TestResult::TrOk;
91 let stdout = if display_stdout && !stdout.is_empty() {
92 Some(String::from_utf8_lossy(stdout))
98 self.write_event("test", desc.name.as_slice(), "ok", exec_time, stdout, None)
101 TestResult::TrFailed => {
102 self.write_event("test", desc.name.as_slice(), "failed", exec_time, stdout, None)
105 TestResult::TrTimedFail => self.write_event(
107 desc.name.as_slice(),
111 Some(r#""reason": "time limit exceeded""#),
114 TestResult::TrFailedMsg(ref m) => self.write_event(
116 desc.name.as_slice(),
120 Some(&*format!(r#""message": "{}""#, EscapedString(m))),
123 TestResult::TrIgnored => {
124 #[cfg(not(bootstrap))]
125 return self.write_event(
127 desc.name.as_slice(),
132 .map(|msg| format!(r#""message": "{}""#, EscapedString(msg)))
137 self.write_event("test", desc.name.as_slice(), "ignored", exec_time, stdout, None)
140 TestResult::TrBench(ref bs) => {
141 let median = bs.ns_iter_summ.median as usize;
142 let deviation = (bs.ns_iter_summ.max - bs.ns_iter_summ.min) as usize;
144 let mbps = if bs.mb_s == 0 {
147 format!(r#", "mib_per_second": {}"#, bs.mb_s)
151 "{{ \"type\": \"bench\", \
154 \"deviation\": {}{} }}",
155 EscapedString(desc.name.as_slice()),
161 self.writeln_message(&*line)
166 fn write_timeout(&mut self, desc: &TestDesc) -> io::Result<()> {
167 self.writeln_message(&*format!(
168 r#"{{ "type": "test", "event": "timeout", "name": "{}" }}"#,
169 EscapedString(desc.name.as_slice())
173 fn write_run_finish(&mut self, state: &ConsoleTestState) -> io::Result<bool> {
174 self.write_message(&*format!(
175 "{{ \"type\": \"suite\", \
181 \"filtered_out\": {}",
182 if state.failed == 0 { "ok" } else { "failed" },
190 if let Some(ref exec_time) = state.exec_time {
191 let time_str = format!(", \"exec_time\": {}", exec_time.0.as_secs_f64());
192 self.write_message(&time_str)?;
195 self.writeln_message(" }")?;
197 Ok(state.failed == 0)
201 /// A formatting utility used to print strings with characters in need of escaping.
202 /// Base code taken form `libserialize::json::escape_str`
203 struct EscapedString<S: AsRef<str>>(S);
205 impl<S: AsRef<str>> std::fmt::Display for EscapedString<S> {
206 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> ::std::fmt::Result {
209 for (i, byte) in self.0.as_ref().bytes().enumerate() {
210 let escaped = match byte {
213 b'\x00' => "\\u0000",
214 b'\x01' => "\\u0001",
215 b'\x02' => "\\u0002",
216 b'\x03' => "\\u0003",
217 b'\x04' => "\\u0004",
218 b'\x05' => "\\u0005",
219 b'\x06' => "\\u0006",
220 b'\x07' => "\\u0007",
224 b'\x0b' => "\\u000b",
227 b'\x0e' => "\\u000e",
228 b'\x0f' => "\\u000f",
229 b'\x10' => "\\u0010",
230 b'\x11' => "\\u0011",
231 b'\x12' => "\\u0012",
232 b'\x13' => "\\u0013",
233 b'\x14' => "\\u0014",
234 b'\x15' => "\\u0015",
235 b'\x16' => "\\u0016",
236 b'\x17' => "\\u0017",
237 b'\x18' => "\\u0018",
238 b'\x19' => "\\u0019",
239 b'\x1a' => "\\u001a",
240 b'\x1b' => "\\u001b",
241 b'\x1c' => "\\u001c",
242 b'\x1d' => "\\u001d",
243 b'\x1e' => "\\u001e",
244 b'\x1f' => "\\u001f",
245 b'\x7f' => "\\u007f",
252 f.write_str(&self.0.as_ref()[start..i])?;
255 f.write_str(escaped)?;
260 if start != self.0.as_ref().len() {
261 f.write_str(&self.0.as_ref()[start..])?;