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};
pub type SetupFn = fn() -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send>>;
pub struct Fixture {
name: &'static str,
parent: Option<&'static Fixture>,
module: Option<&'static str>,
setup: SetupFn,
built: OnceCell<Result<(), Error>>,
}
impl Fixture {
pub const fn new(name: &'static str, setup: SetupFn) -> Self {
Self::__declare(name, None, None, setup)
}
pub const fn extending(parent: &'static Fixture, name: &'static str, setup: SetupFn) -> Self {
Self::__declare(name, Some(parent), None, setup)
}
#[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(),
}
}
pub const fn name(&self) -> &'static str {
self.name
}
pub(super) fn module(&self) -> Option<&'static str> {
self.module
}
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))
}
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 {
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`",
)
})?;
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,
};
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);
}
}
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),
)
}
}
pub fn without_fixture() -> Result<(), Error> {
match active()? {
Some(scope) => scope.choose(None),
None => Ok(()),
}
}
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"))
}
#[linkme::distributed_slice]
pub static FIXTURES: [&'static Fixture];
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))
}
#[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;
};
};
}