Skip to main content

mortise_core/modules/
clover.rs

1//! Test coverage from a clover report, as PHPUnit writes it.
2
3use std::path::{Path, PathBuf};
4
5use quick_xml::events::{BytesStart, Event};
6use quick_xml::{Reader, XmlVersion};
7use serde::{Deserialize, Serialize};
8
9/// Covered and total statements.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
11pub struct Coverage {
12    pub covered: u64,
13    pub statements: u64,
14}
15
16impl Coverage {
17    /// The whole per cent, rounded: 54 for 54.4%. `None` when there is nothing to cover.
18    pub fn percent(self) -> Option<u8> {
19        (self.statements > 0)
20            .then(|| ((self.covered as f64 / self.statements as f64) * 100.0).round() as u8)
21    }
22
23    pub(crate) fn add(&mut self, other: Coverage) {
24        self.covered += other.covered;
25        self.statements += other.statements;
26    }
27}
28
29/// The coverage of one file in a report.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub(crate) struct FileCoverage {
32    /// The path as the report has it, with `/` between the parts. It is the path
33    /// on the machine that ran the tests, which can be a container.
34    pub(crate) path: String,
35    pub(crate) coverage: Coverage,
36}
37
38/// Finds the clover report of an app: the file `phpunit.xml` names, or one of the
39/// places where such a report is usually written.
40pub(crate) fn find_report(root: &Path) -> Option<PathBuf> {
41    let configured = ["phpunit.xml", "phpunit.xml.dist"]
42        .iter()
43        .filter_map(|name| std::fs::read(root.join(name)).ok())
44        .find_map(|xml| report_in_phpunit_config(&xml))
45        .map(|path| root.join(path));
46    let usual = [
47        "build/coverage/clover.xml",
48        "build/logs/clover.xml",
49        "coverage/clover.xml",
50        "clover.xml",
51    ];
52    configured
53        .into_iter()
54        .chain(usual.iter().map(|path| root.join(path)))
55        .find(|path| path.is_file())
56}
57
58/// The `outputFile` of `<coverage><report><clover>` in a PHPUnit config.
59fn report_in_phpunit_config(xml: &[u8]) -> Option<String> {
60    let mut reader = Reader::from_reader(xml);
61    let mut inside: Vec<String> = Vec::new();
62    loop {
63        match reader.read_event().ok()? {
64            Event::Start(tag) => inside.push(tag.name().as_ref().to_owned()),
65            Event::End(_) => {
66                inside.pop();
67            }
68            Event::Empty(tag) if tag.name().as_ref() == "clover" => {
69                let in_report = inside.last().is_some_and(|parent| parent == "report");
70                if in_report && let Some(file) = attribute(&tag, "outputFile") {
71                    return Some(file);
72                }
73            }
74            Event::Eof => return None,
75            _ => {}
76        }
77    }
78}
79
80/// Reads the statements of every file in a clover report. A report that is not
81/// valid XML gives what was read before the fault, and the fault. So does a file
82/// without a `coverage` element, which is no clover report.
83pub(crate) fn read_report(xml: &[u8]) -> (Vec<FileCoverage>, Option<String>) {
84    let mut reader = Reader::from_reader(xml);
85    let mut files = Vec::new();
86    // The file being read, and how deep inside it the reader is.
87    let mut file: Option<(String, usize)> = None;
88    let mut clover = false;
89    loop {
90        let event = match reader.read_event() {
91            Ok(Event::Eof) => break,
92            Err(error) => return (files, Some(error.to_string())),
93            Ok(event) => event,
94        };
95        match event {
96            Event::Start(tag) if tag.name().as_ref() == "coverage" => clover = true,
97            Event::Start(tag) if tag.name().as_ref() == "file" => {
98                file = attribute(&tag, "name").map(|name| (name.replace('\\', "/"), 0));
99            }
100            Event::Start(_) => {
101                if let Some((_, depth)) = &mut file {
102                    *depth += 1;
103                }
104            }
105            Event::End(tag) if tag.name().as_ref() == "file" => file = None,
106            Event::End(_) => {
107                if let Some((_, depth)) = &mut file {
108                    *depth = depth.saturating_sub(1);
109                }
110            }
111            // The metrics of the file itself, not those of a class inside it.
112            Event::Empty(tag) if tag.name().as_ref() == "metrics" => {
113                if let Some((path, 0)) = &file {
114                    let number = |name: &str| {
115                        attribute(&tag, name)
116                            .and_then(|value| value.parse().ok())
117                            .unwrap_or(0)
118                    };
119                    files.push(FileCoverage {
120                        path: path.clone(),
121                        coverage: Coverage {
122                            covered: number("coveredstatements"),
123                            statements: number("statements"),
124                        },
125                    });
126                }
127            }
128            _ => {}
129        }
130    }
131    let fault = (!clover).then(|| "it has no coverage element".to_owned());
132    (files, fault)
133}
134
135fn attribute(tag: &BytesStart<'_>, name: &str) -> Option<String> {
136    tag.attributes()
137        .filter_map(Result::ok)
138        .find(|attribute| attribute.key.as_ref() == name)
139        .and_then(|attribute| attribute.normalized_value(XmlVersion::Implicit1_0).ok())
140        .map(|value| value.into_owned())
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    const REPORT: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
148<coverage generated="1763800000">
149  <project timestamp="1763800000">
150    <file name="/var/www/html/Modules/Billing/app/Models/Invoice.php">
151      <class name="Modules\Billing\Models\Invoice" namespace="global">
152        <metrics complexity="3" methods="2" coveredmethods="1" statements="99" coveredstatements="1" elements="12" coveredelements="9"/>
153      </class>
154      <line num="12" type="stmt" count="1"/>
155      <metrics loc="40" ncloc="30" classes="1" methods="2" coveredmethods="1" statements="10" coveredstatements="8" elements="12" coveredelements="9"/>
156    </file>
157    <package name="Modules\Checkout">
158      <file name="C:\code\shop\Modules\Checkout\app\Services\Cart.php">
159        <metrics loc="20" statements="4" coveredstatements="1"/>
160      </file>
161    </package>
162    <metrics files="2" statements="14" coveredstatements="9"/>
163  </project>
164</coverage>"#;
165
166    #[test]
167    fn reads_the_statements_of_each_file_and_not_of_its_classes() {
168        let (files, fault) = read_report(REPORT.as_bytes());
169        assert_eq!(fault, None);
170        assert_eq!(
171            files,
172            [
173                FileCoverage {
174                    path: "/var/www/html/Modules/Billing/app/Models/Invoice.php".into(),
175                    coverage: Coverage {
176                        covered: 8,
177                        statements: 10
178                    },
179                },
180                FileCoverage {
181                    path: "C:/code/shop/Modules/Checkout/app/Services/Cart.php".into(),
182                    coverage: Coverage {
183                        covered: 1,
184                        statements: 4
185                    },
186                },
187            ]
188        );
189    }
190
191    #[test]
192    fn a_broken_report_gives_what_was_read_and_the_fault() {
193        let broken = REPORT.replace("</file>\n    <package", "</fil>\n    <package");
194        let (files, fault) = read_report(broken.as_bytes());
195        assert_eq!(files.len(), 1);
196        assert!(fault.is_some());
197        for not_clover in [&b"not xml at all"[..], b"", b"<phpunit/>"] {
198            let (files, fault) = read_report(not_clover);
199            assert!(files.is_empty());
200            assert_eq!(fault.as_deref(), Some("it has no coverage element"));
201        }
202    }
203
204    #[test]
205    fn per_cent_is_rounded_and_absent_without_statements() {
206        assert_eq!(
207            Coverage {
208                covered: 8,
209                statements: 10
210            }
211            .percent(),
212            Some(80)
213        );
214        assert_eq!(
215            Coverage {
216                covered: 544,
217                statements: 1000
218            }
219            .percent(),
220            Some(54)
221        );
222        assert_eq!(
223            Coverage {
224                covered: 545,
225                statements: 1000
226            }
227            .percent(),
228            Some(55)
229        );
230        assert_eq!(Coverage::default().percent(), None);
231    }
232
233    #[test]
234    fn the_report_named_in_phpunit_xml_comes_first() {
235        let app = tempfile::tempdir().unwrap();
236        let write = |path: &str, content: &str| {
237            let path = app.path().join(path);
238            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
239            std::fs::write(path, content).unwrap();
240        };
241        assert_eq!(find_report(app.path()), None);
242
243        write("build/logs/clover.xml", "<coverage/>");
244        assert_eq!(
245            find_report(app.path()),
246            Some(app.path().join("build/logs/clover.xml"))
247        );
248
249        write(
250            "phpunit.xml",
251            r#"<phpunit><coverage><report><html outputDirectory="x"/><clover outputFile="storage/cov.xml"/></report></coverage></phpunit>"#,
252        );
253        // Named, but not written yet: the usual place still counts.
254        assert_eq!(
255            find_report(app.path()),
256            Some(app.path().join("build/logs/clover.xml"))
257        );
258        write("storage/cov.xml", "<coverage/>");
259        assert_eq!(
260            find_report(app.path()),
261            Some(app.path().join("storage/cov.xml"))
262        );
263    }
264}