Skip to content

Commit 5ee5531

Browse files
authored
Properly unload modules between tests (RustPython#5192)
There seems to have been a bug in the libregrtest code which unloaded modules between tests. The previous state was calculated using `sys.modules.keys()`, which is actually a mutable object that is updated as the underlying `sys.modules` is updated. The result was that modules were not unloaded between tests, which is the root cause for `test_unittest` failing when run after `test_import` and `test_importlib`. This code is copied from 3.12. Ideally all of `libregrtest` should probably be updated as it seems wildly out of date, but that's a lot more work.
1 parent 3737f2a commit 5ee5531

1 file changed

Lines changed: 13 additions & 5 deletions

File tree

‎Lib/test/libregrtest/main.py‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -373,7 +373,7 @@ def run_tests_sequential(self):
373373
import trace
374374
self.tracer = trace.Trace(trace=False, count=True)
375375

376-
save_modules = sys.modules.keys()
376+
save_modules = set(sys.modules)
377377

378378
print("Run tests sequentially")
379379

@@ -409,10 +409,18 @@ def run_tests_sequential(self):
409409
# be quiet: say nothing if the test passed shortly
410410
previous_test = None
411411

412-
# Unload the newly imported modules (best effort finalization)
413-
for module in sys.modules.keys():
414-
if module not in save_modules and module.startswith("test."):
415-
import_helper.unload(module)
412+
# Unload the newly imported test modules (best effort finalization)
413+
new_modules = [module for module in sys.modules
414+
if module not in save_modules and
415+
module.startswith(("test.", "test_"))]
416+
for module in new_modules:
417+
sys.modules.pop(module, None)
418+
# Remove the attribute of the parent module.
419+
parent, _, name = module.rpartition('.')
420+
try:
421+
delattr(sys.modules[parent], name)
422+
except (KeyError, AttributeError):
423+
pass
416424

417425
if previous_test:
418426
print(previous_test)

0 commit comments

Comments
 (0)