From 515da34fb0d8d423f82592d9757b9ad828bf5894 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABlle=20Huisman?= Date: Tue, 11 Feb 2025 17:03:32 +0100 Subject: [PATCH] Fix unit test deadlock --- packages/dom/tests/config.rs | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/packages/dom/tests/config.rs b/packages/dom/tests/config.rs index 534a17b..c9cc209 100644 --- a/packages/dom/tests/config.rs +++ b/packages/dom/tests/config.rs @@ -1,11 +1,17 @@ -use std::sync::{Arc, LazyLock, Mutex}; +use std::sync::{Arc, LazyLock, Mutex, MutexGuard}; use testing_library_dom::{configure, get_config, ConfigFnOrPartial, PartialConfig}; +static CONFIG_LOCK: Mutex<()> = Mutex::new(()); static ORIGINAL_CONFIG: LazyLock>> = LazyLock::new(|| Arc::new(Mutex::new(PartialConfig::default()))); -fn before_each() { +fn before_each() -> MutexGuard<'static, ()> { + // Ensure only one test modifies the config at the same time. + let lock = CONFIG_LOCK + .lock() + .expect("Config mutex should be acquired."); + configure(ConfigFnOrPartial::Fn(Box::new(|existing_config| { // Grab the existing configuration so we can restore it at the end of the test. let mut original_config = ORIGINAL_CONFIG @@ -16,39 +22,43 @@ fn before_each() { // Don't change the existing config. PartialConfig::default() }))); + + lock } -fn after_each() { +fn after_each(lock: MutexGuard<'_, ()>) { let original_config = ORIGINAL_CONFIG .lock() .expect("Original config mutex should be acquired."); configure(ConfigFnOrPartial::Partial((*original_config).clone())); + + drop(lock); } #[test] fn get_config_returns_existing_configuration() { - before_each(); + let lock = before_each(); let config = get_config(); assert_eq!("data-testid", config.test_id_attribute); - after_each(); + after_each(lock); } #[test] fn configure_merges_a_delta_rather_than_replacing_the_whole_config() { - before_each(); + let lock = before_each(); let config = get_config(); assert_eq!("data-testid", config.test_id_attribute); - after_each(); + after_each(lock); } #[test] fn configure_overrides_existing_values() { - before_each(); + let lock = before_each(); configure(ConfigFnOrPartial::Partial( PartialConfig::default().test_id_attribute("new-id".into()), @@ -57,12 +67,12 @@ fn configure_overrides_existing_values() { let config = get_config(); assert_eq!("new-id", config.test_id_attribute); - after_each(); + after_each(lock); } #[test] fn configure_passes_existing_config_out_to_config_function() { - before_each(); + let lock = before_each(); // Create a new config key based on the value of an existing one. configure(ConfigFnOrPartial::Fn(Box::new(|existing_config| { @@ -74,5 +84,5 @@ fn configure_passes_existing_config_out_to_config_function() { let config = get_config(); assert_eq!("data-testid-derived", config.test_id_attribute); - after_each(); + after_each(lock); }