encore/testing/fixture.rs
1//! Test fixtures for reusable starting states.
2
3use std::future::Future;
4use std::pin::Pin;
5
6use encore_sdk_core::test_scope::FixtureBuild;
7use tokio::sync::{OnceCell, oneshot};
8
9use crate::error::{ErrCode, Error};
10use crate::runtime::core;
11
12use super::{Scope, active, run_in_scope};
13
14/// Setup function for a [`Fixture`], returning a future that populates
15/// resources into the desired starting state.
16pub type SetupFn = fn() -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send>>;
17
18/// A reusable starting state for tests, replacing freshly provisioned empty
19/// resources (for example, pre-seeded database rows).
20///
21/// ```ignore
22/// use encore::testing::Fixture;
23///
24/// static SEEDED: Fixture = Fixture::new("seeded", || Box::pin(seed()));
25///
26/// async fn seed() -> Result<(), encore::Error> {
27/// // Ordinary app code: its resources are the fixture's while it is built.
28/// DB.execute("INSERT INTO users (name) VALUES ('ada'), ('grace')", &[]).await?;
29/// Ok(())
30/// }
31///
32/// #[tokio::test]
33/// async fn lists_users() -> Result<(), encore::Error> {
34/// SEEDED.load().await?;
35/// assert_eq!(list_users().await?.len(), 2);
36/// Ok(())
37/// }
38/// ```
39///
40/// The setup function runs once per test run when a test first loads the
41/// fixture, regardless of how many tests, threads, or test binaries use it.
42/// Each resource modified during setup is snapshotted, and every test that
43/// loads the fixture receives its own isolated copy. Untouched resources start
44/// clean (or inherit from the parent fixture when extending another fixture).
45///
46/// Postgres databases, ClickHouse databases, object buckets, and Redis
47/// databases are snapshotted. Other resource types always start from their
48/// initial state.
49///
50/// Snapshots are cached across test runs as long as the app's source code has
51/// not changed, except for fixtures that modify Redis (which are rebuilt each
52/// run).
53///
54/// For less boilerplate—and to automatically apply a fixture to every
55/// `#[encore::test]` in a module—use the [`fixture!`](crate::fixture) macro.
56pub struct Fixture {
57 name: &'static str,
58 parent: Option<&'static Fixture>,
59 /// The module whose `#[encore::test]`s load it without being told to.
60 module: Option<&'static str>,
61 setup: SetupFn,
62 /// Whether the fixture is built, as far as this process has asked.
63 built: OnceCell<Result<(), Error>>,
64}
65
66impl Fixture {
67 /// Declares a new fixture. `const`, so it can initialize a `static`.
68 ///
69 /// `name` uniquely identifies the fixture across test binaries; two
70 /// declarations with the same name share one snapshot built by whichever
71 /// loads first.
72 pub const fn new(name: &'static str, setup: SetupFn) -> Self {
73 Self::__declare(name, None, None, setup)
74 }
75
76 /// Declares a fixture extending `parent`. Its setup starts from the state
77 /// saved by `parent`.
78 pub const fn extending(parent: &'static Fixture, name: &'static str, setup: SetupFn) -> Self {
79 Self::__declare(name, Some(parent), None, setup)
80 }
81
82 /// What [`fixture!`](crate::fixture) declares a fixture with.
83 #[doc(hidden)]
84 pub const fn __declare(
85 name: &'static str,
86 parent: Option<&'static Fixture>,
87 module: Option<&'static str>,
88 setup: SetupFn,
89 ) -> Self {
90 Self {
91 name,
92 parent,
93 module,
94 setup,
95 built: OnceCell::const_new(),
96 }
97 }
98
99 /// The fixture's name.
100 pub const fn name(&self) -> &'static str {
101 self.name
102 }
103
104 pub(super) fn module(&self) -> Option<&'static str> {
105 self.module
106 }
107
108 /// Loads this fixture for the current test, running its setup first if it
109 /// has not been built yet.
110 ///
111 /// Must be called before the test accesses any resource; calling `load`
112 /// after a resource has already been used returns an error.
113 pub async fn load(&'static self) -> Result<(), Error> {
114 let Some(scope) = active()? else {
115 return Err(Error::new(
116 ErrCode::FailedPrecondition,
117 format!(
118 "cannot load the fixture {:?}: the process is not running under `encore test`",
119 self.name
120 ),
121 ));
122 };
123 self.ensure_built().await?;
124 scope.choose(Some(self))
125 }
126
127 /// Makes sure the fixture is built, by this process or another.
128 async fn ensure_built(&'static self) -> Result<(), Error> {
129 self.built.get_or_init(|| self.build()).await.clone()
130 }
131
132 async fn build(&'static self) -> Result<(), Error> {
133 if let Some(parent) = self.parent {
134 // Boxed: a fixture's future would otherwise contain its parent's.
135 Box::pin(parent.ensure_built()).await?;
136 }
137 let scopes = core().test_scopes().ok_or_else(|| {
138 Error::new(
139 ErrCode::FailedPrecondition,
140 "fixtures are only available under `encore test`",
141 )
142 })?;
143
144 // What the setup runs in, if it is this process that runs it: a scope
145 // of its own, starting from the parent.
146 let (name, parent) = (self.name, self.parent.map(Fixture::name));
147 let acquired = off_thread(move || scopes.acquire_fixture(name, parent))
148 .await
149 .and_then(|acquired| acquired.map_err(|e| self.failed(format!("{e:#}"))))?;
150 let built = match acquired {
151 FixtureBuild::Ready => return Ok(()),
152 FixtureBuild::Build(built) => built,
153 };
154
155 // On a thread and runtime of its own, which are the fixture's: so is
156 // whatever the setup spawns.
157 let setup = self.setup;
158 let scope = Scope::building(built.clone(), format!("fixture {name:?}"));
159 let outcome = off_thread(move || run_in_scope(scope, setup())).await;
160 match outcome {
161 Ok(Ok(())) => {}
162 Ok(Err(err)) | Err(err) => {
163 let err = self.failed(format!("setup failed: {}", err.message));
164 scopes.fail_fixture(name, &err.message);
165 return Err(err);
166 }
167 }
168
169 // The instances become the fixture's: saved, not released.
170 off_thread(move || scopes.save_fixture(name, &built))
171 .await
172 .and_then(|saved| saved.map_err(|e| self.failed(format!("{e:#}"))))
173 }
174
175 fn failed(&self, reason: String) -> Error {
176 Error::new(
177 ErrCode::FailedPrecondition,
178 format!("cannot load fixture {:?}: {reason}", self.name),
179 )
180 }
181}
182
183/// Opts the current test out of any module-level fixture (see
184/// [`fixture!`](crate::fixture)).
185///
186/// Like [`Fixture::load`], this must be called before the test accesses any
187/// resource.
188pub fn without_fixture() -> Result<(), Error> {
189 match active()? {
190 Some(scope) => scope.choose(None),
191 None => Ok(()),
192 }
193}
194
195/// Runs blocking work — a wait on the daemon, a nested runtime — on a thread of
196/// its own, without blocking the caller's runtime. An error if it panics.
197async fn off_thread<T: Send + 'static>(
198 work: impl FnOnce() -> T + Send + 'static,
199) -> Result<T, Error> {
200 let (tx, rx) = oneshot::channel();
201 std::thread::spawn(move || {
202 let _ = tx.send(work());
203 });
204 rx.await
205 .map_err(|_| Error::internal("fixture setup panicked"))
206}
207
208/// Every fixture declared for a module by [`fixture!`](crate::fixture),
209/// collected at link time: a `static` says nothing of itself until it is used.
210#[linkme::distributed_slice]
211pub static FIXTURES: [&'static Fixture];
212
213/// The fixture declared for the module `module` or, failing that, the nearest
214/// module it is in. `module` is a full path when `full`, as `module_path!`
215/// gives it; else it lacks the crate, as the test harness's names do.
216pub(super) fn for_module(module: &str, full: bool) -> Option<&'static Fixture> {
217 FIXTURES
218 .iter()
219 .copied()
220 .filter(|fixture| {
221 let Some(declared) = fixture.module() else {
222 return false;
223 };
224 let declared = if full {
225 declared
226 } else {
227 declared.split_once("::").map_or("", |(_, rest)| rest)
228 };
229 declared.is_empty()
230 || module == declared
231 || module
232 .strip_prefix(declared)
233 .is_some_and(|rest| rest.starts_with("::"))
234 })
235 .max_by_key(|fixture| fixture.module().map_or(0, str::len))
236}
237
238/// Declares one or more [`Fixture`] statics with concise syntax.
239///
240/// ```ignore
241/// encore::fixture! {
242/// /// Two users.
243/// pub static SEEDED = async {
244/// DB.execute("INSERT INTO users (name) VALUES ('ada'), ('grace')", &[]).await?;
245/// Ok(())
246/// };
247///
248/// /// `SEEDED`, plus an invoice for each user.
249/// pub static INVOICED: SEEDED = create_invoices();
250/// }
251/// ```
252///
253/// Each item defines a `static` of type [`Fixture`] named after its module
254/// path and identifier. The expression after `=` produces the setup future (an
255/// `async` block or `async fn` call). Write `static NAME: PARENT = ...` to
256/// extend another fixture.
257///
258/// # Module-level fixtures
259///
260/// Add `for mod` to make a fixture the default for the enclosing module and its
261/// submodules: every [`#[encore::test]`](macro@crate::test) in scope loads it
262/// automatically. The innermost module's fixture takes precedence, and
263/// individual tests can override it with `#[encore::test(fixture = OTHER)]` or
264/// `#[encore::test(fixture = none)]`.
265///
266/// ```ignore
267/// mod billing {
268/// encore::fixture! {
269/// pub static SEEDED for mod = seed();
270/// }
271///
272/// #[encore::test]
273/// async fn lists_users() {
274/// // starts from SEEDED
275/// }
276/// }
277/// ```
278///
279/// Tests that do not use `#[encore::test]` do not load module fixtures
280/// automatically; in a module with a default fixture, they must explicitly call
281/// [`Fixture::load`] or [`without_fixture`] before accessing resources.
282#[macro_export]
283macro_rules! fixture {
284 () => {};
285 ($(#[$meta:meta])* $vis:vis static $name:ident for mod : $parent:path = $setup:expr; $($rest:tt)*) => {
286 $crate::__fixture!([$(#[$meta])*] [$vis] $name, ::core::option::Option::Some(&$parent), ::core::option::Option::Some(::core::module_path!()), $setup);
287 $crate::__fixture_register!($name);
288 $crate::fixture! { $($rest)* }
289 };
290 ($(#[$meta:meta])* $vis:vis static $name:ident for mod = $setup:expr; $($rest:tt)*) => {
291 $crate::__fixture!([$(#[$meta])*] [$vis] $name, ::core::option::Option::None, ::core::option::Option::Some(::core::module_path!()), $setup);
292 $crate::__fixture_register!($name);
293 $crate::fixture! { $($rest)* }
294 };
295 ($(#[$meta:meta])* $vis:vis static $name:ident : $parent:path = $setup:expr; $($rest:tt)*) => {
296 $crate::__fixture!([$(#[$meta])*] [$vis] $name, ::core::option::Option::Some(&$parent), ::core::option::Option::None, $setup);
297 $crate::fixture! { $($rest)* }
298 };
299 ($(#[$meta:meta])* $vis:vis static $name:ident = $setup:expr; $($rest:tt)*) => {
300 $crate::__fixture!([$(#[$meta])*] [$vis] $name, ::core::option::Option::None, ::core::option::Option::None, $setup);
301 $crate::fixture! { $($rest)* }
302 };
303}
304
305#[doc(hidden)]
306#[macro_export]
307macro_rules! __fixture {
308 ([$(#[$meta:meta])*] [$vis:vis] $name:ident, $parent:expr, $module:expr, $setup:expr) => {
309 $(#[$meta])*
310 $vis static $name: $crate::testing::Fixture = $crate::testing::Fixture::__declare(
311 ::core::concat!(::core::module_path!(), "::", ::core::stringify!($name)),
312 $parent,
313 $module,
314 || ::std::boxed::Box::pin($setup),
315 );
316 };
317}
318
319#[doc(hidden)]
320#[macro_export]
321macro_rules! __fixture_register {
322 ($name:ident) => {
323 const _: () = {
324 #[$crate::testing::__private::linkme::distributed_slice(
325 $crate::testing::__private::FIXTURES
326 )]
327 #[linkme(crate = $crate::testing::__private::linkme)]
328 static FIXTURE: &$crate::testing::Fixture = &$name;
329 };
330 };
331}