Skip to main content

Extension to the standard mock framework to support support async

Project description

Awaitable mocks for async code.

https://img.shields.io/badge/code%20style-black-000000.svg https://travis-ci.org/timsavage/asyncmock.svg?branch=master https://img.shields.io/pypi/l/asyncmock.svg https://img.shields.io/pypi/pyversions/asyncmock.svg https://img.shields.io/pypi/status/asyncmock.svg https://img.shields.io/pypi/implementation/asyncmock.svg

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()

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for asyncmock, version 0.4.1
Filename, size File type Python version Upload date Hashes
Filename, size asyncmock-0.4.1-py3-none-any.whl (4.3 kB) File type Wheel Python version py3 Upload date Hashes View hashes
Filename, size asyncmock-0.4.1.tar.gz (3.1 kB) File type Source Python version None Upload date Hashes View hashes

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page