icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! [`Fixture`]: a value a test, its `app` function or another fixture asks for by type, built
//! before the program, started once the harness runs and torn down after the body.

use std::fmt;
use std::future::Future;

use crate::harness::{Harness, TestProgram};

use super::environment::Environment;
use super::support::Context;

/// Something a test asks for by type. The macro checks every parameter against this trait
/// when it expands, so a type that is not a fixture fails the build at that parameter.
#[diagnostic::on_unimplemented(
    message = "`{Self}` is not an icedwright fixture",
    label = "this parameter must implement `icedwright::Fixture`",
    note = "built-in fixtures: `&mut Harness<impl TestProgram>`, `TempDir`, `Environment`, \
            `Locale`, `Seed`, `fake::Calls<Req, Resp>`"
)]
pub trait Fixture: Sized + 'static {
    /// Other fixtures this one is built from, as a tuple: `()`, `(TempDir,)`,
    /// `(TempDir, FakeApi)`.
    type Deps: FixtureSet;

    /// Runs before the program is built, so the program can be given the fixture.
    fn setup(
        deps: <Self::Deps as FixtureSet>::Refs<'_>,
        env: &Environment,
    ) -> Result<Self, FixtureError>;

    /// Runs once the harness exists, with its runtime, for fixtures that start async work.
    fn started(&mut self, runtime: &mut RuntimeRef<'_>) -> Result<(), FixtureError> {
        let _ = runtime;
        Ok(())
    }

    /// Runs after the test body, in reverse order of setup, before the harness finishes.
    fn teardown(
        self,
        outcome: &TestOutcome,
        runtime: &mut RuntimeRef<'_>,
    ) -> Result<(), FixtureError> {
        let _ = (outcome, runtime);
        Ok(())
    }
}

mod sealed {
    pub trait Sealed {}
}

/// A tuple of up to eight fixtures, a fixture's [`Fixture::Deps`]. Sealed.
pub trait FixtureSet: sealed::Sealed + 'static {
    /// The fixtures as references, the shape [`Fixture::setup`] receives.
    type Refs<'a>;

    #[doc(hidden)]
    fn prepare(context: &mut Context) -> Result<(), FixtureError>;

    #[doc(hidden)]
    fn refs(context: &Context) -> Result<Self::Refs<'_>, FixtureError>;
}

impl sealed::Sealed for () {}

impl FixtureSet for () {
    type Refs<'a> = ();

    fn prepare(_: &mut Context) -> Result<(), FixtureError> {
        Ok(())
    }

    fn refs(_: &Context) -> Result<(), FixtureError> {
        Ok(())
    }
}

macro_rules! fixture_sets {
    ($($name:ident),+) => {
        impl<$($name: Fixture),+> sealed::Sealed for ($($name,)+) {}

        impl<$($name: Fixture),+> FixtureSet for ($($name,)+) {
            type Refs<'a> = ($(&'a $name,)+);

            fn prepare(context: &mut Context) -> Result<(), FixtureError> {
                $(context.prepare::<$name>()?;)+
                Ok(())
            }

            fn refs(context: &Context) -> Result<Self::Refs<'_>, FixtureError> {
                Ok(($(context.get::<$name>()?,)+))
            }
        }
    };
}

fixture_sets!(A);
fixture_sets!(A, B);
fixture_sets!(A, B, C);
fixture_sets!(A, B, C, D);
fixture_sets!(A, B, C, D, E);
fixture_sets!(A, B, C, D, E, F);
fixture_sets!(A, B, C, D, E, F, G);
fixture_sets!(A, B, C, D, E, F, G, H);

/// How the test body ended, which teardown sees.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TestOutcome {
    /// The body returned `Ok`.
    Passed,
    /// The body returned an error or panicked, with its report.
    Failed(String),
}

impl TestOutcome {
    /// Whether the body passed.
    #[must_use]
    pub fn passed(&self) -> bool {
        matches!(self, TestOutcome::Passed)
    }
}

/// Which part of a fixture's life failed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stage {
    /// [`Fixture::setup`].
    Setup,
    /// [`Fixture::started`].
    Started,
    /// [`Fixture::teardown`].
    Teardown,
}

impl fmt::Display for Stage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Stage::Setup => "setup",
            Stage::Started => "started",
            Stage::Teardown => "teardown",
        })
    }
}

/// Why a fixture could not be built, started or torn down.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum FixtureError {
    /// Two fixtures name each other in their `Deps`, directly or through others.
    #[error("fixtures {a} and {b} depend on each other through their Deps")]
    #[non_exhaustive]
    Cycle {
        /// The fixture asked for again while it was being built.
        a: &'static str,
        /// The fixture that asked for it.
        b: &'static str,
    },
    /// A fixture's own code failed.
    #[error("fixture {fixture} failed in {stage}: {source}")]
    #[non_exhaustive]
    Failed {
        /// The fixture's type.
        fixture: &'static str,
        /// Where it failed.
        stage: Stage,
        /// Its error.
        source: Box<FixtureError>,
    },
    /// A fixture was read before it was built, which the generated code never does.
    #[error("fixture {0} was read before it was built")]
    NotBuilt(&'static str),
    /// `ICEDWRIGHT_SEED` does not hold a seed.
    #[error(
        "ICEDWRIGHT_SEED={value:?} is not valid; expected a hex seed such as 0x9f3a51c2e07b4d18, or random"
    )]
    #[non_exhaustive]
    BadSeed {
        /// What it held.
        value: String,
    },
    /// The file system.
    #[error(transparent)]
    Io(#[from] std::io::Error),
    /// A harness call made by a fixture, such as [`RuntimeRef::block_on`].
    #[error(transparent)]
    Harness(Box<crate::Error>),
    /// Anything else, from [`FixtureError::other`].
    #[error("{0}")]
    Other(Box<dyn std::error::Error + Send + Sync>),
}

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

impl From<crate::Error> for FixtureError {
    fn from(error: crate::Error) -> Self {
        Self::Harness(Box::new(error))
    }
}

impl From<FixtureError> for crate::Error {
    fn from(error: FixtureError) -> Self {
        crate::Error::other(error)
    }
}

/// The runtime a fixture's async work runs on: the harness's own current-thread, paused-clock
/// runtime with the program type erased, or a bare one built the same way for a test with no
/// `app`. Futures see the same virtual time as the app's tasks.
#[derive(Debug)]
pub struct RuntimeRef<'a> {
    runtime: Option<&'a tokio::runtime::Runtime>,
}

impl<'a> RuntimeRef<'a> {
    pub(crate) fn new(runtime: Option<&'a tokio::runtime::Runtime>) -> Self {
        Self { runtime }
    }

    /// Runs `future` to completion on the runtime.
    pub fn block_on<T>(&mut self, future: impl Future<Output = T>) -> crate::Result<T> {
        let runtime = self.runtime.ok_or(crate::HarnessError::Exited)?;
        Ok(runtime.block_on(future))
    }
}

impl<P: TestProgram> Harness<P> {
    /// The harness's runtime with the program type erased, as fixtures receive it.
    pub fn runtime(&mut self) -> RuntimeRef<'_> {
        RuntimeRef::new(self.tokio.as_ref())
    }
}