glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Snapshot assertions, as Elixir's and Rust's `insta`: a value checked
//! against a copy saved the first time, in `tests/snapshots/`.
//!
//! ```glacier
//! test "lists the books" do
//!   res = get "/books.json"
//!   assert_snapshot("books", res.json(), redact: ["id", "inserted_at"])
//! end
//! ```
//!
//! The first run saves `tests/snapshots/<test>__books.snap` and passes; a
//! later run whose value differs fails, showing the lines that changed.
//! Commit the files: they're the expected values. To accept new values,
//! run the tests with `GLACIER_UPDATE_SNAPSHOTS=1`.

use std::path::PathBuf;

use serde_json::Value;

/// What a snapshot is taken of: JSON (pretty-printed, with redactions) or
/// text as it is.
pub trait Snapshot {
    /// The text saved and compared.
    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)
    }
}

/// Every field named in `redact`, at any depth, replaced with `"[name]"`:
/// values that change from run to run (ids, timestamps) without making
/// the snapshot fail.
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);
            }
        }
        _ => {}
    }
}

/// Checks `value` against the snapshot `name` of the running test,
/// saving it the first time (or with `GLACIER_UPDATE_SNAPSHOTS=1`).
///
/// # Panics
///
/// When the value differs from the snapshot, showing how.
#[track_caller]
pub fn assert_snapshot(name: &str, value: impl Snapshot) {
    assert_snapshot_redacted(name, value, &[]);
}

/// [`assert_snapshot`] with the fields named in `redact` blanked:
/// `assert_snapshot("books", res.json(), redact: ["id"])` in `.glacier`.
///
/// # Panics
///
/// When the value differs from the snapshot, showing how.
#[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());
        }
    }
}

/// `tests/snapshots/<test>__<name>.snap`, under the crate being tested.
fn snapshot_path(name: &str) -> PathBuf {
    let root =
        std::env::var_os("CARGO_MANIFEST_DIR").map_or_else(|| PathBuf::from("."), PathBuf::from);
    // The test's name: its thread's, as `cargo test` (and
    // `#[glacier::test]`) names them (`controllers::books::lists_the_books`).
    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"))
}

/// The lines that differ, as `-` (saved) and `+` (now), with a line of
/// context either side: a small line diff, from the longest common
/// subsequence.
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;
        }
    }
    // Only changed lines and their neighbours.
    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}");
    }
}