]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-29620: iterate over a copy of sys.modules (GH-4800) (GH-20816)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Thu, 11 Jun 2020 18:31:46 +0000 (11:31 -0700)
committerGitHub <noreply@github.com>
Thu, 11 Jun 2020 18:31:46 +0000 (14:31 -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 e5734b6b7a298bd60338d5e599047d1de3cf00b1..3223c0bff6fa2195d201a33f2c954ea59728a952 100644 (file)
@@ -251,7 +251,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.