mod fixture;
pub use fixture::{without_fixture, Fixture, SetupFn};
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::future::{poll_fn, Future};
use std::marker::PhantomData;
use std::pin::pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, Weak};
use encore_sdk_core::objects;
use encore_sdk_core::postgres::{Access, Pool};
use encore_sdk_core::pubsub;
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> {
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 fn set_secret(secret: &impl secrets::AnySecret, value: impl AsRef<[u8]>) -> Result<(), Error> {
match active()? {
Some(test) => {
test.secrets
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(secrets::key_of(secret), value.as_ref().into());
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: &impl config::AnyConfig<T>,
value: serde_json::Value,
) -> Result<(), Error> {
match active()? {
Some(test) => {
let value = config::test_value(config, value)?;
test.configs
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(config::key_of(config), value);
Ok(())
}
None => Err(Error::new(
ErrCode::FailedPrecondition,
"there is no current test: the process is not running under `encore test`",
)),
}
}
#[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) {
if encore_sdk_core::test_mode::test_mode_app_ref().is_none() {
return;
}
let loaded = match fixture {
FixtureArg::Module => match fixture::for_module(info.module, true) {
Some(fixture) => fixture.load().await,
None => Ok(()),
},
FixtureArg::Named(fixture) => fixture.load().await,
FixtureArg::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) {
let scope = Scope::new();
let _ = scope.module.set((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,
test: F,
) -> R {
let (scope, _end) = begin(&info);
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);
runtime.block_on(async {
load_fixture(&info, fixture).await;
test.await
})
}
pub fn run_sync<R, F: FnOnce() -> R>(info: TestInfo, fixture: FixtureArg, test: F) -> R {
let (_scope, _end) = begin(&info);
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));
test()
}
}
pub(crate) struct Scope {
instance_id: String,
name: OnceLock<String>,
module: OnceLock<(String, bool)>,
fixture: Mutex<Choice>,
databases: Mutex<HashMap<&'static str, Arc<Pool>>>,
buckets: Mutex<HashSet<&'static str>>,
redis: Mutex<HashMap<&'static str, Arc<encore_sdk_core::cache::Client>>>,
published: Mutex<HashMap<&'static str, Vec<Published>>>,
secrets: Mutex<HashMap<SecretKey, Arc<[u8]>>>,
configs: Mutex<HashMap<ConfigKey, Arc<dyn std::any::Any + Send + Sync>>>,
}
type SecretKey = (secrets::Scope, &'static str);
type ConfigKey = (config::Scope, &'static str);
#[derive(Clone)]
pub(crate) struct Published {
pub(crate) id: String,
pub(crate) payload: Vec<u8>,
pub(crate) attributes: HashMap<String, String>,
pub(crate) ordering_key: Option<String>,
pub(crate) publish_time: std::time::SystemTime,
}
#[derive(Clone, Copy)]
pub(crate) enum Choice {
Unset,
None,
Fixture(&'static Fixture),
}
impl Choice {
fn is(self, other: Choice) -> bool {
match (self, other) {
(Choice::Unset, Choice::Unset) | (Choice::None, Choice::None) => true,
(Choice::Fixture(a), Choice::Fixture(b)) => std::ptr::eq(a, b),
_ => false,
}
}
}
impl Scope {
fn new() -> Arc<Self> {
static NEXT: AtomicU64 = AtomicU64::new(0);
Arc::new(Self {
instance_id: format!(
"t{:x}x{:x}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
),
name: OnceLock::new(),
module: OnceLock::new(),
fixture: Mutex::new(Choice::Unset),
databases: Mutex::new(HashMap::new()),
buckets: Mutex::new(HashSet::new()),
redis: Mutex::new(HashMap::new()),
published: Mutex::new(HashMap::new()),
secrets: Mutex::new(HashMap::new()),
configs: Mutex::new(HashMap::new()),
})
}
pub(crate) fn choose(&self, choice: Choice) -> Result<(), Error> {
let mut current = self.fixture.lock().unwrap_or_else(|e| e.into_inner());
if current.is(choice) {
return Ok(());
}
let used = !self
.databases
.lock()
.unwrap_or_else(|e| e.into_inner())
.is_empty()
|| !self
.buckets
.lock()
.unwrap_or_else(|e| e.into_inner())
.is_empty()
|| !self
.redis
.lock()
.unwrap_or_else(|e| e.into_inner())
.is_empty();
if used {
return Err(Error::new(
ErrCode::FailedPrecondition,
"the test has already used a resource, so what it starts from can no longer \
change: load the fixture before the test first uses one",
));
}
*current = choice;
Ok(())
}
fn fixture_name(&self) -> Result<&'static str, Error> {
let mut choice = self.fixture.lock().unwrap_or_else(|e| e.into_inner());
if let Choice::Unset = *choice {
if let Some((module, full)) = self.module.get() {
if let Some(fixture) = fixture::for_module(module, *full) {
return Err(Error::new(
ErrCode::FailedPrecondition,
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()
),
));
}
}
*choice = Choice::None;
}
Ok(match *choice {
Choice::Fixture(fixture) => fixture.name(),
Choice::None | Choice::Unset => "",
})
}
fn forget(&self) {
self.databases
.lock()
.unwrap_or_else(|e| e.into_inner())
.clear();
self.buckets
.lock()
.unwrap_or_else(|e| e.into_inner())
.clear();
self.redis.lock().unwrap_or_else(|e| e.into_inner()).clear();
}
pub(crate) fn secret(&self, scope: secrets::Scope, name: &'static str) -> Option<Arc<[u8]>> {
self.secrets
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&(scope, name))
.cloned()
}
pub(crate) fn config(
&self,
scope: config::Scope,
name: &'static str,
) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
self.configs
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&(scope, name))
.cloned()
}
pub(crate) fn topic(&self, name: &'static str) -> Result<pubsub::TopicObj, Error> {
let topic = core()
.pubsub()
.topic_instance(name.into(), &self.instance_id)
.ok_or_else(|| {
Error::unavailable(format!("could not provision the test's topic {name:?}"))
})?;
self.published
.lock()
.unwrap_or_else(|e| e.into_inner())
.entry(name)
.or_default();
Ok(topic)
}
pub(crate) fn note_published(&self, name: &'static str, message: Published) {
self.published
.lock()
.unwrap_or_else(|e| e.into_inner())
.entry(name)
.or_default()
.push(message);
}
pub(crate) fn published(&self, name: &str) -> Vec<Published> {
self.published
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(name)
.cloned()
.unwrap_or_default()
}
pub(crate) fn bucket(&self, name: &'static str) -> Result<objects::Bucket, Error> {
let mut buckets = self.buckets.lock().unwrap_or_else(|e| e.into_inner());
let fixture = if buckets.contains(name) {
""
} else {
self.fixture_name()?
};
let bucket = core()
.objects()
.try_bucket_instance_from(name.into(), &self.instance_id, fixture)
.map_err(|e| Error::wrap(ErrCode::Unavailable, format!("{e:#}")))?;
buckets.insert(name);
Ok(bucket)
}
pub(crate) fn database_pool(&self, name: &'static str) -> Result<Arc<Pool>, Error> {
let mut databases = self.databases.lock().unwrap_or_else(|e| e.into_inner());
if let Some(pool) = databases.get(name) {
return Ok(pool.clone());
}
let fixture = self.fixture_name()?;
let pool = core()
.postgres()
.try_database_instance_from(&name.into(), &self.instance_id, fixture)
.and_then(|db| db.new_pool())
.map_err(|e| Error::wrap(ErrCode::Unavailable, format!("{e:#}")))?;
let pool = Arc::new(pool);
databases.insert(name, pool.clone());
Ok(pool)
}
pub(crate) fn redis_client(
&self,
name: &'static str,
) -> Result<Arc<encore_sdk_core::cache::Client>, Error> {
let mut clients = self.redis.lock().unwrap_or_else(|e| e.into_inner());
if let Some(client) = clients.get(name) {
return Ok(client.clone());
}
let fixture = self.fixture_name()?;
let client = core()
.cache()
.cluster_instance_from(&name.into(), &self.instance_id, fixture)
.client()
.map_err(|e| Error::wrap(ErrCode::Unavailable, format!("{e:#}")))?;
let client = Arc::new(client);
clients.insert(name, client.clone());
Ok(client)
}
pub(crate) fn database_connection_string(
&self,
name: &'static str,
access: Access,
) -> Result<String, Error> {
self.database_pool(name)?;
core()
.postgres()
.try_database_instance(&name.into(), &self.instance_id)
.map(|db| db.proxy_conn_string(access))
.map_err(|e| Error::wrap(ErrCode::Unavailable, format!("{e:#}")))
}
}
impl Drop for Scope {
fn drop(&mut self) {
let databases = std::mem::take(self.databases.get_mut().unwrap_or_else(|e| e.into_inner()));
let names: Vec<&'static str> = databases.keys().copied().collect();
drop(databases);
for name in names {
core()
.postgres()
.release_instance(&name.into(), &self.instance_id);
}
let topics = std::mem::take(self.published.get_mut().unwrap_or_else(|e| e.into_inner()));
for name in topics.into_keys() {
core()
.pubsub()
.release_topic_instance(&name.into(), &self.instance_id);
}
let redis = std::mem::take(self.redis.get_mut().unwrap_or_else(|e| e.into_inner()));
let names: Vec<&'static str> = redis.keys().copied().collect();
drop(redis);
for name in names {
core()
.cache()
.release_instance(&name.into(), &self.instance_id);
}
let buckets = std::mem::take(self.buckets.get_mut().unwrap_or_else(|e| e.into_inner()));
for name in buckets {
core()
.objects()
.release_instance(&name.into(), &self.instance_id);
}
}
}
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 active() -> Result<Option<Arc<Scope>>, Error> {
if !core().postgres().isolates_instances() {
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))
}
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);
let _ = scope.module.set((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::*;
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,
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"
);
}
#[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 what_a_test_starts_from_is_settled_at_first_use() {
let scope = Scope::new();
scope.choose(Choice::Fixture(&billing::EXTRA)).unwrap();
scope.choose(Choice::Fixture(&billing::SEEDED)).unwrap();
assert_eq!(scope.fixture_name().unwrap(), billing::SEEDED.name());
let unsaid = Scope::new();
let _ = unsaid
.module
.set(("testing::tests::billing".to_string(), false));
let err = unsaid.fixture_name().unwrap_err();
assert!(err.message.contains("has not loaded it"), "{err}");
unsaid.choose(Choice::None).unwrap();
assert_eq!(unsaid.fixture_name().unwrap(), "");
let plain = Scope::new();
let _ = plain.module.set(("testing::tests".to_string(), false));
assert_eq!(plain.fixture_name().unwrap(), "");
}
#[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());
}
}