Python unittest.mock.AsyncMock














































Python unittest.mock.AsyncMock



unittest.mock.AsyncMock



class unittest.mock.AsyncMock(spec=Noneside_effect=Nonereturn_value=DEFAULTwraps=Nonename=Nonespec_set=Noneunsafe=False**kwargs)

An asynchronous version of MagicMock. The AsyncMock object will behave so the object is recognized as an async function, and the result of a call is an awaitable.


import asyncio

import inspect

from unittest.mock import AsyncMock

mock = AsyncMock()

print(asyncio.iscoroutinefunction(mock))

True

print(inspect.isawaitable(mock()))

True 
PATH:
RuntimeWarning: coroutine 'AsyncMockMixin._execute_mock_call' was never awaited
  print(inspect.isawaitable(mock()))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

The result of mock() is an async function which will have the outcome of side_effect or return_value after it has been awaited:


    • 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, StopAsyncIteration 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 AsyncMock object.

Setting the spec of a Mock or MagicMock to an async function will result in a coroutine object being returned after calling.


from unittest.mock import AsyncMock, MagicMock
async def async_func(): pass
mock = MagicMock(async_func)
print(mock)
<MagicMock spec='function' id='2740068987424'>
print(mock())
<coroutine object AsyncMockMixin._execute_mock_call at 0x0000027DFB2BC5C0>
PATH: 
RuntimeWarning: coroutine 'AsyncMockMixin._execute_mock_call' was never awaited
  print(mock())
RuntimeWarning: Enable tracemalloc to get the object allocation traceback


Setting the spec of a MockMagicMock, or AsyncMock to a class with asynchronous and synchronous functions will automatically detect the synchronous functions and set them as MagicMock (if the parent mock is AsyncMock or MagicMock) or Mock (if the parent mock is Mock). All asynchronous functions will be AsyncMock.

from unittest.mock import AsyncMock, MagicMock
class ExampleClass:
def sync_foo():
pass
async def
async def async_foo():
pass
a_mock = AsyncMock(ExampleClass)
print(a_mock.sync_foo)
<MagicMock name='mock.sync_foo' id='2371522174352'>
print(a_mock.async_foo)
<AsyncMock name='mock.async_foo' id='2371522248176'>
mock = Mock(ExampleClass)
print(mock.sync_foo)
<Mock name='mock.sync_foo' id='2371522392016'>
print(mock.async_foo)
<AsyncMock name='mock.async_foo' id='2371522174640'>

New in version 3.8.



assert_awaited()

Assert that the mock was awaited at least once. Note that this is separate from the object having been called, the await keyword must be used:

import asyncio
from unittest.mock import AsyncMock
mock = AsyncMock()
async def main(coroutine_mock):
await coroutine_mock
coroutine_mock = mock()
print(mock.called)
True
print(mock.assert_awaited())
Traceback (most recent call last):
  File "mock.py", line 2159, in assert_awaited
    raise AssertionError(msg)
AssertionError: Expected mock to have been awaited.
sys:1: RuntimeWarning: coroutine 'AsyncMockMixin._execute_mock_call' was never awaited
asyncio.run(main(coroutine_mock))
mock.assert_awaited()

assert_awaited_once()

Assert that the mock was awaited exactly once.

import asyncio
from unittest.mock import AsyncMock
mock = AsyncMock()
async def main():
await mock()
asyncio.run(main())
mock.assert_awaited_once()
asyncio.run(main())
mock.method.assert_awaited_once()
Traceback (most recent call last):
...
AssertionError: Expected mock to have been awaited once. Awaited 0 times.

assert_awaited_with(*args**kwargs)

Assert that the last await was with the specified arguments.

import asyncio
from unittest.mock import AsyncMock
mock = AsyncMock()
async def main(*args, **kwargs):
await mock(*args, **kwargs)
asyncio.run(main('cppsecrets', bar='bar'))
mock.assert_awaited_with('cppsecrets', bar='bar')
mock.assert_awaited_with('other')
Traceback (most recent call last):
...
AssertionError: expected call not found.
Expected: mock('other')
Actual: mock('cppsecrets', bar='bar')


assert_awaited_once_with(*args**kwargs)

Assert that the mock was awaited exactly once and with the specified arguments.

import asyncio
from unittest.mock import AsyncMock
mock = AsyncMock()
async def main(*args, **kwargs):
await mock(*args, **kwargs)
asyncio.run(main('cppsecrets', bar='bar'))
mock.assert_awaited_once_with('cppsecrets', bar='bar')
asyncio.run(main('cppsecrets', bar='bar'))
mock.assert_awaited_once_with('cppsecrets', bar='bar')
Traceback (most recent call last):
...
AssertionError: Expected mock to have been awaited once. Awaited 2 times.

assert_any_await(*args**kwargs)

Assert the mock has ever been awaited with the specified arguments.

import asyncio
from unittest.mock import AsyncMock
mock = AsyncMock()
async def main(*args, **kwargs):
await mock(*args, **kwargs)
asyncio.run(main('cppsecrets', bar='bar'))
asyncio.run(main('hello'))
mock.assert_any_await('cppsecrets', bar='bar')
mock.assert_any_await('other')
Traceback (most recent call last):
...
AssertionError: mock('other') await not found

assert_has_awaits(callsany_order=False)

Assert the mock has been awaited with the specified calls. The await_args_list list is checked for the awaits.

If any_order is false then the awaits must be sequential. There can be extra calls before or after the specified awaits.

If any_order is true then the awaits can be in any order, but they must all appear in await_args_list.

import asyncio
from unittest.mock import AsyncMock, call
mock = AsyncMock()
async def main(*args, **kwargs):
await mock(*args, **kwargs)
calls = [call("cppsecrets"), call("bar")]
mock.assert_has_awaits(calls)
Traceback (most recent call last):
...
AssertionError: Awaits not found.
Expected: [call('foo'), call('bar')]
Actual: []
asyncio.run(main('cppsecrets'))
asyncio.run(main('bar'))
mock.assert_has_awaits(calls)

assert_not_awaited()

Assert that the mock was never awaited.

mock = AsyncMock()
mock.assert_not_awaited()

reset_mock(*args**kwargs)

See Mock.reset_mock(). Also sets await_count to 0, await_args to None, and clears the await_args_list.

await_count

An integer keeping track of how many times the mock object has been awaited.

import asyncio
from unittest.mock import AsyncMock, call
mock = AsyncMock()
async def main():
await mock()
asyncio.run(main())
print(mock.await_count)
1
asyncio.run(main())
print(mock.await_count)
2


await_args

This is either None (if the mock hasn't been awaited), or the arguments that the mock was last awaited with. Functions the same as Mock.call_args.


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). Before any awaits have been made it is an empty list.



 <<PREV                                                                                                                                         NEXT>>


More Articles of Shubhanjay Pandey:

Name Views Likes
Python ssl Sockets 998 3
Python unittest.mock side_effect 503 2
Python ssl Example Server Side Operation 771 3
Python unittest.mock method_calls and mock_calls 841 2
Python ssl TLS 1.3 and LibreSSL Support 1450 2
Python unittest.mock The patchers 310 2
Python unittest.mock Attaching Mocks as Attributes 433 2
Python ssl Example Client Side Operations 463 3
Python unittest.mock patch.object and patch.dict 2748 2
Python unittest.mock.call_args and call_args_list 3286 2
Python ssl Certificates 321 3
Python unittest.mock Deleting, Mock Names and the name attribute 517 2
Python unittest.mock FILTER_DIR 254 2
Python ssl Introduction 286 3
Python unitest.mock Where to patch, patching descriptors and proxy objects 268 2
Python ssl Memory BIO Support 539 3
Python mimetypes - Introduction 333 3
Python unittest.mock Helpers call 282 2
Python unittest.mock function assert_*() 283 2
Python unittest.mock Introduction 340 2
Python sunau library 305 2
Python unittest.mock The Mock Class 275 2
Python ssl Constants Part 1 357 3
Python mimetypes.add_type 257 4
Python ssl Socket and Context Creation 1300 3
Python unittest.mock.mock_open 297 2
Python ssl non-blocking sockets 646 3
Python unittest.mock MagicMock and magic method support 847 1
Python unittest.mock Magic Mock 370 2
Python ssl Exceptions 307 3
Python unittest.mock TEST_PREFIX and Nesting Patch Decorators 395 2
Python unittest.mock patch.multiple and builtins 2017 2
Python mimetypes additional data 232 3
Python unittest.mock Other HELPERS 252 2
Python MimeTypes Object 267 3
Python mimetypes.guess_type 332 3
Python unittest.mock Autospeccing 304 2
Python unittest.mock.AsyncMock 2441 2
Python ssl Certificates Handling 375 3
Python ssl Random Generation 290 3
Python unittest.mock Function configure_mock 385 2
Python ssl SSLContexts Part 1 618 3
Python unittest.mock patch methods: start and stop 1693 2
Python unittest.mock Calling 271 2
Python unittest.mock other functions 268 2
Python ssl Constants Part 2 430 3
Python ssl SSLContexts Part 2 764 3
Python ssl Security Considerations and SSL Session 416 3
Python mimetypes.guess_extension 313 3
Python unittest.mock PropertyMock and NonCallableMock 787 2
Python mimetypes additional functions 253 3

Comments