-
-
Notifications
You must be signed in to change notification settings - Fork 33.1k
bpo-36996: Handle async functions when mock.patch is used as a decorator #13562
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Co-authored-by: Andrew Svetlov <[email protected]>
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) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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 <[email protected]>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good, a few very minor comments
Add parens to comment Co-Authored-By: Andrew Svetlov <[email protected]>
Add parens to comment Co-Authored-By: Andrew Svetlov <[email protected]>
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 <[email protected]> https://bugs.python.org/issue36996
Return a coroutine while patching async functions with a decorator.
Co-authored-by: Andrew Svetlov [email protected]
https://bugs.python.org/issue36996