pytest-dev / pytest-dev/pytest-mock
Spy with async function not registering calls until coroutine is awaited
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 2k
- Forks
- 173
- Avg merge
- 1d 10h
- Merged PRs (30d)
- 6
Description
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
async def a(value):
return value * 2
File tests/test_1.py
from unittest.mock import AsyncMock
import pytest
import other_module
pytestmark = pytest.mark.asyncio(loop_scope="session")
def b(value):
return other_module.a(value)
async def test_1(mocker):
a_spy: AsyncMock = mocker.spy(other_module, "a")
result = b(10)
assert not a_spy.called # This should be True because 'a' was called, but it's False
await result
assert a_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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the reproduction in tests/test_1.py and the async function in tests/other_module.py, then compare mocker.spy with unittest.mock.patch and inspect the AsyncMock behavior. Done means a spy reports the call when the coroutine function is invoked, before the returned coroutine is awaited, while the existing assertions pass.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- testing
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100