icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! A save debounced by 500 ms with `tokio::time::sleep`: it fires at exactly 500 ms of
//! virtual time, never at 499, and the same way in every fresh harness, whether or not a
//! declared external source is live.

use std::time::Duration;

use iced::widget::text;
use iced::{Element, Subscription, Task, Theme};
use icedwright::prelude::*;

#[derive(Debug, Clone, PartialEq)]
enum Message {
    Edited(String),
    Elapsed(u64),
    Tick,
}

#[derive(Debug, Default)]
struct Editor {
    text: String,
    edits: u64,
    saved: Option<String>,
    ticks: u32,
}

#[expect(
    clippy::disallowed_methods,
    reason = "the debounce runs on the harness's paused clock"
)]
fn debounce(edit: u64) -> Task<Message> {
    Task::perform(tokio::time::sleep(Duration::from_millis(500)), move |()| {
        Message::Elapsed(edit)
    })
}

impl Editor {
    fn update(&mut self, message: Message) -> Task<Message> {
        match message {
            Message::Edited(text) => {
                self.text = text;
                self.edits += 1;
                debounce(self.edits)
            }
            Message::Elapsed(edit) if edit == self.edits => {
                self.saved = Some(self.text.clone());
                Task::none()
            }
            Message::Elapsed(_) => Task::none(),
            Message::Tick => {
                self.ticks += 1;
                Task::none()
            }
        }
    }

    fn clock(&self) -> Subscription<Message> {
        iced::time::every(Duration::from_secs(1)).map(|_| Message::Tick)
    }

    fn view(&self) -> Element<'_, Message> {
        text(match &self.saved {
            Some(saved) => format!("Saved {saved}"),
            None => "Unsaved".to_owned(),
        })
        .into()
    }
}

fn harness() -> icedwright::Result<Harness<impl TestProgram<State = Editor, Message = Message>>> {
    Harness::new(
        iced::application(Editor::default, Editor::update, Editor::view).theme(Theme::Light),
    )
}

/// The editor with a one-second clock subscription, with subscriptions declared as an
/// external source, so a declared source is live for the whole test.
fn with_live_source()
-> icedwright::Result<Harness<impl TestProgram<State = Editor, Message = Message>>> {
    Harness::builder(
        iced::application(Editor::default, Editor::update, Editor::view)
            .subscription(Editor::clock)
            .theme(Theme::Light),
    )
    .external_source(ExternalSource::Subscriptions)
    .build()
}

#[test]
fn the_debounce_fires_at_500_ms_while_a_declared_source_is_live() -> icedwright::Result {
    let mut h = with_live_source()?;
    h.dispatch(Message::Edited("Dig".to_owned()))?;
    expect(h.get_by_text("Saved Dig")).to_be_visible()?;
    assert_eq!(format!("{:?}", h.now()), "@+0.500s");
    let elapsed = h
        .messages()
        .iter()
        .find(|record| record.message == Message::Elapsed(1));
    assert_eq!(
        elapsed.map(|record| format!("{:?}", record.at)).as_deref(),
        Some("@+0.500s")
    );
    Ok(())
}

#[test]
fn a_clock_subscription_ticks_while_subscriptions_are_a_declared_source() -> icedwright::Result {
    let mut h = with_live_source()?;
    h.expect_state(|editor| editor.ticks).to_equal(3)?;
    assert_eq!(format!("{:?}", h.now()), "@+3.000s");
    Ok(())
}

fn ms(ms: u64) -> VirtualDuration {
    VirtualDuration::from_millis(ms)
}

#[test]
fn the_save_fires_at_500_ms_and_not_at_499() -> icedwright::Result {
    let mut h = harness()?;
    h.dispatch(Message::Edited("Dig".to_owned()))?;
    h.advance(ms(499))?;
    assert_eq!(h.state().saved, None);
    h.advance(ms(1))?;
    assert_eq!(h.state().saved.as_deref(), Some("Dig"));
    let elapsed = h.messages().last().expect("the debounce fired");
    assert_eq!(elapsed.message, Message::Elapsed(1));
    assert_eq!(format!("{:?}", elapsed.at), "@+0.500s");
    assert_eq!(h.get_by_text("Saved Dig").count()?, 1);
    Ok(())
}

#[test]
fn typing_again_restarts_the_debounce() -> icedwright::Result {
    let mut h = harness()?;
    h.dispatch(Message::Edited("Dig".to_owned()))?;
    h.advance(ms(300))?;
    h.dispatch(Message::Edited("Dig the".to_owned()))?;
    h.advance(ms(300))?;
    assert_eq!(h.state().saved, None);
    h.advance(ms(200))?;
    assert_eq!(h.state().saved.as_deref(), Some("Dig the"));
    assert_eq!(format!("{:?}", h.now()), "@+0.800s");
    Ok(())
}

#[test]
fn twenty_fresh_harnesses_give_the_same_log() -> icedwright::Result {
    let mut logs = Vec::new();
    for _ in 0..20 {
        let mut h = harness()?;
        h.dispatch(Message::Edited("a".to_owned()))?;
        h.advance(ms(250))?;
        h.dispatch(Message::Edited("ab".to_owned()))?;
        h.advance(ms(1000))?;
        let log: Vec<String> = h
            .messages()
            .iter()
            .map(|r| format!("{:?} {}", r.at, r.debug))
            .collect();
        logs.push(log);
    }
    assert!(logs.windows(2).all(|pair| pair[0] == pair[1]), "{logs:?}");
    assert_eq!(
        logs[0],
        vec![
            "@+0.000s Edited(\"a\")",
            "@+0.250s Edited(\"ab\")",
            "@+0.500s Elapsed(1)",
            "@+0.750s Elapsed(2)",
        ]
    );
    Ok(())
}

#[test]
fn an_idle_app_reaches_the_deadline_in_one_jump() -> icedwright::Result {
    let mut h = harness()?;
    let deadline = h.now() + VirtualDuration::from_secs(5);
    let waited = h.advance_until(deadline, |h| h.state().saved.is_some())?;
    assert_eq!(waited.at, deadline);
    assert_eq!(format!("{:?}", waited.idle_since), "Some(@+0.000s)");
    Ok(())
}

#[test]
fn a_wait_ends_when_its_condition_holds() -> icedwright::Result {
    let mut h = harness()?;
    h.dispatch(Message::Edited("Dig".to_owned()))?;
    let deadline = h.now() + VirtualDuration::from_secs(5);
    let waited = h.advance_until(deadline, |h| h.state().saved.is_some())?;
    assert_eq!(format!("{:?}", waited.at), "@+0.500s");
    assert_eq!(waited.idle_since, None);
    Ok(())
}