Skip to main content

rumdl_lib/output/formatters/
junit.rs

1//! JUnit XML output format
2
3use crate::output::OutputFormatter;
4use crate::rule::LintWarning;
5
6/// JUnit XML formatter for CI systems
7pub struct JunitFormatter;
8
9impl Default for JunitFormatter {
10    fn default() -> Self {
11        Self
12    }
13}
14
15impl JunitFormatter {
16    pub fn new() -> Self {
17        Self
18    }
19}
20
21impl OutputFormatter for JunitFormatter {
22    fn format_warnings(&self, warnings: &[LintWarning], file_path: &str) -> String {
23        // A single file is one testcase that passes (no warnings) or fails.
24        format_junit_report(
25            &[(file_path.to_string(), warnings.to_vec())],
26            &[file_path.to_string()],
27            0,
28        )
29    }
30}
31
32/// Format a JUnit XML report covering every checked file.
33///
34/// Each checked file is one `<testcase>` ("Lint <file>"): a clean file passes (no
35/// `<failure>` child), a file with warnings fails and carries one `<failure>` per
36/// warning. `all_files` lists every file that was checked (clean and dirty);
37/// `all_warnings` holds only the files that have warnings. Reporting all checked
38/// files means a clean run lists its passing files rather than emitting an empty
39/// report. Counts stay JUnit-consistent: `tests` is the number of checked files and
40/// `failures` the number of files with issues, so `failures <= tests` always holds.
41pub fn format_junit_report(
42    all_warnings: &[(String, Vec<LintWarning>)],
43    all_files: &[String],
44    duration_ms: u64,
45) -> String {
46    use std::collections::HashMap;
47    use std::collections::HashSet;
48
49    let warnings_by_file: HashMap<&str, &[LintWarning]> =
50        all_warnings.iter().map(|(p, w)| (p.as_str(), w.as_slice())).collect();
51
52    // Report every checked file once, in order; defensively include any warning-
53    // bearing file that is not in all_files so a warning is never dropped.
54    let mut files: Vec<&str> = Vec::with_capacity(all_files.len());
55    let mut seen: HashSet<&str> = HashSet::new();
56    for path in all_files {
57        if seen.insert(path.as_str()) {
58            files.push(path.as_str());
59        }
60    }
61    for (path, _) in all_warnings {
62        if seen.insert(path.as_str()) {
63            files.push(path.as_str());
64        }
65    }
66
67    let warnings_for = |file: &str| -> &[LintWarning] { warnings_by_file.get(file).copied().unwrap_or(&[]) };
68
69    let total_tests = files.len();
70    let files_with_issues = files.iter().filter(|f| !warnings_for(f).is_empty()).count();
71    let duration_secs = duration_ms as f64 / 1000.0;
72
73    let mut xml = String::new();
74    xml.push_str(r#"<?xml version="1.0" encoding="UTF-8"?>"#);
75    xml.push('\n');
76
77    xml.push_str(&format!(
78        r#"<testsuites name="rumdl" tests="{total_tests}" failures="{files_with_issues}" errors="0" time="{duration_secs:.3}">"#
79    ));
80    xml.push('\n');
81
82    for file in files {
83        let warnings = warnings_for(file);
84        let failed = usize::from(!warnings.is_empty());
85        let escaped_file = xml_escape(file);
86
87        xml.push_str(&format!(
88            r#"  <testsuite name="{escaped_file}" tests="1" failures="{failed}" errors="0" time="0.000">"#
89        ));
90        xml.push('\n');
91
92        xml.push_str(&format!(
93            r#"    <testcase name="Lint {escaped_file}" classname="rumdl" time="0.000">"#
94        ));
95        xml.push('\n');
96
97        // A clean file's testcase has no <failure> children, so it passes.
98        for warning in warnings {
99            let rule_name = warning.rule_name.as_deref().unwrap_or("unknown");
100            let message = xml_escape(&warning.message);
101
102            xml.push_str(&format!(
103                r#"      <failure type="{}" message="{}">{} at line {}, column {}</failure>"#,
104                rule_name, message, message, warning.line, warning.column
105            ));
106            xml.push('\n');
107        }
108
109        xml.push_str("    </testcase>\n");
110        xml.push_str("  </testsuite>\n");
111    }
112
113    xml.push_str("</testsuites>\n");
114    xml
115}
116
117/// Escape special XML characters
118fn xml_escape(s: &str) -> String {
119    s.replace('&', "&amp;")
120        .replace('<', "&lt;")
121        .replace('>', "&gt;")
122        .replace('"', "&quot;")
123        .replace('\'', "&apos;")
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129    use crate::rule::{Fix, Severity};
130
131    fn warning(line: usize, column: usize, rule: &str, message: &str) -> LintWarning {
132        LintWarning {
133            line,
134            column,
135            end_line: line,
136            end_column: column,
137            rule_name: Some(rule.to_string()),
138            message: message.to_string(),
139            severity: Severity::Warning,
140            fix: None,
141        }
142    }
143
144    /// Count `<failure ...>` elements in the report.
145    fn count_failures(xml: &str) -> usize {
146        xml.matches("<failure ").count()
147    }
148
149    #[test]
150    fn test_junit_formatter_default_and_new() {
151        let _ = JunitFormatter;
152        let _ = JunitFormatter::new();
153    }
154
155    // ---- single-file path (OutputFormatter::format_warnings) -----------------
156
157    #[test]
158    fn test_format_warnings_empty_file_passes() {
159        // A clean file is a passing testcase: present, no <failure>, failures="0".
160        let output = JunitFormatter::new().format_warnings(&[], "test.md");
161
162        assert!(output.starts_with("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
163        assert!(output.contains("<testsuites name=\"rumdl\" tests=\"1\" failures=\"0\" errors=\"0\""));
164        assert!(output.contains("<testsuite name=\"test.md\" tests=\"1\" failures=\"0\" errors=\"0\" time=\"0.000\">"));
165        assert!(output.contains("<testcase name=\"Lint test.md\" classname=\"rumdl\" time=\"0.000\">"));
166        assert_eq!(count_failures(&output), 0);
167    }
168
169    #[test]
170    fn test_format_single_warning() {
171        let warnings = vec![warning(
172            10,
173            5,
174            "MD001",
175            "Heading levels should only increment by one level at a time",
176        )];
177        let output = JunitFormatter::new().format_warnings(&warnings, "README.md");
178
179        assert!(output.contains("<testsuites name=\"rumdl\" tests=\"1\" failures=\"1\" errors=\"0\""));
180        assert!(
181            output.contains("<testsuite name=\"README.md\" tests=\"1\" failures=\"1\" errors=\"0\" time=\"0.000\">")
182        );
183        assert!(output.contains(
184            "<failure type=\"MD001\" message=\"Heading levels should only increment by one level at a time\">"
185        ));
186        assert!(output.contains("at line 10, column 5</failure>"));
187    }
188
189    #[test]
190    fn test_multiple_warnings_in_one_file_are_one_failed_testcase() {
191        // One file with two warnings is ONE failed testcase (failures="1"), with two
192        // <failure> children - not failures="2" (which would exceed tests="1").
193        let warnings = vec![
194            warning(5, 1, "MD001", "First warning"),
195            warning(10, 3, "MD013", "Second warning"),
196        ];
197        let output = JunitFormatter::new().format_warnings(&warnings, "test.md");
198
199        assert!(output.contains("<testsuites name=\"rumdl\" tests=\"1\" failures=\"1\" errors=\"0\""));
200        assert!(output.contains("<testsuite name=\"test.md\" tests=\"1\" failures=\"1\" errors=\"0\" time=\"0.000\">"));
201        assert_eq!(count_failures(&output), 2);
202        assert!(output.contains("<failure type=\"MD001\" message=\"First warning\">"));
203        assert!(output.contains("<failure type=\"MD013\" message=\"Second warning\">"));
204    }
205
206    #[test]
207    fn test_format_single_warning_with_fix_has_no_fixable_marker() {
208        let mut w = warning(10, 5, "MD001", "Heading");
209        w.fix = Some(Fix::new(100..110, "## Heading".to_string()));
210        let output = JunitFormatter::new().format_warnings(&[w], "README.md");
211
212        assert!(output.contains("<failure type=\"MD001\""));
213        assert!(!output.contains("fixable"));
214    }
215
216    #[test]
217    fn test_format_warning_unknown_rule() {
218        let mut w = warning(1, 1, "MD001", "Unknown rule warning");
219        w.rule_name = None;
220        let output = JunitFormatter::new().format_warnings(&[w], "file.md");
221
222        assert!(output.contains("<failure type=\"unknown\" message=\"Unknown rule warning\">"));
223    }
224
225    // ---- batch report (format_junit_report) ----------------------------------
226
227    #[test]
228    fn test_report_no_files_is_empty() {
229        let output = format_junit_report(&[], &[], 1234);
230        assert!(output.starts_with("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
231        assert!(output.contains("<testsuites name=\"rumdl\" tests=\"0\" failures=\"0\" errors=\"0\" time=\"1.234\">"));
232        assert!(output.ends_with("</testsuites>\n"));
233    }
234
235    #[test]
236    fn test_report_all_clean_files_listed_as_passing() {
237        // The core of issue #654: a clean run lists its passing files, not an empty report.
238        let all_files = vec!["a.md".to_string(), "b.md".to_string()];
239        let output = format_junit_report(&[], &all_files, 500);
240
241        assert!(output.contains("<testsuites name=\"rumdl\" tests=\"2\" failures=\"0\" errors=\"0\" time=\"0.500\">"));
242        assert!(output.contains("<testsuite name=\"a.md\" tests=\"1\" failures=\"0\""));
243        assert!(output.contains("<testsuite name=\"b.md\" tests=\"1\" failures=\"0\""));
244        assert!(output.contains("<testcase name=\"Lint a.md\""));
245        assert!(output.contains("<testcase name=\"Lint b.md\""));
246        assert_eq!(count_failures(&output), 0);
247    }
248
249    #[test]
250    fn test_report_mixed_clean_and_dirty() {
251        let all_files = vec!["clean.md".to_string(), "dirty.md".to_string(), "clean2.md".to_string()];
252        let all_warnings = vec![(
253            "dirty.md".to_string(),
254            vec![
255                warning(1, 2, "MD018", "No space after #"),
256                warning(3, 1, "MD012", "Blank lines"),
257            ],
258        )];
259        let output = format_junit_report(&all_warnings, &all_files, 0);
260
261        // 3 files checked, 1 failed file => failures <= tests.
262        assert!(output.contains("<testsuites name=\"rumdl\" tests=\"3\" failures=\"1\" errors=\"0\""));
263        assert!(output.contains("<testsuite name=\"clean.md\" tests=\"1\" failures=\"0\""));
264        assert!(output.contains("<testsuite name=\"clean2.md\" tests=\"1\" failures=\"0\""));
265        assert!(output.contains("<testsuite name=\"dirty.md\" tests=\"1\" failures=\"1\""));
266        // The dirty file carries both warnings; clean files carry none.
267        assert_eq!(count_failures(&output), 2);
268    }
269
270    #[test]
271    fn test_report_failures_never_exceed_tests() {
272        // A file with many warnings is still one failed testcase.
273        let all_files = vec!["x.md".to_string()];
274        let warnings: Vec<LintWarning> = (1..=5).map(|i| warning(i, 1, "MD013", "long line")).collect();
275        let output = format_junit_report(&[("x.md".to_string(), warnings)], &all_files, 0);
276
277        assert!(output.contains("<testsuites name=\"rumdl\" tests=\"1\" failures=\"1\""));
278        assert!(output.contains("<testsuite name=\"x.md\" tests=\"1\" failures=\"1\""));
279        assert_eq!(count_failures(&output), 5);
280    }
281
282    #[test]
283    fn test_report_includes_warning_file_absent_from_all_files() {
284        // Defensive: a warning-bearing file not present in all_files is still reported.
285        let output = format_junit_report(&[("orphan.md".to_string(), vec![warning(1, 1, "MD001", "x")])], &[], 0);
286        assert!(output.contains("<testsuites name=\"rumdl\" tests=\"1\" failures=\"1\""));
287        assert!(output.contains("<testsuite name=\"orphan.md\""));
288    }
289
290    #[test]
291    fn test_report_deduplicates_files() {
292        // A file appearing in both all_files and all_warnings is rendered once.
293        let all_files = vec!["dup.md".to_string()];
294        let all_warnings = vec![("dup.md".to_string(), vec![warning(1, 1, "MD001", "x")])];
295        let output = format_junit_report(&all_warnings, &all_files, 0);
296
297        assert_eq!(output.matches("<testsuite name=\"dup.md\"").count(), 1);
298        assert!(output.contains("<testsuites name=\"rumdl\" tests=\"1\" failures=\"1\""));
299    }
300
301    #[test]
302    fn test_duration_formatting() {
303        let files = vec!["test.md".to_string()];
304        let warnings = vec![("test.md".to_string(), vec![warning(1, 1, "MD001", "x")])];
305        assert!(format_junit_report(&warnings, &files, 1234).contains("time=\"1.234\""));
306        assert!(format_junit_report(&warnings, &files, 500).contains("time=\"0.500\""));
307        assert!(format_junit_report(&warnings, &files, 12345).contains("time=\"12.345\""));
308    }
309
310    // ---- escaping & structure ------------------------------------------------
311
312    #[test]
313    fn test_xml_escape() {
314        assert_eq!(xml_escape("normal text"), "normal text");
315        assert_eq!(xml_escape("text with & ampersand"), "text with &amp; ampersand");
316        assert_eq!(xml_escape("text with < and >"), "text with &lt; and &gt;");
317        assert_eq!(xml_escape("text with \" quotes"), "text with &quot; quotes");
318        assert_eq!(xml_escape("text with ' apostrophe"), "text with &apos; apostrophe");
319        assert_eq!(xml_escape("all: < > & \" '"), "all: &lt; &gt; &amp; &quot; &apos;");
320    }
321
322    #[test]
323    fn test_special_characters_in_message() {
324        let warnings = vec![warning(1, 1, "MD001", "Warning with < > & \" ' special chars")];
325        let output = JunitFormatter::new().format_warnings(&warnings, "test.md");
326
327        assert!(output.contains("message=\"Warning with &lt; &gt; &amp; &quot; &apos; special chars\""));
328        assert!(output.contains(">Warning with &lt; &gt; &amp; &quot; &apos; special chars at line"));
329    }
330
331    #[test]
332    fn test_special_characters_in_file_path() {
333        let warnings = vec![warning(1, 1, "MD001", "Test")];
334        let output = JunitFormatter::new().format_warnings(&warnings, "path/with<special>&chars.md");
335
336        assert!(output.contains("<testsuite name=\"path/with&lt;special&gt;&amp;chars.md\""));
337        assert!(output.contains("<testcase name=\"Lint path/with&lt;special&gt;&amp;chars.md\""));
338    }
339
340    #[test]
341    fn test_xml_structure_nesting() {
342        let warnings = vec![warning(1, 1, "MD001", "Test")];
343        let output = JunitFormatter::new().format_warnings(&warnings, "test.md");
344
345        let lines: Vec<&str> = output.lines().collect();
346        assert_eq!(lines[0], "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
347        assert!(lines[1].starts_with("<testsuites"));
348        assert!(lines[2].starts_with("  <testsuite"));
349        assert!(lines[3].starts_with("    <testcase"));
350        assert!(lines[4].starts_with("      <failure"));
351        assert_eq!(lines[5], "    </testcase>");
352        assert_eq!(lines[6], "  </testsuite>");
353        assert_eq!(lines[7], "</testsuites>");
354    }
355}