Python - object MagicMock can't be used in 'await' expression

前端 未结 5 1147
伪装坚强ぢ
伪装坚强ぢ 2021-02-18 19:49

When I was trying to mock an async function in unittest with MagicMock, I got this exception:

TypeError: object MagicMock can\'t be used in \'await\' expr

5条回答
  •  温柔的废话
    2021-02-18 20:23

    In python 3.8+ you can make use of the AsyncMock

    async def test_that_mock_can_be_awaited():
       mock = AsyncMock()
       mock.x.return_value = 123
       result = await mock.x()
       assert result == 123
    

    The class AsyncMock object will behave so the object is recognized as an async function, and the result of a call is an awaitable.

    >>> mock = AsyncMock()
    >>> asyncio.iscoroutinefunction(mock)
    True
    >>> inspect.isawaitable(mock())
    True
    

提交回复
热议问题