Extension to the standard mock framework to support support async
Project Links
Meta
Author: Tim Savage
Requires Python: >=3.6
Classifiers
Development Status
- 5 - Production/Stable
Intended Audience
- Developers
License
- OSI Approved :: BSD License
Operating System
- OS Independent
Programming Language
- Python :: 3.6
- Python :: 3.7
- Python :: 3.8
- Python :: Implementation :: CPython
- Python :: Implementation :: PyPy
Awaitable mocks for async code.
The package specifically only extends mock and not any other part of unittest.
Installation
Install using pip:
pip install asyncmock
Usage
Async Mock is a drop in replacement for a Mock object eg:
my_mock = AsyncMock()
await my_mock("foo", bar=123)
my_mock.assert_called_with("foo", bar=123)
This also works with nested methods:
my_mock = AsyncMock()
await my_mock.my_method("foo", bar=123)
my_mock.my_method.assert_called_with("foo", bar=123)
Side effects and return values can also be awaited.
Including a non-awaitable item:
my_mock = AsyncMock()
my_mock.my_method.not_async = True
my_mock.my_method("foo", bar=123)
The not_async option can also be provided as an init argument. The not_async argument is not inherited by sub-mocks.
pytest Example
These examples use pytest along with the pytest-asyncio plugin.
Generating an exception:
@pytest.mark.asyncio
async def test_raise_exception():
my_mock = AsyncMock(side_effect=KeyError)
with pytest.raises(KeyError):
await my_mock()
my_mock.assert_called()
Wheel compatibility matrix
Files in release
Extras:
None
Dependencies: