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: parametrized NameError-at-import regression for every persisted service (#499)
Stephan Mielke04d3e3bb5340
diff --git a/tests/test_state_dict_persistence.py b/tests/test_state_dict_persistence.pyindex 281728e1..f8b174fd 100644--- a/tests/test_state_dict_persistence.py+++ b/tests/test_state_dict_persistence.py@@ -212,3 +212,97 @@ def test_ecs_module_reload_with_persisted_attributes_does_not_namerror():"ECS _attributes lost after reload — same root cause.")mod.reset()+++# ── Generic NameError-at-import regression for ALL persisted services ─++def _persisted_services():+ """Return a sorted list of ``(svc_key, mod_name)`` pairs from+ ``ministack.app._state_map``.++ Evaluated by ``@pytest.mark.parametrize(...)`` at test collection+ time — `_state_map` is therefore imported when pytest collects this+ module, NOT lazily per test case. (Calling it inside the parametrize+ decorator means it runs once, at collection.)"""+ from ministack.app import _state_map+ return sorted(_state_map.items())++[email protected]("svc_key,mod_name", _persisted_services())+def test_module_cold_import_with_typical_snapshot_does_not_log_restore_failure(+ svc_key, mod_name, caplog,+):+ """Generic regression for the NameError-at-import pattern that hit+ `ecs._attributes` (this PR) and `acm._synthetic_pem` (#494).++ The bug shape: `restore_state(data)` references a module-level+ symbol declared further down the file. The import-time `try:+ load_state(...)` block calls `restore_state()` BEFORE Python+ evaluates the later definition, so the lookup NameErrors. The+ surrounding try/except logs `Failed to restore persisted state` and+ swallows the exception, so the module appears to import cleanly+ while ALL its persisted state silently disappears.++ The test:+ 1. Captures the module's current `get_state()` snapshot (a+ non-empty dict-of-empty-dicts — important so `restore_state`+ doesn't early-return on truthy emptiness checks).+ 2. Persists that to disk via the production `save_state` path.+ 3. **Removes the module from `sys.modules` and re-imports it+ fresh** — `importlib.reload()` would NOT catch the bug+ because it merges new definitions into the existing+ namespace, leaving any late-declared symbol bound from the+ previous import.+ 4. Asserts no WARNING+ log record mentioning "restore" / "failed"+ / "continuing fresh" was emitted during the cold import.++ Catches: unconditional symbol references in restore_state+ (ECS-style). Does NOT catch: conditional references inside loops+ over restored data when the data is empty (ACM-style needs+ populated state — see the per-service tests above).+ """+ import sys++ # Persistence is already enabled and STATE_DIR is already pointed at+ # a per-test tmp by the autouse `_enable_persistence` fixture.++ # Step 1+2: produce + persist a snapshot using the already-loaded+ # module (so we get a valid get_state() shape).+ mod = _module(mod_name)+ if hasattr(mod, "reset"):+ mod.reset()+ persistence.save_state(svc_key, mod.get_state())++ # Step 3: cold-import — wipe sys.modules and re-import.+ # importlib.reload() won't work because it merges into the+ # existing namespace; the late-declared symbol stays bound from+ # the prior import.+ full_name = f"ministack.services.{mod_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()++ assert not bad, (+ f"Cold import of `{mod_name}` (state-key `{svc_key}`) emitted "+ f"a restore-failure log:\n "+ + "\n ".join(r.getMessage() for r in bad)+ + "\n\nThis usually means `restore_state` references a "+ "module-level symbol that's declared further down the file. "+ "The import-time `try: load_state()` block runs before the "+ "later definition, so the symbol lookup NameErrors and the "+ "surrounding try/except swallows it. Hoist the symbol above "+ "the import-time `load_state` block (see ECS `_attributes` "+ "or ACM `_synthetic_pem` for the canonical fix)."+ )