Skip to content

Spy with async function not registering calls until coroutine is awaited #519

Open

Description

@GabrielSalla

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

Activity

  1. nicoddemus commented on Aug 9, 2025

    @nicoddemus
    Member

    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:

    def spy(self, obj: object, name: str) -> MockType:
    """
    Create a spy of method. It will run method normally, but it is now
    possible to use `mock` call features with it, like call count.
    :param obj: An object.
    :param name: A method in object.
    :return: Spy object.
    """
    method = getattr(obj, name)
    def wrapper(*args, **kwargs):
    spy_obj.spy_return = None
    spy_obj.spy_exception = None
    try:
    r = method(*args, **kwargs)
    except BaseException as e:
    spy_obj.spy_exception = e
    raise
    else:
    spy_obj.spy_return = r
    spy_obj.spy_return_list.append(r)
    return r
    async def async_wrapper(*args, **kwargs):
    spy_obj.spy_return = None
    spy_obj.spy_exception = None
    try:
    r = await method(*args, **kwargs)
    except BaseException as e:
    spy_obj.spy_exception = e
    raise
    else:
    spy_obj.spy_return = r
    spy_obj.spy_return_list.append(r)
    return r
    if inspect.iscoroutinefunction(method):
    wrapped = functools.update_wrapper(async_wrapper, method)
    else:
    wrapped = functools.update_wrapper(wrapper, method)
    autospec = inspect.ismethod(method) or inspect.isfunction(method)
    spy_obj = self.patch.object(obj, name, side_effect=wrapped, autospec=autospec)
    spy_obj.spy_return = None
    spy_obj.spy_return_list = []
    spy_obj.spy_exception = None
    return spy_obj

  2. GabrielSalla commented on Aug 9, 2025

    @GabrielSalla
    Author

    I'll take a look at it and see if I can find out what's happening

  3. GabrielSalla commented on Aug 9, 2025

    @GabrielSalla
    Author

    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.

    Edit 2: I've opened a bug on cpython python/cpython#137594

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions