[New-bugs-announce] [issue37383] call count in not registered in AsyncMock till the coroutine is awaited

Karthikeyan Singaravelan report at bugs.python.org
Mon Jun 24 06:30:16 EDT 2019


New submission from Karthikeyan Singaravelan <tir.karthi at gmail.com>:

I noticed this while working on https://github.com/aio-libs/aiosmtpd/issues/167 where an async function was mocked that now returns an AsyncMock instead of MagicMock. The tests seem to look for call_args, mock_calls etc in the synchronous API without awaiting on the AsyncMock. In AsyncMock __call__ is an async function [0] and hence in the below example mock_calls is not recorded unless the coroutine is awaited. Is this intended since super()._mock_call [1] is inside the async function _mock_call through which the synchronous API is recorded. It's slightly confusing in my opinion while trying to use synchronous helpers before calling await. 

./python.exe -m asyncio
asyncio REPL 3.9.0a0 (heads/master:770847a7db, Jun 24 2019, 10:36:45)
[Clang 7.0.2 (clang-700.1.81)] on darwin
Use "await" directly instead of "asyncio.run()".
Type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>> from unittest.mock import AsyncMock
>>> mock = AsyncMock()
>>> coro = mock(1, 2)
>>> mock.mock_calls
[]
>>> await coro # Await executes _mock_call now and hence mock_calls are registered
<AsyncMock name='mock()' id='4332060752'>
>>> mock.mock_calls
[call(1, 2)]

[0] https://github.com/python/cpython/blob/47fbc4e45b35b3111e2d947a66490a43ac21d363/Lib/unittest/mock.py#L2081
[1] https://github.com/python/cpython/blob/47fbc4e45b35b3111e2d947a66490a43ac21d363/Lib/unittest/mock.py#L2083

----------
components: Library (Lib)
messages: 346364
nosy: cjw296, lisroach, mariocj89, michael.foord, xtreak
priority: normal
severity: normal
status: open
title: call count in not registered in AsyncMock till the coroutine is awaited
type: behavior
versions: Python 3.8, Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue37383>
_______________________________________


More information about the New-bugs-announce mailing list