1#[cfg(feature = "chromiumoxide")]
71pub mod chromiumoxide;
72mod fixture;
73pub mod system;
74
75pub use fixture::{without_fixture, Fixture, SetupFn};
76
77use std::cell::RefCell;
78use std::collections::HashMap;
79use std::future::{poll_fn, Future};
80use std::marker::PhantomData;
81use std::pin::pin;
82use std::sync::{Arc, Mutex, OnceLock, Weak};
83
84use encore_sdk_core::objects;
85use encore_sdk_core::postgres::{Access, Pool};
86use encore_sdk_core::test_scope::{self, FixtureChoiceError, TestScope as CoreScope};
87use tokio::runtime::{Handle, Id, RuntimeFlavor};
88
89use crate::config;
90use crate::error::{ErrCode, Error};
91use crate::runtime::core;
92use crate::secrets;
93
94pub fn current() -> Result<TestScope, Error> {
99 match active()? {
100 Some(scope) => Ok(TestScope { scope }),
101 None => Err(Error::new(
102 ErrCode::FailedPrecondition,
103 "there is no current test: the process is not running under `encore test`",
104 )),
105 }
106}
107
108pub fn published<T, E: crate::pubsub::Encoding<T>, O>(
122 topic: &crate::pubsub::Topic<T, E, O>,
123) -> Result<Vec<crate::pubsub::Message<T>>, Error> {
124 if core().system_test().is_some() {
125 return Err(Error::new(
126 ErrCode::Unimplemented,
127 "messages published in a system test are delivered to services rather than \
128 buffered locally; wait for `encore::testing::system::settled` and inspect \
129 the resulting state instead",
130 ));
131 }
132 match active()? {
133 Some(test) => topic.published_in(&test),
134 None => Err(Error::new(
135 ErrCode::FailedPrecondition,
136 "there is no current test: the process is not running under `encore test`",
137 )),
138 }
139}
140
141pub async fn deliver<T: Send + 'static>(
161 subscription: &'static crate::pubsub::Subscription<T>,
162) -> Result<usize, Error> {
163 if core().system_test().is_some() {
164 return Err(Error::new(
165 ErrCode::FailedPrecondition,
166 "subscriptions run on their own in system tests inside the services that \
167 declare them; wait for delivery with `encore::testing::system::settled`",
168 ));
169 }
170 match active()? {
171 Some(test) => subscription.deliver_in(&test).await,
172 None => Err(Error::new(
173 ErrCode::FailedPrecondition,
174 "there is no current test: the process is not running under `encore test`",
175 )),
176 }
177}
178
179pub fn set_secret<T: secrets::SecretValue>(
190 secret: &secrets::Secret<T>,
191 value: impl AsRef<[u8]>,
192) -> Result<(), Error> {
193 if core().system_test().is_some() {
194 return Err(Error::new(
195 ErrCode::FailedPrecondition,
196 SECRET_IN_SYSTEM_TEST,
197 ));
198 }
199 match active()? {
200 Some(test) => {
201 test.core_scope()?.set_secret(secret.name(), value.as_ref());
203 Ok(())
204 }
205 None => Err(Error::new(
206 ErrCode::FailedPrecondition,
207 "there is no current test: the process is not running under `encore test`",
208 )),
209 }
210}
211
212pub fn set_config<T: config::ConfigType>(
231 config: &config::Config<T>,
232 value: impl serde::Serialize,
233) -> Result<(), Error> {
234 if core().system_test().is_some() {
235 return Err(Error::new(
236 ErrCode::FailedPrecondition,
237 CONFIG_IN_SYSTEM_TEST,
238 ));
239 }
240 match active()? {
241 Some(test) => {
242 let name = config.key();
243 let mut value = serde_json::to_value(value).map_err(|err| {
244 Error::invalid_argument(format!("the value for config {name:?} is not JSON: {err}"))
245 })?;
246 config_form(&mut value);
247 let value = test
248 .core_scope()?
249 .set_config(name, value)
250 .map_err(|errors| {
251 Error::invalid_argument(format!(
252 "the value for config {name:?} does not satisfy its schema: {}",
253 errors.join("; ")
254 ))
255 })?;
256 let value = config::test_value::<T>(name, value)?;
257 test.configs
258 .lock()
259 .unwrap_or_else(|e| e.into_inner())
260 .insert(name, value);
261 Ok(())
262 }
263 None => Err(Error::new(
264 ErrCode::FailedPrecondition,
265 "there is no current test: the process is not running under `encore test`",
266 )),
267 }
268}
269
270fn config_form(value: &mut serde_json::Value) {
274 match value {
275 serde_json::Value::Object(fields) => {
276 fields.retain(|_, field| !field.is_null() && !is_secret_placeholder(field));
277 fields.values_mut().for_each(config_form);
278 }
279 serde_json::Value::Array(items) => items.iter_mut().for_each(config_form),
280 _ => {}
281 }
282}
283
284fn is_secret_placeholder(value: &serde_json::Value) -> bool {
286 value.as_object().is_some_and(|fields| {
287 fields.len() == 1
288 && fields
289 .get(encore_sdk_core::config::PLACEHOLDER_KEY)
290 .is_some_and(serde_json::Value::is_string)
291 })
292}
293
294const SECRET_IN_SYSTEM_TEST: &str = "system tests cannot override secrets per test because \
296 services read their own values; configure test secrets in `secrets.test.toml` instead";
297
298const CONFIG_IN_SYSTEM_TEST: &str = "system tests cannot override config per test because \
300 services read their own values; configure test values in `<name>.test.config.toml` instead";
301
302#[derive(Clone)]
308pub struct TestScope {
309 scope: Arc<Scope>,
310}
311
312impl TestScope {
313 pub fn enter(&self) -> ScopeGuard<'_> {
315 THREAD.with(|thread| thread.borrow_mut().entered.push(self.scope.clone()));
316 ScopeGuard {
317 _scope: PhantomData,
318 _not_send: PhantomData,
319 }
320 }
321
322 pub async fn scope<F: Future>(&self, future: F) -> F::Output {
324 let mut future = pin!(future);
325 poll_fn(|cx| {
326 let _guard = self.enter();
327 future.as_mut().poll(cx)
328 })
329 .await
330 }
331
332 pub fn name(&self) -> Option<&str> {
336 self.scope.name.get().map(String::as_str)
337 }
338}
339
340pub struct ScopeGuard<'a> {
342 _scope: PhantomData<&'a TestScope>,
343 _not_send: PhantomData<*const ()>,
345}
346
347impl Drop for ScopeGuard<'_> {
348 fn drop(&mut self) {
349 THREAD.with(|thread| thread.borrow_mut().entered.pop());
350 }
351}
352
353#[doc(hidden)]
356pub mod __private {
357 use super::*;
358
359 pub struct TestInfo {
361 pub module: &'static str,
362 pub name: &'static str,
363 pub file: &'static str,
364 pub line: u32,
365 }
366
367 pub use super::fixture::FIXTURES;
368 pub use linkme;
369
370 pub struct RuntimeConfig {
372 pub multi_thread: bool,
373 pub worker_threads: Option<usize>,
374 }
375
376 pub enum FixtureArg {
378 Module,
380 Named(&'static Fixture),
381 None,
382 }
383
384 async fn load_fixture(info: &TestInfo, fixture: FixtureArg) {
387 let choice = match fixture {
389 FixtureArg::Module => fixture::for_module(info.module, true).map(Some),
390 FixtureArg::Named(fixture) => Some(Some(fixture)),
391 FixtureArg::None => Some(None),
392 };
393 let Some(choice) = choice else {
394 return;
395 };
396 if core().test_scopes().is_none() {
397 return;
398 }
399 let loaded = match choice {
400 Some(fixture) => fixture.load().await,
401 None => without_fixture(),
402 };
403 if let Err(err) = loaded {
404 panic!("{}", err.message);
405 }
406 }
407
408 pub(in crate::testing) struct EndTest;
411
412 impl Drop for EndTest {
413 fn drop(&mut self) {
414 THREAD.with(|thread| thread.borrow_mut().own = None);
415 }
416 }
417
418 fn begin(info: &TestInfo) -> (Arc<Scope>, EndTest) {
420 BEGUN.store(true, std::sync::atomic::Ordering::Relaxed);
422 let scope = Scope::new();
423 scope.set_module(info.module.to_string(), true);
424 let module = info.module.split_once("::").map_or("", |(_, rest)| rest);
426 let name = if module.is_empty() {
427 info.name.to_string()
428 } else {
429 format!("{module}::{}", info.name)
430 };
431 let _ = scope.name.set(name);
432 THREAD.with(|thread| thread.borrow_mut().own = Some(scope.clone()));
433 (scope, EndTest)
434 }
435
436 pub fn run<R, F: Future<Output = R>>(
439 info: TestInfo,
440 config: RuntimeConfig,
441 fixture: FixtureArg,
442 failed: fn(&R) -> bool,
443 test: F,
444 ) -> R {
445 let (scope, _end) = begin(&info);
447 let reported = system::Reported::new(scope.clone());
448 let mut builder = if config.multi_thread {
449 tokio::runtime::Builder::new_multi_thread()
450 } else {
451 tokio::runtime::Builder::new_current_thread()
452 };
453 if let Some(threads) = config.worker_threads {
454 builder.worker_threads(threads);
455 }
456 let runtime = builder
457 .enable_all()
458 .build()
459 .expect("failed to build the test's Tokio runtime");
460 with_runtimes(|runtimes| link(runtimes, runtime.handle().id(), &scope));
461 drop(scope);
462 let result = runtime.block_on(async {
463 load_fixture(&info, fixture).await;
464 test.await
465 });
466 reported.ended(failed(&result));
467 result
468 }
469
470 pub struct Probe<'a, R>(pub &'a R);
478
479 pub trait FailedIfErr {
480 fn failed(&self) -> bool;
481 }
482
483 impl<T, E> FailedIfErr for Probe<'_, Result<T, E>> {
484 fn failed(&self) -> bool {
485 self.0.is_err()
486 }
487 }
488
489 pub trait NeverFailed {
490 fn failed(&self) -> bool;
491 }
492
493 impl<R> NeverFailed for &Probe<'_, R> {
494 fn failed(&self) -> bool {
495 false
496 }
497 }
498
499 pub fn run_sync<R, F: FnOnce() -> R>(
501 info: TestInfo,
502 fixture: FixtureArg,
503 failed: fn(&R) -> bool,
504 test: F,
505 ) -> R {
506 let (scope, _end) = begin(&info);
507 let reported = system::Reported::new(scope);
508 tokio::runtime::Builder::new_current_thread()
510 .enable_all()
511 .build()
512 .expect("failed to build a Tokio runtime to load the test's fixture")
513 .block_on(load_fixture(&info, fixture));
514 let result = test();
515 reported.ended(failed(&result));
516 result
517 }
518}
519
520pub(crate) struct Scope {
524 name: OnceLock<String>,
525 module: OnceLock<(String, bool)>,
528 core: OnceLock<Arc<CoreScope>>,
532 configs: Mutex<HashMap<ConfigKey, Arc<dyn std::any::Any + Send + Sync>>>,
535}
536
537type ConfigKey = &'static str;
540
541impl Scope {
542 fn new() -> Arc<Self> {
543 Arc::new(Self {
544 name: OnceLock::new(),
545 module: OnceLock::new(),
546 core: OnceLock::new(),
547 configs: Mutex::new(HashMap::new()),
548 })
549 }
550
551 fn building(core: Arc<CoreScope>, name: String) -> Arc<Self> {
553 let scope = Self::new();
554 let _ = scope.name.set(name);
555 let _ = scope.core.set(core);
556 scope
557 }
558
559 pub(crate) fn core_scope(&self) -> Result<&Arc<CoreScope>, Error> {
562 if let Some(scope) = self.core.get() {
563 return Ok(scope);
564 }
565 let scopes = core().test_scopes().ok_or_else(|| {
566 Error::new(
567 ErrCode::FailedPrecondition,
568 "there is no current test: the process is not running under `encore test`",
569 )
570 })?;
571 let scope = self
572 .core
573 .get_or_init(|| scopes.begin(self.name.get().map(String::as_str)));
574 self.require_module_fixture();
575 Ok(scope)
576 }
577
578 fn set_module(&self, module: String, full: bool) {
580 let _ = self.module.set((module, full));
581 self.require_module_fixture();
582 }
583
584 fn require_module_fixture(&self) {
588 let (Some(core), Some((module, full))) = (self.core.get(), self.module.get()) else {
589 return;
590 };
591 if let Some(reason) = unloaded_module_fixture(module, *full) {
592 core.require_use_fixture(reason);
593 }
594 }
595
596 pub(crate) fn choose(&self, fixture: Option<&'static Fixture>) -> Result<(), Error> {
599 self.core_scope()?
600 .use_fixture(fixture.map(Fixture::name))
601 .map_err(infra_err)
602 }
603
604 pub(crate) fn secret(&self, name: &str) -> Option<Arc<[u8]>> {
606 self.core.get()?.secret(name)
607 }
608
609 pub(crate) fn config(
611 &self,
612 name: &'static str,
613 ) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
614 self.configs
615 .lock()
616 .unwrap_or_else(|e| e.into_inner())
617 .get(name)
618 .cloned()
619 }
620
621 pub(crate) fn published(&self, name: &str) -> Vec<test_scope::Published> {
623 self.core
624 .get()
625 .map(|core| core.published(name))
626 .unwrap_or_default()
627 }
628
629 pub(crate) fn bucket(&self, name: &'static str) -> Result<objects::Bucket, Error> {
632 self.core_scope()?.bucket(&name.into()).map_err(infra_err)
633 }
634
635 pub(crate) fn database_pool(&self, name: &'static str) -> Result<Arc<Pool>, Error> {
638 self.core_scope()?.database(&name.into()).map_err(infra_err)
639 }
640
641 pub(crate) fn clickhouse_database(
644 &self,
645 name: &'static str,
646 ) -> Result<Arc<encore_sdk_core::clickhouse::Database>, Error> {
647 self.core_scope()?
648 .clickhouse(&name.into())
649 .map_err(infra_err)
650 }
651
652 pub(crate) fn redis_client(
657 &self,
658 name: &'static str,
659 ) -> Result<Arc<encore_sdk_core::cache::Client>, Error> {
660 self.core_scope()?.redis(&name.into()).map_err(infra_err)
661 }
662
663 pub(crate) fn database_connection_string(
666 &self,
667 name: &'static str,
668 access: Access,
669 ) -> Result<String, Error> {
670 self.core_scope()?
671 .connection_string(&name.into(), access)
672 .map_err(infra_err)
673 }
674}
675
676fn unloaded_module_fixture(module: &str, full: bool) -> Option<String> {
679 let fixture = fixture::for_module(module, full)?;
680 Some(format!(
681 "this test is in a module with default fixture {:?}, but has not loaded it. \
682 Use `#[encore::test]` to load it automatically, or call `.load().await?` on the \
683 fixture (or `encore::testing::without_fixture()?`) before using any resources",
684 fixture.name()
685 ))
686}
687
688fn infra_err(err: anyhow::Error) -> Error {
691 if err.downcast_ref::<FixtureChoiceError>().is_some() {
692 Error::new(ErrCode::FailedPrecondition, err.to_string())
693 } else {
694 Error::wrap(ErrCode::Unavailable, format!("{err:#}"))
695 }
696}
697
698fn run_in_scope<R>(scope: Arc<Scope>, work: impl Future<Output = R>) -> R {
701 THREAD.with(|thread| thread.borrow_mut().own = Some(scope.clone()));
702 let _end = __private::EndTest;
704 let runtime = tokio::runtime::Builder::new_current_thread()
705 .enable_all()
706 .build()
707 .expect("failed to build a Tokio runtime");
708 with_runtimes(|runtimes| link(runtimes, runtime.handle().id(), &scope));
709 drop(scope);
710 runtime.block_on(work)
711}
712
713pub(crate) fn outgoing(
724 cx: &encore_sdk_core::telemetry::opentelemetry::Context,
725) -> encore_sdk_core::telemetry::opentelemetry::Context {
726 try_outgoing(cx).unwrap_or_else(|err| panic!("{}", err.message))
727}
728
729pub(crate) fn outgoing_if_known(
733 cx: &encore_sdk_core::telemetry::opentelemetry::Context,
734) -> encore_sdk_core::telemetry::opentelemetry::Context {
735 try_outgoing(cx).unwrap_or_else(|_| cx.clone())
736}
737
738fn try_outgoing(
740 cx: &encore_sdk_core::telemetry::opentelemetry::Context,
741) -> Result<encore_sdk_core::telemetry::opentelemetry::Context, Error> {
742 if core().system_test().is_none() {
743 return Ok(cx.clone());
744 }
745 outgoing_for(active(), cx)
746}
747
748fn outgoing_for(
751 test: Result<Option<Arc<Scope>>, Error>,
752 cx: &encore_sdk_core::telemetry::opentelemetry::Context,
753) -> Result<encore_sdk_core::telemetry::opentelemetry::Context, Error> {
754 let Some(test) = test? else {
755 return Ok(cx.clone());
756 };
757 Ok(test.core_scope()?.outgoing_context(cx))
758}
759
760pub(crate) fn active() -> Result<Option<Arc<Scope>>, Error> {
763 if core().test_scopes().is_none() {
764 return Ok(None);
765 }
766 resolve().map(Some)
767}
768
769#[derive(Default)]
773struct ThreadScopes {
774 own: Option<Arc<Scope>>,
776 joined: Vec<Arc<Scope>>,
778 entered: Vec<Arc<Scope>>,
780}
781
782thread_local! {
783 static THREAD: RefCell<ThreadScopes> = RefCell::new(ThreadScopes::default());
784}
785
786enum Link {
788 Test(Weak<Scope>),
789 Shared,
791}
792
793static RUNTIMES: Mutex<Option<HashMap<Id, Link>>> = Mutex::new(None);
794
795fn with_runtimes<T>(f: impl FnOnce(&mut HashMap<Id, Link>) -> T) -> T {
796 let mut runtimes = RUNTIMES.lock().unwrap_or_else(|e| e.into_inner());
797 f(runtimes.get_or_insert_with(HashMap::new))
798}
799
800static BEGUN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
805
806pub(crate) fn runner_detected() -> bool {
811 BEGUN.load(std::sync::atomic::Ordering::Relaxed)
812 || std::env::var_os("NEXTEST").is_some()
813 || test_name(std::thread::current().name()).is_some()
814}
815
816fn test_name(thread: Option<&str>) -> Option<&str> {
817 thread.filter(|name| *name != "main" && !name.starts_with("tokio-"))
818}
819
820fn resolve() -> Result<Arc<Scope>, Error> {
823 let handle = Handle::try_current().ok();
824 let runtime = handle.as_ref().map(Handle::id);
825 let thread = std::thread::current();
826 THREAD.with(|state| {
827 let mut state = state.borrow_mut();
828 if let Some(scope) = state.entered.last() {
829 return Ok(scope.clone());
830 }
831
832 if let Some(scope) = &state.own {
834 let scope = scope.clone();
835 if let Some(id) = runtime {
836 with_runtimes(|runtimes| link(runtimes, id, &scope));
837 }
838 return Ok(scope);
839 }
840
841 if let Some(name) = test_name(thread.name()) {
842 let scope = match &state.own {
843 Some(scope) => scope.clone(),
844 None => {
845 let scope = runtime
847 .and_then(|id| {
848 with_runtimes(|runtimes| match runtimes.get(&id) {
849 Some(Link::Test(scope)) => {
850 scope.upgrade().filter(|scope| scope.name.get().is_none())
851 }
852 _ => None,
853 })
854 })
855 .unwrap_or_else(Scope::new);
856 let _ = scope.name.set(name.to_string());
857 let module = name.rsplit_once("::").map_or("", |(module, _)| module);
858 scope.set_module(module.to_string(), false);
859 state.own = Some(scope.clone());
860 scope
861 }
862 };
863 if let Some(id) = runtime {
864 with_runtimes(|runtimes| link(runtimes, id, &scope));
865 }
866 return Ok(scope);
867 }
868
869 let Some(id) = runtime else {
870 return Err(not_a_test_thread(thread.name()));
871 };
872 let scope = with_runtimes(|runtimes| {
873 match runtimes.get(&id) {
874 Some(Link::Shared) => return Err(shared_runtime(thread.name())),
875 Some(Link::Test(scope)) => {
876 if let Some(scope) = scope.upgrade() {
877 return Ok(scope);
878 }
879 }
880 None => {}
881 }
882 let multi_thread = handle
887 .as_ref()
888 .is_some_and(|handle| handle.runtime_flavor() != RuntimeFlavor::CurrentThread);
889 if !multi_thread {
890 return Err(not_a_test_thread(thread.name()));
891 }
892 let scope = Scope::new();
893 link(runtimes, id, &scope);
894 Ok(scope)
895 })?;
896 if !state
897 .joined
898 .iter()
899 .any(|joined| Arc::ptr_eq(joined, &scope))
900 {
901 state.joined.push(scope.clone());
902 }
903 Ok(scope)
904 })
905}
906
907fn link(runtimes: &mut HashMap<Id, Link>, id: Id, scope: &Arc<Scope>) {
910 let shared = match runtimes.get(&id) {
911 Some(Link::Shared) => true,
912 Some(Link::Test(current)) => current
913 .upgrade()
914 .is_some_and(|current| !Arc::ptr_eq(¤t, scope)),
915 None => false,
916 };
917 if !shared {
918 runtimes.retain(|_, link| match link {
920 Link::Test(scope) => scope.strong_count() > 0,
921 Link::Shared => true,
922 });
923 }
924 let link = if shared {
925 Link::Shared
926 } else {
927 Link::Test(Arc::downgrade(scope))
928 };
929 runtimes.insert(id, link);
930}
931
932fn thread_label(name: Option<&str>) -> String {
933 match name {
934 Some(name) => format!("thread {name:?}"),
935 None => "an unnamed thread".to_string(),
936 }
937}
938
939fn not_a_test_thread(thread: Option<&str>) -> Error {
940 Error::new(
941 ErrCode::FailedPrecondition,
942 format!(
943 "an Encore resource was used on {}, which Encore cannot link to a running test. \
944 Each test gets infrastructure of its own, so Encore needs to know which test \
945 this thread belongs to.\n\n\
946 In the test, capture the scope and enter it on the new thread:\n\n \
947 let scope = encore::testing::current()?;\n \
948 std::thread::spawn(move || {{\n \
949 let _guard = scope.enter();\n \
950 …\n \
951 }});",
952 thread_label(thread)
953 ),
954 )
955}
956
957fn shared_runtime(thread: Option<&str>) -> Error {
958 Error::new(
959 ErrCode::FailedPrecondition,
960 format!(
961 "an Encore resource was used on {}, in a Tokio runtime that several tests share, \
962 so Encore cannot tell which test it belongs to. Each test gets infrastructure of \
963 its own.\n\n\
964 Run the work as part of its test:\n\n \
965 let scope = encore::testing::current()?;\n \
966 runtime.spawn(async move {{ scope.scope(work()).await }});",
967 thread_label(thread)
968 ),
969 )
970}
971
972#[cfg(test)]
973mod tests {
974 use super::*;
975
976 #[test]
977 fn a_call_whose_test_cannot_be_told_is_refused() {
978 let cx = encore_sdk_core::telemetry::opentelemetry::Context::new();
981 for (untold, says) in [
982 (
983 not_a_test_thread(Some("worker")),
984 "cannot link to a running test",
985 ),
986 (shared_runtime(None), "several tests share"),
987 ] {
988 let err = outgoing_for(Err(untold), &cx).unwrap_err();
989 assert_eq!(err.code, ErrCode::FailedPrecondition);
990 assert!(err.message.contains(says), "{err}");
991 }
992 assert!(outgoing_for(Ok(None), &cx).is_ok());
994 }
995
996 #[test]
997 fn a_typed_config_value_is_given_in_its_files_form() {
998 #[derive(serde::Serialize)]
999 struct Limits {
1000 max: u32,
1001 timeout: config::Duration,
1002 key: secrets::Secret,
1003 note: Option<String>,
1004 tiers: Vec<Tier>,
1005 }
1006 #[derive(serde::Serialize)]
1007 struct Tier {
1008 name: &'static str,
1009 key: secrets::Secret,
1010 }
1011 let mut value = serde_json::to_value(Limits {
1012 max: 5,
1013 timeout: config::Duration(std::time::Duration::from_millis(1500)),
1014 key: secrets::Secret::new("StripeKey"),
1015 note: None,
1016 tiers: vec![Tier {
1017 name: "gold",
1018 key: secrets::Secret::new("GoldKey"),
1019 }],
1020 })
1021 .unwrap();
1022 config_form(&mut value);
1023 assert_eq!(
1024 value,
1025 serde_json::json!({
1026 "max": 5,
1027 "timeout": "1500000us",
1028 "tiers": [{"name": "gold"}],
1029 })
1030 );
1031 assert_eq!(
1033 config::parse_duration("1500000us"),
1034 Some(std::time::Duration::from_millis(1500))
1035 );
1036 }
1037
1038 fn here() -> Result<(Option<String>, usize), String> {
1040 resolve()
1041 .map(|scope| (scope.name.get().cloned(), Arc::as_ptr(&scope) as usize))
1042 .map_err(|err| err.message)
1043 }
1044
1045 #[test]
1046 fn a_test_thread_is_its_test() {
1047 let (name, id) = here().unwrap();
1048 assert_eq!(
1049 name.as_deref(),
1050 Some("testing::tests::a_test_thread_is_its_test")
1051 );
1052 assert_eq!(here().unwrap().1, id);
1054 }
1055
1056 #[test]
1057 fn a_thread_the_test_starts_is_not_part_of_it_until_it_enters() {
1058 let (_, id) = here().unwrap();
1059 let scope = TestScope {
1060 scope: resolve().unwrap(),
1061 };
1062
1063 let err = std::thread::spawn(here).join().unwrap().unwrap_err();
1064 assert!(err.contains("an unnamed thread"), "{err}");
1065 assert!(err.contains("scope.enter()"), "{err}");
1066
1067 let entered = std::thread::spawn(move || {
1068 let inside = {
1069 let _guard = scope.enter();
1070 here()
1071 };
1072 (inside, here())
1073 })
1074 .join()
1075 .unwrap();
1076 assert_eq!(entered.0.unwrap().1, id);
1077 assert!(entered.1.is_err());
1079 }
1080
1081 #[tokio::test]
1082 async fn a_current_thread_runtime_is_its_test() {
1083 let (name, id) = here().unwrap();
1084 assert!(name.is_some());
1085 assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
1086 assert_eq!(
1087 tokio::task::spawn_blocking(here).await.unwrap().unwrap().1,
1088 id
1089 );
1090 }
1091
1092 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1093 async fn a_multi_thread_runtime_is_its_test() {
1094 let (_, id) = here().unwrap();
1095 for _ in 0..8 {
1096 assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
1097 }
1098 assert_eq!(
1099 tokio::task::spawn_blocking(here).await.unwrap().unwrap().1,
1100 id
1101 );
1102 }
1103
1104 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1105 async fn a_test_adopts_what_its_runtime_started() {
1106 let (name, id) = tokio::spawn(async { here() }).await.unwrap().unwrap();
1108 assert_eq!(name, None);
1109 let (name, adopted) = here().unwrap();
1111 assert_eq!(adopted, id);
1112 assert!(name
1113 .unwrap()
1114 .ends_with("a_test_adopts_what_its_runtime_started"));
1115 let (name, again) = tokio::spawn(async { here() }).await.unwrap().unwrap();
1116 assert_eq!(again, id);
1117 assert!(name.is_some());
1118 }
1119
1120 #[test]
1121 fn tests_sharing_a_runtime_make_its_workers_ambiguous() {
1122 let runtime = tokio::runtime::Builder::new_multi_thread()
1123 .worker_threads(1)
1124 .build()
1125 .unwrap();
1126 let handle = runtime.handle().clone();
1127 let (ready_tx, ready_rx) = std::sync::mpsc::channel();
1128 let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
1129 let first = std::thread::Builder::new()
1131 .name("tests::first".to_string())
1132 .spawn({
1133 let handle = handle.clone();
1134 move || {
1135 let _enter = handle.enter();
1136 let id = here().unwrap().1;
1137 ready_tx.send(id).unwrap();
1138 let _ = done_rx.recv();
1139 }
1140 })
1141 .unwrap();
1142 let first_id = ready_rx.recv().unwrap();
1143 let second_id = std::thread::Builder::new()
1145 .name("tests::second".to_string())
1146 .spawn({
1147 let handle = handle.clone();
1148 move || {
1149 let _enter = handle.enter();
1150 here().unwrap().1
1151 }
1152 })
1153 .unwrap()
1154 .join()
1155 .unwrap();
1156 assert_ne!(first_id, second_id);
1157
1158 let err = runtime.block_on(async { tokio::spawn(async { here() }).await.unwrap() });
1160 let err = err.unwrap_err();
1162 assert!(err.contains("several tests share"), "{err}");
1163 assert!(err.contains("scope.scope("), "{err}");
1164
1165 done_tx.send(()).unwrap();
1166 first.join().unwrap();
1167 }
1168
1169 #[tokio::test]
1170 async fn a_future_runs_as_part_of_the_test_it_is_scoped_to() {
1171 let (_, id) = here().unwrap();
1172 let scope = TestScope {
1173 scope: resolve().unwrap(),
1174 };
1175 assert!(scope.name().unwrap().ends_with("it_is_scoped_to"));
1176 let other = std::thread::spawn(move || {
1178 tokio::runtime::Builder::new_current_thread()
1179 .build()
1180 .unwrap()
1181 .block_on(async {
1182 let outside = here();
1183 let inside = scope.scope(async { here().unwrap().1 }).await;
1184 (outside, inside)
1185 })
1186 })
1187 .join()
1188 .unwrap();
1189 let err = other.0.unwrap_err();
1190 assert!(err.contains("cannot link to a running test"), "{err}");
1191 assert_eq!(other.1, id);
1192 }
1193
1194 #[encore::test]
1195 async fn the_macro_runs_a_test_in_its_own_runtime() {
1196 let (name, id) = here().unwrap();
1197 assert_eq!(
1199 name.as_deref(),
1200 Some("testing::tests::the_macro_runs_a_test_in_its_own_runtime")
1201 );
1202 assert_eq!(tokio::spawn(async { here() }).await.unwrap().unwrap().1, id);
1203 assert_eq!(
1205 Handle::current().runtime_flavor(),
1206 RuntimeFlavor::CurrentThread
1207 );
1208 }
1209
1210 #[encore::test(flavor = "multi_thread", worker_threads = 2)]
1211 async fn the_macro_links_the_runtime_before_the_test_runs() -> Result<(), String> {
1212 let (name, id) = tokio::spawn(async { here() }).await.unwrap()?;
1214 assert!(name.unwrap().ends_with("before_the_test_runs"));
1215 assert_eq!(here()?.1, id);
1216 assert_eq!(Handle::current().metrics().num_workers(), 2);
1217 Ok(())
1218 }
1219
1220 #[encore::test]
1221 #[should_panic(expected = "as any test")]
1222 async fn the_macro_keeps_the_tests_other_attributes() {
1223 panic!("as any test");
1224 }
1225
1226 #[encore::test]
1227 fn the_macro_takes_a_test_that_is_not_async() {
1228 let (name, _) = here().unwrap();
1229 assert!(name.unwrap().ends_with("is_not_async"));
1230 }
1231
1232 #[test]
1233 fn the_macro_ends_the_test_when_it_returns() {
1234 let weak = std::thread::spawn(|| {
1235 let weak = __private::run(
1236 __private::TestInfo {
1237 module: "app::tests",
1238 name: "returns",
1239 file: file!(),
1240 line: line!(),
1241 },
1242 __private::RuntimeConfig {
1243 multi_thread: true,
1244 worker_threads: Some(1),
1245 },
1246 __private::FixtureArg::Module,
1247 |_| false,
1248 async {
1249 tokio::spawn(async { here().unwrap() }).await.unwrap();
1250 Arc::downgrade(&resolve().unwrap())
1251 },
1252 );
1253 assert!(weak.upgrade().is_none());
1255 assert!(here().is_err());
1256 })
1257 .join();
1258 weak.unwrap();
1259 }
1260
1261 mod billing {
1262 crate::fixture! {
1263 pub static SEEDED for mod = async { Ok(()) };
1265
1266 pub static EXTRA: SEEDED = async { Ok(()) };
1268 }
1269
1270 pub mod invoices {
1271 crate::fixture! {
1272 pub static INVOICED for mod: super::SEEDED = async { Ok(()) };
1273 }
1274 }
1275 }
1276
1277 #[test]
1278 fn a_fixture_is_named_after_where_it_is_declared() {
1279 assert_eq!(
1280 billing::SEEDED.name(),
1281 "encore::testing::tests::billing::SEEDED"
1282 );
1283 assert_eq!(
1284 billing::invoices::INVOICED.name(),
1285 "encore::testing::tests::billing::invoices::INVOICED"
1286 );
1287 assert_eq!(
1289 billing::EXTRA.name(),
1290 "encore::testing::tests::billing::EXTRA"
1291 );
1292 }
1293
1294 #[test]
1295 fn a_modules_fixture_is_found_from_the_tests_inside_it() {
1296 let found = |module: &str, full: bool| fixture::for_module(module, full).map(Fixture::name);
1297 assert_eq!(
1299 found("encore::testing::tests::billing", true),
1300 Some(billing::SEEDED.name())
1301 );
1302 assert_eq!(
1303 found("encore::testing::tests::billing::reports::monthly", true),
1304 Some(billing::SEEDED.name())
1305 );
1306 assert_eq!(
1308 found("encore::testing::tests::billing::invoices", true),
1309 Some(billing::invoices::INVOICED.name())
1310 );
1311 assert_eq!(
1313 found("testing::tests::billing::invoices::overdue", false),
1314 Some(billing::invoices::INVOICED.name())
1315 );
1316 assert_eq!(found("encore::testing::tests::billing_reports", true), None);
1319 assert_eq!(found("encore::testing::tests", true), None);
1320 assert_eq!(found("testing::tests", false), None);
1321 }
1322
1323 #[test]
1324 fn a_test_in_a_module_with_a_fixture_has_to_say_what_it_starts_from() {
1325 let reason = unloaded_module_fixture("testing::tests::billing::reports", false).unwrap();
1328 assert!(reason.contains("has not loaded it"), "{reason}");
1329 assert!(reason.contains(billing::SEEDED.name()), "{reason}");
1330 assert!(reason.contains("without_fixture()"), "{reason}");
1331
1332 assert_eq!(unloaded_module_fixture("testing::tests", false), None);
1334 }
1335
1336 #[test]
1337 fn a_scope_ends_with_the_threads_that_are_part_of_it() {
1338 let weak = std::thread::Builder::new()
1339 .name("tests::short_lived".to_string())
1340 .spawn(|| Arc::downgrade(&resolve().unwrap()))
1341 .unwrap()
1342 .join()
1343 .unwrap();
1344 assert!(weak.upgrade().is_none());
1345
1346 let scope = std::thread::Builder::new()
1348 .name("tests::held".to_string())
1349 .spawn(|| TestScope {
1350 scope: resolve().unwrap(),
1351 })
1352 .unwrap()
1353 .join()
1354 .unwrap();
1355 let weak = Arc::downgrade(&scope.scope);
1356 assert!(weak.upgrade().is_some());
1357 drop(scope);
1358 assert!(weak.upgrade().is_none());
1359 }
1360}