icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! A `StepObserver` installed before boot hears every step, event, message, task change,
//! settle, frame and diagnostic, in the order they happen.

use std::cell::RefCell;
use std::panic::Location;
use std::rc::Rc;

use iced::widget::{button, column, text};
use iced::{Element, Task, Theme, window};
use icedwright::prelude::*;
use icedwright::{Diagnostic, MessageRecord, StepObserver, StepRecord, TaskChange, TaskState};

#[derive(Debug, Clone)]
enum Message {
    Add,
    Added(u32),
}

#[derive(Debug, Default)]
struct Counter {
    value: u32,
}

impl Counter {
    fn update(&mut self, message: Message) -> Task<Message> {
        match message {
            Message::Add => Task::perform(std::future::ready(self.value + 1), Message::Added),
            Message::Added(value) => {
                self.value = value;
                Task::none()
            }
        }
    }

    fn view(&self) -> Element<'_, Message> {
        column![
            text(self.value.to_string()),
            button("Add").on_press(Message::Add)
        ]
        .into()
    }
}

/// Writes what it hears to a shared log.
#[derive(Debug, Clone, Default)]
struct Log(Rc<RefCell<Vec<String>>>);

impl Log {
    fn lines(&self) -> Vec<String> {
        self.0.borrow().clone()
    }

    fn push(&self, line: String) {
        self.0.borrow_mut().push(line);
    }
}

impl<P: TestProgram> StepObserver<P> for Log {
    fn step_started(
        &mut self,
        location: &'static Location<'static>,
        _: icedwright::time::VirtualInstant,
    ) {
        self.push(format!("start {}", location.line()));
    }

    fn event(&mut self, _: window::Id, event: &iced::Event, _: iced::event::Status) {
        if let iced::Event::Mouse(iced::mouse::Event::ButtonPressed(_)) = event {
            self.push("press".to_owned());
        }
    }

    fn message(&mut self, record: &MessageRecord<P::Message>) {
        self.push(format!("message {}", record.debug));
    }

    fn task(&mut self, change: &TaskChange) {
        if change.to == TaskState::Finished {
            self.push("task finished".to_owned());
        }
    }

    fn settled(&mut self, _: icedwright::time::VirtualInstant) {
        self.push("settled".to_owned());
    }

    fn frame(&mut self, _: window::Id, frame: &icedwright::Frame) {
        self.push(format!("frame {}", frame.size().get().width));
    }

    fn diagnostic(&mut self, diagnostic: &Diagnostic) {
        self.push(format!("diagnostic {:?}", diagnostic.severity));
    }

    fn step_ended(&mut self, step: &StepRecord<'_>) {
        self.push(format!(
            "end {} {}",
            step.location.line(),
            step.error.is_none()
        ));
    }
}

// milestone: Traces and studio
#[test]
fn an_observer_hears_a_click_from_press_to_settle() -> icedwright::Result {
    let log = Log::default();
    let program =
        iced::application(Counter::default, Counter::update, Counter::view).theme(Theme::Light);
    let mut h = Harness::builder(program)
        .size((200.0, 100.0))
        .observer(log.clone())
        .build()?;
    let booted = log.lines();
    assert!(booted.iter().any(|line| line == "settled"), "{booted:?}");

    log.0.borrow_mut().clear();
    let line = line!() + 1;
    h.get_by_text("Add").click()?;
    let lines = log.lines();
    let at = |wanted: &str| {
        lines
            .iter()
            .position(|line| line == wanted)
            .unwrap_or_else(|| panic!("no {wanted:?} in {lines:?}"))
    };
    let start = at(&format!("start {line}"));
    let press = at("press");
    let add = at("message Add");
    let finished = at("task finished");
    let added = at("message Added(1)");
    let end = at(&format!("end {line} true"));
    assert!(
        start < press && press < add && add < finished && finished < added && added < end,
        "{lines:?}"
    );
    assert!(
        lines[added..end].iter().any(|line| line == "settled"),
        "{lines:?}"
    );
    assert_eq!(
        lines.first(),
        Some(&format!("start {line}")),
        "only the outermost step is reported"
    );

    log.0.borrow_mut().clear();
    let window = h.focused().ok_or(icedwright::HarnessError::NoWindow)?;
    let _ = h.render(window)?;
    assert_eq!(log.lines(), vec!["frame 200".to_owned()]);
    Ok(())
}