我不明白装饰器@pytest.mark.asyncio可以用于什么目的。
我尝试在安装了pytest和pytest-asyncio插件的情况下运行下面的代码片段,但失败了,所以我得出结论,pytest收集没有装饰器的测试协程。为什么它会如此存在?
async def test_div():
return 1 / 0发布于 2019-08-12 22:29:54
当您的测试被标记为@pytest.mark.asyncio时,它们就变成了coroutines,在body中还带有关键字await
pytest将使用event_loop fixture提供的事件循环将其作为异步任务执行:
这段代码使用了装饰器
@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()发布于 2022-02-24 00:30:36
Sławomir Lenart's answer仍然是正确的,但请注意,从pytest-asyncio>=0.17开始,如果您将asyncio_mode = auto添加到pyproject.toml或pytest.ini中,则不需要标记,即自动为异步测试启用此行为。
https://stackoverflow.com/questions/57461868
复制相似问题