rumdl_lib/output/formatters/
junit.rs1use crate::output::OutputFormatter;
4use crate::rule::LintWarning;
5
6pub 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 format_junit_report(
25 &[(file_path.to_string(), warnings.to_vec())],
26 &[file_path.to_string()],
27 0,
28 )
29 }
30}
31
32pub 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 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 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
117fn xml_escape(s: &str) -> String {
119 s.replace('&', "&")
120 .replace('<', "<")
121 .replace('>', ">")
122 .replace('"', """)
123 .replace('\'', "'")
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 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 #[test]
158 fn test_format_warnings_empty_file_passes() {
159 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 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 #[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 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 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 assert_eq!(count_failures(&output), 2);
268 }
269
270 #[test]
271 fn test_report_failures_never_exceed_tests() {
272 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 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 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 #[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 & ampersand");
316 assert_eq!(xml_escape("text with < and >"), "text with < and >");
317 assert_eq!(xml_escape("text with \" quotes"), "text with " quotes");
318 assert_eq!(xml_escape("text with ' apostrophe"), "text with ' apostrophe");
319 assert_eq!(xml_escape("all: < > & \" '"), "all: < > & " '");
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 < > & " ' special chars\""));
328 assert!(output.contains(">Warning with < > & " ' 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<special>&chars.md\""));
337 assert!(output.contains("<testcase name=\"Lint path/with<special>&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}