Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Changes from 1 commit
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
Next Next commit
support inspect.iscoroutinefunction in create_autospec(async_def)
  • Loading branch information
graingert committed Jul 18, 2022
commit 1a393123fe761a5d799a541736ced30ff4489ee5
32 changes: 30 additions & 2 deletions Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,33 @@ def checksig(*args, **kwargs):
_setup_func(funcopy, mock, sig)
return funcopy

def _set_async_signature(mock, original, instance=False, is_async_mock=False):
# creates an async function with signature (*args, **kwargs) that delegates to a
# mock. It still does signature checking by calling a lambda with the same
# signature as the original.

skipfirst = isinstance(original, type)
result = _get_signature_object(original, instance, skipfirst)
if result is None:
return mock
func, sig = result
def checksig(*args, **kwargs):
sig.bind(*args, **kwargs)
_copy_func_details(func, checksig)

name = original.__name__
if not name.isidentifier():
name = 'funcopy'
context = {'_checksig_': checksig, 'mock': mock}
src = """async def %s(*args, **kwargs):
_checksig_(*args, **kwargs)
return await mock(*args, **kwargs)""" % name
exec (src, context)
funcopy = context[name]
_setup_func(funcopy, mock, sig)
_setup_async_mock(funcopy)
return funcopy


def _setup_func(funcopy, mock, sig):
funcopy.mock = mock
Expand Down Expand Up @@ -2681,9 +2708,10 @@ def create_autospec(spec, spec_set=False, instance=False, _parent=None,
if isinstance(spec, FunctionTypes):
# should only happen at the top level because we don't
# recurse for functions
mock = _set_signature(mock, spec)
if is_async_func:
_setup_async_mock(mock)
mock = _set_async_signature(mock, spec)
else:
mock = _set_signature(mock, spec)
else:
_check_signature(spec, mock, is_type, instance)

Expand Down