我不明白装饰器可以用于哪些目的@pytest.mark.asyncio
。
我尝试在安装了插件的情况下运行以下代码片段,pytest
但pytest-asyncio
它失败了,所以我得出结论 pytest 在没有装饰器的情况下收集测试协程。为什么会这样存在?
async def test_div():
return 1 / 0
我不明白装饰器可以用于哪些目的@pytest.mark.asyncio
。
我尝试在安装了插件的情况下运行以下代码片段,pytest
但pytest-asyncio
它失败了,所以我得出结论 pytest 在没有装饰器的情况下收集测试协程。为什么会这样存在?
async def test_div():
return 1 / 0
当您@pytest.mark.asyncio
的测试用await
pytest
将使用夹具提供的事件循环将其作为异步任务执行event_loop
:
这段带有装饰器的代码
@pytest.mark.asyncio
async def test_example(event_loop):
do_stuff()
await asyncio.sleep(0.1, loop=event_loop)
等于写这个:
def test_example():
loop = asyncio.new_event_loop()
try:
do_stuff()
asyncio.set_event_loop(loop)
loop.run_until_complete(asyncio.sleep(0.1, loop=loop))
finally:
loop.close()
Sławomir Lenart 的回答仍然是正确的,但请注意,pytest-asyncio>=0.17
如果您添加asyncio_mode = auto
到您的标记pyproject.toml
或pytest.ini
不需要标记,即自动为异步测试启用此行为。