python / python/cpython

Patched async function not registering calls until coroutine is awaited

Open
#137,594 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

When using autospec=True the patched async function only has calls registered after the coroutine is awaited. This behavior started happening after I upgraded from 3.12 to 3.13.6.

Code to reproduce

File tests/other_module.py

async def a(value):
    return value * 2

File tests/test_1.py

from unittest.mock import patch

import pytest

import other_module

pytestmark = pytest.mark.asyncio(loop_scope="session")

def b(value):
    return other_module.a(value)


async def test_1():
    with patch.object(other_module, "a", side_effect=other_module.a, autospec=True) as a_mock:
        result = b(10)

        assert not a_mock.called  # This should be True because 'a' was called, but it's False

        await result
        assert a_mock.called  # Now it's True
CPython versions tested on:

3.13

Operating systems tested on:

Linux

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the behavior using tests/other_module.py and tests/test_1.py, focusing on patch.object with side_effect and autospec=True. Check when the mock records the call relative to coroutine creation and awaiting. Done means the first assertion passes before await and the behavior is covered by an appropriate CPython test.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing-qa
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.