]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-29620: iterate over a copy of sys.modules (GH-4800)
authorkernc <kerncece@gmail.com>
Thu, 11 Jun 2020 18:03:29 +0000 (20:03 +0200)
committerGitHub <noreply@github.com>
Thu, 11 Jun 2020 18:03:29 +0000 (14:03 -0400)
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.

Patch by Kernc.

Lib/unittest/case.py
Lib/unittest/test/test_case.py
Misc/NEWS.d/next/Library/2018-08-21-16-20-33.bpo-29620.xxx666.rst [new file with mode: 0644]

index f8bc865ee82039f70258ab2fd9e809649ca7896a..52eb7d05ed1431c38c7f151b5e0162265da58582 100644 (file)
@@ -252,7 +252,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)
index f855c4dc00b316ee90b0d750e5f2a614fae6f5d4..3dedcbe6aad5fc7cfc50c23175663abf91b5d6de 100644 (file)
@@ -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')
diff --git a/Misc/NEWS.d/next/Library/2018-08-21-16-20-33.bpo-29620.xxx666.rst b/Misc/NEWS.d/next/Library/2018-08-21-16-20-33.bpo-29620.xxx666.rst
new file mode 100644 (file)
index 0000000..d781919
--- /dev/null
@@ -0,0 +1,3 @@
+:func:`~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. Patch by Kernc.