bpo-36996: Handle async functions when mock.patch is used as a decorator#13562
bpo-36996: Handle async functions when mock.patch is used as a decorator#13562miss-islington merged 6 commits intopython:masterfrom
Conversation
Co-authored-by: Andrew Svetlov <andrew.svetlov@gmail.com>
|
I have tried using below pattern but I am not sure modifying the return value data type based on a flag as a good idea. Also using yield from makes it not usable as a function with the return statement in else part since patched is marked as a generator. So I have used a separate def decorate_callable(self, func, async_func=False):
def patched(func):
if async_func:
yield from func(*args, **keywargs)
else:
return func(*args, **keywargs)
if async_func:
patched = types.coroutine(async_func) |
asvetlov
left a comment
There was a problem hiding this comment.
Interesting challenge.
Let me try to find a way to don't duplicate too much.
Lib/unittest/mock.py
Outdated
|
|
||
|
|
||
| def decorate_async_callable(self, func): | ||
| '''This is same as decorate_callable except patched is a coroutine''' |
There was a problem hiding this comment.
Please replace docstring with just a comment.
Docstrings are for public API but this class is entirely an implementation detail.
In the comment please add an explicit text like NB. Keep the method in sync with decorate_callable.
Add the same comment to decorate_callable.
|
This seems to work fine: |
|
This looks like a cool pattern to me on the control flow with yield and acts like the code is pasted except the logic can be used for sync and async functions. |
Co-authored-by: Andrew Svetlov <andrew.svetlov@gmail.com>
asvetlov
left a comment
There was a problem hiding this comment.
Looks good, a few very minor comments
Add parens to comment Co-Authored-By: Andrew Svetlov <andrew.svetlov@gmail.com>
Add parens to comment Co-Authored-By: Andrew Svetlov <andrew.svetlov@gmail.com>
|
thanks! |
|
Thanks @asvetlov for the review and merge. |
…tor (pythonGH-13562) Return a coroutine while patching async functions with a decorator. Co-authored-by: Andrew Svetlov <andrew.svetlov@gmail.com> https://bugs.python.org/issue36996
Return a coroutine while patching async functions with a decorator.
Co-authored-by: Andrew Svetlov andrew.svetlov@gmail.com
https://bugs.python.org/issue36996