【发布时间】:2019-04-15 07:56:35
【问题描述】:
我正在测试一个可能会死锁的异步函数。我尝试添加一个固定装置以限制该功能在引发故障之前仅运行 5 秒,但到目前为止它还没有起作用。
设置:
pipenv --python==3.6
pipenv install pytest==4.4.1
pipenv install pytest-asyncio==0.10.0
代码:
import asyncio
import pytest
@pytest.fixture
def my_fixture():
# attempt to start a timer that will stop the test somehow
asyncio.ensure_future(time_limit())
yield 'eggs'
async def time_limit():
await asyncio.sleep(5)
print('time limit reached') # this isn't printed
raise AssertionError
@pytest.mark.asyncio
async def test(my_fixture):
assert my_fixture == 'eggs'
await asyncio.sleep(10)
print('this should not print') # this is printed
assert 0
--
编辑:米哈伊尔的解决方案工作正常。不过,我找不到将其合并到固定装置中的方法。
【问题讨论】:
-
你不能在
pytest-asyncio的夹具中等待测试。恐怕米哈伊尔的回答是唯一的解决方案。好问题。 -
在我的测试中,我使用the following hook 添加所需的功能。对我来说效果很好。
标签: python pytest python-asyncio pytest-asyncio