Skip to main content

tpt_snapshot_lite/
lib.rs

1use std::fs;
2use std::path::{Path, PathBuf};
3
4/// Controls snapshot behaviour: read from `UPDATE_SNAPSHOTS` env var at runtime.
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6enum Mode {
7    /// Assert that the stored snapshot matches the current value.
8    Assert,
9    /// Overwrite (or create) the snapshot file unconditionally.
10    Update,
11}
12
13fn current_mode() -> Mode {
14    if std::env::var("UPDATE_SNAPSHOTS")
15        .map(|v| !v.is_empty())
16        .unwrap_or(false)
17    {
18        Mode::Update
19    } else {
20        Mode::Assert
21    }
22}
23
24/// A named snapshot.
25///
26/// Snap files are stored under `<crate_root>/tests/snapshots/<name>.snap`,
27/// where `<crate_root>` is determined by the `CARGO_MANIFEST_DIR` env var
28/// at **test** compile time (passed in by the macro).
29pub struct Snapshot {
30    name: String,
31    snap_dir: PathBuf,
32}
33
34impl Snapshot {
35    /// Create a snapshot with the given name and snap directory (typically
36    /// `concat!(env!("CARGO_MANIFEST_DIR"), "/tests/snapshots")`).
37    pub fn new(name: &str, snap_dir: &str) -> Self {
38        Self {
39            name: name.to_owned(),
40            snap_dir: PathBuf::from(snap_dir),
41        }
42    }
43
44    fn snap_path(&self) -> PathBuf {
45        self.snap_dir.join(format!("{}.snap", self.name))
46    }
47
48    /// Assert that `value`'s `Display` output matches the stored snapshot.
49    ///
50    /// - If the snap file does not exist, it is created and the test **panics**
51    ///   with a message asking you to re-run.
52    /// - If `UPDATE_SNAPSHOTS=1`, the snap file is overwritten and the test passes.
53    pub fn assert_display(&self, value: &dyn std::fmt::Display) {
54        self.assert_str(&value.to_string());
55    }
56
57    /// Assert that `value`'s `Debug` output matches the stored snapshot.
58    pub fn assert_debug(&self, value: &dyn std::fmt::Debug) {
59        self.assert_str(&format!("{value:#?}"));
60    }
61
62    fn assert_str(&self, actual: &str) {
63        let path = self.snap_path();
64        match current_mode() {
65            Mode::Update => {
66                write_snap(&path, actual);
67            }
68            Mode::Assert => {
69                if !path.exists() {
70                    write_snap(&path, actual);
71                    panic!(
72                        "Snapshot '{}' did not exist — it has been created at {}.\n\
73                         Re-run the test to verify.",
74                        self.name,
75                        path.display()
76                    );
77                }
78                let stored = fs::read_to_string(&path)
79                    .unwrap_or_else(|e| panic!("Failed to read snapshot {}: {e}", path.display()));
80                // Normalise line endings for cross-platform compatibility.
81                let stored = stored.replace("\r\n", "\n");
82                let actual = actual.replace("\r\n", "\n");
83                if stored != actual {
84                    panic!(
85                        "Snapshot '{}' mismatch.\n\
86                         --- stored ({}) ---\n{}\n\
87                         --- actual ---\n{}\n\
88                         Set UPDATE_SNAPSHOTS=1 to accept the new output.",
89                        self.name,
90                        path.display(),
91                        stored,
92                        actual
93                    );
94                }
95            }
96        }
97    }
98}
99
100fn write_snap(path: &Path, content: &str) {
101    if let Some(parent) = path.parent() {
102        fs::create_dir_all(parent)
103            .unwrap_or_else(|e| panic!("Failed to create snapshot dir {}: {e}", parent.display()));
104    }
105    fs::write(path, content)
106        .unwrap_or_else(|e| panic!("Failed to write snapshot {}: {e}", path.display()));
107}
108
109// ── Macros ───────────────────────────────────────────────────────────────────
110
111/// Assert that a value's `Display` output matches a named snapshot file.
112///
113/// Snap files are stored at `<crate_root>/tests/snapshots/<name>.snap`.
114///
115/// # Example
116/// ```rust,ignore
117/// assert_snapshot!("greeting", &format!("Hello, {}!", name));
118/// ```
119#[macro_export]
120macro_rules! assert_snapshot {
121    ($name:expr, $value:expr) => {{
122        let snap = $crate::Snapshot::new(
123            $name,
124            concat!(env!("CARGO_MANIFEST_DIR"), "/tests/snapshots"),
125        );
126        snap.assert_display(&$value);
127    }};
128}
129
130/// Assert that a value's `Debug` output matches a named snapshot file.
131#[macro_export]
132macro_rules! assert_snapshot_debug {
133    ($name:expr, $value:expr) => {{
134        let snap = $crate::Snapshot::new(
135            $name,
136            concat!(env!("CARGO_MANIFEST_DIR"), "/tests/snapshots"),
137        );
138        snap.assert_debug(&$value);
139    }};
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145    use std::env;
146    use std::sync::Mutex;
147
148    // Serialise tests that touch UPDATE_SNAPSHOTS to avoid races.
149    static ENV_LOCK: Mutex<()> = Mutex::new(());
150
151    fn tmp_snap_dir() -> (tempfile_compat::Dir, String) {
152        let d = tempfile_compat::Dir::new();
153        let s = d.path().to_string_lossy().into_owned();
154        (d, s)
155    }
156
157    // Minimal inline tempdir so we have zero external test deps.
158    mod tempfile_compat {
159        use std::{
160            fs,
161            path::PathBuf,
162            sync::atomic::{AtomicU64, Ordering},
163        };
164        static COUNTER: AtomicU64 = AtomicU64::new(0);
165        pub struct Dir(PathBuf);
166        impl Dir {
167            pub fn new() -> Self {
168                let n = COUNTER.fetch_add(1, Ordering::SeqCst);
169                let p =
170                    std::env::temp_dir().join(format!("snap-test-{}-{}", std::process::id(), n));
171                fs::create_dir_all(&p).unwrap();
172                Dir(p)
173            }
174            pub fn path(&self) -> &std::path::Path {
175                &self.0
176            }
177        }
178        impl Drop for Dir {
179            fn drop(&mut self) {
180                let _ = fs::remove_dir_all(&self.0);
181            }
182        }
183    }
184
185    #[test]
186    fn creates_snap_on_first_run() {
187        let (dir, dir_s) = tmp_snap_dir();
188        let snap = Snapshot::new("first_run", &dir_s);
189        let result = std::panic::catch_unwind(|| snap.assert_display(&"hello"));
190        assert!(result.is_err(), "should panic asking for re-run");
191        assert!(dir.path().join("first_run.snap").exists());
192    }
193
194    #[test]
195    fn matches_existing_snap() {
196        let (dir, dir_s) = tmp_snap_dir();
197        write_snap(&dir.path().join("existing.snap"), "hello");
198        let snap = Snapshot::new("existing", &dir_s);
199        snap.assert_display(&"hello"); // should not panic
200    }
201
202    #[test]
203    fn panics_on_mismatch() {
204        let _lock = ENV_LOCK.lock().unwrap();
205        env::remove_var("UPDATE_SNAPSHOTS");
206        let (dir, dir_s) = tmp_snap_dir();
207        write_snap(&dir.path().join("mismatch.snap"), "old");
208        let snap = Snapshot::new("mismatch", &dir_s);
209        let result = std::panic::catch_unwind(|| snap.assert_display(&"new"));
210        assert!(result.is_err(), "should panic on mismatch");
211        let msg = result.unwrap_err();
212        let msg_str = msg
213            .downcast_ref::<String>()
214            .map(|s| s.as_str())
215            .or_else(|| msg.downcast_ref::<&str>().copied())
216            .unwrap_or("");
217        assert!(
218            msg_str.contains("mismatch"),
219            "panic message should contain 'mismatch': {msg_str}"
220        );
221    }
222
223    #[test]
224    fn update_mode_overwrites() {
225        let _lock = ENV_LOCK.lock().unwrap();
226        let (dir, dir_s) = tmp_snap_dir();
227        write_snap(&dir.path().join("update.snap"), "old");
228        env::set_var("UPDATE_SNAPSHOTS", "1");
229        let snap = Snapshot::new("update", &dir_s);
230        snap.assert_display(&"new");
231        env::remove_var("UPDATE_SNAPSHOTS");
232        let stored = fs::read_to_string(dir.path().join("update.snap")).unwrap();
233        assert_eq!(stored, "new");
234    }
235}