encore-dev 2.0.0-beta.19

Rust SDK for Encore applications
Documentation
//! Test fixtures for reusable starting states.

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

use encore_sdk_core::test_scope::FixtureBuild;
use tokio::sync::{oneshot, OnceCell};

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

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

/// Setup function for a [`Fixture`], returning a future that populates
/// resources into the desired starting state.
pub type SetupFn = fn() -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send>>;

/// A reusable starting state for tests, replacing freshly provisioned empty
/// resources (for example, pre-seeded database rows).
///
/// ```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 function runs once per test run when a test first loads the
/// fixture, regardless of how many tests, threads, or test binaries use it.
/// Each resource modified during setup is snapshotted, and every test that
/// loads the fixture receives its own isolated copy. Untouched resources start
/// clean (or inherit from the parent fixture when extending another fixture).
///
/// Postgres databases, ClickHouse databases, object buckets, and Redis
/// databases are snapshotted. Other resource types always start from their
/// initial state.
///
/// Snapshots are cached across test runs as long as the app's source code has
/// not changed, except for fixtures that modify Redis (which are rebuilt each
/// run).
///
/// For less boilerplate—and to automatically apply a fixture to every
/// `#[encore::test]` in a module—use the [`fixture!`](crate::fixture) macro.
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 new fixture. `const`, so it can initialize a `static`.
    ///
    /// `name` uniquely identifies the fixture across test binaries; two
    /// declarations with the same name share one snapshot built by whichever
    /// loads first.
    pub const fn new(name: &'static str, setup: SetupFn) -> Self {
        Self::__declare(name, None, None, setup)
    }

    /// Declares a fixture extending `parent`. Its setup starts from the state
    /// saved by `parent`.
    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
    }

    /// Loads this fixture for the current test, running its setup first if it
    /// has not been built yet.
    ///
    /// Must be called before the test accesses any resource; calling `load`
    /// after a resource has already been used returns 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(Some(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 scopes = core().test_scopes().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 (name, parent) = (self.name, self.parent.map(Fixture::name));
        let acquired = off_thread(move || scopes.acquire_fixture(name, parent))
            .await
            .and_then(|acquired| acquired.map_err(|e| self.failed(format!("{e:#}"))))?;
        let built = match acquired {
            FixtureBuild::Ready => return Ok(()),
            FixtureBuild::Build(built) => built,
        };

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

        // The instances become the fixture's: saved, not released.
        off_thread(move || scopes.save_fixture(name, &built))
            .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 fixture {:?}: {reason}", self.name),
        )
    }
}

/// Opts the current test out of any module-level fixture (see
/// [`fixture!`](crate::fixture)).
///
/// Like [`Fixture::load`], this must be called before the test accesses any
/// resource.
pub fn without_fixture() -> Result<(), Error> {
    match active()? {
        Some(scope) => scope.choose(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("fixture 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 one or more [`Fixture`] statics with concise syntax.
///
/// ```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 item defines a `static` of type [`Fixture`] named after its module
/// path and identifier. The expression after `=` produces the setup future (an
/// `async` block or `async fn` call). Write `static NAME: PARENT = ...` to
/// extend another fixture.
///
/// # Module-level fixtures
///
/// Add `for mod` to make a fixture the default for the enclosing module and its
/// submodules: every [`#[encore::test]`](macro@crate::test) in scope loads it
/// automatically. The innermost module's fixture takes precedence, and
/// individual tests can override it with `#[encore::test(fixture = OTHER)]` or
/// `#[encore::test(fixture = none)]`.
///
/// ```ignore
/// mod billing {
///     encore::fixture! {
///         pub static SEEDED for mod = seed();
///     }
///
///     #[encore::test]
///     async fn lists_users() {
///         // starts from SEEDED
///     }
/// }
/// ```
///
/// Tests that do not use `#[encore::test]` do not load module fixtures
/// automatically; in a module with a default fixture, they must explicitly call
/// [`Fixture::load`] or [`without_fixture`] before accessing resources.
#[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;
        };
    };
}