]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-29620: iterate over a copy of sys.modules (GH-4800) (GH-20817)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Thu, 11 Jun 2020 18:34:42 +0000 (11:34 -0700)
committerGitHub <noreply@github.com>
Thu, 11 Jun 2020 18:34:42 +0000 (14:34 -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.
(cherry picked from commit 46398fba4d66ad342cf2504ef947b5fb857423b2)

Co-authored-by: kernc <kerncece@gmail.com>
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 24af29057646a0b0a4e35148a7aecef1141a72a3..d65ff1c5fbab8b1469db3c4b12104a83161f90a4 100644 (file)
@@ -227,7 +227,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 4fac8d59745289a6b238042e53d9c29c66d77eb4..ff541f8cf0512814d202c6a3352163519e93a5fa 100644 (file)
@@ -8,6 +8,7 @@ import logging
 import warnings
 import weakref
 import inspect
+import types
 
 from copy import deepcopy
 from test import support
@@ -1352,6 +1353,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.