icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! Semantic snapshots on the harness: a handle's subtree as YAML, in full through `insta`, or
//! matched against a partial template with retries.

use icedwright_check::{MatchReport, Template};
use icedwright_locator::RoleKind;
use icedwright_semantics::yaml::{self, YamlOptions};
use icedwright_types::VirtualDuration;

use super::visual::STABLE_FRAMES;
use super::{SnapshotEnv, SnapshotError, themes};
use crate::error::Result;
use crate::harness::{Handle, TestProgram};
use crate::testing::matrix::Theme;

/// How a semantic snapshot is written and matched.
#[derive(Debug, Clone, Default)]
#[must_use]
pub struct SemanticOptions {
    /// What the YAML includes.
    pub yaml: YamlOptions,
    /// Whether the theme goes in the snapshot's name, for an app whose tree differs between
    /// themes. The window size always does.
    pub per_theme: bool,
    /// How long `to_match_semantic` retries in virtual time; the harness default when `None`.
    pub timeout: Option<VirtualDuration>,
}

impl SemanticOptions {
    /// The defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// What the YAML includes.
    pub fn yaml(mut self, yaml: YamlOptions) -> Self {
        self.yaml = yaml;
        self
    }

    /// Puts the theme in the snapshot's name.
    pub fn per_theme(mut self, on: bool) -> Self {
        self.per_theme = on;
        self
    }

    /// How long `to_match_semantic` retries.
    pub fn timeout(mut self, timeout: impl Into<VirtualDuration>) -> Self {
        self.timeout = Some(timeout.into());
        self
    }
}

impl<P: TestProgram, R: RoleKind> Handle<'_, P, R> {
    /// The YAML of the node this handle resolves to and its subtree, after settling.
    pub fn semantic_yaml(&mut self, options: &YamlOptions) -> Result<String> {
        let resolved = self.resolve()?;
        Ok(yaml::write(&resolved.tree, resolved.id, options))
    }

    /// The subtree's YAML once it is the same on two consecutive frames.
    pub fn stable_semantic_yaml(&mut self, options: &YamlOptions) -> Result<String> {
        let mut previous = self.semantic_yaml(options)?;
        for _ in 0..STABLE_FRAMES {
            self.harness.next_frame()?;
            let next = self.semantic_yaml(options)?;
            if next == previous {
                return Ok(next);
            }
            previous = next;
        }
        Err(SnapshotError::NeverStableYaml {
            subject: self.locator.to_string(),
            frames: STABLE_FRAMES,
        }
        .into())
    }

    /// Matches the subtree against a partial template, retrying in virtual time until it
    /// matches or the harness's default timeout passes. The template is parsed once.
    pub fn to_match_semantic(&mut self, template: &str) -> Result {
        self.to_match_semantic_with(template, &SemanticOptions::default())
    }

    /// [`to_match_semantic`](Self::to_match_semantic) with a timeout of its own.
    pub fn to_match_semantic_with(&mut self, template: &str, options: &SemanticOptions) -> Result {
        let template = Template::parse(template).map_err(SnapshotError::from)?;
        let locator = self.locator.clone();
        let window = self.window;
        let timeout = options
            .timeout
            .unwrap_or_else(|| self.harness.default_timeout());
        let deadline = self.harness.now() + timeout;
        let mut report: Option<MatchReport> = None;
        let mut missing: Option<crate::Error> = None;
        let _ = self.harness.advance_until(deadline, |harness| {
            let tree = match window {
                Some(window) => harness.tree_of(window),
                None => harness.tree(),
            };
            let tree = match tree {
                Ok(tree) => tree,
                Err(error) => {
                    missing = Some(error);
                    return false;
                }
            };
            match icedwright_locator::resolve(&tree, &locator) {
                Ok(id) => {
                    let matched = template.matches(&tree, id);
                    let done = matched.is_match();
                    report = Some(matched);
                    missing = None;
                    done
                }
                Err(error) => {
                    missing = Some(error.into());
                    false
                }
            }
        })?;
        match (report, missing) {
            (Some(report), None) if report.is_match() => Ok(()),
            (_, Some(error)) => Err(error),
            (Some(report), None) => Err(SnapshotError::Semantic {
                subject: locator.to_string(),
                report: Box::new(report),
            }
            .into()),
            (None, None) => {
                Err(SnapshotError::Location(format!("{locator} was never looked for")).into())
            }
        }
    }
}

/// A semantic snapshot ready for `insta`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Prepared {
    /// The stable YAML.
    pub yaml: String,
    /// The locator, printed, which `insta` shows as the snapshot's description.
    pub description: String,
    /// The variant part of the snapshot's name, empty when the test varies nothing that
    /// changes the tree.
    pub suffix: String,
}

/// Settles and reads the stable YAML of a handle, for `assert_semantic_snapshot!`, named
/// `name` or, without one, after the locator. When the run varies the theme and the name
/// leaves it out, the YAML is checked against the other themes as [`super::themes`] says.
pub fn prepare<P: TestProgram, R: RoleKind>(
    handle: &mut Handle<'_, P, R>,
    name: Option<&str>,
    options: &SemanticOptions,
) -> Result<Prepared> {
    handle.harness.settle()?;
    let yaml = handle.stable_semantic_yaml(&options.yaml)?;
    let prepared = Prepared {
        yaml,
        description: handle.locator.to_string(),
        suffix: handle.harness.variant().semantic_suffix(options.per_theme),
    };
    if let Some(theme) = handle.harness.variant().theme_axis()
        && !options.per_theme
    {
        check_themes(&prepared, name, theme)?;
    }
    Ok(prepared)
}

fn check_themes(prepared: &Prepared, name: Option<&str>, theme: Theme) -> Result {
    let env = SnapshotEnv::current()?;
    let Some(test) = env.test.as_deref() else {
        return Ok(());
    };
    let name = name.unwrap_or(&prepared.description);
    let key = themes::RecordKey::new(&env.crate_name, test, name, &prepared.suffix);
    themes::record(&env.out_dir, &key, theme, &prepared.yaml)?;
    themes::check_within_test(test, &key, name, theme, &prepared.yaml)?;
    Ok(())
}

/// The `insta` settings a semantic snapshot is asserted under.
#[must_use]
pub fn settings(prepared: &Prepared) -> insta::Settings {
    let mut settings = insta::Settings::clone_current();
    settings.set_description(prepared.description.clone());
    settings.set_omit_expression(true);
    settings.set_snapshot_suffix(prepared.suffix.clone());
    settings
}

/// Asserts a handle's subtree against a semantic snapshot stored and reviewed by `insta`.
///
/// The app is settled and the YAML read once it is the same on two consecutive frames. The
/// locator is the snapshot's description, and the window size of the run variant (and the
/// theme, with [`SemanticOptions::per_theme`]) its suffix. Review with `cargo insta review`
/// or `INSTA_UPDATE`, as for any `insta` snapshot. The test crate needs no `insta`
/// dependency of its own.
///
/// The macro uses `?`, so it belongs in a test returning `icedwright::Result`.
///
/// ```ignore
/// assert_semantic_snapshot!(ui.get_by_role(role::Dialog));
/// assert_semantic_snapshot!("delete-dialog", ui.get_by_role(role::Dialog));
/// assert_semantic_snapshot!(ui.get_by_role(role::List), @r#"
/// - list "Items":
///   - listitem: Water the beans
/// "#);
/// assert_semantic_snapshot!(ui.get_by_role(role::List), &SemanticOptions::new().per_theme(true));
/// ```
#[macro_export]
macro_rules! assert_semantic_snapshot {
    ($name:literal, $handle:expr $(,)?) => {{
        let __prepared = $crate::snapshot::__private::prepare(
            &mut $handle,
            ::core::option::Option::Some($name),
            &$crate::snapshot::SemanticOptions::default(),
        )?;
        $crate::snapshot::__private::settings(&__prepared).bind(|| {
            $crate::snapshot::__private::insta::assert_snapshot!($name, __prepared.yaml.as_str());
        });
    }};
    ($handle:expr, @$snapshot:literal $(,)?) => {{
        let __prepared = $crate::snapshot::__private::prepare(
            &mut $handle,
            ::core::option::Option::None,
            &$crate::snapshot::SemanticOptions::default(),
        )?;
        $crate::snapshot::__private::settings(&__prepared).bind(|| {
            $crate::snapshot::__private::insta::assert_snapshot!(
                __prepared.yaml.as_str(),
                @$snapshot
            );
        });
    }};
    ($handle:expr, $options:expr $(,)?) => {{
        let __prepared = $crate::snapshot::__private::prepare(
            &mut $handle,
            ::core::option::Option::None,
            $options,
        )?;
        $crate::snapshot::__private::settings(&__prepared).bind(|| {
            $crate::snapshot::__private::insta::assert_snapshot!(__prepared.yaml.as_str());
        });
    }};
    ($handle:expr $(,)?) => {{
        let __prepared = $crate::snapshot::__private::prepare(
            &mut $handle,
            ::core::option::Option::None,
            &$crate::snapshot::SemanticOptions::default(),
        )?;
        $crate::snapshot::__private::settings(&__prepared).bind(|| {
            $crate::snapshot::__private::insta::assert_snapshot!(__prepared.yaml.as_str());
        });
    }};
}