#[cfg(feature = "chromiumoxide")]
pub mod chromiumoxide;
mod fixture;
pub mod system;
pub use fixture::{without_fixture, Fixture, SetupFn};
use std::cell::RefCell;
use std::collections::HashMap;
use std::future::{poll_fn, Future};
use std::marker::PhantomData;
use std::pin::pin;
use std::sync::{Arc, Mutex, OnceLock, Weak};
use encore_sdk_core::objects;
use encore_sdk_core::postgres::{Access, Pool};
use encore_sdk_core::test_scope::{self, FixtureChoiceError, TestScope as CoreScope};
use tokio::runtime::{Handle, Id, RuntimeFlavor};
use crate::config;
use crate::error::{ErrCode, Error};
use crate::runtime::core;
use crate::secrets;
pub fn current() -> Result<TestScope, Error> {
match active()? {
Some(scope) => Ok(TestScope { scope }),
None => Err(Error::new(
ErrCode::FailedPrecondition,
"there is no current test: the process is not running under `encore test`",
)),
}
}
pub fn published<T, E: crate::pubsub::Encoding<T>, O>(
topic: &crate::pubsub::Topic<T, E, O>,
) -> Result<Vec<crate::pubsub::Message<T>>, Error> {
if core().system_test().is_some() {
return Err(Error::new(
ErrCode::Unimplemented,
"what a system test published is sent, and is not kept by the test: read what \
the app did with it instead, once it has `settled`",
));
}
match active()? {
Some(test) => topic.published_in(&test),
None => Err(Error::new(
ErrCode::FailedPrecondition,
"there is no current test: the process is not running under `encore test`",
)),
}
}
pub async fn deliver<T: Send + 'static>(
subscription: &'static crate::pubsub::Subscription<T>,
) -> Result<usize, Error> {
if core().system_test().is_some() {
return Err(Error::new(
ErrCode::FailedPrecondition,
"subscriptions run on their own in a system test, in the services that declare \
them: wait for them to have handled what was published with \
`encore::testing::system::settled`",
));
}
match active()? {
Some(test) => subscription.deliver_in(&test).await,
None => Err(Error::new(
ErrCode::FailedPrecondition,
"there is no current test: the process is not running under `encore test`",
)),
}
}
pub fn set_secret<T: secrets::SecretValue>(
secret: &secrets::Secret<T>,
value: impl AsRef<[u8]>,
) -> Result<(), Error> {
if core().system_test().is_some() {
return Err(Error::new(
ErrCode::FailedPrecondition,
SECRET_IN_SYSTEM_TEST,
));
}
match active()? {
Some(test) => {
test.core_scope()?.set_secret(secret.name(), value.as_ref());
Ok(())
}
None => Err(Error::new(
ErrCode::FailedPrecondition,
"there is no current test: the process is not running under `encore test`",
)),
}
}
pub fn set_config<T: config::ConfigType>(
config: &config::Config<T>,
value: impl serde::Serialize,
) -> Result<(), Error> {
if core().system_test().is_some() {
return Err(Error::new(
ErrCode::FailedPrecondition,
CONFIG_IN_SYSTEM_TEST,
));
}
match active()? {
Some(test) => {
let name = config.key();
let mut value = serde_json::to_value(value).map_err(|err| {
Error::invalid_argument(format!("the value for config {name:?} is not JSON: {err}"))
})?;
config_form(&mut value);
let value = test
.core_scope()?
.set_config(name, value)
.map_err(|errors| {
Error::invalid_argument(format!(
"the value for config {name:?} does not satisfy its schema: {}",
errors.join("; ")
))
})?;
let value = config::test_value::<T>(name, value)?;
test.configs
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(name, value);
Ok(())
}
None => Err(Error::new(
ErrCode::FailedPrecondition,
"there is no current test: the process is not running under `encore test`",
)),
}
}
fn config_form(value: &mut serde_json::Value) {
match value {
serde_json::Value::Object(fields) => {
fields.retain(|_, field| !field.is_null() && !is_secret_placeholder(field));
fields.values_mut().for_each(config_form);
}
serde_json::Value::Array(items) => items.iter_mut().for_each(config_form),
_ => {}
}
}
fn is_secret_placeholder(value: &serde_json::Value) -> bool {
value.as_object().is_some_and(|fields| {
fields.len() == 1
&& fields
.get(encore_sdk_core::config::PLACEHOLDER_KEY)
.is_some_and(serde_json::Value::is_string)
})
}
const SECRET_IN_SYSTEM_TEST: &str = "a system test can't give a secret a value of its own: the \
services it calls read theirs, not the test's. Give the secret its value for tests in \
secrets.test.toml";
const CONFIG_IN_SYSTEM_TEST: &str = "a system test can't give a config a value of its own: the \
services it calls read theirs, not the test's. Give the config its value for tests in its \
`test` config file (<name>.test.config.toml)";
#[derive(Clone)]
pub struct TestScope {
scope: Arc<Scope>,
}
impl TestScope {
pub fn enter(&self) -> ScopeGuard<'_> {
THREAD.with(|thread| thread.borrow_mut().entered.push(self.scope.clone()));
ScopeGuard {
_scope: PhantomData,
_not_send: PhantomData,
}
}
pub async fn scope<F: Future>(&self, future: F) -> F::Output {
let mut future = pin!(future);
poll_fn(|cx| {
let _guard = self.enter();
future.as_mut().poll(cx)
})
.await
}
pub fn name(&self) -> Option<&str> {
self.scope.name.get().map(String::as_str)
}
}
pub struct ScopeGuard<'a> {
_scope: PhantomData<&'a TestScope>,
_not_send: PhantomData<*const ()>,
}
impl Drop for ScopeGuard<'_> {
fn drop(&mut self) {
THREAD.with(|thread| thread.borrow_mut().entered.pop());
}
}
#[doc(hidden)]
pub mod __private {
use super::*;
pub struct TestInfo {
pub module: &'static str,
pub name: &'static str,
pub file: &'static str,
pub line: u32,
}
pub use super::fixture::FIXTURES;
pub use linkme;
pub struct RuntimeConfig {
pub multi_thread: bool,
pub worker_threads: Option<usize>,
}
pub enum FixtureArg {
Module,
Named(&'static Fixture),
None,
}
async fn load_fixture(info: &TestInfo, fixture: FixtureArg) {
let choice = match fixture {
FixtureArg::Module => fixture::for_module(info.module, true).map(Some),
FixtureArg::Named(fixture) => Some(Some(fixture)),
FixtureArg::None => Some(None),
};
let Some(choice) = choice else {
return;
};
if core().test_scopes().is_none() {
return;
}
let loaded = match choice {
Some(fixture) => fixture.load().await,
None => without_fixture(),
};
if let Err(err) = loaded {
panic!("{}", err.message);
}
}
pub(in crate::testing) struct EndTest;
impl Drop for EndTest {
fn drop(&mut self) {
THREAD.with(|thread| thread.borrow_mut().own = None);
}
}
fn begin(info: &TestInfo) -> (Arc<Scope>, EndTest) {
BEGUN.store(true, std::sync::atomic::Ordering::Relaxed);
let scope = Scope::new();
scope.set_module(info.module.to_string(), true);
let module = info.module.split_once("::").map_or("", |(_, rest)| rest);
let name = if module.is_empty() {
info.name.to_string()
} else {
format!("{module}::{}", info.name)
};
let _ = scope.name.set(name);
THREAD.with(|thread| thread.borrow_mut().own = Some(scope.clone()));
(scope, EndTest)
}
pub fn run<R, F: Future<Output = R>>(
info: TestInfo,
config: RuntimeConfig,
fixture: FixtureArg,
failed: fn(&R) -> bool,
test: F,
) -> R {
let (scope, _end) = begin(&info);
let reported = system::Reported::new(scope.clone());
let mut builder = if config.multi_thread {
tokio::runtime::Builder::new_multi_thread()
} else {
tokio::runtime::Builder::new_current_thread()
};
if let Some(threads) = config.worker_threads {
builder.worker_threads(threads);
}
let runtime = builder
.enable_all()
.build()
.expect("failed to build the test's Tokio runtime");
with_runtimes(|runtimes| link(runtimes, runtime.handle().id(), &scope));
drop(scope);
let result = runtime.block_on(async {
load_fixture(&info, fixture).await;
test.await
});
reported.ended(failed(&result));
result
}
pub struct Probe<'a, R>(pub &'a R);
pub trait FailedIfErr {
fn failed(&self) -> bool;
}
impl<T, E> FailedIfErr for Probe<'_, Result<T, E>> {
fn failed(&self) -> bool {
self.0.is_err()
}
}
pub trait NeverFailed {
fn failed(&self) -> bool;
}
impl<R> NeverFailed for &Probe<'_, R> {
fn failed(&self) -> bool {
false
}
}
pub fn run_sync<R, F: FnOnce() -> R>(
info: TestInfo,
fixture: FixtureArg,
failed: fn(&R) -> bool,
test: F,
) -> R {
let (scope, _end) = begin(&info);
let reported = system::Reported::new(scope);
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("failed to build a Tokio runtime to load the test's fixture")
.block_on(load_fixture(&info, fixture));
let result = test();
reported.ended(failed(&result));
result
}
}
pub(crate) struct Scope {
name: OnceLock<String>,
module: OnceLock<(String, bool)>,
core: OnceLock<Arc<CoreScope>>,
configs: Mutex<HashMap<ConfigKey, Arc<dyn std::any::Any + Send + Sync>>>,
}
type ConfigKey = &'static str;
impl Scope {
fn new() -> Arc<Self> {
Arc::new(Self {
name: OnceLock::new(),
module: OnceLock::new(),
core: OnceLock::new(),
configs: Mutex::new(HashMap::new()),
})
}
fn building(core: Arc<CoreScope>, name: String) -> Arc<Self> {
let scope = Self::new();
let _ = scope.name.set(name);
let _ = scope.core.set(core);
scope
}
pub(crate) fn core_scope(&self) -> Result<&Arc<CoreScope>, Error> {
if let Some(scope) = self.core.get() {
return Ok(scope);
}
let scopes = core().test_scopes().ok_or_else(|| {
Error::new(
ErrCode::FailedPrecondition,
"there is no current test: the process is not running under `encore test`",
)
})?;
let scope = self
.core
.get_or_init(|| scopes.begin(self.name.get().map(String::as_str)));
self.require_module_fixture();
Ok(scope)
}
fn set_module(&self, module: String, full: bool) {
let _ = self.module.set((module, full));
self.require_module_fixture();
}
fn require_module_fixture(&self) {
let (Some(core), Some((module, full))) = (self.core.get(), self.module.get()) else {
return;
};
if let Some(reason) = unloaded_module_fixture(module, *full) {
core.require_use_fixture(reason);
}
}
pub(crate) fn choose(&self, fixture: Option<&'static Fixture>) -> Result<(), Error> {
self.core_scope()?
.use_fixture(fixture.map(Fixture::name))
.map_err(infra_err)
}
pub(crate) fn secret(&self, name: &str) -> Option<Arc<[u8]>> {
self.core.get()?.secret(name)
}
pub(crate) fn config(
&self,
name: &'static str,
) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
self.configs
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(name)
.cloned()
}
pub(crate) fn published(&self, name: &str) -> Vec<test_scope::Published> {
self.core
.get()
.map(|core| core.published(name))
.unwrap_or_default()
}
pub(crate) fn bucket(&self, name: &'static str) -> Result<objects::Bucket, Error> {
self.core_scope()?.bucket(&name.into()).map_err(infra_err)
}
pub(crate) fn database_pool(&self, name: &'static str) -> Result<Arc<Pool>, Error> {
self.core_scope()?.database(&name.into()).map_err(infra_err)
}
pub(crate) fn clickhouse_database(
&self,
name: &'static str,
) -> Result<Arc<encore_sdk_core::clickhouse::Database>, Error> {
self.core_scope()?
.clickhouse(&name.into())
.map_err(infra_err)
}
pub(crate) fn redis_client(
&self,
name: &'static str,
) -> Result<Arc<encore_sdk_core::cache::Client>, Error> {
self.core_scope()?.redis(&name.into()).map_err(infra_err)
}
pub(crate) fn database_connection_string(
&self,
name: &'static str,
access: Access,
) -> Result<String, Error> {
self.core_scope()?
.connection_string(&name.into(), access)
.map_err(infra_err)
}
}
fn unloaded_module_fixture(module: &str, full: bool) -> Option<String> {
let fixture = fixture::for_module(module, full)?;
Some(format!(
"this test is in a module whose tests start from the fixture {:?}, but has not \
loaded it. Make it an `#[encore::test]`, which does, or call `.load().await?` on the \
fixture — or `encore::testing::without_fixture()?` — before the test first uses a \
resource",
fixture.name()
))
}
fn infra_err(err: anyhow::Error) -> Error {
if err.downcast_ref::<FixtureChoiceError>().is_some() {
Error::new(ErrCode::FailedPrecondition, err.to_string())
} else {
Error::wrap(ErrCode::Unavailable, format!("{err:#}"))
}
}
fn run_in_scope<R>(scope: Arc<Scope>, work: impl Future<Output = R>) -> R {
THREAD.with(|thread| thread.borrow_mut().own = Some(scope.clone()));
let _end = __private::EndTest;
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("failed to build a Tokio runtime");
with_runtimes(|runtimes| link(runtimes, runtime.handle().id(), &scope));
drop(scope);
runtime.block_on(work)
}
pub(crate) fn outgoing(
cx: &encore_sdk_core::telemetry::opentelemetry::Context,
) -> encore_sdk_core::telemetry::opentelemetry::Context {
if core().system_test().is_none() {
return cx.clone();
}
let Ok(Some(test)) = active() else {
return cx.clone();
};
match test.core_scope() {
Ok(scope) => scope.outgoing_context(cx),
Err(_) => cx.clone(),
}
}
pub(crate) fn active() -> Result<Option<Arc<Scope>>, Error> {
if core().test_scopes().is_none() {
return Ok(None);
}
resolve().map(Some)
}
#[derive(Default)]
struct ThreadScopes {
own: Option<Arc<Scope>>,
joined: Vec<Arc<Scope>>,
entered: Vec<Arc<Scope>>,
}
thread_local! {
static THREAD: RefCell<ThreadScopes> = RefCell::new(ThreadScopes::default());
}
enum Link {
Test(Weak<Scope>),
Shared,
}
static RUNTIMES: Mutex<Option<HashMap<Id, Link>>> = Mutex::new(None);
fn with_runtimes<T>(f: impl FnOnce(&mut HashMap<Id, Link>) -> T) -> T {
let mut runtimes = RUNTIMES.lock().unwrap_or_else(|e| e.into_inner());
f(runtimes.get_or_insert_with(HashMap::new))
}
static BEGUN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub(crate) fn runner_detected() -> bool {
BEGUN.load(std::sync::atomic::Ordering::Relaxed)
|| std::env::var_os("NEXTEST").is_some()
|| test_name(std::thread::current().name()).is_some()
}
fn test_name(thread: Option<&str>) -> Option<&str> {
thread.filter(|name| *name != "main" && !name.starts_with("tokio-"))
}
fn resolve() -> Result<Arc<Scope>, Error> {
let handle = Handle::try_current().ok();
let runtime = handle.as_ref().map(Handle::id);
let thread = std::thread::current();
THREAD.with(|state| {
let mut state = state.borrow_mut();
if let Some(scope) = state.entered.last() {
return Ok(scope.clone());
}
if let Some(scope) = &state.own {
let scope = scope.clone();
if let Some(id) = runtime {
with_runtimes(|runtimes| link(runtimes, id, &scope));
}
return Ok(scope);
}
if let Some(name) = test_name(thread.name()) {
let scope = match &state.own {
Some(scope) => scope.clone(),
None => {
let scope = runtime
.and_then(|id| {
with_runtimes(|runtimes| match runtimes.get(&id) {
Some(Link::Test(scope)) => {
scope.upgrade().filter(|scope| scope.name.get().is_none())
}
_ => None,
})
})
.unwrap_or_else(Scope::new);
let _ = scope.name.set(name.to_string());
let module = name.rsplit_once("::").map_or("", |(module, _)| module);
scope.set_module(module.to_string(), false);
state.own = Some(scope.clone());
scope
}
};
if let Some(id) = runtime {
with_runtimes(|runtimes| link(runtimes, id, &scope));
}
return Ok(scope);
}
let Some(id) = runtime else {
return Err(not_a_test_thread(thread.name()));
};
let scope = with_runtimes(|runtimes| {
match runtimes.get(&id) {
Some(Link::Shared) => return Err(shared_runtime(thread.name())),
Some(Link::Test(scope)) => {
if let Some(scope) = scope.upgrade() {
return Ok(scope);
}
}
None => {}
}
let multi_thread = handle
.as_ref()
.is_some_and(|handle| handle.runtime_flavor() != RuntimeFlavor::CurrentThread);
if !multi_thread {
return Err(not_a_test_thread(thread.name()));
}
let scope = Scope::new();
link(runtimes, id, &scope);
Ok(scope)
})?;
if !state
.joined
.iter()
.any(|joined| Arc::ptr_eq(joined, &scope))
{
state.joined.push(scope.clone());
}
Ok(scope)
})
}
fn link(runtimes: &mut HashMap<Id, Link>, id: Id, scope: &Arc<Scope>) {
let shared = match runtimes.get(&id) {
Some(Link::Shared) => true,
Some(Link::Test(current)) => current
.upgrade()
.is_some_and(|current| !Arc::ptr_eq(¤t, scope)),
None => false,
};
if !shared {
runtimes.retain(|_, link| match link {
Link::Test(scope) => scope.strong_count() > 0,
Link::Shared => true,
});
}
let link = if shared {
Link::Shared
} else {
Link::Test(Arc::downgrade(scope))
};
runtimes.insert(id, link);
}
fn thread_label(name: Option<&str>) -> String {
match name {
Some(name) => format!("thread {name:?}"),
None => "an unnamed thread".to_string(),
}
}
fn not_a_test_thread(thread: Option<&str>) -> Error {
Error::new(
ErrCode::FailedPrecondition,
format!(
"an Encore resource was used on {}, which Encore cannot link to a running test. \
Each test gets infrastructure of its own, so Encore needs to know which test \
this thread belongs to.\n\n\
In the test, capture the scope and enter it on the new thread:\n\n \
let scope = encore::testing::current()?;\n \
std::thread::spawn(move || {{\n \
let _guard = scope.enter();\n \
…\n \
}});",
thread_label(thread)
),
)
}
fn shared_runtime(thread: Option<&str>) -> Error {
Error::new(
ErrCode::FailedPrecondition,
format!(
"an Encore resource was used on {}, in a Tokio runtime that several tests share, \
so Encore cannot tell which test it belongs to. Each test gets infrastructure of \
its own.\n\n\
Run the work as part of its test:\n\n \
let scope = encore::testing::current()?;\n \
runtime.spawn(async move {{ scope.scope(work()).await }});",
thread_label(thread)
),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_typed_config_value_is_given_in_its_files_form() {
#[derive(serde::Serialize)]
struct Limits {
max: u32,
timeout: config::Duration,
key: secrets::Secret,
note: Option<String>,
tiers: Vec<Tier>,
}
#[derive(serde::Serialize)]
struct Tier {
name: &'static str,
key: secrets::Secret,
}
let mut value = serde_json::to_value(Limits {
max: 5,
timeout: config::Duration(std::time::Duration::from_millis(1500)),
key: secrets::Secret::new("StripeKey"),
note: None,
tiers: vec![Tier {
name: "gold",
key: secrets::Secret::new("GoldKey"),
}],
})
.unwrap();
config_form(&mut value);
assert_eq!(
value,
serde_json::json!({
"max": 5,
"timeout": "1500000us",
"tiers": [{"name": "gold"}],
})
);
assert_eq!(
config::parse_duration("1500000us"),
Some(std::time::Duration::from_millis(1500))
);
}
fn here() -> Result<(Option<String>, usize), String> {
resolve()
.map(|scope| (scope.name.get().cloned(), Arc::as_ptr(&scope) as usize))
.map_err(|err| err.message)
}
#[test]
fn a_test_thread_is_its_test() {
let (name, id) = here().unwrap();
assert_eq!(
name.as_deref(),
Some("testing::tests::a_test_thread_is_its_test")
);
assert_eq!(here().unwrap().1, id);
}
#[test]
fn a_thread_the_test_starts_is_not_part_of_it_until_it_enters() {
let (_, id) = here().unwrap();
let scope = TestScope {
scope: resolve().unwrap(),
};
let err = std::thread::spawn(here).join().unwrap().unwrap_err();
assert!(err.contains("an unnamed thread"), "{err}");
assert!(err.contains("scope.enter()"), "{err}");
let entered = std::thread::spawn(move || {
let inside = {
let _guard = scope.enter();
here()
};
(inside, here())
})
.join()
.unwrap();
assert_eq!(entered.0.unwrap().1, id);
assert!(entered.1.is_err());
}
#[tokio::test]
async fn a_current_thread_runtime_is_its_test() {
let (name, id) = here().unwrap();
assert!(name.is_some());
assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
assert_eq!(
tokio::task::spawn_blocking(here).await.unwrap().unwrap().1,
id
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_multi_thread_runtime_is_its_test() {
let (_, id) = here().unwrap();
for _ in 0..8 {
assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
}
assert_eq!(
tokio::task::spawn_blocking(here).await.unwrap().unwrap().1,
id
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_test_adopts_what_its_runtime_started() {
let (name, id) = tokio::spawn(async { here() }).await.unwrap().unwrap();
assert_eq!(name, None);
let (name, adopted) = here().unwrap();
assert_eq!(adopted, id);
assert!(name
.unwrap()
.ends_with("a_test_adopts_what_its_runtime_started"));
let (name, again) = tokio::spawn(async { here() }).await.unwrap().unwrap();
assert_eq!(again, id);
assert!(name.is_some());
}
#[test]
fn tests_sharing_a_runtime_make_its_workers_ambiguous() {
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.build()
.unwrap();
let handle = runtime.handle().clone();
let (ready_tx, ready_rx) = std::sync::mpsc::channel();
let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
let first = std::thread::Builder::new()
.name("tests::first".to_string())
.spawn({
let handle = handle.clone();
move || {
let _enter = handle.enter();
let id = here().unwrap().1;
ready_tx.send(id).unwrap();
let _ = done_rx.recv();
}
})
.unwrap();
let first_id = ready_rx.recv().unwrap();
let second_id = std::thread::Builder::new()
.name("tests::second".to_string())
.spawn({
let handle = handle.clone();
move || {
let _enter = handle.enter();
here().unwrap().1
}
})
.unwrap()
.join()
.unwrap();
assert_ne!(first_id, second_id);
let err = runtime.block_on(async { tokio::spawn(async { here() }).await.unwrap() });
let err = err.unwrap_err();
assert!(err.contains("several tests share"), "{err}");
assert!(err.contains("scope.scope("), "{err}");
done_tx.send(()).unwrap();
first.join().unwrap();
}
#[tokio::test]
async fn a_future_runs_as_part_of_the_test_it_is_scoped_to() {
let (_, id) = here().unwrap();
let scope = TestScope {
scope: resolve().unwrap(),
};
assert!(scope.name().unwrap().ends_with("it_is_scoped_to"));
let other = std::thread::spawn(move || {
tokio::runtime::Builder::new_current_thread()
.build()
.unwrap()
.block_on(async {
let outside = here();
let inside = scope.scope(async { here().unwrap().1 }).await;
(outside, inside)
})
})
.join()
.unwrap();
let err = other.0.unwrap_err();
assert!(err.contains("cannot link to a running test"), "{err}");
assert_eq!(other.1, id);
}
#[encore::test]
async fn the_macro_runs_a_test_in_its_own_runtime() {
let (name, id) = here().unwrap();
assert_eq!(
name.as_deref(),
Some("testing::tests::the_macro_runs_a_test_in_its_own_runtime")
);
assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
assert_eq!(
Handle::current().runtime_flavor(),
RuntimeFlavor::CurrentThread
);
}
#[encore::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_macro_links_the_runtime_before_the_test_runs() -> Result<(), String> {
let (name, id) = tokio::spawn(async { here() }).await.unwrap()?;
assert!(name.unwrap().ends_with("before_the_test_runs"));
assert_eq!(here()?.1, id);
assert_eq!(Handle::current().metrics().num_workers(), 2);
Ok(())
}
#[encore::test]
#[should_panic(expected = "as any test")]
async fn the_macro_keeps_the_tests_other_attributes() {
panic!("as any test");
}
#[encore::test]
fn the_macro_takes_a_test_that_is_not_async() {
let (name, _) = here().unwrap();
assert!(name.unwrap().ends_with("is_not_async"));
}
#[test]
fn the_macro_ends_the_test_when_it_returns() {
let weak = std::thread::spawn(|| {
let weak = __private::run(
__private::TestInfo {
module: "app::tests",
name: "returns",
file: file!(),
line: line!(),
},
__private::RuntimeConfig {
multi_thread: true,
worker_threads: Some(1),
},
__private::FixtureArg::Module,
|_| false,
async {
tokio::spawn(async { here().unwrap() }).await.unwrap();
Arc::downgrade(&resolve().unwrap())
},
);
assert!(weak.upgrade().is_none());
assert!(here().is_err());
})
.join();
weak.unwrap();
}
mod billing {
crate::fixture! {
pub static SEEDED for mod = async { Ok(()) };
pub static EXTRA: SEEDED = async { Ok(()) };
}
pub mod invoices {
crate::fixture! {
pub static INVOICED for mod: super::SEEDED = async { Ok(()) };
}
}
}
#[test]
fn a_fixture_is_named_after_where_it_is_declared() {
assert_eq!(
billing::SEEDED.name(),
"encore::testing::tests::billing::SEEDED"
);
assert_eq!(
billing::invoices::INVOICED.name(),
"encore::testing::tests::billing::invoices::INVOICED"
);
assert_eq!(
billing::EXTRA.name(),
"encore::testing::tests::billing::EXTRA"
);
}
#[test]
fn a_modules_fixture_is_found_from_the_tests_inside_it() {
let found = |module: &str, full: bool| fixture::for_module(module, full).map(Fixture::name);
assert_eq!(
found("encore::testing::tests::billing", true),
Some(billing::SEEDED.name())
);
assert_eq!(
found("encore::testing::tests::billing::reports::monthly", true),
Some(billing::SEEDED.name())
);
assert_eq!(
found("encore::testing::tests::billing::invoices", true),
Some(billing::invoices::INVOICED.name())
);
assert_eq!(
found("testing::tests::billing::invoices::overdue", false),
Some(billing::invoices::INVOICED.name())
);
assert_eq!(found("encore::testing::tests::billing_reports", true), None);
assert_eq!(found("encore::testing::tests", true), None);
assert_eq!(found("testing::tests", false), None);
}
#[test]
fn a_test_in_a_module_with_a_fixture_has_to_say_what_it_starts_from() {
let reason = unloaded_module_fixture("testing::tests::billing::reports", false).unwrap();
assert!(reason.contains("has not loaded it"), "{reason}");
assert!(reason.contains(billing::SEEDED.name()), "{reason}");
assert!(reason.contains("without_fixture()"), "{reason}");
assert_eq!(unloaded_module_fixture("testing::tests", false), None);
}
#[test]
fn a_scope_ends_with_the_threads_that_are_part_of_it() {
let weak = std::thread::Builder::new()
.name("tests::short_lived".to_string())
.spawn(|| Arc::downgrade(&resolve().unwrap()))
.unwrap()
.join()
.unwrap();
assert!(weak.upgrade().is_none());
let scope = std::thread::Builder::new()
.name("tests::held".to_string())
.spawn(|| TestScope {
scope: resolve().unwrap(),
})
.unwrap()
.join()
.unwrap();
let weak = Arc::downgrade(&scope.scope);
assert!(weak.upgrade().is_some());
drop(scope);
assert!(weak.upgrade().is_none());
}
}