Python-无法在'await'表达式中使用对象MagicMock [英] Python - object MagicMock can't be used in 'await' expression

查看:77
本文介绍了Python-无法在'await'表达式中使用对象MagicMock的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在MagicMock的单元测试中模拟异步功能时,出现了以下异常:

When I was trying to mock an async function in unittest with MagicMock, I got this exception:

TypeError:对象MagicMock不能在等待"表达式中使用

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库对其进行修复?

How should I fix it with built-in python3 libraries?

推荐答案

我最终遇到了这种黑客攻击.

I ended up with this hack.

# monkey patch MagicMock
async def async_magic():
    pass

MagicMock.__await__ = lambda x: async_magic().__await__()

它仅适用于MagicMock,不适用于其他预定义的return_value

It only works for MagicMock, not other pre-defined return_value

这篇关于Python-无法在'await'表达式中使用对象MagicMock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆