简体   繁体   English

如何使用包含代码的 `asyncio.sleep()` 进行单元测试?

[英]How to make unit test with `asyncio.sleep()` contained code?

I have a problem to write asyncio.sleep contained unit tests.我在编写包含 asyncio.sleep 的单元测试时遇到问题。 Do I wait actual sleep time...?我是否要等待实际的睡眠时间...?

I used freezegun to mocking time.我用freezegun来嘲笑时间。 This library is really helpful when I try to run tests with normal callables.当我尝试使用普通可调用对象运行测试时,这个库非常有用。 but I cannot find answer to run tests which contains asyncio.sleep!但我找不到运行包含 asyncio.sleep 的测试的答案!

async def too_many_sleep(delay):
    await asyncio.sleep(delay)
    do_something()

def test_code():
    task = event_loop.create_task(too_many_sleep(10000))
    # I want test like `assert_called(do_something)` without realtime delays

What I want:我想要的是:

def test_code():
    task = event_loop.create_task(too_many_sleep(10000))

    ...
    # trick the time
    with time_shift(sec=10000):
        assert task.done()

What I'm doing:我在做什么:

def test_code():
    task = event_loop.create_task(too_many_sleep(10000))
    # run tests and I will see a sunrise

No, freezegun doesn't patch affect asyncio.sleep() , because freezegun doesn't patch the asyncio loop.time() method .不, freezegun不会修补影响asyncio.sleep() ,因为freezegun不会修补asyncio loop.time()方法

There is an existing issue in the freezegun project repository that asks how to deal with asyncio.sleep() , but it is still open with no proposed solution. freezegun项目存储库中存在一个问题,询问如何处理asyncio.sleep() ,但它仍然是开放的,没有提出解决方案。

You could just mock asyncio.sleep() yourself:你可以自己模拟asyncio.sleep()

from unittest import mock

class AsyncMock(mock.MagicMock):
    async def __call__(self, *args, **kwargs):
        return super(AsyncMock, self).__call__(*args, **kwargs)

with mock.patch('asyncio.sleep', new_callable=AsyncMock):
    task = event_loop.create_task(too_many_sleep(10000))

The above replaces asyncio.sleep with an AsyncMock() instance for the duration of the test, and AsyncMock() , when called, just does nothing.以上内容替换asyncio.sleepAsyncMock()实例测试的持续时间和AsyncMock()被调用时,就什么都不做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM