]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-29620: iterate over a copy of sys.modules (GH-4800) (GH-29605)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Thu, 18 Nov 2021 16:09:41 +0000 (08:09 -0800)
committerGitHub <noreply@github.com>
Thu, 18 Nov 2021 16:09:41 +0000 (17:09 +0100)
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.
(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 34f03628ed068a986a99aeda1162a8c48dc22966..88f1a40865156d67d8e40c5a443e2f86a8b2d828 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 590dd74997aaf8ebc7c9feb6baf07ab971dde47e..65dc0c65d556648e6d4ea7ca083e0f89b32ff0c8 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.