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

前端 未结 5 1171
伪装坚强ぢ
伪装坚强ぢ 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:21

    I found this comment very useful when trying to await a mock object in Python < 3.8. You simply create a child class AsyncMock that inherits from MagicMock and overwrites a __call__ method to be a coroutine:

    class AsyncMock(MagicMock):
        async def __call__(self, *args, **kwargs):
            return super(AsyncMock, self).__call__(*args, **kwargs)
    

    Then, inside your test, do:

    @pytest.mark.asyncio
    async def test_my_method():
        # Test "my_method" coroutine by injecting an async mock
        my_mock = AsyncMock()
        assert await my_method(my_mock)
    

    you might also want to install pytest-asyncio

提交回复
热议问题