icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! Unit tests for the actions' own decisions: option defaults, option matching, ranges and
//! slider points, byte ranges, the pointer hold, click separation through the harness, and
//! the error text.

use std::num::NonZeroU16;
use std::ops::Bound;

use iced::widget::{button, column, text, text_input};
use iced::{Element, Theme};
use icedwright_check::ClickCount;
use icedwright_locator::Scope as _;
use icedwright_probe::semantic;
use icedwright_semantics::{NodePath, TreeBuilder};
use icedwright_types::{Logical, Point, Rect, Size, role};

use super::devices::Devices;
use super::error::{ActionError, ActionFailure};
use super::options::{Click, Drag, Hover, OptionMatch, Type};
use super::pointer::{Range, char_span, slider_points};
use crate::harness::Harness;
use crate::{Error, TestProgram};

#[test]
fn option_defaults_are_the_documented_ones() {
    let click = Click::default();
    assert_eq!(click.button, iced::mouse::Button::Left);
    assert_eq!(click.count, ClickCount::Single);
    assert_eq!(click.steps, NonZeroU16::MIN);
    assert!(click.position.is_none() && !click.force && !click.trial && !click.no_wait_after);
    assert_eq!(click.timeout, None);
    assert_eq!(Drag::default().steps.get(), 5);
    assert_eq!(Hover::default().steps, NonZeroU16::MIN);
    assert_eq!(
        Type::default().delay,
        icedwright_types::VirtualDuration::ZERO
    );
}

#[test]
fn builders_set_what_they_name() {
    let click = Click::new()
        .button(iced::mouse::Button::Right)
        .count(ClickCount::Double)
        .position(Logical(Point::new(3.0, 4.0)))
        .force()
        .trial()
        .no_wait_after()
        .timeout(std::time::Duration::from_millis(20))
        .steps(NonZeroU16::new(4).unwrap());
    assert_eq!(click.button, iced::mouse::Button::Right);
    assert_eq!(click.count, ClickCount::Double);
    assert_eq!(click.position, Some(Logical(Point::new(3.0, 4.0))));
    assert!(click.force && click.trial && click.no_wait_after);
    assert_eq!(
        click.timeout,
        Some(icedwright_types::VirtualDuration::from_millis(20))
    );
    assert_eq!(click.steps.get(), 4);
    let drag = Drag::new()
        .source_position(Logical(Point::new(1.0, 1.0)))
        .target_position(Logical(Point::new(2.0, 2.0)));
    assert_eq!(drag.source, Some(Logical(Point::new(1.0, 1.0))));
    assert_eq!(drag.target, Some(Logical(Point::new(2.0, 2.0))));
}

#[test]
fn an_option_is_picked_by_name_text_index_or_value() {
    let by_name = OptionMatch::from("Banana");
    assert!(by_name.picks(1, Some("Banana"), "Banana", None));
    assert!(by_name.picks(1, None, "Banana", None));
    assert!(!by_name.picks(1, Some("Apple"), "Apple", None));
    assert!(OptionMatch::index(2).picks(2, None, "", None));
    assert!(!OptionMatch::index(2).picks(1, None, "", None));
    assert!(OptionMatch::value("b").picks(0, Some("Banana"), "Banana", Some("b")));
    assert!(!OptionMatch::value("b").picks(0, Some("Banana"), "Banana", None));
}

#[test]
fn a_range_admits_values_inside_it_and_on_its_step() {
    let range = Range {
        now: 0.0,
        min: 0.0,
        max: 10.0,
        step: Some(0.5),
    };
    assert!(range.admits(0.0) && range.admits(10.0) && range.admits(2.5));
    assert!(!range.admits(2.6), "off the step");
    assert!(!range.admits(10.5) && !range.admits(-1.0) && !range.admits(f64::NAN));
    let free = Range {
        step: None,
        ..range
    };
    assert!(free.admits(2.6));
}

#[test]
fn slider_points_map_values_along_the_track() {
    let bounds = Rect::new(Point::new(100.0, 50.0), Size::new(200.0, 20.0));
    let range = Range {
        now: 25.0,
        min: 0.0,
        max: 100.0,
        step: None,
    };
    let (press, target) = slider_points(bounds, &range, 75.0);
    assert_eq!(press, Logical(Point::new(50.0, 10.0)));
    assert_eq!(target, Logical(Point::new(250.0, 60.0)));
    let at_min = Range { now: 0.0, ..range };
    let (press, _) = slider_points(bounds, &at_min, 0.0);
    assert_eq!(press.0.x, 0.5, "the press stays inside the track");
    let tall = Rect::new(Point::ORIGIN, Size::new(20.0, 200.0));
    let (press, target) = slider_points(tall, &range, 100.0);
    assert_eq!(press, Logical(Point::new(10.0, 150.0)));
    assert_eq!(
        target,
        Logical(Point::new(10.0, 0.0)),
        "a vertical slider runs upwards"
    );
}

#[test]
fn a_byte_range_becomes_character_counts() {
    let text = "héllo wörld";
    assert_eq!(
        char_span(text, Bound::Unbounded, Bound::Unbounded),
        Some((0, 11))
    );
    let start = text.find('w').unwrap();
    assert_eq!(
        char_span(text, Bound::Included(&start), Bound::Unbounded),
        Some((6, 5))
    );
    assert_eq!(
        char_span(text, Bound::Included(&2), Bound::Excluded(&4)),
        None,
        "inside é"
    );
    assert_eq!(
        char_span(text, Bound::Included(&0), Bound::Excluded(&99)),
        None
    );
}

#[test]
fn the_pointer_hold_nests() {
    let mut devices = Devices::default();
    assert!(!devices.pointer_held());
    devices.hold();
    devices.hold();
    devices.release();
    assert!(devices.pointer_held());
    devices.release();
    devices.release();
    assert!(!devices.pointer_held());
}

#[test]
fn ime_not_enabled_names_the_window_and_what_to_do() {
    let error = ActionError::new(
        "ime().commit",
        "the focused window",
        ActionFailure::ImeNotEnabled {
            window: "Notes".to_owned(),
        },
    );
    let text = error.to_string();
    assert!(
        text.starts_with("ime().commit on the focused window was not sent\n\n  "),
        "{text}"
    );
    for part in ["\"Notes\"", "winit", "focus()", "fill()"] {
        assert!(text.contains(part), "{text}");
    }
    assert!(!error.is_refusal());
}

#[test]
fn an_action_error_names_the_action_and_the_target() {
    let error = ActionError::new(
        "focus",
        "get_by_role(role::Button)",
        ActionFailure::NotFocusable {
            node: NodePath::default(),
        },
    );
    let text = error.to_string();
    assert!(
        text.starts_with("focus on get_by_role(role::Button) was not sent\n\n  "),
        "{text}"
    );
    assert!(!error.is_refusal());
    let tree = TreeBuilder::window("App")
        .child(role::TextBox, "Title", |b| b.bounds(0.0, 0.0, 100.0, 20.0))
        .build();
    let node = tree
        .iter()
        .find(|n| n.role == role::TextBox.into())
        .unwrap()
        .path
        .clone();
    let refused = icedwright_check::clicks::multi_click_allowed(&tree, &node).unwrap_err();
    let error = ActionError::new("dblclick", "x", ActionFailure::Refused(refused));
    assert!(error.is_refusal());
    assert!(
        error
            .to_string()
            .starts_with("dblclick on x is not supported yet")
    );
}

#[derive(Debug, Clone)]
enum Message {
    Pressed,
    Typed(String),
}

#[derive(Debug, Default)]
struct App {
    presses: u32,
    typed: String,
}

impl App {
    fn update(&mut self, message: Message) {
        match message {
            Message::Pressed => self.presses += 1,
            Message::Typed(typed) => self.typed = typed,
        }
    }

    fn view(&self) -> Element<'_, Message> {
        column![
            semantic(
                button(text("Go"))
                    .on_press(Message::Pressed)
                    .width(60)
                    .height(30)
            )
            .role(role::Button)
            .name("Go"),
            text_input("Field", &self.typed).on_input(Message::Typed),
        ]
        .into()
    }
}

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

#[test]
fn every_press_is_recorded_and_kept_six_pixels_apart() -> crate::Result {
    let mut ui = harness()?;
    for _ in 0..3 {
        let _ = ui.get_by_role(role::Button).name("Go").click()?;
    }
    assert_eq!(ui.state().presses, 3);
    let presses = ui.devices.history.presses();
    assert_eq!(presses.len(), 3);
    for (i, a) in presses.iter().enumerate() {
        for b in presses.iter().skip(i + 1) {
            assert!(a.point.distance(b.point) >= 6.0);
        }
    }
    Ok(())
}

#[test]
fn a_refused_press_is_not_recorded_and_moves_no_time() -> crate::Result {
    let mut ui = harness()?;
    let _ = ui.get_by_role(role::TextBox).click()?;
    let before = ui.now();
    let refused = ui.get_by_role(role::TextBox).click();
    assert!(
        matches!(refused, Err(Error::Action(ref e)) if e.is_refusal()),
        "{refused:?}"
    );
    assert_eq!(ui.now(), before);
    assert_eq!(ui.devices.history.presses().len(), 1);
    Ok(())
}

/// An annotated button under a full-window `opaque` layer, annotated as a scrim or not.
fn under_opaque(
    scrim: bool,
) -> crate::Result<Harness<impl TestProgram<State = bool, Message = Message>>> {
    fn update(_: &mut bool, _: Message) {}
    fn view(scrim: &bool) -> Element<'_, Message> {
        let layer = iced::widget::container(iced::widget::space())
            .width(iced::Fill)
            .height(iced::Fill);
        let layer: Element<'_, Message> = if *scrim {
            semantic(layer).role(role::Scrim).into()
        } else {
            layer.into()
        };
        iced::widget::stack![
            semantic(button(text("Behind")).on_press(Message::Pressed))
                .role(role::Button)
                .name("Behind"),
            iced::widget::opaque(layer),
        ]
        .into()
    }
    Harness::new(iced::application(move || scrim, update, view).theme(Theme::Light))
}

fn blocker_text(result: crate::Result<super::Done>) -> String {
    match result {
        Err(Error::Action(ActionError {
            reason: ActionFailure::Timeout { last, .. },
            ..
        })) => last.to_string(),
        other => format!("{other:?}"),
    }
}

#[test]
fn a_cover_nothing_in_the_tree_explains_is_named_by_the_pointer_probe() -> crate::Result {
    let quick = Click::new().timeout(crate::time::VirtualDuration::from_millis(50));
    let mut ui = under_opaque(false)?;
    let text = blocker_text(
        ui.get_by_role(role::Button)
            .name("Behind")
            .click_with(quick.clone()),
    );
    assert!(text.contains("reports Idle"), "{text}");
    assert!(text.contains("role::Scrim"), "{text}");

    let mut ui = under_opaque(true)?;
    let text = blocker_text(
        ui.get_by_role(role::Button)
            .name("Behind")
            .include_hidden(true)
            .click_with(quick),
    );
    assert!(
        text.contains("is covered by") && text.contains("scrim"),
        "{text}"
    );
    Ok(())
}

#[test]
fn fill_never_presses() -> crate::Result {
    let mut ui = harness()?;
    let _ = ui.get_by_role(role::TextBox).fill("one")?;
    let _ = ui.get_by_role(role::TextBox).fill("two")?;
    assert_eq!(ui.state().typed, "two");
    assert!(ui.devices.history.presses().is_empty());
    assert!(
        !ui.devices.pointer_held(),
        "the hold is released after the action"
    );
    Ok(())
}