icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! A two-window daemon: Preferences opens in its own window, handles scoped to it work,
//! closing it returns focus to the main window, and only an application exits when its last
//! window closes.

mod common;

use iced::widget::{button, column, text};
use iced::{Element, Subscription, Task, Theme, window};
use icedwright::prelude::*;
use icedwright::{HarnessError, WindowRequest};
use icedwright_probe::semantic;

#[derive(Debug, Clone, PartialEq)]
enum Message {
    Opened(window::Id),
    OpenPreferences,
    Done,
    Closed(window::Id),
    Drag,
}

#[derive(Debug, Default)]
struct App {
    main: Option<window::Id>,
    preferences: Option<window::Id>,
    closed: Vec<window::Id>,
}

impl App {
    fn boot() -> (Self, Task<Message>) {
        let (id, open) = window::open(window::Settings::default());
        let app = App {
            main: Some(id),
            ..App::default()
        };
        (app, open.map(Message::Opened))
    }

    fn update(&mut self, message: Message) -> Task<Message> {
        match message {
            Message::Opened(_) => Task::none(),
            Message::OpenPreferences => {
                let (id, open) = window::open(window::Settings {
                    size: iced::Size::new(400.0, 300.0),
                    ..window::Settings::default()
                });
                self.preferences = Some(id);
                open.map(Message::Opened)
            }
            Message::Done => match self.preferences {
                Some(id) => window::close(id),
                None => Task::none(),
            },
            Message::Closed(id) => {
                self.closed.push(id);
                if self.preferences == Some(id) {
                    self.preferences = None;
                }
                Task::none()
            }
            Message::Drag => match self.main {
                Some(id) => window::drag(id),
                None => Task::none(),
            },
        }
    }

    fn title(&self, id: window::Id) -> String {
        if Some(id) == self.preferences {
            "Preferences".to_owned()
        } else {
            "Main".to_owned()
        }
    }

    fn view(&self, id: window::Id) -> Element<'_, Message> {
        if Some(id) == self.preferences {
            return column![
                text("Theme"),
                semantic(button(text("Done")).on_press(Message::Done))
                    .role(role::Button)
                    .name("Done"),
            ]
            .into();
        }
        column![
            text("Notes"),
            semantic(button(text("Preferences")).on_press(Message::OpenPreferences))
                .role(role::Button)
                .name("Preferences"),
        ]
        .into()
    }

    fn single(&self) -> Element<'_, Message> {
        text("Single").into()
    }

    fn subscription(&self) -> Subscription<Message> {
        window::close_events().map(Message::Closed)
    }
}

fn harness() -> icedwright::Result<Harness<impl TestProgram<State = App, Message = Message>>> {
    let program = iced::daemon(App::boot, App::update, App::view)
        .title(App::title)
        .subscription(App::subscription)
        .theme(|_: &App, _| Theme::Light);
    Harness::new(program)
}

#[test]
fn the_daemon_opens_its_main_window_at_boot() -> icedwright::Result {
    let mut h = harness()?;
    let main = h.state().main.expect("boot opened a window");
    assert_eq!(h.windows(), vec![main]);
    assert_eq!(h.focused(), Some(main));
    assert_eq!(h.window_info(main)?.title, "Main");
    assert!(common::shows(&mut h, "Notes")?);
    Ok(())
}

#[test]
fn preferences_opens_in_its_own_window_and_closing_it_returns_focus() -> icedwright::Result {
    let mut h = harness()?;
    let main = h.state().main.expect("boot opened a window");
    common::click(h.get_by_role(role::Button).name("Preferences"))?;
    let preferences = h.wait_for_window(|info| info.title == "Preferences")?;
    assert_eq!(h.windows().len(), 2);
    assert_eq!(h.focused(), Some(preferences));
    let size = h.window_info(preferences)?.logical_size;
    assert_eq!(size, Logical(icedwright::units::Size::new(400.0, 300.0)));

    assert_eq!(h.window(preferences)?.get_by_text("Theme").count()?, 1);
    assert_eq!(h.window(main)?.get_by_text("Theme").count()?, 0);

    common::click(
        h.window(preferences)?
            .get_by_role(role::Button)
            .name("Done"),
    )?;
    assert_eq!(h.windows(), vec![main]);
    assert_eq!(h.focused(), Some(main));
    assert_eq!(h.state().preferences, None);
    assert_eq!(h.state().closed, vec![preferences]);
    Ok(())
}

#[test]
fn the_page_is_the_focused_windows_root() -> icedwright::Result {
    let mut h = harness()?;
    let main = h.state().main.expect("boot opened a window");
    expect(h.page().name("Main")).to_be_visible()?;
    common::click(h.page().get_by_role(role::Button).name("Preferences"))?;
    let preferences = h.wait_for_window(|info| info.title == "Preferences")?;
    assert_eq!(h.focused(), Some(preferences));
    expect(h.page().name("Preferences")).to_contain_text("Theme")?;
    h.page().to_match_semantic(r#"- button "Done""#)?;
    expect(h.page().get_by_role(role::Button).name("Preferences")).to_have_count(0)?;
    expect(
        h.window(main)?
            .page()
            .get_by_role(role::Button)
            .name("Preferences"),
    )
    .to_have_count(1)?;
    Ok(())
}

#[test]
fn closing_the_last_window_of_a_daemon_does_not_exit() -> icedwright::Result {
    let mut h = harness()?;
    h.main_window()?.request_close()?;
    assert!(h.windows().is_empty());
    assert!(!h.has_exited());
    h.dispatch(Message::Opened(window::Id::unique()))?;
    Ok(())
}

#[test]
fn closing_the_last_window_of_an_application_exits() -> icedwright::Result {
    let program = iced::application(App::default, App::update, App::single);
    let mut h = Harness::new(program)?;
    h.main_window()?.request_close()?;
    assert!(h.has_exited());
    let error = h.dispatch(Message::Done).unwrap_err();
    assert!(
        matches!(error, icedwright::Error::Harness(HarnessError::Exited)),
        "{error:?}"
    );
    Ok(())
}

#[test]
fn resize_mid_test_changes_the_layout_size() -> icedwright::Result {
    let mut h = harness()?;
    h.main_window()?.resize((640.0, 480.0))?;
    let main = h.state().main.expect("boot opened a window");
    let window = h.tree_of(main)?;
    let root = window.get(window.roots()[0]).expect("a window node");
    assert_eq!(root.bounds.width, 640.0);
    assert_eq!(root.bounds.height, 480.0);
    let frame = h.render(main)?;
    assert_eq!(frame.size().get().width, 640);
    Ok(())
}

#[test]
fn a_scale_factor_of_two_doubles_the_frame_and_keeps_logical_bounds() -> icedwright::Result {
    let mut h = harness()?;
    let main = h.state().main.expect("boot opened a window");
    let before = h.get_by_role(role::Button).name("Preferences").resolve()?;
    let before = before.node().expect("found").bounds;
    h.main_window()?.set_scale_factor(ScaleFactor::TWO)?;
    let frame = h.render(main)?;
    assert_eq!(frame.size().get().width, 2048);
    let after = h.get_by_role(role::Button).name("Preferences").resolve()?;
    assert_eq!(after.node().expect("found").bounds, before);
    Ok(())
}

#[test]
fn a_drag_request_is_recorded_for_its_window() -> icedwright::Result {
    let mut h = harness()?;
    h.dispatch(Message::Drag)?;
    assert_eq!(h.main_window()?.requests()?, &[WindowRequest::Drag]);
    Ok(())
}

#[test]
fn the_system_theme_follows_for_a_window_without_its_own() -> icedwright::Result {
    let program = iced::daemon(App::boot, App::update, App::view)
        .title(App::title)
        .subscription(App::subscription);
    let mut h = Harness::builder(program)
        .system_theme(iced::theme::Mode::Dark)
        .build()?;
    let main = h.state().main.expect("boot opened a window");
    assert_eq!(h.window_info(main)?.theme_mode, iced::theme::Mode::Dark);
    h.set_system_theme(iced::theme::Mode::Light)?;
    assert_eq!(h.window_info(main)?.theme_mode, iced::theme::Mode::Light);
    Ok(())
}