Skip to content

Commit

Permalink
gh-98086: Now patch.dict can decorate async functions (#98095)
Browse files Browse the repository at this point in the history
Backports: 67b4d2772c5124b908f8ed9b13166a79bbeb88d2
Signed-off-by: Chris Withers <chris@simplistix.co.uk>
  • Loading branch information
sobolevn authored and cjw296 committed Dec 28, 2022
1 parent 4d3f197 commit a2cb0be
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions NEWS.d/2022-10-08-19-39-27.gh-issue-98086.y---WC.rst
@@ -0,0 +1 @@
Make sure ``patch.dict()`` can be applied on async functions.
18 changes: 18 additions & 0 deletions mock/mock.py
Expand Up @@ -1839,6 +1839,12 @@ def __init__(self, in_dict, values=(), clear=False, **kwargs):
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()
Expand All @@ -1850,6 +1856,18 @@ def _inner(*args, **kw):
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)
Expand Down
17 changes: 17 additions & 0 deletions mock/tests/testasync.py
Expand Up @@ -159,6 +159,23 @@ async def test_async():

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):
Expand Down

0 comments on commit a2cb0be

Please sign in to comment.