如何使用pytest对asyncio call_later进行单元测试?

时间:2019-07-26 11:39:29

标签: pytest python-asyncio pytest-asyncio

我正在编写一些基于异步的代码,并且试图完成计划的操作。我想为我的代码编写一些单元测试。涉及call_later()个动作的单元测试代码的“良好”方式是什么?我想避免实际等待几秒钟,所以我需要以某种方式模拟时间。

最小示例:

import asyncio

def do_more_stuff():
    print("doing more stuff")

async def do_stuff():
    print("doing stuff")
    await asyncio.sleep(0.1)
    print("scheduling more stuff")
    asyncio.get_event_loop().call_later(2, do_more_stuff)


def test_delayed_action(event_loop: asyncio.AbstractEventLoop):
    asyncio.set_event_loop(event_loop)

    asyncio.get_event_loop().create_task(do_stuff())
    event_loop.run_forever()

此示例存在多个问题:

  • 由于run_forever(),它在调用do_more_stuff()之后不会终止。我想运行event_loop直到不再安排任何回调。这可能吗?

  • 即使我日后入侵并使用event_loop.run_until_complete(fut),该测试仍然需要2秒钟才能完成。我只想运行do_stuff()并检查计划的回调;或者提前一些时间来加快回调的触发。这些可能吗?

0 个答案:

没有答案