icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! The built-in fixtures: [`TempDir`], [`Seed`], the [`Environment`] and its [`Locale`], and
//! `fake::Calls`.

use std::fmt;
use std::hash::{BuildHasher, Hasher};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::OnceLock;

use crate::config::EnvOverrides;
use crate::fakes::calls::Calls;

use super::environment::Environment;
use super::fixture::{Fixture, FixtureError, RuntimeRef, TestOutcome};
use super::matrix::Locale;

/// The output directory: `ICEDWRIGHT_OUT_DIR`, or `icedwright` in the target directory the test
/// binary was built into.
pub(crate) fn out_dir() -> Result<PathBuf, crate::Error> {
    let overrides = EnvOverrides::from_env()?;
    let dir = overrides
        .out_dir
        .clone()
        .unwrap_or_else(|| PathBuf::from("target/icedwright"));
    let exe = std::env::current_exe().ok();
    Ok(crate::trace::resolve_out_dir(&dir, exe.as_deref()))
}

/// `dir` with one directory per `::` segment of `test`, the last segment as `file`.
pub(crate) fn test_path(dir: &Path, package: &str, test: &str, extension: &str) -> PathBuf {
    let mut path = dir.join(package);
    let mut segments: Vec<&str> = test.split("::").collect();
    let last = segments.pop().unwrap_or("test");
    segments.into_iter().for_each(|segment| path.push(segment));
    path.push(format!("{last}{extension}"));
    path
}

/// A directory for one test, under `target/icedwright/tmp/`, emptied when it is made and
/// deleted when dropped. As a fixture it is kept, and its path printed, when the test failed.
#[derive(Debug)]
pub struct TempDir {
    path: PathBuf,
    keep: bool,
}

impl TempDir {
    /// A fresh directory named after `test`, in `package`, under the output directory.
    pub fn for_test(package: &str, test: &str) -> crate::Result<Self> {
        let path = test_path(&out_dir()?.join("tmp"), package, test, "");
        Ok(Self::at(path)?)
    }

    /// A fresh, empty directory at `path`, removing whatever was there.
    pub fn at(path: impl Into<PathBuf>) -> std::io::Result<Self> {
        let path = path.into();
        match std::fs::remove_dir_all(&path) {
            Err(error) if error.kind() != std::io::ErrorKind::NotFound => return Err(error),
            _ => {}
        }
        std::fs::create_dir_all(&path)?;
        Ok(Self { path, keep: false })
    }

    /// The directory.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Keeps the directory after the value is dropped, and returns its path.
    #[must_use]
    pub fn keep(mut self) -> PathBuf {
        self.keep = true;
        self.path.clone()
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        if !self.keep {
            let _ = std::fs::remove_dir_all(&self.path);
        }
    }
}

impl Fixture for TempDir {
    type Deps = ();

    fn setup(_: (), env: &Environment) -> Result<Self, FixtureError> {
        TempDir::for_test(env.package(), env.test()).map_err(FixtureError::from)
    }

    fn teardown(self, outcome: &TestOutcome, _: &mut RuntimeRef<'_>) -> Result<(), FixtureError> {
        if !outcome.passed() {
            let path = self.keep();
            eprintln!("icedwright: kept {} for the failed test", path.display());
        }
        Ok(())
    }
}

/// A 64-bit seed for exploration and property tests: the FNV-1a hash of the test's path, so
/// every run explores the same cases, unless `ICEDWRIGHT_SEED` gives one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Seed(u64);

impl Seed {
    /// A seed of this value.
    #[must_use]
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// The value.
    #[must_use]
    pub const fn get(self) -> u64 {
        self.0
    }

    /// The fixed seed for a test path.
    #[must_use]
    pub const fn for_test(path: &str) -> Self {
        let bytes = path.as_bytes();
        let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
        let mut index = 0;
        while index < bytes.len() {
            hash ^= bytes[index] as u64;
            hash = hash.wrapping_mul(0x0100_0000_01b3);
            index += 1;
        }
        Self(hash)
    }

    /// The seed for a test path, with `ICEDWRIGHT_SEED` taking precedence: a hex seed replays
    /// it, `random` draws a fresh one and prints it.
    pub fn from_env_or(path: &str) -> Result<Self, FixtureError> {
        static SETTING: OnceLock<Result<Option<Setting>, String>> = OnceLock::new();
        let setting = SETTING.get_or_init(|| match std::env::var("ICEDWRIGHT_SEED") {
            Ok(value) => Setting::parse(&value).map(Some).ok_or(value),
            Err(_) => Ok(None),
        });
        match setting {
            Ok(None) => Ok(Self::for_test(path)),
            Ok(Some(Setting::Fixed(seed))) => Ok(*seed),
            Ok(Some(Setting::Random)) => {
                let seed = Self(std::hash::RandomState::new().build_hasher().finish());
                eprintln!("icedwright: {path} uses the random seed {seed}");
                Ok(seed)
            }
            Err(value) => Err(FixtureError::BadSeed {
                value: value.clone(),
            }),
        }
    }

    /// 32 bytes for an RNG such as proptest's ChaCha, spread from the seed.
    #[must_use]
    pub fn to_bytes(self) -> [u8; 32] {
        let mut state = self.0;
        let mut out = [0; 32];
        for chunk in out.chunks_mut(8) {
            state = state.wrapping_add(0x9e37_79b9_7f4a_7c15);
            let mut z = state;
            z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
            z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
            chunk.copy_from_slice(&(z ^ (z >> 31)).to_le_bytes());
        }
        out
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Setting {
    Fixed(Seed),
    Random,
}

impl Setting {
    fn parse(value: &str) -> Option<Self> {
        if value == "random" {
            return Some(Self::Random);
        }
        value.parse().ok().map(Self::Fixed)
    }
}

impl fmt::Display for Seed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:#018x}", self.0)
    }
}

/// A seed that is not `0x` followed by up to sixteen hex digits.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{0:?} is not a seed; expected 0x followed by up to sixteen hex digits")]
pub struct InvalidSeed(pub String);

impl FromStr for Seed {
    type Err = InvalidSeed;

    fn from_str(value: &str) -> Result<Self, InvalidSeed> {
        let digits = value
            .strip_prefix("0x")
            .filter(|digits| !digits.is_empty())
            .ok_or_else(|| InvalidSeed(value.to_owned()))?;
        u64::from_str_radix(digits, 16)
            .map(Self)
            .map_err(|_| InvalidSeed(value.to_owned()))
    }
}

impl Fixture for Seed {
    type Deps = ();

    fn setup(_: (), env: &Environment) -> Result<Self, FixtureError> {
        Seed::from_env_or(env.test())
    }
}

impl Fixture for Environment {
    type Deps = ();

    fn setup(_: (), env: &Environment) -> Result<Self, FixtureError> {
        Ok(env.clone())
    }
}

impl Fixture for Locale {
    type Deps = ();

    fn setup(_: (), env: &Environment) -> Result<Self, FixtureError> {
        Ok(env.locale)
    }
}

impl<Req, Resp> Fixture for Calls<Req, Resp>
where
    Req: Clone + fmt::Debug + Send + 'static,
    Resp: Send + 'static,
{
    type Deps = ();

    fn setup(_: (), _: &Environment) -> Result<Self, FixtureError> {
        Ok(Calls::new(std::any::type_name::<Self>()))
    }
}

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

    #[test]
    fn a_test_path_always_gives_the_same_seed() {
        let seed = Seed::for_test("ui::explores::phone_dark");
        assert_eq!(seed, Seed::for_test("ui::explores::phone_dark"));
        assert_ne!(seed, Seed::for_test("ui::explores::phone_light"));
        assert_eq!(Seed::for_test("").get(), 0xcbf2_9ce4_8422_2325);
        assert_eq!(seed.to_bytes(), seed.to_bytes());
    }

    #[test]
    fn seeds_print_and_parse_as_hex() {
        let seed = Seed::new(0x9f3a_51c2_e07b_4d18);
        assert_eq!(seed.to_string(), "0x9f3a51c2e07b4d18");
        assert_eq!("0x9f3a51c2e07b4d18".parse::<Seed>(), Ok(seed));
        assert_eq!(Seed::new(1).to_string(), "0x0000000000000001");
        for bad in ["", "0x", "9f3a", "0xzz", "0x11112222333344445"] {
            assert!(bad.parse::<Seed>().is_err(), "{bad}");
        }
        assert_eq!(Setting::parse("random"), Some(Setting::Random));
        assert_eq!(Setting::parse("0x2"), Some(Setting::Fixed(Seed::new(2))));
        assert_eq!(Setting::parse("soon"), None);
    }

    #[test]
    fn test_paths_become_directories() {
        assert_eq!(
            test_path(Path::new("/out"), "notes", "ui::saves::phone_dark", ".json"),
            PathBuf::from("/out/notes/ui/saves/phone_dark.json")
        );
        assert_eq!(
            test_path(Path::new("/out"), "notes", "plain", ""),
            PathBuf::from("/out/notes/plain")
        );
    }
}