【发布时间】:2018-07-18 05:49:41
【问题描述】:
当我尝试使用 MagicMock 在 unittest 中模拟异步函数时,我遇到了这个异常:
TypeError: object MagicMock can't be used in 'await' expression
示例代码如下:
# 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 库来修复它?
【问题讨论】:
-
我没有使用 asynctest 作为第三方库。是否有任何标准方法可以在没有任何外部依赖的情况下修复它?
标签: python unit-testing asynchronous mocking