Content-Length: 292224 | pFad | http://github.com/python/cpython/commit/88b101ff52010f795b34e3afc04c0e934d662d82

52 [3.10] gh-98086: Now ``patch.dict`` can decorate async functions (GH-… · python/cpython@88b101f · GitHub
Skip to content

Commit

Permalink
[3.10] gh-98086: Now patch.dict can decorate async functions (GH-…
Browse files Browse the repository at this point in the history
…98095) (GH-99366)

gh-98086: Now ``patch.dict`` can decorate async functions (GH-98095)
(cherry picked from commit 67b4d27)

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
Co-authored-by: Chris Withers <chris@withers.org>
  • Loading branch information
3 people authored Nov 20, 2022
1 parent 42b7b21 commit 88b101f
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
18 changes: 18 additions & 0 deletions Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -1820,6 +1820,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 @@ -1831,6 +1837,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 Lib/unittest/test/testmock/testasync.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Make sure ``patch.dict()`` can be applied on async functions.

0 comments on commit 88b101f

Please sign in to comment.








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: http://github.com/python/cpython/commit/88b101ff52010f795b34e3afc04c0e934d662d82

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy