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::resolver::FixtureAcquired;
7use tokio::sync::{oneshot, OnceCell};
8
9use crate::error::{ErrCode, Error};
10use crate::runtime::core;
11
12use super::{active, run_in_scope, Choice, 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(Choice::Fixture(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 resolver = core().postgres().resolver().cloned().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 scope = Scope::new();
147 let _ = scope.name.set(format!("fixture {:?}", self.name));
148 scope.choose(match self.parent {
149 Some(parent) => Choice::Fixture(parent),
150 None => Choice::None,
151 })?;
152
153 let name = self.name;
154 let acquired = off_thread({
155 let (resolver, id) = (resolver.clone(), scope.instance_id.clone());
156 move || resolver.acquire_fixture(name, &id)
157 })
158 .await
159 .and_then(|acquired| acquired.map_err(|e| self.failed(format!("{e:#}"))))?;
160 if acquired == FixtureAcquired::Ready {
161 return Ok(());
162 }
163
164 // On a thread and runtime of its own, which are the fixture's: so is
165 // whatever the setup spawns.
166 let setup = self.setup;
167 let outcome = off_thread({
168 let scope = scope.clone();
169 move || run_in_scope(scope, setup())
170 })
171 .await;
172 match outcome {
173 Ok(Ok(())) => {}
174 Ok(Err(err)) | Err(err) => {
175 let err = self.failed(format!("its setup failed: {}", err.message));
176 resolver.fail_fixture(name, &err.message);
177 return Err(err);
178 }
179 }
180
181 // The instances become the fixture's: let go of them without releasing.
182 let id = scope.instance_id.clone();
183 scope.forget();
184 let parent = self.parent.map_or("", Fixture::name);
185 off_thread(move || resolver.save_fixture(name, &id, parent))
186 .await
187 .and_then(|saved| saved.map_err(|e| self.failed(format!("{e:#}"))))
188 }
189
190 fn failed(&self, reason: String) -> Error {
191 Error::new(
192 ErrCode::FailedPrecondition,
193 format!("cannot load the fixture {:?}: {reason}", self.name),
194 )
195 }
196}
197
198/// Makes the current test start without a fixture, where a module's would
199/// otherwise apply (see [`fixture!`](crate::fixture)). Like
200/// [`Fixture::load`], it must come before the test first uses a resource.
201pub fn without_fixture() -> Result<(), Error> {
202 match active()? {
203 Some(scope) => scope.choose(Choice::None),
204 None => Ok(()),
205 }
206}
207
208/// Runs blocking work — a wait on the daemon, a nested runtime — on a thread of
209/// its own, without blocking the caller's runtime. An error if it panics.
210async fn off_thread<T: Send + 'static>(
211 work: impl FnOnce() -> T + Send + 'static,
212) -> Result<T, Error> {
213 let (tx, rx) = oneshot::channel();
214 std::thread::spawn(move || {
215 let _ = tx.send(work());
216 });
217 rx.await
218 .map_err(|_| Error::internal("a fixture's setup panicked"))
219}
220
221/// Every fixture declared for a module by [`fixture!`](crate::fixture),
222/// collected at link time: a `static` says nothing of itself until it is used.
223#[linkme::distributed_slice]
224pub static FIXTURES: [&'static Fixture];
225
226/// The fixture declared for the module `module` or, failing that, the nearest
227/// module it is in. `module` is a full path when `full`, as `module_path!`
228/// gives it; else it lacks the crate, as the test harness's names do.
229pub(super) fn for_module(module: &str, full: bool) -> Option<&'static Fixture> {
230 FIXTURES
231 .iter()
232 .copied()
233 .filter(|fixture| {
234 let Some(declared) = fixture.module() else {
235 return false;
236 };
237 let declared = if full {
238 declared
239 } else {
240 declared.split_once("::").map_or("", |(_, rest)| rest)
241 };
242 declared.is_empty()
243 || module == declared
244 || module
245 .strip_prefix(declared)
246 .is_some_and(|rest| rest.starts_with("::"))
247 })
248 .max_by_key(|fixture| fixture.module().map_or(0, str::len))
249}
250
251/// Declares fixtures: [`Fixture`]s, with less to write.
252///
253/// ```ignore
254/// encore::fixture! {
255/// /// Two users.
256/// pub static SEEDED = async {
257/// DB.execute("INSERT INTO users (name) VALUES ('ada'), ('grace')", &[]).await?;
258/// Ok(())
259/// };
260///
261/// /// `SEEDED`, plus an invoice for each user.
262/// pub static INVOICED: SEEDED = create_invoices();
263/// }
264/// ```
265///
266/// Each is a `static` of type [`Fixture`], named after its module and itself.
267/// Its setup is the expression after the `=`: a future, such as an `async`
268/// block or a call of an `async fn`. A fixture declared `static NAME: PARENT`
269/// extends `PARENT`.
270///
271/// # A module's fixture
272///
273/// `for mod` makes it the fixture of the module it is declared in: every
274/// [`#[encore::test]`](macro@crate::test) there and in the modules inside it
275/// loads it before the test runs. The innermost module's fixture wins, and a
276/// test can ask otherwise: `#[encore::test(fixture = OTHER)]`,
277/// `#[encore::test(fixture = none)]`.
278///
279/// ```ignore
280/// mod billing {
281/// encore::fixture! {
282/// pub static SEEDED for mod = seed();
283/// }
284///
285/// #[encore::test]
286/// async fn lists_users() {
287/// // starts from SEEDED
288/// }
289/// }
290/// ```
291///
292/// A test that is not an `#[encore::test]` loads no fixture by itself, and in
293/// such a module is told to — to call [`Fixture::load`] or
294/// [`without_fixture`] — rather than left to run on the wrong data.
295#[macro_export]
296macro_rules! fixture {
297 () => {};
298 ($(#[$meta:meta])* $vis:vis static $name:ident for mod : $parent:path = $setup:expr; $($rest:tt)*) => {
299 $crate::__fixture!([$(#[$meta])*] [$vis] $name, ::core::option::Option::Some(&$parent), ::core::option::Option::Some(::core::module_path!()), $setup);
300 $crate::__fixture_register!($name);
301 $crate::fixture! { $($rest)* }
302 };
303 ($(#[$meta:meta])* $vis:vis static $name:ident for mod = $setup:expr; $($rest:tt)*) => {
304 $crate::__fixture!([$(#[$meta])*] [$vis] $name, ::core::option::Option::None, ::core::option::Option::Some(::core::module_path!()), $setup);
305 $crate::__fixture_register!($name);
306 $crate::fixture! { $($rest)* }
307 };
308 ($(#[$meta:meta])* $vis:vis static $name:ident : $parent:path = $setup:expr; $($rest:tt)*) => {
309 $crate::__fixture!([$(#[$meta])*] [$vis] $name, ::core::option::Option::Some(&$parent), ::core::option::Option::None, $setup);
310 $crate::fixture! { $($rest)* }
311 };
312 ($(#[$meta:meta])* $vis:vis static $name:ident = $setup:expr; $($rest:tt)*) => {
313 $crate::__fixture!([$(#[$meta])*] [$vis] $name, ::core::option::Option::None, ::core::option::Option::None, $setup);
314 $crate::fixture! { $($rest)* }
315 };
316}
317
318#[doc(hidden)]
319#[macro_export]
320macro_rules! __fixture {
321 ([$(#[$meta:meta])*] [$vis:vis] $name:ident, $parent:expr, $module:expr, $setup:expr) => {
322 $(#[$meta])*
323 $vis static $name: $crate::testing::Fixture = $crate::testing::Fixture::__declare(
324 ::core::concat!(::core::module_path!(), "::", ::core::stringify!($name)),
325 $parent,
326 $module,
327 || ::std::boxed::Box::pin($setup),
328 );
329 };
330}
331
332#[doc(hidden)]
333#[macro_export]
334macro_rules! __fixture_register {
335 ($name:ident) => {
336 const _: () = {
337 #[$crate::testing::__private::linkme::distributed_slice(
338 $crate::testing::__private::FIXTURES
339 )]
340 #[linkme(crate = $crate::testing::__private::linkme)]
341 static FIXTURE: &$crate::testing::Fixture = &$name;
342 };
343 };
344}