Skip to main content

bynk_driver/
snapshots.rs

1//! #2842: the driver's half of snapshot testing.
2//!
3//! The compiler inlines each suite file's stored snapshots into its test module
4//! and the harness compares against them, reading nothing at test time. Only the
5//! driver writes: under `--update-snapshots` the runner hands back, per snapshot
6//! file, its counts and (when the file changes) the text to write, and
7//! [`SnapshotRun::settle`] writes or deletes the files. A `snapshots/` file no
8//! suite takes a snapshot into any more is obsolete as a whole; the build says
9//! which files are live ([`crate::project::ProjectOutput::snapshot_files`]).
10
11// A human-format run's report is one marked stdout line, taken out of the output;
12// a line of test output that starts with the same marker is hidden too (the real
13// report comes last and wins).
14use std::collections::{BTreeMap, BTreeSet};
15use std::path::{Path, PathBuf};
16
17use serde::Serialize;
18
19/// The marker the human-format runner puts at the start of the one line that
20/// carries the report (`BYNK_SNAPSHOT_REPORT=1`).
21pub const REPORT_MARKER: char = '\u{1}';
22const REPORT_PREFIX: &str = "bynk-snapshots ";
23
24/// Environment: `1` makes the human-format runner print the report line.
25pub use bynk_project::env_protocol::SNAPSHOT_REPORT as REPORT_ENV;
26/// Environment: `1` makes the runner record rather than compare.
27pub use bynk_project::env_protocol::UPDATE_SNAPSHOTS as UPDATE_ENV;
28
29/// What a run did to the project's snapshots, as the report states it: in every
30/// output format (`snapshots` in the JSON document and the NDJSON `run-end`).
31/// `obsolete` counts snapshots no case takes any more — removed under
32/// `--update-snapshots`, otherwise left and reported.
33#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize)]
34pub struct Counts {
35    pub written: u32,
36    pub updated: u32,
37    pub obsolete: u32,
38}
39
40/// One snapshot file's part of the runner's report.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct FileReport {
43    pub file: String,
44    pub written: u32,
45    pub updated: u32,
46    pub obsolete: u32,
47    /// Under the update flag, when the file changes: its new text, or `None` to
48    /// delete it. Absent (`Absent`) when the file stays as it is.
49    pub content: Change,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum Change {
54    Absent,
55    Write(String),
56    Delete,
57}
58
59/// The runner's report: every selected module's snapshot files.
60#[derive(Debug, Default, Clone, PartialEq, Eq)]
61pub struct Report {
62    pub files: Vec<FileReport>,
63}
64
65impl Report {
66    /// The report in a runner event's `files` (an NDJSON `snapshots` event, or the
67    /// human format's marked line).
68    pub fn from_files_value(files: &serde_json::Value) -> Self {
69        let num = |v: &serde_json::Value, key: &str| {
70            v.get(key)
71                .and_then(serde_json::Value::as_u64)
72                .map_or(0, |n| u32::try_from(n).unwrap_or(u32::MAX))
73        };
74        let files = files
75            .as_array()
76            .map(|a| {
77                a.iter()
78                    .filter_map(|f| {
79                        Some(FileReport {
80                            file: f.get("file")?.as_str()?.to_string(),
81                            written: num(f, "written"),
82                            updated: num(f, "updated"),
83                            obsolete: num(f, "obsolete"),
84                            content: match f.get("content") {
85                                None => Change::Absent,
86                                Some(serde_json::Value::Null) => Change::Delete,
87                                Some(v) => Change::Write(v.as_str()?.to_string()),
88                            },
89                        })
90                    })
91                    .collect()
92            })
93            .unwrap_or_default();
94        Report { files }
95    }
96
97    /// The report a human-format runner line carries, or `None` for any other
98    /// line.
99    pub fn from_marked_line(line: &str) -> Option<Self> {
100        let rest = line
101            .strip_prefix(REPORT_MARKER)?
102            .strip_prefix(REPORT_PREFIX)?;
103        let value: serde_json::Value = serde_json::from_str(rest.trim()).ok()?;
104        Some(Self::from_files_value(&value))
105    }
106}
107
108/// The project's snapshots for one run: which files the build takes snapshots
109/// into, and what is stored.
110#[derive(Debug, Clone)]
111pub struct SnapshotRun {
112    /// `--update-snapshots`.
113    pub update: bool,
114    root: PathBuf,
115    live: BTreeSet<String>,
116    stored: BTreeMap<String, String>,
117}
118
119impl SnapshotRun {
120    /// `None` when the build takes no snapshot and nothing is stored: a project
121    /// without snapshots is untouched and reports none.
122    pub fn new(
123        update: bool,
124        root: &Path,
125        live: BTreeSet<String>,
126        stored: BTreeMap<String, String>,
127    ) -> Option<Self> {
128        let run = SnapshotRun {
129            update,
130            root: root.to_path_buf(),
131            live,
132            stored,
133        };
134        (!run.live.is_empty() || !run.orphans().is_empty()).then_some(run)
135    }
136
137    /// The stored files no suite takes a snapshot into, each with its snapshot
138    /// count.
139    pub fn orphans(&self) -> Vec<(String, u32)> {
140        self.stored
141            .iter()
142            .filter(|(file, _)| !self.live.contains(*file))
143            .map(|(file, text)| (file.clone(), entries_in(text)))
144            .collect()
145    }
146
147    /// The report to settle: the runner's, or, when no module of the build takes a
148    /// snapshot (so the runner reports none), an empty one — the stored files
149    /// are all obsolete. `None` when a report was due and never came, as when the
150    /// runner died: then nothing is written.
151    pub fn report_for<'r>(&self, sent: Option<&'r Report>) -> Option<std::borrow::Cow<'r, Report>> {
152        match sent {
153            Some(report) => Some(std::borrow::Cow::Borrowed(report)),
154            None if self.live.is_empty() => Some(std::borrow::Cow::Owned(Report::default())),
155            None => None,
156        }
157    }
158
159    /// The counts the run reports: the runner's, with each orphaned file's
160    /// snapshots counted obsolete. `report` is `None` before the runner has said
161    /// (the counts are then just the orphans').
162    pub fn counts(&self, report: Option<&Report>) -> Counts {
163        let mut counts = Counts::default();
164        for f in report.map_or(&[][..], |r| r.files.as_slice()) {
165            counts.written += f.written;
166            counts.updated += f.updated;
167            counts.obsolete += f.obsolete;
168        }
169        counts.obsolete += self.orphans().iter().map(|(_, n)| n).sum::<u32>();
170        counts
171    }
172
173    /// Under `--update-snapshots`, write what the report says to write and
174    /// delete what it says to delete, orphaned files included. Without the flag
175    /// nothing changes. Returns the counts either way.
176    pub fn settle(&self, report: &Report) -> std::io::Result<Counts> {
177        if self.update {
178            // Only the build's own snapshot files are written: the report may be
179            // forged by test output on a human-format run.
180            for f in report.files.iter().filter(|f| self.live.contains(&f.file)) {
181                match &f.content {
182                    Change::Absent => {}
183                    Change::Write(text) => {
184                        let path = self.root.join(&f.file);
185                        if let Some(dir) = path.parent() {
186                            std::fs::create_dir_all(dir)?;
187                        }
188                        std::fs::write(&path, text)?;
189                    }
190                    Change::Delete => self.remove(&f.file)?,
191                }
192            }
193            for (file, _) in self.orphans() {
194                self.remove(&file)?;
195            }
196        }
197        Ok(self.counts(Some(report)))
198    }
199
200    /// Delete a snapshot file, then each directory it leaves empty, up to and
201    /// including `snapshots/` itself.
202    fn remove(&self, file: &str) -> std::io::Result<()> {
203        let path = self.root.join(file);
204        match std::fs::remove_file(&path) {
205            Ok(()) => {}
206            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
207            Err(e) => return Err(e),
208        }
209        let stop = self
210            .root
211            .join(bynk_project::snapshots::PROJECT_SNAPSHOTS_DIR);
212        let mut dir = path.parent().map(Path::to_path_buf);
213        while let Some(d) = dir {
214            if !d.starts_with(&stop) || std::fs::remove_dir(&d).is_err() {
215                break;
216            }
217            dir = d.parent().map(Path::to_path_buf);
218        }
219        Ok(())
220    }
221
222    /// The line `rich` output ends with, or `None` when there is nothing to say.
223    pub fn summary_line(&self, counts: Counts) -> Option<String> {
224        let mut parts = Vec::new();
225        if counts.written > 0 {
226            parts.push(format!("{} written", counts.written));
227        }
228        if counts.updated > 0 {
229            parts.push(format!("{} updated", counts.updated));
230        }
231        if counts.obsolete > 0 {
232            parts.push(if self.update {
233                format!("{} obsolete removed", counts.obsolete)
234            } else {
235                format!(
236                    "{} obsolete (remove with --update-snapshots)",
237                    counts.obsolete
238                )
239            });
240        }
241        (!parts.is_empty()).then(|| format!("snapshots: {}", parts.join(", ")))
242    }
243}
244
245/// How many snapshots a stored file holds (its cases' entries). An unreadable
246/// file counts as one, so it is still reported.
247fn entries_in(text: &str) -> u32 {
248    match serde_json::from_str::<serde_json::Value>(text) {
249        Ok(serde_json::Value::Object(cases)) => cases
250            .values()
251            .map(|c| c.as_object().map_or(1, |o| o.len()))
252            .sum::<usize>()
253            .try_into()
254            .unwrap_or(u32::MAX),
255        _ => 1,
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262
263    fn run(update: bool, live: &[&str], stored: &[(&str, &str)]) -> Option<SnapshotRun> {
264        SnapshotRun::new(
265            update,
266            Path::new("/nowhere"),
267            live.iter().map(|s| s.to_string()).collect(),
268            stored
269                .iter()
270                .map(|(k, v)| (k.to_string(), v.to_string()))
271                .collect(),
272        )
273    }
274
275    #[test]
276    fn a_project_without_snapshots_has_no_run() {
277        assert!(run(false, &[], &[]).is_none());
278    }
279
280    #[test]
281    fn an_unclaimed_file_is_obsolete_by_its_entries() {
282        let r = run(
283            false,
284            &["snapshots/a.snap.json"],
285            &[
286                ("snapshots/a.snap.json", "{}"),
287                (
288                    "snapshots/b.snap.json",
289                    r#"{"c":{"x":1,"y":2},"d":{"z":3}}"#,
290                ),
291            ],
292        )
293        .unwrap();
294        assert_eq!(r.orphans(), vec![("snapshots/b.snap.json".to_string(), 3)]);
295        assert_eq!(r.counts(None).obsolete, 3);
296    }
297
298    #[test]
299    fn a_report_line_round_trips() {
300        let line = "\u{1}bynk-snapshots [{\"file\":\"snapshots/a.snap.json\",\"written\":1,\"updated\":2,\"obsolete\":3,\"content\":\"{}\\n\"},{\"file\":\"snapshots/b.snap.json\",\"written\":0,\"updated\":0,\"obsolete\":1,\"content\":null}]";
301        let report = Report::from_marked_line(line).unwrap();
302        assert_eq!(report.files.len(), 2);
303        assert_eq!(report.files[0].content, Change::Write("{}\n".to_string()));
304        assert_eq!(report.files[1].content, Change::Delete);
305        assert!(Report::from_marked_line("  ✓ a case").is_none());
306    }
307
308    #[test]
309    fn the_summary_says_what_changed() {
310        let r = run(false, &["snapshots/a.snap.json"], &[]).unwrap();
311        assert_eq!(r.summary_line(Counts::default()), None);
312        assert_eq!(
313            r.summary_line(Counts {
314                written: 2,
315                updated: 1,
316                obsolete: 3
317            })
318            .as_deref(),
319            Some("snapshots: 2 written, 1 updated, 3 obsolete (remove with --update-snapshots)")
320        );
321    }
322}