Skip to content

Commit a610f8d

Browse files
committed
Populate condition-coverage field in cobertura xml reports
Some parsers require the presence of the `condition-coverage` field on the `line` elements in the report. This change adds and populates this field based on the available `Conditions` data. See: https://github.com/cobertura/cobertura/blob/master/cobertura/src/site/htdocs/xml/coverage-03.dtd Implements #1029
1 parent 8278678 commit a610f8d

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/cobertura.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -530,6 +530,11 @@ fn write_lines(writer: &mut Writer<Cursor<Vec<u8>>>, lines: &[Line]) {
530530
l.push_attribute(("number", number.to_string().as_ref()));
531531
l.push_attribute(("hits", hits.to_string().as_ref()));
532532
l.push_attribute(("branch", "true"));
533+
l.push_attribute((
534+
"condition-coverage",
535+
format_condition_coverage(conditions).as_ref(),
536+
));
537+
533538
writer.write_event(Event::Start(l)).unwrap();
534539

535540
let conditions_tag = "conditions";
@@ -562,6 +567,17 @@ fn write_lines(writer: &mut Writer<Cursor<Vec<u8>>>, lines: &[Line]) {
562567
.unwrap();
563568
}
564569

570+
fn format_condition_coverage(conditions: &[Condition]) -> String {
571+
let conditions_hit: f64 = conditions.iter().map(|c| c.coverage).sum();
572+
let num_conditions = conditions.len();
573+
format!(
574+
"{:.0}% ({:.0}/{})",
575+
100.0 * conditions_hit / num_conditions as f64,
576+
conditions_hit,
577+
num_conditions
578+
)
579+
}
580+
565581
#[cfg(test)]
566582
mod tests {
567583
use super::*;
@@ -860,4 +876,24 @@ mod tests {
860876
assert!(results.contains(r#"<source>src</source>"#));
861877
assert!(results.contains(r#"package name="main.rs""#));
862878
}
879+
880+
#[test]
881+
fn test_condition_coverage() {
882+
const HIT: Condition = Condition {
883+
coverage: 1.0,
884+
number: 0,
885+
cond_type: ConditionType::Jump,
886+
};
887+
const MISS: Condition = Condition {
888+
coverage: 0.0,
889+
number: 0,
890+
cond_type: ConditionType::Jump,
891+
};
892+
893+
assert_eq!("100% (1/1)", format_condition_coverage(&[HIT]));
894+
assert_eq!("0% (0/1)", format_condition_coverage(&[MISS]));
895+
assert_eq!("50% (1/2)", format_condition_coverage(&[HIT, MISS]));
896+
assert_eq!("33% (1/3)", format_condition_coverage(&[HIT, MISS, MISS]));
897+
assert_eq!("67% (2/3)", format_condition_coverage(&[HIT, HIT, MISS]));
898+
}
863899
}

0 commit comments

Comments
 (0)