7

我不明白装饰器可以用于哪些目的@pytest.mark.asyncio

我尝试在安装了插件的情况下运行以下代码片段,pytestpytest-asyncio它失败了,所以我得出结论 pytest 在没有装饰器的情况下收集测试协程。为什么会这样存在?

async def test_div():
    return 1 / 0
4

2 回答 2

13

当您@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()
于 2019-08-12T14:29:54.400 回答
0

Sławomir Lenart 的回答仍然是正确的,但请注意,pytest-asyncio>=0.17如果您添加asyncio_mode = auto到您的标记pyproject.tomlpytest.ini不需要标记,即自动为异步测试启用此行为。

请参阅https://github.com/pytest-dev/pytest-asyncio#modes

于 2022-02-24T00:30:36.090 回答