Skip to content

Commit 3e499cd

Browse files
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 46398fb) Co-authored-by: kernc <[email protected]>
1 parent 5b8e3a5 commit 3e499cd

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

Lib/unittest/case.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ class _AssertWarnsContext(_AssertRaisesBaseContext):
251251
def __enter__(self):
252252
# The __warningregistry__'s need to be in a pristine state for tests
253253
# to work properly.
254-
for v in sys.modules.values():
254+
for v in list(sys.modules.values()):
255255
if getattr(v, '__warningregistry__', None):
256256
v.__warningregistry__ = {}
257257
self.warnings_manager = warnings.catch_warnings(record=True)

Lib/unittest/test/test_case.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import warnings
99
import weakref
1010
import inspect
11+
import types
1112

1213
from copy import deepcopy
1314
from test import support
@@ -1350,6 +1351,20 @@ class MyWarn(Warning):
13501351
pass
13511352
self.assertRaises(TypeError, self.assertWarnsRegex, MyWarn, lambda: True)
13521353

1354+
def testAssertWarnsModifySysModules(self):
1355+
# bpo-29620: handle modified sys.modules during iteration
1356+
class Foo(types.ModuleType):
1357+
@property
1358+
def __warningregistry__(self):
1359+
sys.modules['@bar@'] = 'bar'
1360+
1361+
sys.modules['@foo@'] = Foo('foo')
1362+
try:
1363+
self.assertWarns(UserWarning, warnings.warn, 'expected')
1364+
finally:
1365+
del sys.modules['@foo@']
1366+
del sys.modules['@bar@']
1367+
13531368
def testAssertRaisesRegexMismatch(self):
13541369
def Stub():
13551370
raise Exception('Unexpected')
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:func:`~unittest.TestCase.assertWarns` no longer raises a ``RuntimeException``
2+
when accessing a module's ``__warningregistry__`` causes importation of a new
3+
module, or when a new module is imported in another thread. Patch by Kernc.

0 commit comments

Comments
 (0)