You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Spy with async function not registering calls until coroutine is awaited #519
Started happening after I upgraded to Python version 3.13.
Pytest mock version 3.14.1
AsyncMock is only registering calls after the coroutine is awaited, when it should do it when the function is called.
Code to reproduce
File tests/other_module.py
asyncdefa(value):
returnvalue*2
File tests/test_1.py
fromunittest.mockimportAsyncMockimportpytestimportother_modulepytestmark=pytest.mark.asyncio(loop_scope="session")
defb(value):
returnother_module.a(value)
asyncdeftest_1(mocker):
a_spy: AsyncMock=mocker.spy(other_module, "a")
result=b(10)
assertnota_spy.called# This should be True because 'a' was called, but it's Falseawaitresultasserta_spy.called# Now it's True
Expected result: a_spy.called should return True even if the coroutine was not awaited.
I could not reproduce the behavior using unittest's patch.
async def test_1():
with patch("other_module.a") as a_spy:
result = b(10)
> assert not a_spy.called # This should be True because 'a' was called, but it's False
^^^^^^^^^^^^^^^^^^^^^^^
E AssertionError: assert not True
E + where True = <AsyncMock name='a' id='139651671861504'>.called
tests/test_1.py:18: AssertionError
Digging with the debugger, I was able to narrow down the problem to the autospec parameter.
Using unittest's patch.object with autospec=True (which is the same value when using spy) I'm able to reproduce the same behavior. I'll dig deeper to understand this parameter.
Edit: I think it's a Python bug, not pytest-mock's.
Activity
nicoddemus commentedon Aug 9, 2025
Thanks @GabrielSalla for the report!
I'm short on time to investigate this now, but here is the relevant code if somebody wants to investigate:
pytest-mock/src/pytest_mock/plugin.py
Lines 161 to 209 in ba83a70
GabrielSalla commentedon Aug 9, 2025
I'll take a look at it and see if I can find out what's happening
GabrielSalla commentedon Aug 9, 2025
Digging with the debugger, I was able to narrow down the problem to the
autospecparameter.Using unittest's
patch.objectwithautospec=True(which is the same value when using spy) I'm able to reproduce the same behavior. I'll dig deeper to understand this parameter.Edit: I think it's a Python bug, not pytest-mock's.
Edit 2: I've opened a bug on cpython python/cpython#137594