icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! Component tests: [`Mount`] puts one view function on screen with its props, typed on the
//! component's own message, inside an ordinary harness.

use std::cell::RefCell;
use std::fmt;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;

use iced_core::{Element, Settings, Theme, window};
use iced_runtime::Task;

use crate::config::HarnessConfig;
use crate::harness::Harness;

type View<Props, M> = dyn for<'a> Fn(&'a Props) -> Element<'a, M, Theme, iced_renderer::Renderer>;
type OnMessage<Props, M> = dyn Fn(&mut Props, &M);

struct Parts<Props, M> {
    make: Box<dyn Fn() -> Props>,
    view: Box<View<Props, M>>,
    on_message: RefCell<Option<Box<OnMessage<Props, M>>>>,
}

/// The program a [`Mount`] runs: its state is the props, `update` hands each message to the
/// `on_message` closure, and `view` is the mounted function.
pub struct MountProgram<Props, M> {
    parts: Rc<Parts<Props, M>>,
}

impl<Props, M> fmt::Debug for MountProgram<Props, M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MountProgram").finish_non_exhaustive()
    }
}

impl<Props: 'static, M: Clone + fmt::Debug + Send + 'static> iced_program::Program
    for MountProgram<Props, M>
{
    type State = Props;
    type Message = M;
    type Theme = Theme;
    type Renderer = iced_renderer::Renderer;
    type Executor = iced_futures::backend::null::Executor;

    fn name() -> &'static str {
        "icedwright_mount"
    }

    fn settings(&self) -> Settings {
        Settings::default()
    }

    fn window(&self) -> Option<window::Settings> {
        Some(window::Settings::default())
    }

    fn boot(&self) -> (Props, Task<M>) {
        ((self.parts.make)(), Task::none())
    }

    fn update(&self, state: &mut Props, message: M) -> Task<M> {
        if let Some(apply) = self.parts.on_message.borrow().as_ref() {
            apply(state, &message);
        }
        Task::none()
    }

    fn view<'a>(
        &self,
        state: &'a Props,
        _: window::Id,
    ) -> Element<'a, M, Theme, iced_renderer::Renderer> {
        (self.parts.view)(state)
    }

    fn title(&self, _: &Props, _: window::Id) -> String {
        "Mount".to_owned()
    }
}

/// One widget or view function mounted with props and no app around it. It derefs to its
/// [`Harness`], so locators, actions, `expect` and the typed message log work as in an app
/// test, and it has no method whose name a `Harness` method uses.
#[must_use]
pub struct Mount<Props: 'static, M: Clone + fmt::Debug + Send + 'static> {
    harness: Harness<MountProgram<Props, M>>,
    parts: Rc<Parts<Props, M>>,
}

impl<Props: 'static, M: Clone + fmt::Debug + Send + 'static> fmt::Debug for Mount<Props, M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Mount")
            .field("harness", &self.harness)
            .finish_non_exhaustive()
    }
}

impl<Props: 'static, M: Clone + fmt::Debug + Send + 'static> Mount<Props, M> {
    /// Mounts `view` over a copy of `props`; a reboot through
    /// [`with_config`](Self::with_config) starts from `props` again.
    pub fn new(
        props: Props,
        view: impl Fn(&Props) -> Element<'_, M, Theme, iced_renderer::Renderer> + 'static,
    ) -> crate::Result<Self>
    where
        Props: Clone,
    {
        Self::from_fn(move || props.clone(), view)
    }

    /// Mounts `view` over props built by `make`, for props that cannot be cloned.
    pub fn from_fn(
        make: impl Fn() -> Props + 'static,
        view: impl Fn(&Props) -> Element<'_, M, Theme, iced_renderer::Renderer> + 'static,
    ) -> crate::Result<Self> {
        let parts = Rc::new(Parts {
            make: Box::new(make),
            view: Box::new(view),
            on_message: RefCell::new(None),
        });
        Self::boot(parts, HarnessConfig::default())
    }

    fn boot(
        parts: Rc<Parts<Props, M>>,
        config: HarnessConfig<MountProgram<Props, M>>,
    ) -> crate::Result<Self> {
        let program = MountProgram {
            parts: parts.clone(),
        };
        let harness = Harness::with_config(program, config)?;
        Ok(Self { harness, parts })
    }

    /// Mounts again from fresh props with `config`, such as one from `Environment::apply`.
    pub fn with_config(self, config: HarnessConfig<MountProgram<Props, M>>) -> crate::Result<Self> {
        let Self { harness, parts } = self;
        drop(harness);
        Self::boot(parts, config)
    }

    /// What a message does to the props, as the parent would apply it. Without one, messages
    /// are only logged.
    pub fn on_message(self, apply: impl Fn(&mut Props, &M) + 'static) -> Self {
        self.parts.on_message.replace(Some(Box::new(apply)));
        self
    }

    /// Changes the props as a parent would between frames, then settles, so the next tree
    /// shows the change.
    pub fn set_props(&mut self, change: impl FnOnce(&mut Props)) -> crate::Result {
        change(&mut self.harness.state);
        self.harness.dirty = true;
        self.harness.settle()
    }

    /// The harness, for calls that consume it such as [`Harness::finish`].
    pub fn into_harness(self) -> Harness<MountProgram<Props, M>> {
        self.harness
    }
}

impl<Props: 'static, M: Clone + fmt::Debug + Send + 'static> Deref for Mount<Props, M> {
    type Target = Harness<MountProgram<Props, M>>;

    fn deref(&self) -> &Self::Target {
        &self.harness
    }
}

impl<Props: 'static, M: Clone + fmt::Debug + Send + 'static> DerefMut for Mount<Props, M> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.harness
    }
}