encore/testing/fixture.rs
1//! Fixtures: saved states for tests to start from.
2
3use std::future::Future;
4use std::pin::Pin;
5
6use encore_sdk_core::test_scope::FixtureBuild;
7use tokio::sync::{oneshot, OnceCell};
8
9use crate::error::{ErrCode, Error};
10use crate::runtime::core;
11
12use super::{active, run_in_scope, Scope};
13
14/// A fixture's setup: a function returning the future that puts the app's
15/// resources in the state the fixture saves.
16pub type SetupFn = fn() -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send>>;
17
18/// A saved state for tests to start from, in place of the app's freshly
19/// provisioned one: the rows a setup inserted, say.
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 runs once per test run, the first time a test loads the fixture,
41/// however many tests, threads and test binaries load it. What it leaves in
42/// each resource it touched is saved; a test that loads the fixture gets a
43/// copy of its own, to change as it likes. A resource the setup did not touch
44/// starts as it would without the fixture — or, in a fixture that extends
45/// another, as that one left it.
46///
47/// Databases, buckets and Redis databases are saved. The other kinds of
48/// resource start a test from their initial state, with or without a fixture.
49///
50/// A fixture is kept from one test run to the next for as long as the app's
51/// source is unchanged, so its setup need not run again — unless it touched a
52/// Redis database, which lasts only as long as the run: such a fixture is set
53/// up again each run.
54///
55/// The [`fixture!`](crate::fixture) macro declares one with less ceremony, and
56/// can have a fixture loaded by every `#[encore::test]` in a module.
57pub struct Fixture {
58 name: &'static str,
59 parent: Option<&'static Fixture>,
60 /// The module whose `#[encore::test]`s load it without being told to.
61 module: Option<&'static str>,
62 setup: SetupFn,
63 /// Whether the fixture is built, as far as this process has asked.
64 built: OnceCell<Result<(), Error>>,
65}
66
67impl Fixture {
68 /// Declares a fixture. `const`, so it can initialize a `static`.
69 ///
70 /// The name identifies the fixture across the app's test binaries: two
71 /// fixtures of one name are one fixture, built by whichever is loaded 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 built on another: its setup starts from what
77 /// `parent` saved.
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 /// Makes the current test start from this fixture, building it first if no
109 /// test of the run has yet.
110 ///
111 /// Call it before the test first uses a resource: a test that already has
112 /// a database cannot change what it started from, and gets 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!("its 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 the fixture {:?}: {reason}", self.name),
179 )
180 }
181}
182
183/// Makes the current test start without a fixture, where a module's would
184/// otherwise apply (see [`fixture!`](crate::fixture)). Like
185/// [`Fixture::load`], it must come before the test first uses a resource.
186pub fn without_fixture() -> Result<(), Error> {
187 match active()? {
188 Some(scope) => scope.choose(None),
189 None => Ok(()),
190 }
191}
192
193/// Runs blocking work — a wait on the daemon, a nested runtime — on a thread of
194/// its own, without blocking the caller's runtime. An error if it panics.
195async fn off_thread<T: Send + 'static>(
196 work: impl FnOnce() -> T + Send + 'static,
197) -> Result<T, Error> {
198 let (tx, rx) = oneshot::channel();
199 std::thread::spawn(move || {
200 let _ = tx.send(work());
201 });
202 rx.await
203 .map_err(|_| Error::internal("a fixture's setup panicked"))
204}
205
206/// Every fixture declared for a module by [`fixture!`](crate::fixture),
207/// collected at link time: a `static` says nothing of itself until it is used.
208#[linkme::distributed_slice]
209pub static FIXTURES: [&'static Fixture];
210
211/// The fixture declared for the module `module` or, failing that, the nearest
212/// module it is in. `module` is a full path when `full`, as `module_path!`
213/// gives it; else it lacks the crate, as the test harness's names do.
214pub(super) fn for_module(module: &str, full: bool) -> Option<&'static Fixture> {
215 FIXTURES
216 .iter()
217 .copied()
218 .filter(|fixture| {
219 let Some(declared) = fixture.module() else {
220 return false;
221 };
222 let declared = if full {
223 declared
224 } else {
225 declared.split_once("::").map_or("", |(_, rest)| rest)
226 };
227 declared.is_empty()
228 || module == declared
229 || module
230 .strip_prefix(declared)
231 .is_some_and(|rest| rest.starts_with("::"))
232 })
233 .max_by_key(|fixture| fixture.module().map_or(0, str::len))
234}
235
236/// Declares fixtures: [`Fixture`]s, with less to write.
237///
238/// ```ignore
239/// encore::fixture! {
240/// /// Two users.
241/// pub static SEEDED = async {
242/// DB.execute("INSERT INTO users (name) VALUES ('ada'), ('grace')", &[]).await?;
243/// Ok(())
244/// };
245///
246/// /// `SEEDED`, plus an invoice for each user.
247/// pub static INVOICED: SEEDED = create_invoices();
248/// }
249/// ```
250///
251/// Each is a `static` of type [`Fixture`], named after its module and itself.
252/// Its setup is the expression after the `=`: a future, such as an `async`
253/// block or a call of an `async fn`. A fixture declared `static NAME: PARENT`
254/// extends `PARENT`.
255///
256/// # A module's fixture
257///
258/// `for mod` makes it the fixture of the module it is declared in: every
259/// [`#[encore::test]`](macro@crate::test) there and in the modules inside it
260/// loads it before the test runs. The innermost module's fixture wins, and a
261/// test can ask otherwise: `#[encore::test(fixture = OTHER)]`,
262/// `#[encore::test(fixture = none)]`.
263///
264/// ```ignore
265/// mod billing {
266/// encore::fixture! {
267/// pub static SEEDED for mod = seed();
268/// }
269///
270/// #[encore::test]
271/// async fn lists_users() {
272/// // starts from SEEDED
273/// }
274/// }
275/// ```
276///
277/// A test that is not an `#[encore::test]` loads no fixture by itself, and in
278/// such a module is told to — to call [`Fixture::load`] or
279/// [`without_fixture`] — rather than left to run on the wrong data.
280#[macro_export]
281macro_rules! fixture {
282 () => {};
283 ($(#[$meta:meta])* $vis:vis static $name:ident for mod : $parent:path = $setup:expr; $($rest:tt)*) => {
284 $crate::__fixture!([$(#[$meta])*] [$vis] $name, ::core::option::Option::Some(&$parent), ::core::option::Option::Some(::core::module_path!()), $setup);
285 $crate::__fixture_register!($name);
286 $crate::fixture! { $($rest)* }
287 };
288 ($(#[$meta:meta])* $vis:vis static $name:ident for mod = $setup:expr; $($rest:tt)*) => {
289 $crate::__fixture!([$(#[$meta])*] [$vis] $name, ::core::option::Option::None, ::core::option::Option::Some(::core::module_path!()), $setup);
290 $crate::__fixture_register!($name);
291 $crate::fixture! { $($rest)* }
292 };
293 ($(#[$meta:meta])* $vis:vis static $name:ident : $parent:path = $setup:expr; $($rest:tt)*) => {
294 $crate::__fixture!([$(#[$meta])*] [$vis] $name, ::core::option::Option::Some(&$parent), ::core::option::Option::None, $setup);
295 $crate::fixture! { $($rest)* }
296 };
297 ($(#[$meta:meta])* $vis:vis static $name:ident = $setup:expr; $($rest:tt)*) => {
298 $crate::__fixture!([$(#[$meta])*] [$vis] $name, ::core::option::Option::None, ::core::option::Option::None, $setup);
299 $crate::fixture! { $($rest)* }
300 };
301}
302
303#[doc(hidden)]
304#[macro_export]
305macro_rules! __fixture {
306 ([$(#[$meta:meta])*] [$vis:vis] $name:ident, $parent:expr, $module:expr, $setup:expr) => {
307 $(#[$meta])*
308 $vis static $name: $crate::testing::Fixture = $crate::testing::Fixture::__declare(
309 ::core::concat!(::core::module_path!(), "::", ::core::stringify!($name)),
310 $parent,
311 $module,
312 || ::std::boxed::Box::pin($setup),
313 );
314 };
315}
316
317#[doc(hidden)]
318#[macro_export]
319macro_rules! __fixture_register {
320 ($name:ident) => {
321 const _: () = {
322 #[$crate::testing::__private::linkme::distributed_slice(
323 $crate::testing::__private::FIXTURES
324 )]
325 #[linkme(crate = $crate::testing::__private::linkme)]
326 static FIXTURE: &$crate::testing::Fixture = &$name;
327 };
328 };
329}