icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! [`Handle`]: a locator bound to a harness, which actions, `expect` and snapshots build on.

use std::fmt;
use std::sync::Arc;

use iced_core::window;
use icedwright_locator::{
    AnyRole, IntoLocator, IntoTestId, Locator, RoleKind, RoleType, Scope, TextMatch, role,
};
use icedwright_semantics::{Node, NodeId, SemanticTree};

use super::{Harness, TestProgram};
use crate::error::Result;

/// A [`Locator`] bound to `&mut Harness`, optionally scoped to one window. Scoping methods
/// come from [`Scope`] and take `self`; actions take `&mut self`, so one handle can act twice.
///
/// Its fields are crate-visible so the action, assertion and snapshot modules can reach the
/// harness and the locator without consuming the handle.
#[must_use]
pub struct Handle<'h, P: TestProgram, R: RoleKind = AnyRole> {
    /// The harness the locator is evaluated against.
    pub(crate) harness: &'h mut Harness<P>,
    /// The query.
    pub(crate) locator: Locator<R>,
    /// The window it is scoped to; `None` searches every window.
    pub(crate) window: Option<window::Id>,
}

/// A node a handle resolved to, in the tree it was found in.
#[derive(Debug, Clone)]
pub struct Resolved {
    /// The tree, as collected for the settled frame.
    pub tree: Arc<SemanticTree>,
    /// The node.
    pub id: NodeId,
}

impl Resolved {
    /// The node.
    #[must_use]
    pub fn node(&self) -> Option<&Node> {
        self.tree.get(self.id)
    }
}

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

impl<'h, P: TestProgram, R: RoleKind> Handle<'h, P, R> {
    pub(crate) fn new(
        harness: &'h mut Harness<P>,
        locator: Locator<R>,
        window: Option<window::Id>,
    ) -> Self {
        Self {
            harness,
            locator,
            window,
        }
    }

    /// The locator.
    pub fn locator(&self) -> &Locator<R> {
        &self.locator
    }

    /// The window it is scoped to.
    #[must_use]
    pub fn window(&self) -> Option<window::Id> {
        self.window
    }

    /// The harness, for steps that are not about this handle.
    pub fn harness(&mut self) -> &mut Harness<P> {
        self.harness
    }

    /// The tree the handle searches: its window's, or every window's.
    pub(crate) fn current_tree(&mut self) -> Result<Arc<SemanticTree>> {
        match self.window {
            Some(window) => self.harness.tree_of(window),
            None => self.harness.tree(),
        }
    }

    /// Settles and finds exactly one node, or fails with the locator's own error.
    pub fn resolve(&mut self) -> Result<Resolved> {
        self.harness.run_until_settled()?;
        let tree = self.current_tree()?;
        let id = icedwright_locator::resolve(&tree, &self.locator)?;
        Ok(Resolved { tree, id })
    }

    /// How many nodes match now, after settling.
    pub fn count(&mut self) -> Result<usize> {
        self.harness.run_until_settled()?;
        let tree = self.current_tree()?;
        Ok(self.locator.count(&tree))
    }
}

impl<'h, P: TestProgram, R: RoleKind> Scope for Handle<'h, P, R> {
    type Role = R;
    type With<R2: RoleKind> = Handle<'h, P, R2>;

    fn map_locator<R2: RoleKind>(
        self,
        f: impl FnOnce(Locator<R>) -> Locator<R2>,
    ) -> Handle<'h, P, R2> {
        Handle {
            harness: self.harness,
            locator: f(self.locator),
            window: self.window,
        }
    }

    fn as_locator(&self) -> &Locator<R> {
        &self.locator
    }
}

impl<P: TestProgram> Harness<P> {
    /// Binds a locator to this harness: `ui.locate(&save)`, `ui.locate("Delete")`.
    pub fn locate<R: RoleKind>(&mut self, locator: impl IntoLocator<R>) -> Handle<'_, P, R> {
        Handle::new(self, locator.into_locator(), None)
    }

    /// The focused window's root, so `expect(ui.page())` takes the whole window and
    /// `ui.page().get_by_role(..)` searches inside it. With no window focused it is every
    /// window's root, which resolves only while one window is open.
    pub fn page(&mut self) -> Handle<'_, P, role::Window> {
        let window = self.focused();
        Handle::new(self, icedwright_locator::page(), window)
    }

    /// Nodes of a role: `ui.get_by_role(role::Button).name("Save")`.
    pub fn get_by_role<R: RoleType>(&mut self, role: R) -> Handle<'_, P, R> {
        Handle::new(self, icedwright_locator::get_by_role(role), None)
    }

    /// Nodes whose text matches.
    pub fn get_by_text(&mut self, text: impl Into<TextMatch>) -> Handle<'_, P, AnyRole> {
        Handle::new(self, icedwright_locator::get_by_text(text), None)
    }

    /// Nodes labelled by matching text.
    pub fn get_by_label(&mut self, text: impl Into<TextMatch>) -> Handle<'_, P, AnyRole> {
        Handle::new(self, icedwright_locator::get_by_label(text), None)
    }

    /// Nodes whose placeholder matches.
    pub fn get_by_placeholder(&mut self, text: impl Into<TextMatch>) -> Handle<'_, P, AnyRole> {
        Handle::new(self, icedwright_locator::get_by_placeholder(text), None)
    }

    /// Nodes whose tooltip matches.
    pub fn get_by_tooltip(&mut self, text: impl Into<TextMatch>) -> Handle<'_, P, AnyRole> {
        Handle::new(self, icedwright_locator::get_by_tooltip(text), None)
    }

    /// The node with a test id, typed or a string.
    pub fn get_by_test_id<'a>(&mut self, id: impl IntoTestId<'a>) -> Handle<'_, P, AnyRole> {
        Handle::new(self, icedwright_locator::get_by_test_id(id), None)
    }

    /// The node with an iced `widget::Id`.
    pub fn get_by_widget_id(&mut self, id: impl Into<String>) -> Handle<'_, P, AnyRole> {
        Handle::new(self, icedwright_locator::get_by_widget_id(id), None)
    }
}