encore-dev 2.0.0-alpha.17

Rust SDK for Encore applications
Documentation
//! Fixtures: saved states for tests to start from.

use std::future::Future;
use std::pin::Pin;

use encore_sdk_core::resolver::FixtureAcquired;
use tokio::sync::{oneshot, OnceCell};

use crate::error::{ErrCode, Error};
use crate::runtime::core;

use super::{active, run_in_scope, Choice, Scope};

/// A fixture's setup: a function returning the future that puts the app's
/// resources in the state the fixture saves.
pub type SetupFn = fn() -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send>>;

/// A saved state for tests to start from, in place of the app's freshly
/// provisioned one: the rows a setup inserted, say.
///
/// ```ignore
/// use encore::testing::Fixture;
///
/// static SEEDED: Fixture = Fixture::new("seeded", || Box::pin(seed()));
///
/// async fn seed() -> Result<(), encore::Error> {
///     // Ordinary app code: its resources are the fixture's while it is built.
///     DB.execute("INSERT INTO users (name) VALUES ('ada'), ('grace')", &[]).await?;
///     Ok(())
/// }
///
/// #[tokio::test]
/// async fn lists_users() -> Result<(), encore::Error> {
///     SEEDED.load().await?;
///     assert_eq!(list_users().await?.len(), 2);
///     Ok(())
/// }
/// ```
///
/// The setup runs once per test run, the first time a test loads the fixture,
/// however many tests, threads and test binaries load it. What it leaves in
/// each resource it touched is saved; a test that loads the fixture gets a
/// copy of its own, to change as it likes. A resource the setup did not touch
/// starts as it would without the fixture — or, in a fixture that extends
/// another, as that one left it.
///
/// Databases, buckets and Redis databases are saved. The other kinds of
/// resource start a test from their initial state, with or without a fixture.
///
/// A fixture is kept from one test run to the next for as long as the app's
/// source is unchanged, so its setup need not run again — unless it touched a
/// Redis database, which lasts only as long as the run: such a fixture is set
/// up again each run.
///
/// The [`fixture!`](crate::fixture) macro declares one with less ceremony, and
/// can have a fixture loaded by every `#[encore::test]` in a module.
pub struct Fixture {
    name: &'static str,
    parent: Option<&'static Fixture>,
    /// The module whose `#[encore::test]`s load it without being told to.
    module: Option<&'static str>,
    setup: SetupFn,
    /// Whether the fixture is built, as far as this process has asked.
    built: OnceCell<Result<(), Error>>,
}

impl Fixture {
    /// Declares a fixture. `const`, so it can initialize a `static`.
    ///
    /// The name identifies the fixture across the app's test binaries: two
    /// fixtures of one name are one fixture, built by whichever is loaded first.
    pub const fn new(name: &'static str, setup: SetupFn) -> Self {
        Self::__declare(name, None, None, setup)
    }

    /// Declares a fixture built on another: its setup starts from what
    /// `parent` saved.
    pub const fn extending(parent: &'static Fixture, name: &'static str, setup: SetupFn) -> Self {
        Self::__declare(name, Some(parent), None, setup)
    }

    /// What [`fixture!`](crate::fixture) declares a fixture with.
    #[doc(hidden)]
    pub const fn __declare(
        name: &'static str,
        parent: Option<&'static Fixture>,
        module: Option<&'static str>,
        setup: SetupFn,
    ) -> Self {
        Self {
            name,
            parent,
            module,
            setup,
            built: OnceCell::const_new(),
        }
    }

    /// The fixture's name.
    pub const fn name(&self) -> &'static str {
        self.name
    }

    pub(super) fn module(&self) -> Option<&'static str> {
        self.module
    }

    /// Makes the current test start from this fixture, building it first if no
    /// test of the run has yet.
    ///
    /// Call it before the test first uses a resource: a test that already has
    /// a database cannot change what it started from, and gets an error.
    pub async fn load(&'static self) -> Result<(), Error> {
        let Some(scope) = active()? else {
            return Err(Error::new(
                ErrCode::FailedPrecondition,
                format!(
                    "cannot load the fixture {:?}: the process is not running under `encore test`",
                    self.name
                ),
            ));
        };
        self.ensure_built().await?;
        scope.choose(Choice::Fixture(self))
    }

    /// Makes sure the fixture is built, by this process or another.
    async fn ensure_built(&'static self) -> Result<(), Error> {
        self.built.get_or_init(|| self.build()).await.clone()
    }

    async fn build(&'static self) -> Result<(), Error> {
        if let Some(parent) = self.parent {
            // Boxed: a fixture's future would otherwise contain its parent's.
            Box::pin(parent.ensure_built()).await?;
        }
        let resolver = core().postgres().resolver().cloned().ok_or_else(|| {
            Error::new(
                ErrCode::FailedPrecondition,
                "fixtures are only available under `encore test`",
            )
        })?;

        // What the setup runs in, if it is this process that runs it: a scope
        // of its own, starting from the parent.
        let scope = Scope::new();
        let _ = scope.name.set(format!("fixture {:?}", self.name));
        scope.choose(match self.parent {
            Some(parent) => Choice::Fixture(parent),
            None => Choice::None,
        })?;

        let name = self.name;
        let acquired = off_thread({
            let (resolver, id) = (resolver.clone(), scope.instance_id.clone());
            move || resolver.acquire_fixture(name, &id)
        })
        .await
        .and_then(|acquired| acquired.map_err(|e| self.failed(format!("{e:#}"))))?;
        if acquired == FixtureAcquired::Ready {
            return Ok(());
        }

        // On a thread and runtime of its own, which are the fixture's: so is
        // whatever the setup spawns.
        let setup = self.setup;
        let outcome = off_thread({
            let scope = scope.clone();
            move || run_in_scope(scope, setup())
        })
        .await;
        match outcome {
            Ok(Ok(())) => {}
            Ok(Err(err)) | Err(err) => {
                let err = self.failed(format!("its setup failed: {}", err.message));
                resolver.fail_fixture(name, &err.message);
                return Err(err);
            }
        }

        // The instances become the fixture's: let go of them without releasing.
        let id = scope.instance_id.clone();
        scope.forget();
        let parent = self.parent.map_or("", Fixture::name);
        off_thread(move || resolver.save_fixture(name, &id, parent))
            .await
            .and_then(|saved| saved.map_err(|e| self.failed(format!("{e:#}"))))
    }

    fn failed(&self, reason: String) -> Error {
        Error::new(
            ErrCode::FailedPrecondition,
            format!("cannot load the fixture {:?}: {reason}", self.name),
        )
    }
}

/// Makes the current test start without a fixture, where a module's would
/// otherwise apply (see [`fixture!`](crate::fixture)). Like
/// [`Fixture::load`], it must come before the test first uses a resource.
pub fn without_fixture() -> Result<(), Error> {
    match active()? {
        Some(scope) => scope.choose(Choice::None),
        None => Ok(()),
    }
}

/// Runs blocking work — a wait on the daemon, a nested runtime — on a thread of
/// its own, without blocking the caller's runtime. An error if it panics.
async fn off_thread<T: Send + 'static>(
    work: impl FnOnce() -> T + Send + 'static,
) -> Result<T, Error> {
    let (tx, rx) = oneshot::channel();
    std::thread::spawn(move || {
        let _ = tx.send(work());
    });
    rx.await
        .map_err(|_| Error::internal("a fixture's setup panicked"))
}

/// Every fixture declared for a module by [`fixture!`](crate::fixture),
/// collected at link time: a `static` says nothing of itself until it is used.
#[linkme::distributed_slice]
pub static FIXTURES: [&'static Fixture];

/// The fixture declared for the module `module` or, failing that, the nearest
/// module it is in. `module` is a full path when `full`, as `module_path!`
/// gives it; else it lacks the crate, as the test harness's names do.
pub(super) fn for_module(module: &str, full: bool) -> Option<&'static Fixture> {
    FIXTURES
        .iter()
        .copied()
        .filter(|fixture| {
            let Some(declared) = fixture.module() else {
                return false;
            };
            let declared = if full {
                declared
            } else {
                declared.split_once("::").map_or("", |(_, rest)| rest)
            };
            declared.is_empty()
                || module == declared
                || module
                    .strip_prefix(declared)
                    .is_some_and(|rest| rest.starts_with("::"))
        })
        .max_by_key(|fixture| fixture.module().map_or(0, str::len))
}

/// Declares fixtures: [`Fixture`]s, with less to write.
///
/// ```ignore
/// encore::fixture! {
///     /// Two users.
///     pub static SEEDED = async {
///         DB.execute("INSERT INTO users (name) VALUES ('ada'), ('grace')", &[]).await?;
///         Ok(())
///     };
///
///     /// `SEEDED`, plus an invoice for each user.
///     pub static INVOICED: SEEDED = create_invoices();
/// }
/// ```
///
/// Each is a `static` of type [`Fixture`], named after its module and itself.
/// Its setup is the expression after the `=`: a future, such as an `async`
/// block or a call of an `async fn`. A fixture declared `static NAME: PARENT`
/// extends `PARENT`.
///
/// # A module's fixture
///
/// `for mod` makes it the fixture of the module it is declared in: every
/// [`#[encore::test]`](macro@crate::test) there and in the modules inside it
/// loads it before the test runs. The innermost module's fixture wins, and a
/// test can ask otherwise: `#[encore::test(fixture = OTHER)]`,
/// `#[encore::test(fixture = none)]`.
///
/// ```ignore
/// mod billing {
///     encore::fixture! {
///         pub static SEEDED for mod = seed();
///     }
///
///     #[encore::test]
///     async fn lists_users() {
///         // starts from SEEDED
///     }
/// }
/// ```
///
/// A test that is not an `#[encore::test]` loads no fixture by itself, and in
/// such a module is told to — to call [`Fixture::load`] or
/// [`without_fixture`] — rather than left to run on the wrong data.
#[macro_export]
macro_rules! fixture {
    () => {};
    ($(#[$meta:meta])* $vis:vis static $name:ident for mod : $parent:path = $setup:expr; $($rest:tt)*) => {
        $crate::__fixture!([$(#[$meta])*] [$vis] $name, ::core::option::Option::Some(&$parent), ::core::option::Option::Some(::core::module_path!()), $setup);
        $crate::__fixture_register!($name);
        $crate::fixture! { $($rest)* }
    };
    ($(#[$meta:meta])* $vis:vis static $name:ident for mod = $setup:expr; $($rest:tt)*) => {
        $crate::__fixture!([$(#[$meta])*] [$vis] $name, ::core::option::Option::None, ::core::option::Option::Some(::core::module_path!()), $setup);
        $crate::__fixture_register!($name);
        $crate::fixture! { $($rest)* }
    };
    ($(#[$meta:meta])* $vis:vis static $name:ident : $parent:path = $setup:expr; $($rest:tt)*) => {
        $crate::__fixture!([$(#[$meta])*] [$vis] $name, ::core::option::Option::Some(&$parent), ::core::option::Option::None, $setup);
        $crate::fixture! { $($rest)* }
    };
    ($(#[$meta:meta])* $vis:vis static $name:ident = $setup:expr; $($rest:tt)*) => {
        $crate::__fixture!([$(#[$meta])*] [$vis] $name, ::core::option::Option::None, ::core::option::Option::None, $setup);
        $crate::fixture! { $($rest)* }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __fixture {
    ([$(#[$meta:meta])*] [$vis:vis] $name:ident, $parent:expr, $module:expr, $setup:expr) => {
        $(#[$meta])*
        $vis static $name: $crate::testing::Fixture = $crate::testing::Fixture::__declare(
            ::core::concat!(::core::module_path!(), "::", ::core::stringify!($name)),
            $parent,
            $module,
            || ::std::boxed::Box::pin($setup),
        );
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __fixture_register {
    ($name:ident) => {
        const _: () = {
            #[$crate::testing::__private::linkme::distributed_slice(
                $crate::testing::__private::FIXTURES
            )]
            #[linkme(crate = $crate::testing::__private::linkme)]
            static FIXTURE: &$crate::testing::Fixture = &$name;
        };
    };
}