Skip to main content

targeted_mutation/
baseline.rs

1//! Findings the user has already looked at: `// tmt:ignore` comments and baseline files.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::path::Path;
5
6use anyhow::{Context, Result};
7
8use crate::report::Finding;
9
10/// What identifies a finding across runs: its kind, file, code and surviving mutants.
11/// Line numbers are left out, so code that merely moves keeps its fingerprint.
12pub fn fingerprint(finding: &Finding) -> String {
13    // A mutant built on its own was an assertion gap when fingerprints were written.
14    let kind = match finding {
15        Finding::InputGap { .. } => "input_gap",
16        Finding::AssertionGap { .. } | Finding::Survivor { .. } => "assertion_gap",
17    };
18    let (at, survivors) = (finding.at(), finding.survivors());
19    format!(
20        "{kind}\t{}\t{}\t{}",
21        at.file,
22        at.code,
23        survivors.join(" | ")
24    )
25}
26
27/// The findings a baseline file lists.
28#[derive(Debug, PartialEq)]
29pub enum Baseline {
30    /// As written before findings had names of their own: by [`fingerprint`].
31    Fingerprints(BTreeSet<String>),
32    /// By the name of the finding (`report::finding_id`).
33    Ids(BTreeSet<String>),
34}
35
36impl Baseline {
37    pub fn knows(&self, finding: &Finding) -> bool {
38        let at = finding.at();
39        match self {
40            Baseline::Fingerprints(prints) => prints.contains(&fingerprint(finding)),
41            Baseline::Ids(ids) => !at.id.is_empty() && ids.contains(&at.id),
42        }
43    }
44}
45
46/// The version of the file [`write`] writes.
47const VERSION: u64 = 2;
48
49/// Reads a baseline: the object [`write`] writes, or the list of fingerprints earlier
50/// versions wrote.
51pub fn load(path: &Path) -> Result<Baseline> {
52    let text =
53        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
54    parse(&text).with_context(|| format!("{} is not a tmt baseline", path.display()))
55}
56
57fn parse(text: &str) -> Result<Baseline> {
58    let mut value: serde_json::Value = serde_json::from_str(text)?;
59    if value.is_array() {
60        return Ok(Baseline::Fingerprints(serde_json::from_value(value)?));
61    }
62    match value["version"].as_u64() {
63        Some(VERSION) => Ok(Baseline::Ids(serde_json::from_value(
64            value["findings"].take(),
65        )?)),
66        Some(other) => anyhow::bail!("version {other} of the format is not known to this tmt"),
67        None => anyhow::bail!("neither a list nor an object with a version"),
68    }
69}
70
71pub fn write(path: &Path, findings: &[Finding]) -> Result<()> {
72    let mut text = render(findings);
73    text.push('\n');
74    std::fs::write(path, text).with_context(|| format!("writing {}", path.display()))
75}
76
77fn render(findings: &[Finding]) -> String {
78    #[derive(serde::Serialize)]
79    struct BaselineFile<'a> {
80        findings: BTreeSet<&'a str>,
81        version: u64,
82    }
83
84    let ids: BTreeSet<&str> = findings
85        .iter()
86        .map(|finding| {
87            let at = finding.at();
88            at.id.as_str()
89        })
90        .collect();
91    serde_json::to_string_pretty(&BaselineFile {
92        findings: ids,
93        version: VERSION,
94    })
95    .expect("strings serialise")
96}
97
98/// Lines covered by a `// tmt:ignore` comment, with the reason given after it. The
99/// comment covers its own line and the next one, so it can sit above the code.
100pub fn ignored_lines(source: &str) -> BTreeMap<usize, String> {
101    let mut ignored = BTreeMap::new();
102    for (index, line) in source.lines().enumerate() {
103        let Some(comment) = line.find("//").map(|at| &line[at + 2..]) else {
104            continue;
105        };
106        let Some(rest) = comment.trim_start().strip_prefix("tmt:ignore") else {
107            continue;
108        };
109        // `tmt:ignored` is some other word, and `"http://tmt:ignore"` is not a comment.
110        if !(rest.is_empty() || rest.starts_with(|c: char| c.is_whitespace() || c == ':')) {
111            continue;
112        }
113        let rest = rest.trim_start_matches(':');
114        let reason = rest.trim().to_string();
115        ignored.insert(index + 1, reason.clone());
116        ignored.entry(index + 2).or_insert(reason);
117    }
118    ignored
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124    use crate::report::Location;
125
126    fn gap(line: usize, code: &str, survivors: &[&str]) -> Finding {
127        Finding::AssertionGap {
128            at: Location {
129                file: "src/lib.rs".into(),
130                line,
131                column: 5,
132                code: code.into(),
133                ..Location::default()
134            },
135            survivors: survivors.iter().map(|s| s.to_string()).collect(),
136            tests: vec!["tests::t".into()],
137            effects: vec![],
138            effects_of: None,
139            witness: None,
140        }
141    }
142
143    #[test]
144    fn a_baseline_knows_findings_by_name_and_old_ones_by_fingerprint() {
145        let named = |id: &str, survivors: &[&str]| {
146            let mut finding = gap(10, "a > b", survivors);
147            let Finding::AssertionGap { at, .. } = &mut finding else {
148                unreachable!()
149            };
150            at.id = id.to_string();
151            finding
152        };
153        let one = named("assertion_gap|src/lib.rs|f|a > b|0", &["`a >= b`"]);
154        let other = named("assertion_gap|src/lib.rs|g|a > b|0", &["`a >= b`"]);
155        let written = render(std::slice::from_ref(&one));
156        let baseline = parse(&written).unwrap();
157        assert!(baseline.knows(&one));
158        // The same code in another function is another finding.
159        assert!(!baseline.knows(&other));
160        // Other words for the mutants, or one more of them, and it is still the one.
161        assert!(baseline.knows(&named(
162            "assertion_gap|src/lib.rs|f|a > b|0",
163            &["`a >= b`", "the negation"]
164        )));
165        // A finding without a name is not known by having none.
166        assert!(
167            !parse(&render(&[gap(1, "x", &[])]))
168                .unwrap()
169                .knows(&gap(2, "y", &[]))
170        );
171        // A file of an earlier version lists fingerprints, and still works as it did.
172        let old = serde_json::to_string(&[fingerprint(&one)]).unwrap();
173        let baseline = parse(&old).unwrap();
174        assert!(matches!(baseline, Baseline::Fingerprints(_)));
175        assert!(baseline.knows(&one) && baseline.knows(&other));
176        assert!(!baseline.knows(&named("x", &["`a >= b`", "the negation"])));
177        // Anything else is refused, with a later version said to be one.
178        let later = parse(r#"{"version": 3, "findings": []}"#).unwrap_err();
179        assert!(later.to_string().contains("version 3"), "{later}");
180        for bad in [
181            "{}",
182            "3",
183            r#"{"version": 2}"#,
184            r#"{"version": 2, "findings": null}"#,
185            r#"{"version": 2, "findings": [1]}"#,
186            r#"["a", 1]"#,
187        ] {
188            assert!(parse(bad).is_err(), "{bad}");
189        }
190    }
191
192    #[test]
193    fn fingerprints_ignore_position_but_not_content() {
194        let base = fingerprint(&gap(10, "a > b", &["`a >= b`"]));
195        assert_eq!(
196            base,
197            fingerprint(&gap(99, "a > b", &["`a >= b`"])),
198            "moved code"
199        );
200        assert_ne!(base, fingerprint(&gap(10, "a > c", &["`a >= b`"])));
201        assert_ne!(
202            base,
203            fingerprint(&gap(10, "a > b", &["`a >= b`", "`!(a > b)`"])),
204            "a new survivor"
205        );
206        let input = Finding::InputGap {
207            at: Location {
208                file: "src/lib.rs".into(),
209                line: 10,
210                column: 5,
211                code: "a > b".into(),
212                ..Location::default()
213            },
214            survivors: vec!["`a >= b`".into()],
215            survivor_count: 1,
216            add_tests: vec![],
217            observed: None,
218            verified: true,
219        };
220        assert_ne!(base, fingerprint(&input), "another kind of finding");
221    }
222
223    #[test]
224    fn baseline_round_trip() {
225        let path =
226            std::env::temp_dir().join(format!("tmt-baseline-test-{}.json", std::process::id()));
227        let mut findings = vec![
228            gap(1, "a > b", &["`a >= b`"]),
229            gap(2, "x();", &["delete `x();`"]),
230        ];
231        for (index, finding) in findings.iter_mut().enumerate() {
232            let Finding::AssertionGap { at, .. } = finding else {
233                unreachable!()
234            };
235            at.id = format!("id-{index}-é\n");
236        }
237        findings.reverse();
238        findings.push(findings[0].clone());
239        write(&path, &findings).unwrap();
240        assert_eq!(
241            std::fs::read_to_string(&path).unwrap(),
242            "{\n  \"findings\": [\n    \"id-0-é\\n\",\n    \"id-1-é\\n\"\n  ],\n  \"version\": 2\n}\n"
243        );
244        let loaded = load(&path).unwrap();
245        let ids: BTreeSet<String> = ["id-0-é\n", "id-1-é\n"].map(str::to_string).into();
246        assert_eq!(loaded, Baseline::Ids(ids));
247        assert!(findings.iter().all(|f| loaded.knows(f)));
248        std::fs::write(&path, "not json").unwrap();
249        assert!(load(&path).is_err());
250        std::fs::remove_file(&path).unwrap();
251        assert!(load(&path).is_err());
252    }
253
254    #[test]
255    fn ignore_comments() {
256        let source = "\
257fn f() {
258    // tmt:ignore equivalent: both branches return the same
259    if a >= b { a } else { b }
260    let x = 1; // tmt:ignore
261    let y = 2;
262    let z = 3;
263    let w = 4; // tmt:ignore: with a colon
264    // tmt:ignored is another word
265    // not tmt:ignore here? it is: tmt:ignore must start the comment
266    let url = \"http://tmt:ignore\";
267}
268";
269        let ignored = ignored_lines(source);
270        assert_eq!(
271            ignored.keys().copied().collect::<Vec<_>>(),
272            [2, 3, 4, 5, 7, 8]
273        );
274        assert_eq!(ignored[&7], "with a colon");
275        assert_eq!(ignored[&2], "equivalent: both branches return the same");
276        assert_eq!(ignored[&3], "equivalent: both branches return the same");
277        assert_eq!(ignored[&4], "");
278        assert!(ignored_lines("").is_empty());
279    }
280}