python - 如何模拟异步协程?

标签 python python-3.x unit-testing mocking python-asyncio

以下代码因 TypeError: 'Mock' object is not iterableImBeingTested.i_call_other_coroutines 中失败,因为我已将 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 库不支持协程,我手动创建模拟协程并将它们分配给模拟对象。有点冗长,但它有效。

您的示例可能如下所示:

import asyncio
import unittest
from unittest.mock import Mock


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)

        @asyncio.coroutine
        def mock_coro():
            return "sup"
        mocked.yeah_im_not_going_to_run = mock_coro

        ret = asyncio.get_event_loop().run_until_complete(
            ibt.i_call_other_coroutines())
        self.assertEqual("sup", ret)


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

关于python - 如何模拟异步协程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29881236/

相关文章:

python - 在 Django 中,什么是一对一关系?

python - 一个接一个地运行 django 迁移

python - 拆分 df 中的每一行并为每个元素添加值

Python3函数将列表映射到字典中

javascript - 对正在馈送的可观察流进行单元测试的正确方法

javascript - Angularjs 服务单元测试

unit-testing - 使用 grpc.SetHeader 或 grpc.SendHeader 调用测试函数时无法设置 header

python - 在 python 中使用 MySQL boolean 值

python - 使用两个可能的名称验证输入字段

python - Pytest 失败并出现 AssertionError False is False