icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! [`StepObserver`]: callbacks for everything the harness does, installed through
//! [`HarnessConfig::observer`](crate::HarnessConfig::observer) before boot.

use std::collections::BTreeMap;
use std::panic::Location;

use iced_core::{Event, event, window};
use icedwright_trace::StepKind;
use icedwright_types::{Frame, VirtualInstant};

use crate::effects::{TaskInfo, TaskState, UntypedTaskId};
use crate::harness::{Diagnostic, Harness, TestProgram};
use crate::messages::MessageRecord;

/// One public step the test took, once it has ended.
#[derive(Debug)]
#[non_exhaustive]
pub struct StepRecord<'a> {
    /// What the test asked for.
    pub kind: &'a StepKind,
    /// The line of the test that made the call.
    pub location: &'static Location<'static>,
    /// When the step began.
    pub started: VirtualInstant,
    /// When it ended.
    pub ended: VirtualInstant,
    /// Its error, if it failed.
    pub error: Option<&'a crate::Error>,
}

/// A task moved from one state to another, or appeared.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TaskChange {
    /// The task.
    pub task: UntypedTaskId,
    /// Its name, for a named task.
    pub name: Option<&'static str>,
    /// Its state before, or `None` for a task seen for the first time.
    pub from: Option<TaskState>,
    /// Its state now.
    pub to: TaskState,
    /// When the harness saw the change.
    pub at: VirtualInstant,
}

/// Called as the harness runs. Every method has an empty default, so an observer implements
/// only what it reads. Callbacks run on the test thread, in the order things happen.
pub trait StepObserver<P: TestProgram> {
    /// A public step began, at the test's source line.
    fn step_started(&mut self, location: &'static Location<'static>, at: VirtualInstant) {
        let _ = (location, at);
    }

    /// An input event reached a window's widgets, with the status they returned.
    fn event(&mut self, window: window::Id, event: &Event, status: event::Status) {
        let _ = (window, event, status);
    }

    /// `update` is about to receive a message.
    fn message(&mut self, record: &MessageRecord<P::Message>) {
        let _ = record;
    }

    /// A task started, was held, released, resolved, finished, failed or aborted.
    fn task(&mut self, change: &TaskChange) {
        let _ = change;
    }

    /// The app settled: nothing was runnable at this instant.
    fn settled(&mut self, at: VirtualInstant) {
        let _ = at;
    }

    /// A window was drawn, for a render, a snapshot or a trace.
    fn frame(&mut self, window: window::Id, frame: &Frame) {
        let _ = (window, frame);
    }

    /// The harness noted something that did not fail the step.
    fn diagnostic(&mut self, diagnostic: &Diagnostic) {
        let _ = diagnostic;
    }

    /// A public step ended.
    fn step_ended(&mut self, step: &StepRecord<'_>) {
        let _ = step;
    }
}

/// The installed observers and what they have been told about tasks.
pub(crate) struct Observers<P: TestProgram> {
    list: Vec<Box<dyn StepObserver<P>>>,
    tasks: BTreeMap<UntypedTaskId, TaskState>,
}

impl<P: TestProgram> Default for Observers<P> {
    fn default() -> Self {
        Self {
            list: Vec::new(),
            tasks: BTreeMap::new(),
        }
    }
}

impl<P: TestProgram> std::fmt::Debug for Observers<P> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Observers")
            .field("count", &self.list.len())
            .finish_non_exhaustive()
    }
}

impl<P: TestProgram> Observers<P> {
    pub(crate) fn new(list: Vec<Box<dyn StepObserver<P>>>) -> Self {
        Self {
            list,
            tasks: BTreeMap::new(),
        }
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.list.is_empty()
    }

    pub(crate) fn each(&mut self, mut call: impl FnMut(&mut dyn StepObserver<P>)) {
        for observer in &mut self.list {
            call(observer.as_mut());
        }
    }

    /// The changes between what the observers were last told and `infos`, which it then
    /// remembers.
    pub(crate) fn task_changes(
        &mut self,
        infos: &[TaskInfo],
        at: VirtualInstant,
    ) -> Vec<TaskChange> {
        task_changes(&mut self.tasks, infos, at)
    }
}

/// Every task in `infos` whose state differs from `known`, in task order; `known` is updated.
pub(crate) fn task_changes(
    known: &mut BTreeMap<UntypedTaskId, TaskState>,
    infos: &[TaskInfo],
    at: VirtualInstant,
) -> Vec<TaskChange> {
    infos
        .iter()
        .filter_map(|info| {
            let to = info.state();
            let from = known.insert(info.id(), to);
            (from != Some(to)).then(|| TaskChange {
                task: info.id(),
                name: info.name(),
                from,
                to,
                at,
            })
        })
        .collect()
}

impl<P: TestProgram> Harness<P> {
    /// Calls every observer, if any are installed.
    pub(crate) fn observe(&mut self, call: impl FnMut(&mut dyn StepObserver<P>)) {
        if self.observers.is_empty() {
            return;
        }
        self.observers.each(call);
    }

    /// Tells the observers about task changes since they were last told.
    pub(crate) fn observe_tasks(&mut self) {
        if self.observers.is_empty() {
            return;
        }
        let infos = self.task_infos();
        let at = self.now();
        let changes = self.observers.task_changes(&infos, at);
        for change in &changes {
            self.observers.each(|observer| observer.task(change));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::effects::Spawn;
    use crate::runtime::TaskRecord;
    use icedwright_types::VirtualDuration;

    fn info(id: u64, state: TaskState) -> TaskInfo {
        let mut record = TaskRecord::new(
            Spawn::Boot,
            VirtualInstant::__from_offset(VirtualDuration::ZERO),
        );
        record.state = state;
        TaskInfo::from_record(UntypedTaskId::new(id), &record)
    }

    #[test]
    fn a_task_is_reported_when_first_seen_and_on_each_change_only() {
        let at = VirtualInstant::__from_offset(VirtualDuration::from_millis(5));
        let mut known = BTreeMap::new();
        let first = task_changes(
            &mut known,
            &[info(1, TaskState::Pending), info(2, TaskState::Held)],
            at,
        );
        let seen: Vec<_> = first.iter().map(|c| (c.task.get(), c.from, c.to)).collect();
        assert_eq!(
            seen,
            vec![(1, None, TaskState::Pending), (2, None, TaskState::Held)]
        );
        assert!(
            task_changes(
                &mut known,
                &[info(1, TaskState::Pending), info(2, TaskState::Held)],
                at
            )
            .is_empty()
        );
        let later = task_changes(
            &mut known,
            &[info(1, TaskState::Finished), info(2, TaskState::Held)],
            at,
        );
        assert_eq!(
            later,
            vec![TaskChange {
                task: UntypedTaskId::new(1),
                name: None,
                from: Some(TaskState::Pending),
                to: TaskState::Finished,
                at,
            }]
        );
    }
}