summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2020-06-11 18:31:46 (GMT)
committerGitHub <noreply@github.com>2020-06-11 18:31:46 (GMT)
commit3e499cda47afe2282ca3f1d04151e2c86f2e7e09 (patch)
tree689ab461cf045475ee9db35c75b6b75f40565792 /Lib
parent5b8e3a533560c39eb40b2fb950d2b14caacfaf6a (diff)
downloadcpython-3e499cda47afe2282ca3f1d04151e2c86f2e7e09.zip
cpython-3e499cda47afe2282ca3f1d04151e2c86f2e7e09.tar.gz
cpython-3e499cda47afe2282ca3f1d04151e2c86f2e7e09.tar.bz2
bpo-29620: iterate over a copy of sys.modules (GH-4800) (GH-20816)
unittest.TestCase.assertWarns no longer raises a RuntimeException when accessing a module's ``__warningregistry__`` causes importation of a new module, or when a new module is imported in another thread. (cherry picked from commit 46398fba4d66ad342cf2504ef947b5fb857423b2) Co-authored-by: kernc <kerncece@gmail.com>
Diffstat (limited to 'Lib')
-rw-r--r--Lib/unittest/case.py2
-rw-r--r--Lib/unittest/test/test_case.py15
2 files changed, 16 insertions, 1 deletions
diff --git a/Lib/unittest/case.py b/Lib/unittest/case.py
index e5734b6..3223c0b 100644
--- a/Lib/unittest/case.py
+++ b/Lib/unittest/case.py
@@ -251,7 +251,7 @@ class _AssertWarnsContext(_AssertRaisesBaseContext):
def __enter__(self):
# The __warningregistry__'s need to be in a pristine state for tests
# to work properly.
- for v in sys.modules.values():
+ for v in list(sys.modules.values()):
if getattr(v, '__warningregistry__', None):
v.__warningregistry__ = {}
self.warnings_manager = warnings.catch_warnings(record=True)
diff --git a/Lib/unittest/test/test_case.py b/Lib/unittest/test/test_case.py
index f855c4d..3dedcbe 100644
--- a/Lib/unittest/test/test_case.py
+++ b/Lib/unittest/test/test_case.py
@@ -8,6 +8,7 @@ import logging
import warnings
import weakref
import inspect
+import types
from copy import deepcopy
from test import support
@@ -1350,6 +1351,20 @@ test case
pass
self.assertRaises(TypeError, self.assertWarnsRegex, MyWarn, lambda: True)
+ def testAssertWarnsModifySysModules(self):
+ # bpo-29620: handle modified sys.modules during iteration
+ class Foo(types.ModuleType):
+ @property
+ def __warningregistry__(self):
+ sys.modules['@bar@'] = 'bar'
+
+ sys.modules['@foo@'] = Foo('foo')
+ try:
+ self.assertWarns(UserWarning, warnings.warn, 'expected')
+ finally:
+ del sys.modules['@foo@']
+ del sys.modules['@bar@']
+
def testAssertRaisesRegexMismatch(self):
def Stub():
raise Exception('Unexpected')