Skip to content

Commit f881c86

Browse files
bpo-29620: iterate over a copy of sys.modules (GH-4800) (GH-20817)
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 0490398 commit f881c86

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
@@ -227,7 +227,7 @@ class _AssertWarnsContext(_AssertRaisesBaseContext):
227227
def __enter__(self):
228228
# The __warningregistry__'s need to be in a pristine state for tests
229229
# to work properly.
230-
for v in sys.modules.values():
230+
for v in list(sys.modules.values()):
231231
if getattr(v, '__warningregistry__', None):
232232
v.__warningregistry__ = {}
233233
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
@@ -1352,6 +1353,20 @@ class MyWarn(Warning):
13521353
pass
13531354
self.assertRaises(TypeError, self.assertWarnsRegex, MyWarn, lambda: True)
13541355

1356+
def testAssertWarnsModifySysModules(self):
1357+
# bpo-29620: handle modified sys.modules during iteration
1358+
class Foo(types.ModuleType):
1359+
@property
1360+
def __warningregistry__(self):
1361+
sys.modules['@bar@'] = 'bar'
1362+
1363+
sys.modules['@foo@'] = Foo('foo')
1364+
try:
1365+
self.assertWarns(UserWarning, warnings.warn, 'expected')
1366+
finally:
1367+
del sys.modules['@foo@']
1368+
del sys.modules['@bar@']
1369+
13551370
def testAssertRaisesRegexMismatch(self):
13561371
def Stub():
13571372
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)