python-3.x - 'pytest.mark.asyncio' 用于什么?

标签 python-3.x pytest pytest-asyncio

我不明白装饰器的用途 @pytest.mark.asyncio可以使用。

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

async def test_div():
    return 1 / 0

最佳答案

当您的测试标记为 @pytest.mark.asyncio 时,他们变成 coroutines , 连同关键字 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()

关于python-3.x - 'pytest.mark.asyncio' 用于什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57461868/

相关文章:

python - 没有名为 pyVim 的模块

python - 如何在失败的情况下调用 py.test 中的 'debug' 方法?

python - Pytest 跳过测试说 "asyncio not installed"

python - 在 Apache Airflow 中保存算子的结果

python - 用 Python 计算密度

algorithm - NumPy:均匀分布的N维样本

pytest doctest 与 conftest.py 中的固定装置

python - 使用 pytest-django 对现有数据库运行测试

python - 使用 @pytest.fixture(scope ="module") 和 @pytest.mark.asyncio