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

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

    You can get mocks to return objects that can be awaited by using a Future. The following is a pytest test case, but something similar should be possible with unittest.

    async def test_that_mock_can_be_awaited():
        mock = MagicMock(return_value=Future())
        mock.return_value.set_result(123)
        result = await mock()
        assert result == 123
    

    In your case, since you're patching Service (which gets passed in as mock), mock.return_value = Future() should do the trick.

提交回复
热议问题