Skip to content

Commit af75d55

Browse files
committed
bpo-29620: iterate over a copy of sys.modules
1 parent 457306b commit af75d55

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-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: 13 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
@@ -1341,6 +1342,18 @@ class MyWarn(Warning):
13411342
pass
13421343
self.assertRaises(TypeError, self.assertWarnsRegex, MyWarn, lambda: True)
13431344

1345+
def testAssertWarnsModifySysModules(self):
1346+
# bpo-29620: handle modified sys.modules during iteration
1347+
class Foo(types.ModuleType):
1348+
@property
1349+
def __warningregistry__(self):
1350+
sys.modules['@bar@'] = 'bar'
1351+
1352+
sys.modules['@foo@'] = Foo('foo')
1353+
self.assertWarns(UserWarning, warnings.warn, 'expected')
1354+
del sys.modules['@foo@']
1355+
del sys.modules['@bar@']
1356+
13441357
def testAssertRaisesRegexMismatch(self):
13451358
def Stub():
13461359
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)