icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! [`Error`], the one error every icedwright call returns, and the harness's own errors.

use std::fmt;

use iced_core::window;
use icedwright_types::VirtualDuration;

use crate::effects::{TaskState, UntypedTaskId};

/// What every harness call returns.
pub type Result<T = (), E = Error> = std::result::Result<T, E>;

/// Every way an icedwright call can fail. Its `Debug` output is the full report, because
/// libtest prints a returned error with `{:?}`.
#[derive(thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The harness itself.
    #[error(transparent)]
    Harness(#[from] HarnessError),
    /// A configuration or environment value.
    #[error(transparent)]
    Config(#[from] ConfigError),
    /// An assertion or actionability check.
    #[error(transparent)]
    Check(#[from] icedwright_check::CheckError),
    /// An action that was not sent, or did not take.
    #[error(transparent)]
    Action(#[from] crate::actions::ActionError),
    /// An expectation that failed, with its full report.
    #[error(transparent)]
    Expect(#[from] crate::expect::ExpectError),
    /// A locator used directly, such as a selector string that did not parse.
    #[error(transparent)]
    Locator(#[from] icedwright_locator::Error),
    /// The semantic tree's YAML or paths.
    #[error(transparent)]
    Semantics(#[from] icedwright_semantics::Error),
    /// Writing or reading a trace.
    #[error(transparent)]
    Trace(#[from] icedwright_trace::TraceError),
    /// The remote protocol.
    #[error(transparent)]
    Protocol(#[from] icedwright_protocol::ProtocolError),
    /// A frame whose bytes do not match its size.
    #[error(transparent)]
    Frame(#[from] icedwright_types::FrameError),
    /// A scale factor out of range.
    #[error(transparent)]
    ScaleFactor(#[from] icedwright_types::InvalidScaleFactor),
    /// A ratio out of range.
    #[error(transparent)]
    Ratio(#[from] icedwright_types::InvalidRatio),
    /// A key chord that did not parse.
    #[error(transparent)]
    Chord(#[from] icedwright_types::ChordError),
    /// A role name that did not parse.
    #[error(transparent)]
    Role(#[from] icedwright_types::ParseRoleError),
    /// A role that did not match the one asked for.
    #[error(transparent)]
    RoleMismatch(#[from] icedwright_types::RoleMismatch),
    /// A state name that did not parse.
    #[error(transparent)]
    State(#[from] icedwright_types::ParseStateError),
    /// The file system.
    #[error(transparent)]
    Io(#[from] std::io::Error),
    /// JSON.
    #[error(transparent)]
    Json(#[from] serde_json::Error),
    /// A semantic or visual snapshot, or the fonts they depend on.
    #[error(transparent)]
    Snapshot(#[from] crate::snapshot::SnapshotError),
    /// Anything else, from [`Error::other`].
    #[error("{0}")]
    Other(#[source] Box<dyn std::error::Error + Send + Sync>),
}

impl Error {
    /// Wraps any error, such as an app's own, keeping it as the source.
    pub fn other(error: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self::Other(Box::new(error))
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self}")?;
        let mut source = std::error::Error::source(self);
        if matches!(self, Error::Other(_)) {
            source = source.and_then(std::error::Error::source);
        }
        while let Some(cause) = source {
            write!(f, "\n  caused by: {cause}")?;
            source = cause.source();
        }
        Ok(())
    }
}

/// Why the harness could not take a step.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum HarnessError {
    /// A harness was built inside another tokio runtime.
    #[error(
        "icedwright runs its own runtime; use #[test] or #[icedwright::test], not #[tokio::test]"
    )]
    InsideRuntime,
    /// The app asked to exit, so no later step can run.
    #[error("the app has exited")]
    Exited,
    /// No window with this id is open.
    #[error("no window {0:?}")]
    NoSuchWindow(window::Id),
    /// A user cannot resize this window: its settings say it is not resizable.
    #[error("window {0:?} is not resizable; use force_size for a tiling window manager")]
    NotResizable(window::Id),
    /// The step needs a window and none is open.
    #[error("no window is open")]
    NoWindow,
    /// The headless renderer could not be created.
    #[error("the tiny-skia renderer could not be created for a window")]
    Renderer,
    /// The app kept doing work at one instant without settling.
    #[error("the app never settled after {turns} turns; busiest tasks: {busiest:?}")]
    #[non_exhaustive]
    NeverIdle {
        /// The turn bound that was reached.
        turns: u32,
        /// The tasks polled most, busiest first.
        busiest: Vec<UntypedTaskId>,
    },
    /// Nothing made progress for the whole hang window.
    #[error("the process hung: no progress for {since_progress:?} during {step}. {cause}")]
    #[non_exhaustive]
    Hung {
        /// The step that was running.
        step: String,
        /// How long nothing had progressed, in real time.
        since_progress: std::time::Duration,
        /// What the harness was waiting for.
        cause: HangCause,
    },
    /// A task panicked while the harness polled it.
    #[error("task {task} panicked: {message}")]
    #[non_exhaustive]
    TaskPanicked {
        /// The task.
        task: UntypedTaskId,
        /// The panic message.
        message: String,
    },
    /// iced was built with a time backend other than tokio.
    #[error(
        "iced's time backend is {executor}, not tokio; add `iced = {{ version = \"0.14\", features = [\"tokio\"] }}` to [dev-dependencies]"
    )]
    #[non_exhaustive]
    NonTokioTimeBackend {
        /// The backend's type name.
        executor: &'static str,
    },
    /// A component declared a timer on the real clock.
    #[error("{component} runs on real time, so its ticks would depend on the machine")]
    #[non_exhaustive]
    RealTimer {
        /// The component.
        component: &'static str,
    },
    /// A runtime action that has no headless meaning.
    #[error("{0} is not supported headlessly")]
    UnsupportedAction(&'static str),
    /// A named task started that a `deny_unrouted` rule covers, with no route or hold.
    #[error("task {task} ({name}) started at {location} with no route or hold")]
    #[non_exhaustive]
    Unrouted {
        /// The task.
        task: UntypedTaskId,
        /// Its name.
        name: &'static str,
        /// Where it was named.
        location: String,
    },
    /// The task cannot be acted on any more.
    #[error("task {task} is {state:?}")]
    #[non_exhaustive]
    TaskGone {
        /// The task.
        task: UntypedTaskId,
        /// Its state.
        state: TaskState,
    },
    /// No task of the name was held before the timeout.
    #[error("no held {name} task within {timeout}; tasks that did start: {started:?}")]
    #[non_exhaustive]
    NoTask {
        /// The name waited for.
        name: &'static str,
        /// The virtual timeout.
        timeout: VirtualDuration,
        /// The names of named tasks that did start, newest first.
        started: Vec<&'static str>,
    },
    /// A fake was called with nothing to answer.
    #[error("fake {fake} had no answer for {request}")]
    #[non_exhaustive]
    Unanswered {
        /// The fake's name.
        fake: &'static str,
        /// The request, printed.
        request: String,
    },
    /// No task with this id was started by this harness.
    #[error("no task {0}")]
    UnknownTask(UntypedTaskId),
    /// A route or resolution made for another name reached a task.
    #[error("task {task} was answered with a value made for {name}")]
    #[non_exhaustive]
    RejectedPayload {
        /// The task.
        task: UntypedTaskId,
        /// The name the value was made for.
        name: &'static str,
    },
    /// Held tasks were still pending when the test finished.
    #[error("held tasks were still pending at the end of the test: {0:?}")]
    HeldAtEnd(Vec<UntypedTaskId>),
}

/// What a hung step was waiting for.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum HangCause {
    /// A call into app code.
    AppCall {
        /// The call.
        what: &'static str,
    },
    /// Blocking work on the harness's one blocking thread.
    BlockingWork {
        /// The task waiting for it, when known.
        job: Option<UntypedTaskId>,
    },
    /// Declared external sources, during a wait with a fixed real-time ceiling.
    ExternalSources {
        /// The declared sources.
        sources: Vec<String>,
    },
    /// Studio's headed socket, which stayed open but stopped taking or acknowledging steps.
    HeadedStudio,
}

impl fmt::Display for HangCause {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HangCause::AppCall { what } => write!(f, "The app call {what} did not return."),
            HangCause::BlockingWork { .. } => f.write_str(
                "A spawn_blocking job never finished. The harness runs blocking work on one \
                 thread, so a long-lived worker holds it: run the worker on the app's own \
                 thread and declare it as an external source, or put it behind the app's own \
                 trait and fake it in tests.",
            ),
            HangCause::ExternalSources { sources } => write!(
                f,
                "The wait reached its fixed real-time ceiling while waiting on the declared \
                 external sources {sources:?}."
            ),
            HangCause::HeadedStudio => f.write_str(
                "Studio's headed socket stayed open but neither took the step nor acknowledged \
                 it. Whatever listens on the socket has stopped answering: restart \
                 `icedwright-studio headed`, or run without ICEDWRIGHT_HEADED.",
            ),
        }
    }
}

/// A configuration value that cannot be used.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ConfigError {
    /// An environment variable whose value does not parse.
    #[error("{var}={value:?} is not valid; expected {expected}")]
    #[non_exhaustive]
    Invalid {
        /// The variable.
        var: &'static str,
        /// What it held.
        value: String,
        /// The accepted forms.
        expected: &'static str,
    },
}

impl ConfigError {
    pub(crate) fn invalid(
        var: &'static str,
        value: impl Into<String>,
        expected: &'static str,
    ) -> Self {
        Self::Invalid {
            var,
            value: value.into(),
            expected,
        }
    }
}