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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/*
 * Copyright (c) 2018 Pascal Bach
 * Copyright (c) 2021 Siemens Mobility GmbH
 *
 * SPDX-License-Identifier:     MIT
 */

use std::io::Write;

use derive_getters::Getters;
use quick_xml::events::BytesDecl;
use quick_xml::{
    events::{BytesCData, Event},
    ElementWriter, Result, Writer,
};
use time::format_description::well_known::Rfc3339;

use crate::{TestCase, TestResult, TestSuite};

/// Root element of a JUnit report
#[derive(Default, Debug, Clone, Getters)]
pub struct Report {
    testsuites: Vec<TestSuite>,
}

impl Report {
    /// Create a new empty Report
    pub fn new() -> Report {
        Report {
            testsuites: Vec::new(),
        }
    }

    /// Add a [`TestSuite`](struct.TestSuite.html) to this report.
    ///
    /// The function takes ownership of the supplied [`TestSuite`](struct.TestSuite.html).
    pub fn add_testsuite(&mut self, testsuite: TestSuite) {
        self.testsuites.push(testsuite);
    }

    /// Add multiple[`TestSuite`s](struct.TestSuite.html) from an iterator.
    pub fn add_testsuites(&mut self, testsuites: impl IntoIterator<Item = TestSuite>) {
        self.testsuites.extend(testsuites);
    }

    /// Write the XML version of the Report to the given `Writer`.
    pub fn write_xml<W: Write>(&self, sink: W) -> Result<()> {
        let mut writer = Writer::new(sink);

        writer.write_event(Event::Decl(BytesDecl::new("1.0", Some("utf-8"), None)))?;

        writer
            .create_element("testsuites")
            .write_empty_or_inner(
                |_| self.testsuites.is_empty(),
                |w| {
                    w.write_iter(self.testsuites.iter().enumerate(), |w, (id, ts)| {
                        w.create_element("testsuite")
                            .with_attributes([
                                ("id", id.to_string().as_str()),
                                ("name", &ts.name),
                                ("package", &ts.package),
                                ("tests", &ts.tests().to_string()),
                                ("errors", &ts.errors().to_string()),
                                ("failures", &ts.failures().to_string()),
                                ("hostname", &ts.hostname),
                                ("timestamp", &ts.timestamp.format(&Rfc3339).unwrap()),
                                ("time", &ts.time().as_seconds_f64().to_string()),
                            ])
                            .write_empty_or_inner(
                                |_| {
                                    ts.testcases.is_empty()
                                        && ts.system_out.is_none()
                                        && ts.system_err.is_none()
                                },
                                |w| {
                                    w.write_iter(ts.testcases.iter(), |w, tc| tc.write_xml(w))?
                                        .write_opt(ts.system_out.as_ref(), |writer, out| {
                                            writer
                                                .create_element("system-out")
                                                .write_cdata_content(BytesCData::new(out))
                                        })?
                                        .write_opt(ts.system_err.as_ref(), |writer, err| {
                                            writer
                                                .create_element("system-err")
                                                .write_cdata_content(BytesCData::new(err))
                                        })
                                        .map(drop)
                                },
                            )
                    })
                    .map(drop)
                },
            )
            .map(drop)
    }
}

impl TestCase {
    /// Write the XML version of the [`TestCase`] to the given [`Writer`].
    fn write_xml<'a, W: Write>(&self, w: &'a mut Writer<W>) -> Result<&'a mut Writer<W>> {
        let time = self.time.as_seconds_f64().to_string();
        w.create_element("testcase")
            .with_attributes(
                [
                    Some(("name", self.name.as_str())),
                    Some(("time", time.as_str())),
                    self.classname.as_ref().map(|cl| ("classname", cl.as_str())),
                    self.filepath.as_ref().map(|f| ("file", f.as_str())),
                ]
                .into_iter()
                .flatten(),
            )
            .write_empty_or_inner(
                |_| {
                    matches!(self.result, TestResult::Success)
                        && self.system_out.is_none()
                        && self.system_err.is_none()
                },
                |w| {
                    match self.result {
                        TestResult::Success => w
                            .write_opt(self.system_out.as_ref(), |w, out| {
                                w.create_element("system-out")
                                    .write_cdata_content(BytesCData::new(out.as_str()))
                            })?
                            .write_opt(self.system_err.as_ref(), |w, err| {
                                w.create_element("system-err")
                                    .write_cdata_content(BytesCData::new(err.as_str()))
                            }),
                        TestResult::Error {
                            ref type_,
                            ref message,
                        } => w
                            .create_element("error")
                            .with_attributes([
                                ("type", type_.as_str()),
                                ("message", message.as_str()),
                            ])
                            .write_empty_or_inner(
                                |_| self.system_out.is_none() && self.system_err.is_none(),
                                |w| {
                                    w.write_opt(self.system_out.as_ref(), |w, stdout| {
                                        let data = strip_ansi_escapes::strip(stdout);
                                        w.write_event(Event::CData(BytesCData::new(
                                            String::from_utf8_lossy(&data),
                                        )))
                                        .map(|_| w)
                                    })?
                                    .write_opt(self.system_err.as_ref(), |w, stderr| {
                                        let data = strip_ansi_escapes::strip(stderr);
                                        w.write_event(Event::CData(BytesCData::new(
                                            String::from_utf8_lossy(&data),
                                        )))
                                        .map(|_| w)
                                    })
                                    .map(drop)
                                },
                            ),
                        TestResult::Failure {
                            ref type_,
                            ref message,
                        } => w
                            .create_element("failure")
                            .with_attributes([
                                ("type", type_.as_str()),
                                ("message", message.as_str()),
                            ])
                            .write_empty_or_inner(
                                |_| self.system_out.is_none() && self.system_err.is_none(),
                                |w| {
                                    w.write_opt(self.system_out.as_ref(), |w, stdout| {
                                        let data = strip_ansi_escapes::strip(stdout);
                                        w.write_event(Event::CData(BytesCData::new(
                                            String::from_utf8_lossy(&data),
                                        )))
                                        .map(|_| w)
                                    })?
                                    .write_opt(self.system_err.as_ref(), |w, stderr| {
                                        let data = strip_ansi_escapes::strip(stderr);
                                        w.write_event(Event::CData(BytesCData::new(
                                            String::from_utf8_lossy(&data),
                                        )))
                                        .map(|_| w)
                                    })
                                    .map(drop)
                                },
                            ),
                        TestResult::Skipped => w.create_element("skipped").write_empty(),
                    }
                    .map(drop)
                },
            )
    }
}

/// Builder for JUnit [`Report`](struct.Report.html) objects
#[derive(Default, Debug, Clone, Getters)]
pub struct ReportBuilder {
    report: Report,
}

impl ReportBuilder {
    /// Create a new empty ReportBuilder
    pub fn new() -> ReportBuilder {
        ReportBuilder {
            report: Report::new(),
        }
    }

    /// Add a [`TestSuite`](struct.TestSuite.html) to this report builder.
    ///
    /// The function takes ownership of the supplied [`TestSuite`](struct.TestSuite.html).
    pub fn add_testsuite(&mut self, testsuite: TestSuite) -> &mut Self {
        self.report.testsuites.push(testsuite);
        self
    }

    /// Add multiple[`TestSuite`s](struct.TestSuite.html) from an iterator.
    pub fn add_testsuites(&mut self, testsuites: impl IntoIterator<Item = TestSuite>) -> &mut Self {
        self.report.testsuites.extend(testsuites);
        self
    }

    /// Build and return a [`Report`](struct.Report.html) object based on the data stored in this ReportBuilder object.
    pub fn build(&self) -> Report {
        self.report.clone()
    }
}

/// [`Writer`] extension.
trait WriterExt {
    /// [`Write`]s in case `val` is [`Some`] or does nothing otherwise.
    fn write_opt<T>(
        &mut self,
        val: Option<T>,
        inner: impl FnOnce(&mut Self, T) -> Result<&mut Self>,
    ) -> Result<&mut Self>;

    /// [`Write`]s every item of the [`Iterator`].
    fn write_iter<T, I>(
        &mut self,
        val: I,
        inner: impl FnMut(&mut Self, T) -> Result<&mut Self>,
    ) -> Result<&mut Self>
    where
        I: IntoIterator<Item = T>;
}

impl<W: Write> WriterExt for Writer<W> {
    fn write_opt<T>(
        &mut self,
        val: Option<T>,
        inner: impl FnOnce(&mut Self, T) -> Result<&mut Self>,
    ) -> Result<&mut Self> {
        if let Some(val) = val {
            inner(self, val)
        } else {
            Ok(self)
        }
    }

    fn write_iter<T, I>(
        &mut self,
        iter: I,
        inner: impl FnMut(&mut Self, T) -> Result<&mut Self>,
    ) -> Result<&mut Self>
    where
        I: IntoIterator<Item = T>,
    {
        iter.into_iter().try_fold(self, inner)
    }
}

/// [`ElementWriter`] extension.
trait ElementWriterExt<'a, W: Write> {
    /// [`Writes`] with `inner` in case `is_empty` resolves to [`false`] or
    /// [`Write`]s with [`ElementWriter::write_empty`] otherwise.
    fn write_empty_or_inner<Inner>(
        self,
        is_empty: impl FnOnce(&mut Self) -> bool,
        inner: Inner,
    ) -> Result<&'a mut Writer<W>>
    where
        Inner: Fn(&mut Writer<W>) -> Result<()>;
}

impl<'a, W: Write> ElementWriterExt<'a, W> for ElementWriter<'a, W> {
    fn write_empty_or_inner<Inner>(
        mut self,
        is_empty: impl FnOnce(&mut Self) -> bool,
        inner: Inner,
    ) -> Result<&'a mut Writer<W>>
    where
        Inner: Fn(&mut Writer<W>) -> Result<()>,
    {
        if is_empty(&mut self) {
            self.write_empty()
        } else {
            self.write_inner_content(inner)
        }
    }
}