use std::path::PathBuf;
use serde_json::Value;
pub trait Snapshot {
fn snapshot(&self, redact: &[&str]) -> String;
}
impl Snapshot for Value {
fn snapshot(&self, redact: &[&str]) -> String {
let mut value = self.clone();
redact_fields(&mut value, redact);
serde_json::to_string_pretty(&value).unwrap_or_default()
}
}
impl Snapshot for str {
fn snapshot(&self, _redact: &[&str]) -> String {
self.to_owned()
}
}
impl Snapshot for String {
fn snapshot(&self, redact: &[&str]) -> String {
self.as_str().snapshot(redact)
}
}
impl<T: Snapshot + ?Sized> Snapshot for &T {
fn snapshot(&self, redact: &[&str]) -> String {
(**self).snapshot(redact)
}
}
fn redact_fields(value: &mut Value, redact: &[&str]) {
match value {
Value::Object(fields) => {
for (key, field) in fields.iter_mut() {
if redact.contains(&key.as_str()) {
*field = Value::String(format!("[{key}]"));
} else {
redact_fields(field, redact);
}
}
}
Value::Array(items) => {
for item in items {
redact_fields(item, redact);
}
}
_ => {}
}
}
#[track_caller]
pub fn assert_snapshot(name: &str, value: impl Snapshot) {
assert_snapshot_redacted(name, value, &[]);
}
#[track_caller]
pub fn assert_snapshot_redacted(name: &str, value: impl Snapshot, redact: &[&str]) {
let actual = value.snapshot(redact);
let path = snapshot_path(name);
let update = std::env::var("GLACIER_UPDATE_SNAPSHOTS").is_ok_and(|v| !v.is_empty() && v != "0");
match std::fs::read_to_string(&path) {
Ok(expected) if !update => {
let expected = expected.strip_suffix('\n').unwrap_or(&expected);
if expected != actual {
panic!(
"snapshot `{name}` changed ({}):\n{}\nIf the new value is right, run the tests with GLACIER_UPDATE_SNAPSHOTS=1.",
path.display(),
diff(expected, &actual)
);
}
}
_ => {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)
.unwrap_or_else(|e| panic!("creating {}: {e}", dir.display()));
}
std::fs::write(&path, format!("{actual}\n"))
.unwrap_or_else(|e| panic!("writing {}: {e}", path.display()));
eprintln!("saved snapshot {}", path.display());
}
}
}
fn snapshot_path(name: &str) -> PathBuf {
let root =
std::env::var_os("CARGO_MANIFEST_DIR").map_or_else(|| PathBuf::from("."), PathBuf::from);
let test = std::thread::current()
.name()
.filter(|name| *name != "main")
.unwrap_or("snapshot")
.replace("::", "__");
let name: String = name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
c
} else {
'_'
}
})
.collect();
root.join("tests")
.join("snapshots")
.join(format!("{test}__{name}.snap"))
}
fn diff(expected: &str, actual: &str) -> String {
let old: Vec<&str> = expected.lines().collect();
let new: Vec<&str> = actual.lines().collect();
let (n, m) = (old.len(), new.len());
let mut lcs = vec![vec![0usize; m + 1]; n + 1];
for i in (0..n).rev() {
for j in (0..m).rev() {
lcs[i][j] = if old[i] == new[j] {
lcs[i + 1][j + 1] + 1
} else {
lcs[i + 1][j].max(lcs[i][j + 1])
};
}
}
let mut lines = Vec::new();
let (mut i, mut j) = (0, 0);
while i < n || j < m {
if i < n && j < m && old[i] == new[j] {
lines.push((' ', old[i]));
i += 1;
j += 1;
} else if i < n && (j == m || lcs[i + 1][j] >= lcs[i][j + 1]) {
lines.push(('-', old[i]));
i += 1;
} else {
lines.push(('+', new[j]));
j += 1;
}
}
let changed: Vec<bool> = lines.iter().map(|(sign, _)| *sign != ' ').collect();
let near = |k: usize| {
changed[k.saturating_sub(1)..(k + 2).min(changed.len())]
.iter()
.any(|c| *c)
};
lines
.iter()
.enumerate()
.filter(|(k, _)| near(*k))
.map(|(_, (sign, line))| format!("{sign} {line}"))
.collect::<Vec<_>>()
.join("\n")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn redacts_fields_at_any_depth() {
let value = serde_json::json!({"id": 7, "books": [{"id": 1, "title": "Dune"}]});
assert_eq!(
value.snapshot(&["id"]),
"{\n \"id\": \"[id]\",\n \"books\": [\n {\n \"id\": \"[id]\",\n \"title\": \"Dune\"\n }\n ]\n}"
);
}
#[test]
fn diffs_show_changed_lines() {
assert_eq!(diff("a\nb\nc\nd\ne", "a\nb\nC\nd\ne"), " b\n- c\n+ C\n d");
}
#[test]
fn saves_then_checks() {
let name = format!("unit-{}", std::process::id());
assert_snapshot(&name, "first");
assert_snapshot(&name, "first");
let path = snapshot_path(&name);
let failed = std::panic::catch_unwind(|| assert_snapshot(&name, "second"));
let _ = std::fs::remove_file(&path);
let message = failed.unwrap_err();
let message = message.downcast_ref::<String>().unwrap();
assert!(message.contains("- first\n+ second"), "{message}");
}
}