Skip to content

Commit 38485a9

Browse files
committed
feat(libtest): Add JUnit formatter
1 parent 58bdb08 commit 38485a9

File tree

5 files changed

+150
-5
lines changed

5 files changed

+150
-5
lines changed

library/test/src/cli.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,9 @@ fn optgroups() -> getopts::Options {
9595
"Configure formatting of output:
9696
pretty = Print verbose output;
9797
terse = Display one character per test;
98-
json = Output a json document",
99-
"pretty|terse|json",
98+
json = Output a json document;
99+
junit = Output a JUnit document",
100+
"pretty|terse|json|junit",
100101
)
101102
.optflag("", "show-output", "Show captured stdout of successful tests")
102103
.optopt(
@@ -336,10 +337,15 @@ fn get_format(
336337
}
337338
OutputFormat::Json
338339
}
339-
340+
Some("junit") => {
341+
if !allow_unstable {
342+
return Err("The \"junit\" format is only accepted on the nightly compiler".into());
343+
}
344+
OutputFormat::Junit
345+
}
340346
Some(v) => {
341347
return Err(format!(
342-
"argument for --format must be pretty, terse, or json (was \
348+
"argument for --format must be pretty, terse, json or junit (was \
343349
{})",
344350
v
345351
));

library/test/src/console.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use super::{
1010
cli::TestOpts,
1111
event::{CompletedTest, TestEvent},
1212
filter_tests,
13-
formatters::{JsonFormatter, OutputFormatter, PrettyFormatter, TerseFormatter},
13+
formatters::{JsonFormatter, JunitFormatter, OutputFormatter, PrettyFormatter, TerseFormatter},
1414
helpers::{concurrency::get_concurrency, metrics::MetricMap},
1515
options::{Options, OutputFormat},
1616
run_tests,
@@ -277,6 +277,7 @@ pub fn run_tests_console(opts: &TestOpts, tests: Vec<TestDescAndFn>) -> io::Resu
277277
Box::new(TerseFormatter::new(output, opts.use_color(), max_name_len, is_multithreaded))
278278
}
279279
OutputFormat::Json => Box::new(JsonFormatter::new(output)),
280+
OutputFormat::Junit => Box::new(JunitFormatter::new(output)),
280281
};
281282
let mut st = ConsoleTestState::new(opts)?;
282283

library/test/src/formatters/junit.rs

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
use std::io::{self, prelude::Write};
2+
use std::time::Duration;
3+
4+
use super::OutputFormatter;
5+
use crate::{
6+
console::{ConsoleTestState, OutputLocation},
7+
test_result::TestResult,
8+
time,
9+
types::TestDesc,
10+
};
11+
12+
pub struct JunitFormatter<T> {
13+
out: OutputLocation<T>,
14+
results: Vec<(TestDesc, TestResult, Duration)>,
15+
}
16+
17+
impl<T: Write> JunitFormatter<T> {
18+
pub fn new(out: OutputLocation<T>) -> Self {
19+
Self { out, results: Vec::new() }
20+
}
21+
22+
fn write_message(&mut self, s: &str) -> io::Result<()> {
23+
assert!(!s.contains('\n'));
24+
25+
self.out.write_all(s.as_ref())
26+
}
27+
}
28+
29+
impl<T: Write> OutputFormatter for JunitFormatter<T> {
30+
fn write_run_start(&mut self, _test_count: usize) -> io::Result<()> {
31+
// We write xml header on run start
32+
self.write_message(&"<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
33+
}
34+
35+
fn write_test_start(&mut self, _desc: &TestDesc) -> io::Result<()> {
36+
// We do not output anything on test start.
37+
Ok(())
38+
}
39+
40+
fn write_timeout(&mut self, _desc: &TestDesc) -> io::Result<()> {
41+
// We do not output anything on test timeout.
42+
Ok(())
43+
}
44+
45+
fn write_result(
46+
&mut self,
47+
desc: &TestDesc,
48+
result: &TestResult,
49+
exec_time: Option<&time::TestExecTime>,
50+
_stdout: &[u8],
51+
_state: &ConsoleTestState,
52+
) -> io::Result<()> {
53+
// Because testsuit node holds some of the information as attributes, we can't write it
54+
// until all of the tests has ran. Instead of writting every result as they come in, we add
55+
// them to a Vec and write them all at once when run is complete.
56+
let duration = exec_time.map(|t| t.0.clone()).unwrap_or_default();
57+
self.results.push((desc.clone(), result.clone(), duration));
58+
Ok(())
59+
}
60+
fn write_run_finish(&mut self, state: &ConsoleTestState) -> io::Result<bool> {
61+
self.write_message("<testsuites>")?;
62+
63+
self.write_message(&*format!(
64+
"<testsuite name=\"test\" package=\"test\" id=\"0\" \
65+
errors=\"0\" \
66+
failures=\"{}\" \
67+
tests=\"{}\" \
68+
skipped=\"{}\" \
69+
>",
70+
state.failed, state.total, state.ignored
71+
))?;
72+
for (desc, result, duration) in std::mem::replace(&mut self.results, Vec::new()) {
73+
match result {
74+
TestResult::TrIgnored => { /* no-op */ }
75+
TestResult::TrFailed => {
76+
self.write_message(&*format!(
77+
"<testcase classname=\"test.global\" \
78+
name=\"{}\" time=\"{}\">",
79+
desc.name.as_slice(),
80+
duration.as_secs()
81+
))?;
82+
self.write_message("<failure type=\"assert\"/>")?;
83+
self.write_message("</testcase>")?;
84+
}
85+
86+
TestResult::TrFailedMsg(ref m) => {
87+
self.write_message(&*format!(
88+
"<testcase classname=\"test.global\" \
89+
name=\"{}\" time=\"{}\">",
90+
desc.name.as_slice(),
91+
duration.as_secs()
92+
))?;
93+
self.write_message(&*format!("<failure message=\"{}\" type=\"assert\"/>", m))?;
94+
self.write_message("</testcase>")?;
95+
}
96+
97+
TestResult::TrTimedFail => {
98+
self.write_message(&*format!(
99+
"<testcase classname=\"test.global\" \
100+
name=\"{}\" time=\"{}\">",
101+
desc.name.as_slice(),
102+
duration.as_secs()
103+
))?;
104+
self.write_message("<failure type=\"timeout\"/>")?;
105+
self.write_message("</testcase>")?;
106+
}
107+
108+
TestResult::TrBench(ref b) => {
109+
self.write_message(&*format!(
110+
"<testcase classname=\"benchmark.global\" \
111+
name=\"{}\" time=\"{}\" />",
112+
desc.name.as_slice(),
113+
b.ns_iter_summ.sum
114+
))?;
115+
}
116+
117+
TestResult::TrOk | TestResult::TrAllowedFail => {
118+
self.write_message(&*format!(
119+
"<testcase classname=\"test.global\" \
120+
name=\"{}\" time=\"{}\"/>",
121+
desc.name.as_slice(),
122+
duration.as_secs()
123+
))?;
124+
}
125+
}
126+
}
127+
self.write_message("<system-out/>")?;
128+
self.write_message("<system-err/>")?;
129+
self.write_message("</testsuite>")?;
130+
self.write_message("</testsuites>")?;
131+
132+
Ok(state.failed == 0)
133+
}
134+
}

library/test/src/formatters/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,12 @@ use crate::{
88
};
99

1010
mod json;
11+
mod junit;
1112
mod pretty;
1213
mod terse;
1314

1415
pub(crate) use self::json::JsonFormatter;
16+
pub(crate) use self::junit::JunitFormatter;
1517
pub(crate) use self::pretty::PrettyFormatter;
1618
pub(crate) use self::terse::TerseFormatter;
1719

library/test/src/options.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ pub enum OutputFormat {
3939
Terse,
4040
/// JSON output
4141
Json,
42+
/// JUnit output
43+
Junit,
4244
}
4345

4446
/// Whether ignored test should be run or not

0 commit comments

Comments
 (0)