icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! The library side of `cargo icedwright review`: listing the visual snapshots that failed or
//! had no baseline, and accepting or rejecting one.
//!
//! A failed comparison leaves `actual.png`, `expected.png` (absent for a new snapshot),
//! `diff.png` and `pending.json` in its own directory under
//! `<out>/snapshots-failed/<crate>/<module path>/<test>/<snapshot>/`. Accepting copies
//! `actual.png` to the baseline recorded in `pending.json`, after checking the baseline has
//! not changed since the comparison, and removes the directory; rejecting removes the
//! directory and leaves the baseline alone. With `CI` set, accepting is refused, because
//! baselines change only on a developer's machine and through a commit.
//!
//! The rules are pure functions over a [`PendingStore`], with [`FsPendingStore`] as the file
//! system implementation.

use std::io;
use std::path::{Path, PathBuf};

pub use super::baseline::PendingRecord;
use super::baseline::file_hash;

/// One pending visual snapshot.
#[derive(Debug, Clone, PartialEq)]
pub struct PendingSnapshot {
    /// The directory holding its images and `pending.json`.
    pub dir: PathBuf,
    /// What `pending.json` says.
    pub record: PendingRecord,
}

impl PendingSnapshot {
    /// The render that failed, which accepting makes the baseline.
    #[must_use]
    pub fn actual(&self) -> PathBuf {
        self.dir.join("actual.png")
    }

    /// The baseline as it was compared, absent for a new snapshot.
    #[must_use]
    pub fn expected(&self) -> PathBuf {
        self.dir.join("expected.png")
    }

    /// The diff image, present for a changed snapshot.
    #[must_use]
    pub fn diff(&self) -> PathBuf {
        self.dir.join("diff.png")
    }
}

/// Where pending snapshots are kept.
#[cfg_attr(test, mockall::automock)]
pub trait PendingStore {
    /// Every pending snapshot, in any order.
    fn list(&self) -> io::Result<Vec<PendingSnapshot>>;
    /// The hash of the baseline file as it is now, `None` when there is none.
    fn baseline_hash(&self, baseline: &Path) -> io::Result<Option<String>>;
    /// Copies the actual image to the baseline path and removes the pending directory.
    fn accept(&self, entry: &PendingSnapshot) -> io::Result<()>;
    /// Removes the pending directory.
    fn reject(&self, entry: &PendingSnapshot) -> io::Result<()>;
}

/// Why a pending snapshot could not be accepted or rejected.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ReviewError {
    /// `CI` is set.
    #[error("baselines are not accepted with CI set; accept them on a developer's machine")]
    Ci,
    /// The baseline changed after the comparison that produced this entry.
    #[error("{} changed after the comparison; rerun the test and review again", baseline.display())]
    BaselineChanged {
        /// The baseline.
        baseline: PathBuf,
    },
    /// The file system.
    #[error(transparent)]
    Io(#[from] io::Error),
}

/// The pending snapshots whose test path contains `filter`, sorted by test and snapshot.
pub fn pending(store: &dyn PendingStore, filter: Option<&str>) -> io::Result<Vec<PendingSnapshot>> {
    let mut entries: Vec<PendingSnapshot> = store
        .list()?
        .into_iter()
        .filter(|entry| filter.is_none_or(|filter| entry.record.test.contains(filter)))
        .collect();
    entries.sort_by(|a, b| {
        (a.record.test.as_str(), a.record.snapshot.as_str())
            .cmp(&(b.record.test.as_str(), b.record.snapshot.as_str()))
    });
    Ok(entries)
}

/// Accepts a pending snapshot, refusing under `CI` or when the baseline changed since.
pub fn accept(
    store: &dyn PendingStore,
    entry: &PendingSnapshot,
    ci: bool,
) -> Result<(), ReviewError> {
    if ci {
        return Err(ReviewError::Ci);
    }
    if store.baseline_hash(&entry.record.baseline)? != entry.record.baseline_hash {
        return Err(ReviewError::BaselineChanged {
            baseline: entry.record.baseline.clone(),
        });
    }
    Ok(store.accept(entry)?)
}

/// Rejects a pending snapshot, leaving its baseline alone.
pub fn reject(store: &dyn PendingStore, entry: &PendingSnapshot) -> Result<(), ReviewError> {
    Ok(store.reject(entry)?)
}

/// How many `insta` snapshots wait for `cargo insta review` under `root`: `.snap.new` and
/// `.pending-snap` files, outside `target`.
pub fn pending_insta(root: &Path) -> io::Result<usize> {
    let mut count = 0;
    let mut dirs = vec![root.to_path_buf()];
    while let Some(dir) = dirs.pop() {
        for entry in std::fs::read_dir(&dir)? {
            let path = entry?.path();
            let name = path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or_default();
            if path.is_dir() {
                if name != "target" && !name.starts_with('.') {
                    dirs.push(path);
                }
                continue;
            }
            if name.ends_with(".snap.new") || name.ends_with(".pending-snap") {
                count += 1;
            }
        }
    }
    Ok(count)
}

/// Pending snapshots in a `snapshots-failed` directory.
#[derive(Debug, Clone)]
pub struct FsPendingStore {
    root: PathBuf,
}

impl FsPendingStore {
    /// The store under `<out>/snapshots-failed`.
    #[must_use]
    pub fn new(out_dir: &Path) -> Self {
        Self {
            root: out_dir.join("snapshots-failed"),
        }
    }

    /// The store for this process's output directory, `ICEDWRIGHT_OUT_DIR` or
    /// `target/icedwright`.
    pub fn from_env() -> Result<Self, crate::error::ConfigError> {
        Ok(Self::new(&super::SnapshotEnv::current()?.out_dir))
    }
}

impl PendingStore for FsPendingStore {
    fn list(&self) -> io::Result<Vec<PendingSnapshot>> {
        let mut out = Vec::new();
        if !self.root.is_dir() {
            return Ok(out);
        }
        let mut dirs = vec![self.root.clone()];
        while let Some(dir) = dirs.pop() {
            for entry in std::fs::read_dir(&dir)? {
                let path = entry?.path();
                if path.is_dir() {
                    dirs.push(path);
                    continue;
                }
                if path.file_name().is_some_and(|name| name == "pending.json") {
                    let text = std::fs::read_to_string(&path)?;
                    let record: PendingRecord = serde_json::from_str(&text)
                        .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
                    out.push(PendingSnapshot {
                        dir: dir.clone(),
                        record,
                    });
                }
            }
        }
        Ok(out)
    }

    fn baseline_hash(&self, baseline: &Path) -> io::Result<Option<String>> {
        match std::fs::read(baseline) {
            Ok(bytes) => Ok(Some(file_hash(&bytes))),
            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
            Err(error) => Err(error),
        }
    }

    fn accept(&self, entry: &PendingSnapshot) -> io::Result<()> {
        if let Some(parent) = entry.record.baseline.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::copy(entry.actual(), &entry.record.baseline)?;
        std::fs::remove_dir_all(&entry.dir)
    }

    fn reject(&self, entry: &PendingSnapshot) -> io::Result<()> {
        std::fs::remove_dir_all(&entry.dir)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn entry(test: &str, snapshot: &str, hash: Option<&str>) -> PendingSnapshot {
        PendingSnapshot {
            dir: PathBuf::from("/out/snapshots-failed")
                .join(test)
                .join(snapshot),
            record: PendingRecord {
                baseline: PathBuf::from("/src/tests/screenshots").join(format!("{snapshot}.png")),
                test: test.to_owned(),
                snapshot: snapshot.to_owned(),
                variant: String::new(),
                kind: "changed".to_owned(),
                changed: Some(3),
                total: Some(100),
                max_diff_pixels: 0,
                max_diff_ratio: 0.0,
                baseline_hash: hash.map(str::to_owned),
            },
        }
    }

    #[test]
    fn pending_filters_by_test_and_sorts() {
        let mut store = MockPendingStore::new();
        store.expect_list().returning(|| {
            Ok(vec![
                entry("ui::toolbar", "b", None),
                entry("ui::reader", "z", None),
                entry("ui::reader", "a", None),
            ])
        });
        let all = pending(&store, None).unwrap();
        let names: Vec<(&str, &str)> = all
            .iter()
            .map(|e| (e.record.test.as_str(), e.record.snapshot.as_str()))
            .collect();
        assert_eq!(
            names,
            [
                ("ui::reader", "a"),
                ("ui::reader", "z"),
                ("ui::toolbar", "b")
            ]
        );
        assert_eq!(pending(&store, Some("toolbar")).unwrap().len(), 1);
    }

    #[test]
    fn accepting_copies_when_the_baseline_is_unchanged() {
        let mut store = MockPendingStore::new();
        store
            .expect_baseline_hash()
            .returning(|_| Ok(Some("abc".to_owned())));
        store.expect_accept().times(1).returning(|_| Ok(()));
        accept(&store, &entry("t", "s", Some("abc")), false).unwrap();
    }

    #[test]
    fn a_changed_baseline_or_ci_refuses() {
        let mut store = MockPendingStore::new();
        store
            .expect_baseline_hash()
            .returning(|_| Ok(Some("new".to_owned())));
        store.expect_accept().never();
        assert!(matches!(
            accept(&store, &entry("t", "s", Some("old")), false),
            Err(ReviewError::BaselineChanged { .. })
        ));
        assert!(matches!(
            accept(&store, &entry("t", "s", Some("new")), true),
            Err(ReviewError::Ci)
        ));
    }

    #[test]
    fn a_new_snapshot_is_accepted_while_no_baseline_exists() {
        let mut store = MockPendingStore::new();
        store.expect_baseline_hash().returning(|_| Ok(None));
        store.expect_accept().times(1).returning(|_| Ok(()));
        accept(&store, &entry("t", "s", None), false).unwrap();
    }

    #[test]
    fn rejecting_leaves_the_baseline() {
        let mut store = MockPendingStore::new();
        store.expect_accept().never();
        store.expect_reject().times(1).returning(|_| Ok(()));
        reject(&store, &entry("t", "s", None)).unwrap();
    }
}