-
Notifications
You must be signed in to change notification settings - Fork 313
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Prefer AsyncMock to as_future (#1366)
In Python, calling an async function `f()` can be done in two steps: 1. call the function using regular function call `f()` 2. `await` the result, possibly later The driver tests took advantage of this detail to make `MagicMock` work with async functions by using `as_future`. With that trick, mocked functions return an awaitable result, which are then awaited in the tested code. However, coroutines are best thought as an implementation detail, and it's better to always call an async function `f` using `await f()`, never separating the two steps mentioned above. Thankfully, Python 3.8 introduced `AsyncMock` that allows removing `as_future` by just specifying a return value, which avoids thinking about coroutines, which is what we want. There's just one wrinkle: while `mock.patch()` replaces the target with an `AsyncMock`, it does not work recursively. So while we would like to rewrite ``` es.cluster.health.return_value = as_future({"status": "green", "relocating_shards": 0}) ``` to ``` es.cluster.health.return_value = {"status": "green", "relocating_shards": 0} ``` we need to use ``` es.cluster.health = mock.AsyncMock(return_value={"status": "green", "relocating_shards": 0}) ``` which is still an improvement as it avoids the `as_future` code smell.
- Loading branch information
Showing
3 changed files
with
446 additions
and
465 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.