Skip to main content

litz_cli/
report.rs

1//! Machine-readable results.
2//!
3//! A CI job should not have to parse a terminal. Two shapes cover nearly
4//! everything: a single JSON object for a script that wants one answer, and
5//! JUnit XML for the dashboards that already read test reports. Both are
6//! derived from the same [`Outcome`], so they cannot disagree with the exit
7//! code the process returns.
8
9use crate::runner::Outcome;
10use serde_json::json;
11
12/// Why the run ended, in the vocabulary a CI consumer recognises.
13fn reason(outcome: &Outcome) -> &'static str {
14    if outcome.tests.is_empty() {
15        return if outcome.exit_code == 0 {
16            "ok"
17        } else {
18            "failed"
19        };
20    }
21    if outcome.exit_code == 0 {
22        "all tests passed"
23    } else if outcome
24        .tests
25        .iter()
26        .any(|t| t.output.contains("electrical fault"))
27    {
28        "electrical fault"
29    } else if outcome.tests.iter().any(|t| t.output.contains("never saw")) {
30        "assertion failed"
31    } else if outcome
32        .tests
33        .iter()
34        .any(|t| t.output.contains("found failure text"))
35    {
36        "failure text matched"
37    } else {
38        "timed out"
39    }
40}
41
42pub fn json(outcome: &Outcome) -> String {
43    let tests: Vec<_> = outcome
44        .tests
45        .iter()
46        .map(|test| {
47            json!({
48                "name": test.name,
49                "status": if test.passed { "passed" } else { "failed" },
50                "exit_code": test.exit_code,
51                "sim_time_ms": test.sim_ms,
52                "output": test.output,
53            })
54        })
55        .collect();
56    let document = json!({
57        "status": if outcome.exit_code == 0 { "passed" } else { "failed" },
58        "reason": reason(outcome),
59        "exit_code": outcome.exit_code,
60        "sim_time_ms": outcome.sim_ms,
61        "tests": tests,
62    });
63    serde_json::to_string_pretty(&document).expect("a JSON value always serialises")
64}
65
66/// JUnit XML, one `testcase` per `[[test]]`, with the transcript in
67/// `system-out` — the same place a failing CI user looks first.
68pub fn junit(outcome: &Outcome, suite: &str) -> String {
69    let failures = outcome.tests.iter().filter(|t| !t.passed).count();
70    let mut xml = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
71    xml.push_str(&format!(
72        "<testsuites tests=\"{}\" failures=\"{failures}\">\n",
73        outcome.tests.len()
74    ));
75    xml.push_str(&format!(
76        "  <testsuite name=\"{}\" tests=\"{}\" failures=\"{failures}\">\n",
77        escape(suite),
78        outcome.tests.len()
79    ));
80    for test in &outcome.tests {
81        xml.push_str(&format!(
82            "    <testcase name=\"{}\" classname=\"{}\"",
83            escape(&test.name),
84            escape(suite)
85        ));
86        if test.passed {
87            xml.push_str("/>\n");
88            continue;
89        }
90        xml.push_str(">\n");
91        xml.push_str(&format!(
92            "      <failure message=\"exit {}\">{}</failure>\n",
93            test.exit_code,
94            escape(first_note(&test.output))
95        ));
96        xml.push_str(&format!(
97            "      <system-out>{}</system-out>\n",
98            escape(&test.output)
99        ));
100        xml.push_str("    </testcase>\n");
101    }
102    xml.push_str("  </testsuite>\n</testsuites>\n");
103    xml
104}
105
106/// The one line a dashboard shows: the `litz:` note if there is one, else the
107/// last non-empty line of the transcript.
108fn first_note(output: &str) -> &str {
109    output
110        .lines()
111        .find(|line| line.starts_with("litz: "))
112        .or_else(|| output.lines().rev().find(|line| !line.trim().is_empty()))
113        .unwrap_or("failed")
114}
115
116/// XML text escaping. Control characters are dropped rather than encoded:
117/// they are illegal in XML 1.0 even as references, and a serial log can
118/// contain anything the firmware printed.
119fn escape(text: &str) -> String {
120    let mut out = String::with_capacity(text.len());
121    for ch in text.chars() {
122        match ch {
123            '&' => out.push_str("&amp;"),
124            '<' => out.push_str("&lt;"),
125            '>' => out.push_str("&gt;"),
126            '"' => out.push_str("&quot;"),
127            '\'' => out.push_str("&apos;"),
128            '\n' | '\r' | '\t' => out.push(ch),
129            c if (c as u32) < 0x20 => out.push(' '),
130            c => out.push(c),
131        }
132    }
133    out
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139    use crate::runner::TestOutcome;
140
141    fn outcome(tests: Vec<TestOutcome>, exit_code: i32) -> Outcome {
142        Outcome {
143            exit_code,
144            output: String::new(),
145            sim_ms: tests.iter().map(|t| t.sim_ms).max().unwrap_or(0),
146            tests,
147        }
148    }
149
150    fn test(name: &str, passed: bool, output: &str) -> TestOutcome {
151        TestOutcome {
152            name: name.into(),
153            passed,
154            exit_code: if passed { 0 } else { 1 },
155            output: output.into(),
156            sim_ms: 250,
157        }
158    }
159
160    #[test]
161    fn the_json_record_says_what_happened_and_why() {
162        let out = outcome(
163            vec![
164                test("blinks", true, "litz: blinky\n"),
165                test("stays dark", false, "litz: never saw \"x\"\n"),
166            ],
167            1,
168        );
169        let value: serde_json::Value = serde_json::from_str(&json(&out)).unwrap();
170        assert_eq!(value["status"], "failed");
171        assert_eq!(value["reason"], "assertion failed");
172        assert_eq!(value["exit_code"], 1);
173        assert_eq!(value["sim_time_ms"], 250);
174        assert_eq!(value["tests"][0]["status"], "passed");
175        assert_eq!(value["tests"][1]["name"], "stays dark");
176    }
177
178    #[test]
179    fn a_fault_is_reported_as_a_fault() {
180        let out = outcome(
181            vec![test("x", false, "litz: electrical fault on net 0: boom\n")],
182            1,
183        );
184        let value: serde_json::Value = serde_json::from_str(&json(&out)).unwrap();
185        assert_eq!(value["reason"], "electrical fault");
186    }
187
188    #[test]
189    fn junit_counts_failures_and_keeps_the_transcript() {
190        let out = outcome(
191            vec![
192                test("ok", true, "fine\n"),
193                test("bad", false, "litz: never saw \"x\"\n"),
194            ],
195            1,
196        );
197        let xml = junit(&out, "litz");
198        assert!(xml.contains("tests=\"2\" failures=\"1\""), "{xml}");
199        assert!(
200            xml.contains("<failure message=\"exit 1\">litz: never saw &quot;x&quot;</failure>"),
201            "{xml}"
202        );
203        assert!(
204            xml.contains("<system-out>litz: never saw &quot;x&quot;"),
205            "{xml}"
206        );
207        assert!(
208            xml.contains("<testcase name=\"ok\" classname=\"litz\"/>"),
209            "{xml}"
210        );
211    }
212
213    #[test]
214    fn xml_special_characters_are_escaped_and_controls_are_dropped() {
215        assert_eq!(escape("a<b&c>\"d\"\u{1}"), "a&lt;b&amp;c&gt;&quot;d&quot; ");
216    }
217}