PyDocs

Nav

Development Tools

AsyncMock

unittest.mock

class · Added in 3.8 (source)
  • AsyncMock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs)
Enhance :class:`Mock` with features allowing to mock
an async function.

The :class:`AsyncMock` object will behave so the object is
recognized as an async function, and the result of a call is an awaitable:

>>> mock = AsyncMock()
>>> inspect.iscoroutinefunction(mock)
True
>>> inspect.isawaitable(mock())
True


The result of ``mock()`` is an async function which will have the outcome
of ``side_effect`` or ``return_value``:

- if ``side_effect`` is a function, the async function will return the
  result of that function,
- if ``side_effect`` is an exception, the async function will raise the
  exception,
- if ``side_effect`` is an iterable, the async function will return the
  next value of the iterable, however, if the sequence of result is
  exhausted, ``StopIteration`` is raised immediately,
- if ``side_effect`` is not defined, the async function will return the
  value defined by ``return_value``, hence, by default, the async function
  returns a new :class:`AsyncMock` object.

If the outcome of ``side_effect`` or ``return_value`` is an async function,
the mock async function obtained when the mock object is called will be this
async function itself (and not an async function returning an async
function).

The test author can also specify a wrapped object with ``wraps``. In this
case, the :class:`Mock` object behavior is the same as with an
:class:`.Mock` object: the wrapped object may have methods
defined as async function functions.

Based on Martin Richard's asynctest project.
Members of AsyncMock

a

assert_any_await
Assert the mock has ever been awaited with the specified arguments.
assert_awaited
Assert that the mock was awaited at least once.
assert_awaited_once
Assert that the mock was awaited exactly once.
assert_awaited_once_with
Assert that the mock was awaited exactly once and with the specified arguments.
assert_awaited_with
Assert that the last await was with the specified arguments.
assert_has_awaits
Assert the mock has been awaited with the specified calls.
assert_not_awaited
Assert that the mock was never awaited.
await_args
This is either None (if the mock hasn’t been awaited), or the arguments that the mock was last awaited with.
await_args_list
This is a list of all the awaits made to the mock object in sequence (so the length of the list is the number of times it has been awaited).
await_count
An integer keeping track of how many times the mock object has been awaited.

r

reset_mock
See :func:`.Mock.reset_mock()`
1 Example
>>> mock = AsyncMock()
>>> inspect.iscoroutinefunction(mock)
True
>>> inspect.isawaitable(mock())
True
from the Python docs
See Also
No see-alsos for unittest.mock/AsyncMock
0 Notes
No notes for AsyncMock