Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
test(persistence): restore cold-imported module to fix cross-module desync flake (#934)
Yuriy Rf8af2e6211af
diff --git a/tests/test_persistence.py b/tests/test_persistence.pyindex 0a639752..b6a6d568 100644--- a/tests/test_persistence.py+++ b/tests/test_persistence.py@@ -674,22 +674,43 @@ def test_module_cold_import_with_typical_snapshot_does_not_log_restore_failure(# importlib.reload() won't work because it merges into the# existing namespace; the late-declared symbol stays bound from# the prior import.+ import ministack.services as _services_pkg+full_name = f"ministack.services.{mod_name}"+ # The cold-import swaps a brand-new module object into BOTH sys.modules and+ # the `ministack.services` package attribute. Other already-imported modules+ # that did `from ministack.services import <mod>` keep a reference to the+ # ORIGINAL object, so we must restore it afterwards. Otherwise the fresh+ # module (with empty, reset state) leaks into later tests on the same xdist+ # worker and desyncs cross-module references — e.g. cold-importing `ecs`+ # then `secretsmanager` leaves the fresh `ecs` pointing at a stale+ # `secretsmanager`, so ECS RunTask can no longer resolve Secrets Manager+ # secrets created via the live module. Both the sys.modules entry and the+ # package attribute must be restored: `from ministack.services import <mod>`+ # reads the package attribute, not sys.modules directly.+ original_mod = sys.modules.get(full_name)sys.modules.pop(full_name, None)- caplog.clear()- with caplog.at_level("WARNING"):- mod = importlib.import_module(full_name)-- bad = [- r for r in caplog.records- if r.levelno >= 30 # WARNING+- and any(needle in r.getMessage().lower()- for needle in ("failed to restore", "restore failed",- "continuing fresh", "continuing with fresh"))- ]- if hasattr(mod, "reset"):- mod.reset()+ try:+ caplog.clear()+ with caplog.at_level("WARNING"):+ mod = importlib.import_module(full_name)++ bad = [+ r for r in caplog.records+ if r.levelno >= 30 # WARNING++ and any(needle in r.getMessage().lower()+ for needle in ("failed to restore", "restore failed",+ "continuing fresh", "continuing with fresh"))+ ]+ if hasattr(mod, "reset"):+ mod.reset()+ finally:+ # Re-register the original module so references bound before this test+ # (e.g. `ecs.secretsmanager`) stay valid for subsequent tests.+ if original_mod is not None:+ sys.modules[full_name] = original_mod+ setattr(_services_pkg, mod_name, original_mod)assert not bad, (f"Cold import of `{mod_name}` (state-key `{svc_key}`) emitted "