Python - 对象 MagicMock 不能用于 'await' 表达式

新手上路,请多包涵

当我尝试使用 MagicMock 在 unittest 中模拟异步函数时,我得到了这个异常:

类型错误:对象 MagicMock 不能用于“等待”表达式

示例代码如下:

 # source code
class Service:
    async def compute(self, x):
        return x

class App:
    def __init__(self):
        self.service = Service()

    async def handle(self, x):
        return await self.service.compute(x)

# test code
import asyncio
import unittest
from unittest.mock import patch

class TestApp(unittest.TestCase):
    @patch('__main__.Service')
    def test_handle(self, mock):
        loop = asyncio.get_event_loop()
        app = App()
        res = loop.run_until_complete(app.handle('foo'))
        app.service.compute.assert_called_with("foo")

if __name__ == '__main__':
    unittest.main()

我应该如何使用内置的 python3 库修复它?

原文由 shaun shia 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 509
1 个回答

在 python 3.8+ 中,您可以使用 AsyncMock

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

AsyncMock 对象的行为将被识别为异步函数,并且调用的结果是可等待的。

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

原文由 Thulani Chivandikwa 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题