icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! `expect`: retrying assertions on widgets, and the harness's expectations about messages,
//! tasks, the clipboard, windows and state.
//!
//! Every matcher settles, evaluates on the fresh state, and waits in virtual time until it
//! holds or its timeout passes, through `icedwright_check::retry`. An app with nothing left
//! to do reaches the deadline in one jump, so a failing assertion costs no real time.

mod others;
mod report;
#[cfg(test)]
mod tests;

use std::fmt;
use std::panic::Location;

use icedwright_check::assertion::{Assertion, Evaluation, NodeMatcher, evaluate_matcher};
use icedwright_check::{CheckError, RetryPolicy, ValueMatch, retry};
use icedwright_locator::{AnyRole, Locator, RoleKind, TextMatch};
use icedwright_semantics::SemanticTree;
use icedwright_trace::{CanonicalSelector, SelectorText, StepKind};
use icedwright_types::role::{
    Checkable, Editable, Expandable, HasValue, Leveled, Pressable, SelectableItem,
};
use icedwright_types::{Checked, Ratio, Role, VirtualDuration};

pub use others::{
    ClipboardExpect, Mark, MessagePattern, MessagesExpect, SoftMessages, StateExpect, TasksExpect,
    WindowsExpect,
};
pub use report::ExpectError;
pub(crate) use report::ExpectState;

use crate::driver::Scoped;
use crate::error::Result;
use crate::harness::{Handle, Harness, TestProgram};

/// The options every expectation shares.
#[derive(Debug, Clone, Default)]
pub(crate) struct Settings {
    pub(crate) timeout: Option<VirtualDuration>,
    pub(crate) during: Option<VirtualDuration>,
    pub(crate) negated: bool,
    pub(crate) message: Option<String>,
    pub(crate) soft: bool,
}

impl Settings {
    pub(crate) fn policy<D>(&self, default: VirtualDuration) -> RetryPolicy<D>
    where
        D: icedwright_check::Driver<Duration = VirtualDuration>,
    {
        RetryPolicy {
            timeout: self.timeout.unwrap_or(default),
            during: self.during,
            negated: self.negated,
        }
    }
}

/// A locator's canonical text, for the trace.
struct Canonical(String);

impl CanonicalSelector for Canonical {
    fn canonical(&self) -> String {
        self.0.clone()
    }
}

/// Records a failure of a soft expectation and passes, or returns it.
pub(crate) fn settle_soft<P: TestProgram>(
    h: &mut Harness<P>,
    soft: bool,
    result: Result,
) -> Result {
    match result {
        Err(crate::Error::Expect(error)) if soft => {
            h.expectations.record_soft(error);
            Ok(())
        }
        other => other,
    }
}

/// Starts an expectation about a widget: `expect(ui.get_by_text("Saved")).to_be_visible()?`.
pub fn expect<'h, P: TestProgram, R: RoleKind>(subject: Handle<'h, P, R>) -> Expect<'h, P, R> {
    Expect {
        handle: subject,
        settings: Settings::default(),
    }
}

/// An expectation about the node a handle resolves to. Its matchers retry until they hold or
/// the timeout passes in virtual time.
#[must_use = "an expectation does nothing until a matcher is called and its result is used"]
pub struct Expect<'h, P: TestProgram, R: RoleKind> {
    handle: Handle<'h, P, R>,
    settings: Settings,
}

impl<P: TestProgram, R: RoleKind> fmt::Debug for Expect<'_, P, R> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Expect")
            .field("locator", &self.handle.locator.to_string())
            .field("settings", &self.settings)
            .finish_non_exhaustive()
    }
}

/// The same matchers as [`Expect`], recording a failure on the harness instead of returning
/// it. `Harness::finish` reports every recorded failure.
#[must_use = "a soft expectation does nothing until a matcher is called"]
pub struct Soft<'h, P: TestProgram, R: RoleKind>(Expect<'h, P, R>);

impl<P: TestProgram, R: RoleKind> fmt::Debug for Soft<'_, P, R> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Soft").field(&self.0).finish()
    }
}

/// `expect(x).not()`, or `!expect(x)`: reverses what counts as success, so the matcher retries
/// until it does not hold. The prelude brings [`std::ops::Not`] into scope for the method form.
impl<P: TestProgram, R: RoleKind> std::ops::Not for Expect<'_, P, R> {
    type Output = Self;

    fn not(mut self) -> Self {
        self.settings.negated = !self.settings.negated;
        self
    }
}

/// The type of a widget matcher's evaluation, run once per attempt.
type Evaluate<'a> =
    dyn Fn(&SemanticTree, &Locator<AnyRole>) -> std::result::Result<Evaluation, CheckError> + 'a;

impl<'h, P: TestProgram, R: RoleKind> Expect<'h, P, R> {
    /// How long to retry, in virtual time. `VirtualDuration::ZERO` evaluates once.
    pub fn timeout(mut self, timeout: impl Into<VirtualDuration>) -> Self {
        self.settings.timeout = Some(timeout.into());
        self
    }

    /// Once it holds, it must keep holding for this long.
    pub fn during(mut self, window: impl Into<VirtualDuration>) -> Self {
        self.settings.during = Some(window.into());
        self
    }

    /// Shown above the failure.
    pub fn message(mut self, context: impl Into<String>) -> Self {
        self.settings.message = Some(context.into());
        self
    }

    /// The same matchers, recording a failure instead of returning it.
    pub fn soft(mut self) -> Soft<'h, P, R> {
        self.settings.soft = true;
        Soft(self)
    }

    /// Passes when a custom matcher holds for the node.
    #[track_caller]
    pub fn to_satisfy(self, matcher: impl NodeMatcher) -> Result {
        let name = matcher.name().into_owned();
        self.run(&name, &|tree, locator| {
            evaluate_matcher(tree, locator, &matcher)
        })
    }

    #[track_caller]
    fn assert(self, assertion: Assertion) -> Result {
        self.run(assertion.name(), &|tree, locator| {
            assertion.evaluate(tree, locator)
        })
    }

    #[track_caller]
    fn run(self, matcher: &str, evaluate: &Evaluate<'_>) -> Result {
        let location = Location::caller();
        let Self { handle, settings } = self;
        let Handle {
            harness,
            locator,
            window,
        } = handle;
        let locator = locator.any_role();
        let subject = icedwright_check::report::subject(&locator);
        let kind = StepKind::Expect {
            subject: SelectorText::of(&Canonical(locator.to_string())),
            assertion: matcher.to_owned(),
            negated: settings.negated,
        };
        let result = harness.step(
            || kind,
            |h| {
                let policy = settings.policy(h.default_timeout());
                let mut driver = Scoped::new(h, window);
                let passed = retry(
                    &mut driver,
                    matcher,
                    &|tree| evaluate(tree, &locator),
                    &policy,
                );
                let tree = driver.last_tree();
                let Err(error) = passed else {
                    return Ok(());
                };
                let context = report::Context {
                    subject,
                    location,
                    message: settings.message.as_deref(),
                    tree: tree.as_deref(),
                    window,
                    soft: settings.soft,
                };
                Err(report::fail(h, error, &context))
            },
        );
        settle_soft(harness, settings.soft, result)
    }
}

/// Generates each matcher on [`Expect`] and its soft copy on [`Soft`], so the two lists
/// cannot drift.
macro_rules! matchers {
    ($(
        $(#[doc = $doc:literal])+
        fn $name:ident($($arg:ident: $ty:ty),*) $(where R: $bound:path)? => $assertion:expr;
    )+) => {
        impl<P: TestProgram, R: RoleKind> Expect<'_, P, R> {
            $(
                $(#[doc = $doc])+
                #[track_caller]
                pub fn $name(self, $($arg: $ty),*) -> Result $(where R: $bound)? {
                    self.assert($assertion)
                }
            )+
        }

        impl<P: TestProgram, R: RoleKind> Soft<'_, P, R> {
            $(
                $(#[doc = $doc])+
                #[track_caller]
                pub fn $name(self, $($arg: $ty),*) -> Result $(where R: $bound)? {
                    self.0.assert($assertion)
                }
            )+
        }
    };
}

matchers! {
    /// The locator resolves to exactly one node.
    fn to_be_attached() => Assertion::Attached;
    /// The node is attached, not hidden, and has a visible part.
    fn to_be_visible() => Assertion::Visible;
    /// Nothing matches, or nothing that matches has a visible part.
    fn to_be_hidden() => Assertion::Hidden;
    /// A source reports the node enabled.
    fn to_be_enabled() => Assertion::Enabled;
    /// A source reports the node disabled.
    fn to_be_disabled() => Assertion::Disabled;
    /// The node has keyboard focus.
    fn to_be_focused() => Assertion::Focused;
    /// Some part of the node is inside the window and every enclosing viewport.
    fn to_be_in_viewport() => Assertion::InViewport(None);
    /// At least `ratio` of the node's area is in view.
    fn to_be_in_viewport_ratio(ratio: Ratio) => Assertion::InViewport(Some(ratio));
    /// The node's whole text matches.
    fn to_have_text(text: impl Into<TextMatch>) => Assertion::Text(text.into());
    /// The matched nodes have these texts, in order.
    fn to_have_texts(texts: impl IntoIterator<Item = impl Into<TextMatch>>) => Assertion::Texts(texts.into_iter().map(Into::into).collect());
    /// The node's text contains this.
    fn to_contain_text(text: impl Into<TextMatch>) => Assertion::ContainText(text.into());
    /// The locator matches this many nodes.
    fn to_have_count(count: usize) => Assertion::Count(count);
    /// The node has this role.
    fn to_have_role(role: Role) => Assertion::Role(role);
    /// The node's accessible name matches.
    fn to_have_accessible_name(name: impl Into<TextMatch>) => Assertion::AccessibleName(name.into());
    /// The node's description matches.
    fn to_have_accessible_description(text: impl Into<TextMatch>) => Assertion::AccessibleDescription(text.into());
    /// The node is checked.
    fn to_be_checked() where R: Checkable => Assertion::Checked(Checked::True);
    /// The node's checked state is this one.
    fn to_be_checked_with(state: Checked) where R: Checkable => Assertion::Checked(state);
    /// The toggle button is pressed.
    fn to_be_pressed() where R: Pressable => Assertion::Pressed;
    /// The node is expanded.
    fn to_be_expanded() where R: Expandable => Assertion::Expanded;
    /// The item is selected.
    fn to_be_selected() where R: SelectableItem => Assertion::Selected;
    /// The node's value matches, as text or as a number.
    fn to_have_value(value: impl Into<ValueMatch>) where R: HasValue => Assertion::Value(value.into());
    /// The node's nesting level is this.
    fn to_have_level(level: u16) where R: Leveled => Assertion::Level(level);
    /// The field is neither disabled nor read-only.
    fn to_be_editable() where R: Editable => Assertion::Editable;
}