Skip to content

Conversation

@secrett2633
Copy link
Contributor

Description

This issue is related to a known Python bug that was fixed in Python 3.13 but has not been backported to earlier versions: python/cpython#94924
As a workaround for versions prior to Python 3.13, we could consider using conditional imports based on the Python version:

Resolves #14021

if sys.version_info < (3, 13):
    from asyncio import iscoroutinefunction
else:
    from inspect import iscoroutinefunction

Example Code

import sys
import asyncio
import inspect
from unittest.mock import create_autospec, patch

print(f"Python version: {sys.version_info[:2]}") # (3, 12)

async def foo():
    pass

mock_autospec = create_autospec(foo)
print(asyncio.iscoroutinefunction(mock_autospec)) # True
print(inspect.iscoroutinefunction(mock_autospec)) # False

with patch('__main__.foo', autospec=True) as mock_foo:
    print(asyncio.iscoroutinefunction(mock_foo)) # True
    print(inspect.iscoroutinefunction(mock_foo)) # False

@YuriiMotov YuriiMotov changed the title 🐛 Fix inspect.getcoroutinefunction() can break testing with unittest.mock.patch() 🐛 Fix inspect.getcoroutinefunction() can break testing with unittest.mock.patch() Aug 31, 2025
@YuriiMotov YuriiMotov added the bug Something isn't working label Aug 31, 2025
Copy link
Member

@YuriiMotov YuriiMotov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Thanks!

Copy link
Member

@tiangolo tiangolo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, thank you! 🚀 🍰

@tiangolo tiangolo merged commit c831cdb into fastapi:master Sep 20, 2025
31 of 32 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants