gh-108927: Fix removing testing modules from sys.modules (GH-108952)

It breaks import machinery if the test module has submodules used in
other tests.
This commit is contained in:
Serhiy Storchaka 2023-12-04 17:43:27 +02:00 committed by GitHub
parent c718ab92a5
commit e08b70fab1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 67 additions and 9 deletions

View file

@ -311,7 +311,7 @@ class Regrtest:
else:
tracer = None
save_modules = sys.modules.keys()
save_modules = set(sys.modules)
jobs = runtests.get_jobs()
if jobs is not None:
@ -335,10 +335,18 @@ class Regrtest:
result = self.run_test(test_name, runtests, tracer)
# Unload the newly imported modules (best effort finalization)
for module in sys.modules.keys():
if module not in save_modules and module.startswith("test."):
support.unload(module)
# Unload the newly imported test modules (best effort finalization)
new_modules = [module for module in sys.modules
if module not in save_modules and
module.startswith(("test.", "test_"))]
for module in new_modules:
sys.modules.pop(module, None)
# Remove the attribute of the parent module.
parent, _, name = module.rpartition('.')
try:
delattr(sys.modules[parent], name)
except (KeyError, AttributeError):
pass
if result.must_stop(self.fail_fast, self.fail_env_changed):
break