以下代码在ImBeingTested.i_call_other_coroutines
中的TypeError: 'Mock' object is not iterable
失败,因为我已经用模拟对象替换了ImGoingToBeMocked
。
我怎么能模仿郊游呢?
class ImGoingToBeMocked:
@asyncio.coroutine
def yeah_im_not_going_to_run(self):
yield from asyncio.sleep(1)
return "sup"
class ImBeingTested:
def __init__(self, hidude):
self.hidude = hidude
@asyncio.coroutine
def i_call_other_coroutines(self):
return (yield from self.hidude.yeah_im_not_going_to_run())
class TestImBeingTested(unittest.TestCase):
def test_i_call_other_coroutines(self):
mocked = Mock(ImGoingToBeMocked)
ibt = ImBeingTested(mocked)
ret = asyncio.get_event_loop().run_until_complete(ibt.i_call_other_coroutines())
由于
mock
库不支持协同路由,所以我手动创建模拟协同路由并将它们分配给模拟对象。更详细一点,但它有效。您的示例可能如下所示:
从Andrew Svetlov的answer中跳出来,我只想共享这个helper函数:
这允许您使用标准的
assert_called_with
、call_count
和其他方法和属性,一个常规的unittest.Mock提供给您。您可以将其与问题中的代码一起使用,例如:
我正在为unittest编写一个包装器,目的是在为异步编写测试时切断样板。
代码就在这里:https://github.com/Martiusweb/asynctest
您可以用
asynctest.CoroutineMock
模拟协同程序:它还可以使用
side_effect
属性,而具有spec
的asynctest.Mock
可以返回coroutimock:unittest.Mock的所有功能都应该正常工作(patch(),等等)。
相关问题 更多 >
编程相关推荐