2024-05-12 20:13:33 发布
网友
我正在测试一个可能会死锁的异步函数。我尝试添加一个fixture来限制函数在引发失败之前只运行5秒,但到目前为止还没有起作用。在
设置:
pipenv --python==3.6 pipenv install pytest==4.4.1 pipenv install pytest-asyncio==0.10.0
代码:
—
编辑:米哈伊尔的解决方案很有效。不过,我找不到一种方法把它整合到一个固定装置中。在
限制函数(或代码块)超时的方便方法是使用async-timeout模块。您可以在测试函数中使用它,或者创建一个decorator。与fixture不同,它允许为每个测试指定具体时间:
import asyncio import pytest from async_timeout import timeout def with_timeout(t): def wrapper(corofunc): async def run(*args, **kwargs): with timeout(t): return await corofunc(*args, **kwargs) return run return wrapper @pytest.mark.asyncio @with_timeout(2) async def test_sleep_1(): await asyncio.sleep(1) assert 1 == 1 @pytest.mark.asyncio @with_timeout(2) async def test_sleep_3(): await asyncio.sleep(3) assert 1 == 1
为具体时间(with_timeout_5 = partial(with_timeout, 5))创建装饰器并不难。在
with_timeout_5 = partial(with_timeout, 5)
我不知道如何创建纹理(如果你真的需要fixture),但上面的代码可以提供起点。也不确定是否有一个共同的方法来更好地实现目标。在
限制函数(或代码块)超时的方便方法是使用async-timeout模块。您可以在测试函数中使用它,或者创建一个decorator。与fixture不同,它允许为每个测试指定具体时间:
为具体时间(
with_timeout_5 = partial(with_timeout, 5)
)创建装饰器并不难。在我不知道如何创建纹理(如果你真的需要fixture),但上面的代码可以提供起点。也不确定是否有一个共同的方法来更好地实现目标。在
相关问题 更多 >
编程相关推荐