Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock an async function returning a tuple?

I need to test the following function

class C:
    async def f():
        a, b = await self.g()  # need to mock g

However, the following test got the error of TypeError: object tuple can't be used in 'await' expression

@pytest.mark.asyncio
async def test_f():
    sut = C()
    sut.g = MagicMock(return_value=(1,2)) # TypeError: object tuple can't be used in 'await' expression
    await sut.f()
    sut.g.assert_called_once()
like image 386
ca9163d9 Avatar asked Feb 13 '26 21:02

ca9163d9


1 Answers

Use AsyncMock instead of the MagicMock:

from unittest.mock import AsyncMock

@pytest.mark.asyncio
async def test_f():
    sut = C()
    sut.g = AsyncMock(return_value=(1,2))
    await sut.f()
    sut.g.assert_called_once()

AsyncMock is part of the standard library since Python 3.8; if you need a backport for older versions, install and use the asyncmock package.

like image 136
hoefling Avatar answered Feb 17 '26 08:02

hoefling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!