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 strings = |value: &serde_json::Value| -> Result<BTreeSet<String>> {
59        Ok(serde_json::from_value(value.clone())?)
60    };
61    let value: serde_json::Value = serde_json::from_str(text)?;
62    if value.is_array() {
63        return Ok(Baseline::Fingerprints(strings(&value)?));
64    }
65    match value["version"].as_u64() {
66        Some(VERSION) => Ok(Baseline::Ids(strings(&value["findings"])?)),
67        Some(other) => anyhow::bail!("version {other} of the format is not known to this tmt"),
68        None => anyhow::bail!("neither a list nor an object with a version"),
69    }
70}
71
72pub fn write(path: &Path, findings: &[Finding]) -> Result<()> {
73    let text = render(findings);
74    std::fs::write(path, format!("{text}\n")).with_context(|| format!("writing {}", path.display()))
75}
76
77fn render(findings: &[Finding]) -> String {
78    let ids: BTreeSet<&str> = findings
79        .iter()
80        .map(|finding| {
81            let at = finding.at();
82            at.id.as_str()
83        })
84        .collect();
85    let file = serde_json::json!({ "version": VERSION, "findings": ids });
86    serde_json::to_string_pretty(&file).expect("strings serialise")
87}
88
89/// Lines covered by a `// tmt:ignore` comment, with the reason given after it. The
90/// comment covers its own line and the next one, so it can sit above the code.
91pub fn ignored_lines(source: &str) -> BTreeMap<usize, String> {
92    let mut ignored = BTreeMap::new();
93    for (index, line) in source.lines().enumerate() {
94        let Some(comment) = line.find("//").map(|at| &line[at + 2..]) else {
95            continue;
96        };
97        let Some(rest) = comment.trim_start().strip_prefix("tmt:ignore") else {
98            continue;
99        };
100        // `tmt:ignored` is some other word, and `"http://tmt:ignore"` is not a comment.
101        if !(rest.is_empty() || rest.starts_with(|c: char| c.is_whitespace() || c == ':')) {
102            continue;
103        }
104        let rest = rest.trim_start_matches(':');
105        let reason = rest.trim().to_string();
106        ignored.insert(index + 1, reason.clone());
107        ignored.entry(index + 2).or_insert(reason);
108    }
109    ignored
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115    use crate::report::Location;
116
117    fn gap(line: usize, code: &str, survivors: &[&str]) -> Finding {
118        Finding::AssertionGap {
119            at: Location {
120                file: "src/lib.rs".into(),
121                line,
122                column: 5,
123                code: code.into(),
124                ..Location::default()
125            },
126            survivors: survivors.iter().map(|s| s.to_string()).collect(),
127            tests: vec!["tests::t".into()],
128            effects: vec![],
129            effects_of: None,
130        }
131    }
132
133    #[test]
134    fn a_baseline_knows_findings_by_name_and_old_ones_by_fingerprint() {
135        let named = |id: &str, survivors: &[&str]| {
136            let mut finding = gap(10, "a > b", survivors);
137            let Finding::AssertionGap { at, .. } = &mut finding else {
138                unreachable!()
139            };
140            at.id = id.to_string();
141            finding
142        };
143        let one = named("assertion_gap|src/lib.rs|f|a > b|0", &["`a >= b`"]);
144        let other = named("assertion_gap|src/lib.rs|g|a > b|0", &["`a >= b`"]);
145        let written = render(std::slice::from_ref(&one));
146        let baseline = parse(&written).unwrap();
147        assert!(baseline.knows(&one));
148        // The same code in another function is another finding.
149        assert!(!baseline.knows(&other));
150        // Other words for the mutants, or one more of them, and it is still the one.
151        assert!(baseline.knows(&named(
152            "assertion_gap|src/lib.rs|f|a > b|0",
153            &["`a >= b`", "the negation"]
154        )));
155        // A finding without a name is not known by having none.
156        assert!(
157            !parse(&render(&[gap(1, "x", &[])]))
158                .unwrap()
159                .knows(&gap(2, "y", &[]))
160        );
161        // A file of an earlier version lists fingerprints, and still works as it did.
162        let old = serde_json::to_string(&[fingerprint(&one)]).unwrap();
163        let baseline = parse(&old).unwrap();
164        assert!(matches!(baseline, Baseline::Fingerprints(_)));
165        assert!(baseline.knows(&one) && baseline.knows(&other));
166        assert!(!baseline.knows(&named("x", &["`a >= b`", "the negation"])));
167        // Anything else is refused, with a later version said to be one.
168        let later = parse(r#"{"version": 3, "findings": []}"#).unwrap_err();
169        assert!(later.to_string().contains("version 3"), "{later}");
170        for bad in [
171            "{}",
172            "3",
173            r#"{"version": 2, "findings": [1]}"#,
174            r#"["a", 1]"#,
175        ] {
176            assert!(parse(bad).is_err(), "{bad}");
177        }
178    }
179
180    #[test]
181    fn fingerprints_ignore_position_but_not_content() {
182        let base = fingerprint(&gap(10, "a > b", &["`a >= b`"]));
183        assert_eq!(
184            base,
185            fingerprint(&gap(99, "a > b", &["`a >= b`"])),
186            "moved code"
187        );
188        assert_ne!(base, fingerprint(&gap(10, "a > c", &["`a >= b`"])));
189        assert_ne!(
190            base,
191            fingerprint(&gap(10, "a > b", &["`a >= b`", "`!(a > b)`"])),
192            "a new survivor"
193        );
194        let input = Finding::InputGap {
195            at: Location {
196                file: "src/lib.rs".into(),
197                line: 10,
198                column: 5,
199                code: "a > b".into(),
200                ..Location::default()
201            },
202            survivors: vec!["`a >= b`".into()],
203            survivor_count: 1,
204            add_tests: vec![],
205            observed: None,
206            verified: true,
207        };
208        assert_ne!(base, fingerprint(&input), "another kind of finding");
209    }
210
211    #[test]
212    fn baseline_round_trip() {
213        let path =
214            std::env::temp_dir().join(format!("tmt-baseline-test-{}.json", std::process::id()));
215        let mut findings = [
216            gap(1, "a > b", &["`a >= b`"]),
217            gap(2, "x();", &["delete `x();`"]),
218        ];
219        for (index, finding) in findings.iter_mut().enumerate() {
220            let Finding::AssertionGap { at, .. } = finding else {
221                unreachable!()
222            };
223            at.id = format!("id-{index}");
224        }
225        write(&path, &findings).unwrap();
226        let loaded = load(&path).unwrap();
227        let ids: BTreeSet<String> = ["id-0", "id-1"].iter().map(|id| id.to_string()).collect();
228        assert_eq!(loaded, Baseline::Ids(ids));
229        assert!(findings.iter().all(|f| loaded.knows(f)));
230        std::fs::write(&path, "not json").unwrap();
231        assert!(load(&path).is_err());
232        std::fs::remove_file(&path).unwrap();
233        assert!(load(&path).is_err());
234    }
235
236    #[test]
237    fn ignore_comments() {
238        let source = "\
239fn f() {
240    // tmt:ignore equivalent: both branches return the same
241    if a >= b { a } else { b }
242    let x = 1; // tmt:ignore
243    let y = 2;
244    let z = 3;
245    let w = 4; // tmt:ignore: with a colon
246    // tmt:ignored is another word
247    // not tmt:ignore here? it is: tmt:ignore must start the comment
248    let url = \"http://tmt:ignore\";
249}
250";
251        let ignored = ignored_lines(source);
252        assert_eq!(
253            ignored.keys().copied().collect::<Vec<_>>(),
254            [2, 3, 4, 5, 7, 8]
255        );
256        assert_eq!(ignored[&7], "with a colon");
257        assert_eq!(ignored[&2], "equivalent: both branches return the same");
258        assert_eq!(ignored[&3], "equivalent: both branches return the same");
259        assert_eq!(ignored[&4], "");
260        assert!(ignored_lines("").is_empty());
261    }
262}