icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! Whether the theme variants of one semantic snapshot agree.
//!
//! A semantic snapshot whose name leaves the theme out (no [`SemanticOptions::per_theme`])
//! claims the tree is the same in every theme. Two harnesses in one test that take the same
//! snapshot in different themes are compared at once, and the second fails with
//! [`SnapshotError::ThemesDisagree`]. Separate tests, such as the combinations of a matrix, may
//! run in separate processes and in any order, so each one records its YAML under
//! `<out>/semantic-themes/` and [`disagreements`] compares the records once the run is over.
//!
//! [`SemanticOptions::per_theme`]: super::SemanticOptions::per_theme

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, PoisonError};

use super::SnapshotError;
use super::variant::theme_name;
use crate::testing::matrix::Theme;

/// Where theme records go under the output directory.
pub const DIR: &str = "semantic-themes";

/// One semantic snapshot whose theme variants gave different YAML.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Disagreement {
    /// The snapshot's record directory, relative to `<out>/semantic-themes/`.
    pub snapshot: PathBuf,
    /// Each theme's YAML, by theme name.
    pub yaml: BTreeMap<String, String>,
}

/// Where one snapshot's theme records live: the crate, the test path with the theme left out
/// of its last segment, and the snapshot's name with its suffix.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct RecordKey {
    parts: Vec<String>,
}

/// File-safe text: letters, digits, `-`, `_` and `.` are kept, anything else is `_`.
fn safe(text: &str) -> String {
    text.chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
                c
            } else {
                '_'
            }
        })
        .collect()
}

/// The test path with theme names taken out of the last segment, so `board::dark_phone` and
/// `board::light_phone` give `board::phone`, and `board::dark` gives `board`.
pub(crate) fn without_theme(test: &str) -> Vec<String> {
    let mut parts: Vec<String> = test.split("::").map(str::to_owned).collect();
    let Some(last) = parts.pop() else {
        return parts;
    };
    let kept: Vec<&str> = last
        .split('_')
        .filter(|token| !matches!(*token, "light" | "dark"))
        .collect();
    if !kept.is_empty() {
        parts.push(kept.join("_"));
    }
    parts
}

impl RecordKey {
    pub(crate) fn new(crate_name: &str, test: &str, name: &str, suffix: &str) -> Self {
        let mut parts = vec![safe(crate_name)];
        parts.extend(without_theme(test).iter().map(|part| safe(part)));
        let stem = if suffix.is_empty() {
            safe(name)
        } else {
            format!("{}@{}", safe(name), safe(suffix))
        };
        parts.push(stem);
        Self { parts }
    }

    fn dir(&self, out_dir: &Path) -> PathBuf {
        let mut dir = out_dir.join(DIR);
        dir.extend(&self.parts);
        dir
    }
}

/// What one test has recorded in this process, keyed by its thread and the snapshot.
type Seen = BTreeMap<(String, RecordKey), BTreeMap<&'static str, String>>;

fn seen() -> std::sync::MutexGuard<'static, Seen> {
    static SEEN: Mutex<Seen> = Mutex::new(BTreeMap::new());
    SEEN.lock().unwrap_or_else(PoisonError::into_inner)
}

/// Compares `yaml`, taken in `theme`, with what earlier harnesses of the same test took in
/// another theme, then remembers it.
pub(crate) fn check_within_test(
    thread: &str,
    key: &RecordKey,
    display_name: &str,
    theme: Theme,
    yaml: &str,
) -> Result<(), SnapshotError> {
    let theme = theme_name(theme);
    let mut seen = seen();
    let entry = seen.entry((thread.to_owned(), key.clone())).or_default();
    if let Some((other, other_yaml)) = entry
        .iter()
        .find(|(other, other_yaml)| **other != theme && other_yaml.as_str() != yaml)
    {
        return Err(SnapshotError::ThemesDisagree {
            name: display_name.to_owned(),
            theme,
            yaml: yaml.to_owned(),
            other,
            other_yaml: other_yaml.clone(),
        });
    }
    entry.insert(theme, yaml.to_owned());
    Ok(())
}

/// Writes `yaml` as the record of `theme` for [`disagreements`] to compare later.
pub(crate) fn record(
    out_dir: &Path,
    key: &RecordKey,
    theme: Theme,
    yaml: &str,
) -> std::io::Result<()> {
    let dir = key.dir(out_dir);
    std::fs::create_dir_all(&dir)?;
    std::fs::write(dir.join(format!("{}.yaml", theme_name(theme))), yaml)
}

/// Every snapshot among `records` (record directory, theme name, YAML) whose themes differ,
/// in directory order.
#[must_use]
pub fn compare(records: impl IntoIterator<Item = (PathBuf, String, String)>) -> Vec<Disagreement> {
    let mut by_snapshot: BTreeMap<PathBuf, BTreeMap<String, String>> = BTreeMap::new();
    for (snapshot, theme, yaml) in records {
        by_snapshot.entry(snapshot).or_default().insert(theme, yaml);
    }
    by_snapshot
        .into_iter()
        .filter(|(_, yaml)| {
            let mut texts = yaml.values();
            texts
                .next()
                .is_some_and(|first| texts.any(|other| other != first))
        })
        .map(|(snapshot, yaml)| Disagreement { snapshot, yaml })
        .collect()
}

fn collect(
    root: &Path,
    dir: &Path,
    out: &mut Vec<(PathBuf, String, String)>,
) -> std::io::Result<()> {
    let mut entries: Vec<PathBuf> = std::fs::read_dir(dir)?
        .map(|entry| entry.map(|entry| entry.path()))
        .collect::<std::io::Result<_>>()?;
    entries.sort();
    for path in entries {
        if path.is_dir() {
            collect(root, &path, out)?;
            continue;
        }
        if path.extension().and_then(|e| e.to_str()) != Some("yaml") {
            continue;
        }
        let (Some(theme), Some(parent)) = (
            path.file_stem().and_then(|s| s.to_str()),
            path.parent().and_then(|p| p.strip_prefix(root).ok()),
        ) else {
            continue;
        };
        out.push((
            parent.to_path_buf(),
            theme.to_owned(),
            std::fs::read_to_string(&path)?,
        ));
    }
    Ok(())
}

/// Every semantic snapshot recorded under `<out_dir>/semantic-themes/` whose theme variants
/// gave different YAML. Run it once every test has run; records are overwritten by each
/// run, so a snapshot removed from the suite keeps its last records until the directory is
/// cleared.
pub fn disagreements(out_dir: &Path) -> std::io::Result<Vec<Disagreement>> {
    let root = out_dir.join(DIR);
    if !root.exists() {
        return Ok(Vec::new());
    }
    let mut records = Vec::new();
    collect(&root, &root, &mut records)?;
    Ok(compare(records))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::snapshot::fonts::Fnv;

    #[test]
    fn theme_names_leave_the_test_path() {
        assert_eq!(
            without_theme("ui::board::dark_phone"),
            ["ui", "board", "phone"]
        );
        assert_eq!(
            without_theme("ui::board::light_phone"),
            ["ui", "board", "phone"]
        );
        assert_eq!(without_theme("ui::board::dark"), ["ui", "board"]);
        assert_eq!(without_theme("ui::darkness"), ["ui", "darkness"]);
    }

    #[test]
    fn keys_are_file_safe_and_ignore_the_theme() {
        let dark = RecordKey::new("app", "ui::t::dark", "role=list[name=\"Items\"]", "phone");
        let light = RecordKey::new("app", "ui::t::light", "role=list[name=\"Items\"]", "phone");
        assert_eq!(dark, light);
        assert_eq!(
            dark.dir(Path::new("/out")),
            PathBuf::from("/out/semantic-themes/app/ui/t/role_list_name__Items__@phone")
        );
    }

    #[test]
    fn only_snapshots_whose_themes_differ_are_reported() {
        let records = vec![
            (PathBuf::from("a"), "light".to_owned(), "- list".to_owned()),
            (PathBuf::from("a"), "dark".to_owned(), "- list".to_owned()),
            (PathBuf::from("b"), "light".to_owned(), "- list".to_owned()),
            (
                PathBuf::from("b"),
                "dark".to_owned(),
                "- list \"Dark\"".to_owned(),
            ),
            (
                PathBuf::from("c"),
                "dark".to_owned(),
                "- only one".to_owned(),
            ),
        ];
        let found = compare(records);
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].snapshot, PathBuf::from("b"));
        assert_eq!(found[0].yaml.len(), 2);
    }

    #[test]
    fn a_second_harness_in_the_same_test_is_compared_at_once() {
        let key = RecordKey::new("app", "within::test", "list", "");
        let thread = "themes::tests::a_second_harness_in_the_same_test_is_compared_at_once";
        check_within_test(thread, &key, "list", Theme::Light, "- list").unwrap();
        check_within_test(thread, &key, "list", Theme::Light, "- list").unwrap();
        let error =
            check_within_test(thread, &key, "list", Theme::Dark, "- list \"x\"").unwrap_err();
        let text = error.to_string();
        assert!(text.contains("per_theme(true)"), "{text}");
        assert!(text.contains("light") && text.contains("dark"), "{text}");
        check_within_test("another::test", &key, "list", Theme::Dark, "- list \"x\"").unwrap();
    }

    #[test]
    fn records_written_by_two_tests_are_compared_after_the_run() -> std::io::Result<()> {
        let out = std::env::temp_dir().join(format!(
            "icedwright-themes-{}",
            Fnv::of(b"records_written_by_two_tests_are_compared_after_the_run")
        ));
        if out.exists() {
            std::fs::remove_dir_all(&out)?;
        }
        let key = RecordKey::new("app", "ui::board::dark", "items", "");
        record(&out, &key, Theme::Dark, "- list \"Dark\"")?;
        let other = RecordKey::new("app", "ui::board::light", "items", "");
        record(&out, &other, Theme::Light, "- list")?;
        let found = disagreements(&out)?;
        std::fs::remove_dir_all(&out)?;
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].snapshot, PathBuf::from("app/ui/board/items"));
        Ok(())
    }
}