Skip to content

Commit ecb48f1

Browse files
committed
pythongh-98086: Now patch.dict can decorate async functions
1 parent 4ed00be commit ecb48f1

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

Lib/test/test_unittest/testmock/testasync.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,23 @@ async def test_async():
149149

150150
run(test_async())
151151

152+
def test_patch_dict_async_def(self):
153+
foo = {'a': 'a'}
154+
@patch.dict(foo, {'a': 'b'})
155+
async def test_async():
156+
self.assertEqual(foo['a'], 'b')
157+
158+
self.assertTrue(iscoroutinefunction(test_async))
159+
run(test_async())
160+
161+
def test_patch_dict_async_def_context(self):
162+
foo = {'a': 'a'}
163+
async def test_async():
164+
with patch.dict(foo, {'a': 'b'}):
165+
self.assertEqual(foo['a'], 'b')
166+
167+
run(test_async())
168+
152169

153170
class AsyncMockTest(unittest.TestCase):
154171
def test_iscoroutinefunction_default(self):

Lib/unittest/mock.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1799,6 +1799,12 @@ def __init__(self, in_dict, values=(), clear=False, **kwargs):
17991799
def __call__(self, f):
18001800
if isinstance(f, type):
18011801
return self.decorate_class(f)
1802+
if inspect.iscoroutinefunction(f):
1803+
return self.decorate_async_callable(f)
1804+
return self.decorate_callable(f)
1805+
1806+
1807+
def decorate_callable(self, f):
18021808
@wraps(f)
18031809
def _inner(*args, **kw):
18041810
self._patch_dict()
@@ -1810,6 +1816,18 @@ def _inner(*args, **kw):
18101816
return _inner
18111817

18121818

1819+
def decorate_async_callable(self, f):
1820+
@wraps(f)
1821+
async def _inner(*args, **kw):
1822+
self._patch_dict()
1823+
try:
1824+
return await f(*args, **kw)
1825+
finally:
1826+
self._unpatch_dict()
1827+
1828+
return _inner
1829+
1830+
18131831
def decorate_class(self, klass):
18141832
for attr in dir(klass):
18151833
attr_value = getattr(klass, attr)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Make sure ``patch.dict()`` can be applied on async functions.

0 commit comments

Comments
 (0)