1#[cfg(feature = "chromiumoxide")]
68pub mod chromiumoxide;
69mod fixture;
70pub mod system;
71
72pub use fixture::{without_fixture, Fixture, SetupFn};
73
74use std::cell::RefCell;
75use std::collections::HashMap;
76use std::future::{poll_fn, Future};
77use std::marker::PhantomData;
78use std::pin::pin;
79use std::sync::{Arc, Mutex, OnceLock, Weak};
80
81use encore_sdk_core::objects;
82use encore_sdk_core::postgres::{Access, Pool};
83use encore_sdk_core::test_scope::{self, FixtureChoiceError, TestScope as CoreScope};
84use tokio::runtime::{Handle, Id, RuntimeFlavor};
85
86use crate::config;
87use crate::error::{ErrCode, Error};
88use crate::runtime::core;
89use crate::secrets;
90
91pub fn current() -> Result<TestScope, Error> {
96 match active()? {
97 Some(scope) => Ok(TestScope { scope }),
98 None => Err(Error::new(
99 ErrCode::FailedPrecondition,
100 "there is no current test: the process is not running under `encore test`",
101 )),
102 }
103}
104
105pub fn published<T, E: crate::pubsub::Encoding<T>, O>(
119 topic: &crate::pubsub::Topic<T, E, O>,
120) -> Result<Vec<crate::pubsub::Message<T>>, Error> {
121 if core().system_test().is_some() {
122 return Err(Error::new(
123 ErrCode::Unimplemented,
124 "what a system test published is sent, and is not kept by the test: read what \
125 the app did with it instead, once it has `settled`",
126 ));
127 }
128 match active()? {
129 Some(test) => topic.published_in(&test),
130 None => Err(Error::new(
131 ErrCode::FailedPrecondition,
132 "there is no current test: the process is not running under `encore test`",
133 )),
134 }
135}
136
137pub async fn deliver<T: Send + 'static>(
158 subscription: &'static crate::pubsub::Subscription<T>,
159) -> Result<usize, Error> {
160 if core().system_test().is_some() {
161 return Err(Error::new(
162 ErrCode::FailedPrecondition,
163 "subscriptions run on their own in a system test, in the services that declare \
164 them: wait for them to have handled what was published with \
165 `encore::testing::system::settled`",
166 ));
167 }
168 match active()? {
169 Some(test) => subscription.deliver_in(&test).await,
170 None => Err(Error::new(
171 ErrCode::FailedPrecondition,
172 "there is no current test: the process is not running under `encore test`",
173 )),
174 }
175}
176
177pub fn set_secret<T: secrets::SecretValue>(
188 secret: &secrets::Secret<T>,
189 value: impl AsRef<[u8]>,
190) -> Result<(), Error> {
191 if core().system_test().is_some() {
192 return Err(Error::new(
193 ErrCode::FailedPrecondition,
194 SECRET_IN_SYSTEM_TEST,
195 ));
196 }
197 match active()? {
198 Some(test) => {
199 test.core_scope()?.set_secret(secret.name(), value.as_ref());
201 Ok(())
202 }
203 None => Err(Error::new(
204 ErrCode::FailedPrecondition,
205 "there is no current test: the process is not running under `encore test`",
206 )),
207 }
208}
209
210pub fn set_config<T: config::ConfigType>(
228 config: &config::Config<T>,
229 value: impl serde::Serialize,
230) -> Result<(), Error> {
231 if core().system_test().is_some() {
232 return Err(Error::new(
233 ErrCode::FailedPrecondition,
234 CONFIG_IN_SYSTEM_TEST,
235 ));
236 }
237 match active()? {
238 Some(test) => {
239 let name = config.key();
240 let mut value = serde_json::to_value(value).map_err(|err| {
241 Error::invalid_argument(format!("the value for config {name:?} is not JSON: {err}"))
242 })?;
243 config_form(&mut value);
244 let value = test
245 .core_scope()?
246 .set_config(name, value)
247 .map_err(|errors| {
248 Error::invalid_argument(format!(
249 "the value for config {name:?} does not satisfy its schema: {}",
250 errors.join("; ")
251 ))
252 })?;
253 let value = config::test_value::<T>(name, value)?;
254 test.configs
255 .lock()
256 .unwrap_or_else(|e| e.into_inner())
257 .insert(name, value);
258 Ok(())
259 }
260 None => Err(Error::new(
261 ErrCode::FailedPrecondition,
262 "there is no current test: the process is not running under `encore test`",
263 )),
264 }
265}
266
267fn config_form(value: &mut serde_json::Value) {
271 match value {
272 serde_json::Value::Object(fields) => {
273 fields.retain(|_, field| !field.is_null() && !is_secret_placeholder(field));
274 fields.values_mut().for_each(config_form);
275 }
276 serde_json::Value::Array(items) => items.iter_mut().for_each(config_form),
277 _ => {}
278 }
279}
280
281fn is_secret_placeholder(value: &serde_json::Value) -> bool {
283 value.as_object().is_some_and(|fields| {
284 fields.len() == 1
285 && fields
286 .get(encore_sdk_core::config::PLACEHOLDER_KEY)
287 .is_some_and(serde_json::Value::is_string)
288 })
289}
290
291const SECRET_IN_SYSTEM_TEST: &str = "a system test can't give a secret a value of its own: the \
293 services it calls read theirs, not the test's. Give the secret its value for tests in \
294 secrets.test.toml";
295
296const CONFIG_IN_SYSTEM_TEST: &str = "a system test can't give a config a value of its own: the \
298 services it calls read theirs, not the test's. Give the config its value for tests in its \
299 `test` config file (<name>.test.config.toml)";
300
301#[derive(Clone)]
307pub struct TestScope {
308 scope: Arc<Scope>,
309}
310
311impl TestScope {
312 pub fn enter(&self) -> ScopeGuard<'_> {
314 THREAD.with(|thread| thread.borrow_mut().entered.push(self.scope.clone()));
315 ScopeGuard {
316 _scope: PhantomData,
317 _not_send: PhantomData,
318 }
319 }
320
321 pub async fn scope<F: Future>(&self, future: F) -> F::Output {
323 let mut future = pin!(future);
324 poll_fn(|cx| {
325 let _guard = self.enter();
326 future.as_mut().poll(cx)
327 })
328 .await
329 }
330
331 pub fn name(&self) -> Option<&str> {
335 self.scope.name.get().map(String::as_str)
336 }
337}
338
339pub struct ScopeGuard<'a> {
341 _scope: PhantomData<&'a TestScope>,
342 _not_send: PhantomData<*const ()>,
344}
345
346impl Drop for ScopeGuard<'_> {
347 fn drop(&mut self) {
348 THREAD.with(|thread| thread.borrow_mut().entered.pop());
349 }
350}
351
352#[doc(hidden)]
355pub mod __private {
356 use super::*;
357
358 pub struct TestInfo {
360 pub module: &'static str,
361 pub name: &'static str,
362 pub file: &'static str,
363 pub line: u32,
364 }
365
366 pub use super::fixture::FIXTURES;
367 pub use linkme;
368
369 pub struct RuntimeConfig {
371 pub multi_thread: bool,
372 pub worker_threads: Option<usize>,
373 }
374
375 pub enum FixtureArg {
377 Module,
379 Named(&'static Fixture),
380 None,
381 }
382
383 async fn load_fixture(info: &TestInfo, fixture: FixtureArg) {
386 let choice = match fixture {
388 FixtureArg::Module => fixture::for_module(info.module, true).map(Some),
389 FixtureArg::Named(fixture) => Some(Some(fixture)),
390 FixtureArg::None => Some(None),
391 };
392 let Some(choice) = choice else {
393 return;
394 };
395 if core().test_scopes().is_none() {
396 return;
397 }
398 let loaded = match choice {
399 Some(fixture) => fixture.load().await,
400 None => without_fixture(),
401 };
402 if let Err(err) = loaded {
403 panic!("{}", err.message);
404 }
405 }
406
407 pub(in crate::testing) struct EndTest;
410
411 impl Drop for EndTest {
412 fn drop(&mut self) {
413 THREAD.with(|thread| thread.borrow_mut().own = None);
414 }
415 }
416
417 fn begin(info: &TestInfo) -> (Arc<Scope>, EndTest) {
419 BEGUN.store(true, std::sync::atomic::Ordering::Relaxed);
421 let scope = Scope::new();
422 scope.set_module(info.module.to_string(), true);
423 let module = info.module.split_once("::").map_or("", |(_, rest)| rest);
425 let name = if module.is_empty() {
426 info.name.to_string()
427 } else {
428 format!("{module}::{}", info.name)
429 };
430 let _ = scope.name.set(name);
431 THREAD.with(|thread| thread.borrow_mut().own = Some(scope.clone()));
432 (scope, EndTest)
433 }
434
435 pub fn run<R, F: Future<Output = R>>(
438 info: TestInfo,
439 config: RuntimeConfig,
440 fixture: FixtureArg,
441 failed: fn(&R) -> bool,
442 test: F,
443 ) -> R {
444 let (scope, _end) = begin(&info);
446 let reported = system::Reported::new(scope.clone());
447 let mut builder = if config.multi_thread {
448 tokio::runtime::Builder::new_multi_thread()
449 } else {
450 tokio::runtime::Builder::new_current_thread()
451 };
452 if let Some(threads) = config.worker_threads {
453 builder.worker_threads(threads);
454 }
455 let runtime = builder
456 .enable_all()
457 .build()
458 .expect("failed to build the test's Tokio runtime");
459 with_runtimes(|runtimes| link(runtimes, runtime.handle().id(), &scope));
460 drop(scope);
461 let result = runtime.block_on(async {
462 load_fixture(&info, fixture).await;
463 test.await
464 });
465 reported.ended(failed(&result));
466 result
467 }
468
469 pub struct Probe<'a, R>(pub &'a R);
477
478 pub trait FailedIfErr {
479 fn failed(&self) -> bool;
480 }
481
482 impl<T, E> FailedIfErr for Probe<'_, Result<T, E>> {
483 fn failed(&self) -> bool {
484 self.0.is_err()
485 }
486 }
487
488 pub trait NeverFailed {
489 fn failed(&self) -> bool;
490 }
491
492 impl<R> NeverFailed for &Probe<'_, R> {
493 fn failed(&self) -> bool {
494 false
495 }
496 }
497
498 pub fn run_sync<R, F: FnOnce() -> R>(
500 info: TestInfo,
501 fixture: FixtureArg,
502 failed: fn(&R) -> bool,
503 test: F,
504 ) -> R {
505 let (scope, _end) = begin(&info);
506 let reported = system::Reported::new(scope);
507 tokio::runtime::Builder::new_current_thread()
509 .enable_all()
510 .build()
511 .expect("failed to build a Tokio runtime to load the test's fixture")
512 .block_on(load_fixture(&info, fixture));
513 let result = test();
514 reported.ended(failed(&result));
515 result
516 }
517}
518
519pub(crate) struct Scope {
523 name: OnceLock<String>,
524 module: OnceLock<(String, bool)>,
527 core: OnceLock<Arc<CoreScope>>,
531 configs: Mutex<HashMap<ConfigKey, Arc<dyn std::any::Any + Send + Sync>>>,
534}
535
536type ConfigKey = &'static str;
539
540impl Scope {
541 fn new() -> Arc<Self> {
542 Arc::new(Self {
543 name: OnceLock::new(),
544 module: OnceLock::new(),
545 core: OnceLock::new(),
546 configs: Mutex::new(HashMap::new()),
547 })
548 }
549
550 fn building(core: Arc<CoreScope>, name: String) -> Arc<Self> {
552 let scope = Self::new();
553 let _ = scope.name.set(name);
554 let _ = scope.core.set(core);
555 scope
556 }
557
558 pub(crate) fn core_scope(&self) -> Result<&Arc<CoreScope>, Error> {
561 if let Some(scope) = self.core.get() {
562 return Ok(scope);
563 }
564 let scopes = core().test_scopes().ok_or_else(|| {
565 Error::new(
566 ErrCode::FailedPrecondition,
567 "there is no current test: the process is not running under `encore test`",
568 )
569 })?;
570 let scope = self
571 .core
572 .get_or_init(|| scopes.begin(self.name.get().map(String::as_str)));
573 self.require_module_fixture();
574 Ok(scope)
575 }
576
577 fn set_module(&self, module: String, full: bool) {
579 let _ = self.module.set((module, full));
580 self.require_module_fixture();
581 }
582
583 fn require_module_fixture(&self) {
587 let (Some(core), Some((module, full))) = (self.core.get(), self.module.get()) else {
588 return;
589 };
590 if let Some(reason) = unloaded_module_fixture(module, *full) {
591 core.require_use_fixture(reason);
592 }
593 }
594
595 pub(crate) fn choose(&self, fixture: Option<&'static Fixture>) -> Result<(), Error> {
598 self.core_scope()?
599 .use_fixture(fixture.map(Fixture::name))
600 .map_err(infra_err)
601 }
602
603 pub(crate) fn secret(&self, name: &str) -> Option<Arc<[u8]>> {
605 self.core.get()?.secret(name)
606 }
607
608 pub(crate) fn config(
610 &self,
611 name: &'static str,
612 ) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
613 self.configs
614 .lock()
615 .unwrap_or_else(|e| e.into_inner())
616 .get(name)
617 .cloned()
618 }
619
620 pub(crate) fn published(&self, name: &str) -> Vec<test_scope::Published> {
622 self.core
623 .get()
624 .map(|core| core.published(name))
625 .unwrap_or_default()
626 }
627
628 pub(crate) fn bucket(&self, name: &'static str) -> Result<objects::Bucket, Error> {
631 self.core_scope()?.bucket(&name.into()).map_err(infra_err)
632 }
633
634 pub(crate) fn database_pool(&self, name: &'static str) -> Result<Arc<Pool>, Error> {
637 self.core_scope()?.database(&name.into()).map_err(infra_err)
638 }
639
640 pub(crate) fn clickhouse_database(
643 &self,
644 name: &'static str,
645 ) -> Result<Arc<encore_sdk_core::clickhouse::Database>, Error> {
646 self.core_scope()?
647 .clickhouse(&name.into())
648 .map_err(infra_err)
649 }
650
651 pub(crate) fn redis_client(
656 &self,
657 name: &'static str,
658 ) -> Result<Arc<encore_sdk_core::cache::Client>, Error> {
659 self.core_scope()?.redis(&name.into()).map_err(infra_err)
660 }
661
662 pub(crate) fn database_connection_string(
665 &self,
666 name: &'static str,
667 access: Access,
668 ) -> Result<String, Error> {
669 self.core_scope()?
670 .connection_string(&name.into(), access)
671 .map_err(infra_err)
672 }
673}
674
675fn unloaded_module_fixture(module: &str, full: bool) -> Option<String> {
678 let fixture = fixture::for_module(module, full)?;
679 Some(format!(
680 "this test is in a module whose tests start from the fixture {:?}, but has not \
681 loaded it. Make it an `#[encore::test]`, which does, or call `.load().await?` on the \
682 fixture — or `encore::testing::without_fixture()?` — before the test first uses a \
683 resource",
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}