当我试图用MagicMock在单元测试中模拟异步函数时,我得到了以下异常:
TypeError:对象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库修复它?
发布于 2018-07-18 02:32:40
最后我被黑客袭击了。
# monkey patch MagicMock
async def async_magic():
pass
MagicMock.__await__ = lambda x: async_magic().__await__()
它只适用于MagicMock,而不适用于其他预定义的return_value。
发布于 2020-08-15 10:32:04
在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
发布于 2019-01-21 18:09:32
https://stackoverflow.com/questions/51394411
复制