icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! What snapshots read from the process: how the tests were started, whether to accept new
//! baselines, and where files go. Everything is parsed by pure functions over the variables, so
//! tests inject them instead of setting the real environment.

use std::path::{Path, PathBuf};
use std::sync::OnceLock;

use super::SnapshotError;
use crate::error::ConfigError;

const UPDATE: &str = "ICEDWRIGHT_UPDATE";
const OUT_DIR: &str = "ICEDWRIGHT_OUT_DIR";

/// How the test process was started, which decides whether pixels can depend on fonts other
/// tests loaded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Runner {
    /// nextest's default mode: this process runs one test.
    ProcessPerTest,
    /// Plain `cargo test`, or nextest in another mode: tests share the process.
    Shared,
}

impl Runner {
    /// Reads `NEXTEST` and `NEXTEST_EXECUTION_MODE` through `get`.
    #[must_use]
    pub fn from_vars(get: impl Fn(&str) -> Option<String>) -> Runner {
        let nextest = get("NEXTEST").as_deref() == Some("1");
        let per_test = get("NEXTEST_EXECUTION_MODE").as_deref() == Some("process-per-test");
        if nextest && per_test {
            Runner::ProcessPerTest
        } else {
            Runner::Shared
        }
    }

    /// The runner of this process, read once.
    #[must_use]
    pub fn current() -> Runner {
        static RUNNER: OnceLock<Runner> = OnceLock::new();
        *RUNNER.get_or_init(|| Runner::from_vars(|name| std::env::var(name).ok()))
    }

    /// Fails with [`SnapshotError::NeedsProcessPerTest`] unless this is a process per test.
    pub fn require(self, what: &str) -> Result<(), SnapshotError> {
        match self {
            Runner::ProcessPerTest => Ok(()),
            Runner::Shared => Err(SnapshotError::NeedsProcessPerTest {
                what: what.to_owned(),
            }),
        }
    }
}

/// What to do with a new or changed visual snapshot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum UpdateMode {
    /// Fail, and write the files `cargo icedwright review` reads.
    #[default]
    Review,
    /// `ICEDWRIGHT_UPDATE=always`: write the baseline and pass, except under `CI`.
    Always,
}

impl UpdateMode {
    /// Parses `ICEDWRIGHT_UPDATE`.
    pub fn parse(value: Option<&str>) -> Result<UpdateMode, ConfigError> {
        match value {
            None | Some("" | "no") => Ok(UpdateMode::Review),
            Some("always") => Ok(UpdateMode::Always),
            Some(other) => Err(ConfigError::invalid(UPDATE, other, "always or no")),
        }
    }
}

/// Everything a visual snapshot reads from the process, parsed once per comparison.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SnapshotEnv {
    /// How the tests were started.
    pub runner: Runner,
    /// `ICEDWRIGHT_UPDATE`.
    pub update: UpdateMode,
    /// Whether `CI` is set, in which case nothing is written next to the source.
    pub ci: bool,
    /// Where failure files go: `snapshots-failed/` under this.
    pub out_dir: PathBuf,
    /// The test crate's directory, `CARGO_MANIFEST_DIR`, which baselines live under.
    pub manifest_dir: Option<PathBuf>,
    /// The package name, `CARGO_PKG_NAME`.
    pub crate_name: String,
    /// The test binary's name, without cargo's hash.
    pub binary: String,
    /// The running test's path, which libtest gives its thread.
    pub test: Option<String>,
}

impl SnapshotEnv {
    /// Parses the variables `get` returns, with the test binary's path and the current
    /// thread's name.
    pub fn from_vars(
        get: impl Fn(&str) -> Option<String>,
        exe: Option<&Path>,
        thread: Option<&str>,
    ) -> Result<SnapshotEnv, ConfigError> {
        let ci = get("CI").is_some_and(|value| !matches!(value.as_str(), "" | "0" | "false"));
        let out = get(OUT_DIR)
            .filter(|dir| !dir.is_empty())
            .map_or_else(|| PathBuf::from("target/icedwright"), PathBuf::from);
        Ok(SnapshotEnv {
            runner: Runner::from_vars(&get),
            update: UpdateMode::parse(get(UPDATE).as_deref())?,
            ci,
            out_dir: crate::trace::resolve_out_dir(&out, exe),
            manifest_dir: get("CARGO_MANIFEST_DIR").map(PathBuf::from),
            crate_name: get("CARGO_PKG_NAME").unwrap_or_else(|| "unknown".to_owned()),
            binary: exe.map(binary_name).unwrap_or_else(|| "unknown".to_owned()),
            test: thread
                .filter(|name| *name != "main" && !name.is_empty())
                .map(str::to_owned),
        })
    }

    /// The process's environment, with the runner read once per process.
    pub fn current() -> Result<SnapshotEnv, ConfigError> {
        let exe = std::env::current_exe().ok();
        let thread = std::thread::current();
        let mut env = SnapshotEnv::from_vars(
            |name| std::env::var(name).ok(),
            exe.as_deref(),
            thread.name(),
        )?;
        env.runner = Runner::current();
        Ok(env)
    }

    /// The running test's path, or an error saying why it is unknown.
    pub(crate) fn test_path(&self) -> Result<&str, SnapshotError> {
        self.test.as_deref().ok_or_else(|| {
            SnapshotError::Location(
                "could not tell which test is running: libtest names each test's thread after it, and this thread has no such name".to_owned(),
            )
        })
    }
}

/// `snapshots-a1b2c3d4e5f6a7b8` is `snapshots`: cargo appends a hash to test binaries.
fn binary_name(exe: &Path) -> String {
    let stem = exe
        .file_stem()
        .and_then(|stem| stem.to_str())
        .unwrap_or("unknown");
    match stem.rsplit_once('-') {
        Some((name, hash)) if hash.len() == 16 && hash.chars().all(|c| c.is_ascii_hexdigit()) => {
            name.to_owned()
        }
        _ => stem.to_owned(),
    }
}

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

    fn vars(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
        move |name| {
            pairs
                .iter()
                .find(|(key, _)| *key == name)
                .map(|(_, value)| (*value).to_owned())
        }
    }

    #[test]
    fn only_nextest_in_process_per_test_mode_is_a_process_per_test() {
        let per_test = vars(&[
            ("NEXTEST", "1"),
            ("NEXTEST_EXECUTION_MODE", "process-per-test"),
        ]);
        assert_eq!(Runner::from_vars(per_test), Runner::ProcessPerTest);
        assert_eq!(Runner::from_vars(vars(&[])), Runner::Shared);
        assert_eq!(Runner::from_vars(vars(&[("NEXTEST", "1")])), Runner::Shared);
        let shared = vars(&[("NEXTEST", "1"), ("NEXTEST_EXECUTION_MODE", "test-group")]);
        assert_eq!(Runner::from_vars(shared), Runner::Shared);
    }

    #[test]
    fn a_shared_process_refuses_with_the_fixed_message() {
        let Err(error) = Runner::Shared.require("to_match_image(\"reader\")") else {
            panic!("a shared process should refuse");
        };
        assert_eq!(
            error.to_string(),
            "to_match_image(\"reader\") needs a process per test\n\n  The font database is shared by every test in this process, and a font\n  loaded by another test can change the glyphs this snapshot draws\n  (cosmic-text falls back to any loaded face for missing glyphs).\n  Run visual snapshot tests with `cargo nextest run`, which starts a\n  process per test. Semantic snapshots and actions work under cargo test."
        );
        assert!(Runner::ProcessPerTest.require("anything").is_ok());
    }

    #[test]
    fn the_update_mode_takes_always_or_nothing() {
        assert_eq!(UpdateMode::parse(None).ok(), Some(UpdateMode::Review));
        assert_eq!(UpdateMode::parse(Some("no")).ok(), Some(UpdateMode::Review));
        assert_eq!(
            UpdateMode::parse(Some("always")).ok(),
            Some(UpdateMode::Always)
        );
        assert!(UpdateMode::parse(Some("yes")).is_err());
    }

    #[test]
    fn the_environment_is_read_from_the_variables_given() {
        let env = SnapshotEnv::from_vars(
            vars(&[
                ("CI", "true"),
                ("ICEDWRIGHT_OUT_DIR", "/tmp/out"),
                ("CARGO_MANIFEST_DIR", "/src/app"),
                ("CARGO_PKG_NAME", "app"),
                ("ICEDWRIGHT_UPDATE", "always"),
            ]),
            Some(Path::new("/target/debug/deps/looks-0123456789abcdef")),
            Some("ui::reader"),
        )
        .unwrap();
        assert!(env.ci);
        assert_eq!(env.update, UpdateMode::Always);
        assert_eq!(env.out_dir, PathBuf::from("/tmp/out"));
        assert_eq!(env.manifest_dir, Some(PathBuf::from("/src/app")));
        assert_eq!(env.binary, "looks");
        assert_eq!(env.test.as_deref(), Some("ui::reader"));

        let default = SnapshotEnv::from_vars(
            vars(&[("CI", "false")]),
            Some(Path::new("/work/target/debug/deps/looks-0123456789abcdef")),
            Some("main"),
        )
        .unwrap();
        assert!(!default.ci);
        assert_eq!(
            default.out_dir,
            PathBuf::from("/work/target/icedwright"),
            "the default follows the target directory"
        );
        assert!(default.test_path().is_err());
    }
}