Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions Lib/test/test_unittest/testmock/testasync.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,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
18 changes: 18 additions & 0 deletions Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -1799,6 +1799,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 @@ -1810,6 +1816,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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Make sure ``patch.dict()`` can be applied on async functions.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For future PRs, please make sure that the news fragment makes sense when it’s read in the compiled changelog.
Here patch is mentioned but there is no such builtin, it would be better to name unittest.mock.patch.dict (like the issue helpfully did). Thanks!