Skip to content

Commit 20b7e8f

Browse files
committed
fix: avoid re-executing modules between @djc_test cycles (#1598 root cause)
#1630 patched the registry-corruption symptom from #1598, but the underlying trigger remained: `_clear_djc_global_state` popped every entry from `LOADED_MODULES` out of `sys.modules`, including modules that had already been imported before the test ran. The next test's `autodiscover()` then re-executed those modules, producing a fresh class object with the same `class_id` as the original - exactly the input PR #1630 had to defend against. Snapshot `sys.modules.keys()` in `_wrapper_impl` and pass it through to `_clear_djc_global_state`, which now only pops `LOADED_MODULES` entries that were absent from the snapshot. Modules the test itself imported are still cleared; modules carried in from production startup or earlier tests stay put. This implements Options B/C suggested in #1598.
1 parent 1c972de commit 20b7e8f

2 files changed

Lines changed: 45 additions & 3 deletions

File tree

‎src/django_components/util/testing.py‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,10 @@ def _wrapper_impl(*args: Any, **kwargs: Any) -> Any:
333333
continue
334334
_all_registries_copies.append((reg_ref, list(reg._registry.keys())))
335335

336+
# Snapshot which modules were already imported before the test ran.
337+
# See `_clear_djc_global_state` for why this matters.
338+
_initial_sys_modules = frozenset(sys.modules)
339+
336340
# Prepare global state
337341
_setup_djc_global_state(gen_id_patcher, csrf_token_patcher)
338342

@@ -342,6 +346,7 @@ def cleanup() -> None:
342346
csrf_token_patcher,
343347
_all_components, # type: ignore[arg-type]
344348
_all_registries_copies,
349+
_initial_sys_modules,
345350
gc_collect,
346351
)
347352

@@ -457,6 +462,7 @@ def _clear_djc_global_state(
457462
csrf_token_patcher: CsrfTokenPatcher,
458463
initial_components: InitialComponents,
459464
initial_registries_copies: RegistriesCopies,
465+
initial_sys_modules: frozenset[str],
460466
gc_collect: bool = False,
461467
) -> None:
462468
gen_id_patcher.stop()
@@ -540,12 +546,16 @@ def _clear_djc_global_state(
540546
for key in keys_registered_during_test:
541547
registry_original.unregister(key)
542548

543-
# Delete autoimported modules from memory, so the module
544-
# is executed also the next time one of the tests calls `autodiscover`.
549+
# Drop modules that the test brought in itself, so a later test sees a clean import.
550+
# Modules that were already in `sys.modules` before the test ran are left alone -
551+
# popping them would force `importlib.import_module()` to re-execute the file on
552+
# the next test, creating a new class object with the same `class_id` as the old one
553+
# (the precondition behind #1598).
545554
from django_components.autodiscovery import LOADED_MODULES # noqa: PLC0415
546555

547556
for mod in LOADED_MODULES:
548-
sys.modules.pop(mod, None)
557+
if mod not in initial_sys_modules:
558+
sys.modules.pop(mod, None)
549559
LOADED_MODULES.clear()
550560

551561
# Clear extensions caches

‎tests/test_autodiscover.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,35 @@ def test_import_libraries_map_modules(self):
9595
pytest.fail("Autodiscover should not raise AlreadyRegistered exception")
9696

9797
assert seen == ["tests.components.single_file", "tests.components.multi_file.multi_file"]
98+
99+
100+
@djc_test
101+
class TestSysModulesIsolation:
102+
"""Regression coverage for #1598: modules present before a @djc_test should not be
103+
re-executed by the test teardown."""
104+
105+
def test_modules_present_before_test_are_not_reimported(self):
106+
# The module must be imported before any @djc_test cycle touches it.
107+
import tests.components.single_file # noqa: PLC0415
108+
109+
module_before = sys.modules.get("tests.components.single_file")
110+
assert module_before is not None
111+
module_id_before = id(module_before)
112+
113+
@djc_test
114+
def inner_test() -> None:
115+
from django_components.autodiscovery import autodiscover # noqa: PLC0415
116+
117+
autodiscover(map_module=lambda p: "tests." + p if p.startswith("components") else p)
118+
119+
# Run two cycles - prior to the fix, the first teardown would pop the module from
120+
# `sys.modules`, and the second setup's `autodiscover` would re-execute it.
121+
inner_test()
122+
inner_test()
123+
124+
module_after = sys.modules.get("tests.components.single_file")
125+
assert module_after is not None
126+
assert id(module_after) == module_id_before, (
127+
"tests.components.single_file was re-executed across @djc_test cycles; "
128+
"the sys.modules snapshot in _clear_djc_global_state should have prevented this."
129+
)

0 commit comments

Comments
 (0)