'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()


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hoefling