]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-98086: Now ``patch.dict`` can decorate async functions (#98095)
authorNikita Sobolev <mail@sobolevn.me>
Fri, 11 Nov 2022 08:04:30 +0000 (11:04 +0300)
committerGitHub <noreply@github.com>
Fri, 11 Nov 2022 08:04:30 +0000 (08:04 +0000)
Lib/test/test_unittest/testmock/testasync.py
Lib/unittest/mock.py
Misc/NEWS.d/next/Library/2022-10-08-19-39-27.gh-issue-98086.y---WC.rst [new file with mode: 0644]

index 1bab671acdef182f5536c82b47804e981456e6f7..e05a22861d47bfad56ac108d8e1e92718d7ef095 100644 (file)
@@ -149,6 +149,23 @@ class AsyncPatchCMTest(unittest.TestCase):
 
         run(test_async())
 
+    def test_patch_dict_async_def(self):
+        foo = {'a': 'a'}
+        @patch.dict(foo, {'a': 'b'})
+        async def test_async():
+            self.assertEqual(foo['a'], 'b')
+
+        self.assertTrue(iscoroutinefunction(test_async))
+        run(test_async())
+
+    def test_patch_dict_async_def_context(self):
+        foo = {'a': 'a'}
+        async def test_async():
+            with patch.dict(foo, {'a': 'b'}):
+                self.assertEqual(foo['a'], 'b')
+
+        run(test_async())
+
 
 class AsyncMockTest(unittest.TestCase):
     def test_iscoroutinefunction_default(self):
index 096b1a571473629a3b65e5753ba1762f8014661c..a273753d6a0abb6896107fde2b9e27e2551203e8 100644 (file)
@@ -1809,6 +1809,12 @@ class _patch_dict(object):
     def __call__(self, f):
         if isinstance(f, type):
             return self.decorate_class(f)
+        if inspect.iscoroutinefunction(f):
+            return self.decorate_async_callable(f)
+        return self.decorate_callable(f)
+
+
+    def decorate_callable(self, f):
         @wraps(f)
         def _inner(*args, **kw):
             self._patch_dict()
@@ -1820,6 +1826,18 @@ class _patch_dict(object):
         return _inner
 
 
+    def decorate_async_callable(self, f):
+        @wraps(f)
+        async def _inner(*args, **kw):
+            self._patch_dict()
+            try:
+                return await f(*args, **kw)
+            finally:
+                self._unpatch_dict()
+
+        return _inner
+
+
     def decorate_class(self, klass):
         for attr in dir(klass):
             attr_value = getattr(klass, attr)
diff --git a/Misc/NEWS.d/next/Library/2022-10-08-19-39-27.gh-issue-98086.y---WC.rst b/Misc/NEWS.d/next/Library/2022-10-08-19-39-27.gh-issue-98086.y---WC.rst
new file mode 100644 (file)
index 0000000..f4a1d27
--- /dev/null
@@ -0,0 +1 @@
+Make sure ``patch.dict()`` can be applied on async functions.