gpt4 book ai didi

python - 为模拟的 asyncio.coroutine 设置返回值

转载 作者:太空宇宙 更新时间:2023-11-04 00:59:04 25 4
gpt4 key购买 nike

我试图在我正在测试的类中模拟一个辅助方法,但我无法设置返回值。相反,它是 None,这会导致进行调用的方法出错。

import unittest
import asyncio
import unittest.mock

class MyClass:

@asyncio.coroutine
def return_number(self):
return 5

@asyncio.coroutine
def add_two(self):
val = yield from self.return_number()
return val + 2


class TestMyClass(unittest.TestCase):

def setUp(self):
self.mc = MyClass()

def test_add(self):
val = asyncio.get_event_loop().run_until_complete(self.mc.add_two())
self.assertEqual(val, 7)

def test_with_mock(self):
""" Replace return_number with mocked method """
mm = unittest.mock.MagicMock()
mm.iter.return_value = 2
self.mc.return_number = unittest.mock.Mock(return_value=mm)

val = asyncio.get_event_loop().run_until_complete(self.mc.add_two())
self.assertEqual(val, 4)


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

在这个例子中有什么方法可以模拟 return_number 以返回特定值吗?

最佳答案

你也可以做类似的事情:

def test_with_mock(self):
""" Replace return_number with mocked method """
with mock.patch.object(self.mc, "return_number", return_value=2):
self.mc.return_number = asyncio.coroutine(self.mc.return_number)
val = asyncio.get_event_loop().run_until_complete(self.mc.add_two())
self.assertEqual(val, 4)

关于python - 为模拟的 asyncio.coroutine 设置返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33682765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com