[3.12] gh-108927: Fix removing testing modules from sys.modules (GH-108952) (ПР-112711)

It breaks import machinery if the test module has submodules used in
other tests.
(cherry picked from commit e08b70fab1)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
This commit is contained in:
Miss Islington (bot) 2023-12-04 17:17:38 +01:00 committed by GitHub
parent f49d07327a
commit 8d21242bd1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 67 additions and 9 deletions

View file

@ -306,7 +306,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:
@ -330,10 +330,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