pytest asyncio 支持插件 pytest-asyncio

pytest 是 Python 测试框架,但其不支持基于 asyncio 的异步程序(例如,测试 FastAPI 异步代码),pytest-asyncio 是一个 pytest 插件,该插件赋予 pytest 可以测试使用 asyncio 库代码的能力。
https://github.com/pytest-dev/pytest-asyncio

python 复制代码
@pytest.mark.asyncio
async def test_some_asyncio_code():
    res = await library.do_something()
    assert b"expected result" == res

异步 fixture

python 复制代码
import asyncio

import pytest

import pytest_asyncio


@pytest_asyncio.fixture
async def current_loop():
    return asyncio.get_running_loop()

默认事件循环范围是函数范围。可能的循环范围包括 session、package、module、class 和 function。

python 复制代码
import asyncio

import pytest

import pytest_asyncio


@pytest_asyncio.fixture(loop_scope="module")
async def current_loop():
    return asyncio.get_running_loop()


@pytest.mark.asyncio(loop_scope="module")
async def test_runs_in_module_loop(current_loop):
    assert current_loop is asyncio.get_running_loop()
相关推荐
weixin_4196583112 小时前
pytest 零基础入门实战指南
python·pycharm·pytest
姚青&3 天前
软件测试基础概念
单元测试·pytest
爆更小哇6 天前
pytest集成Allure报告教程
python·测试工具·pytest·接口测试·allure
gCode Teacher 格码致知7 天前
Python提高:pytest的简单案例-由Deepseek产生
python·pytest
gCode Teacher 格码致知7 天前
Python提高: unittest和 pytest的使用方法-由Deepseek产生
开发语言·python·pytest
我的xiaodoujiao11 天前
API 接口自动化测试详细图文教程学习系列11--Requests模块3--测试练习
开发语言·python·学习·测试工具·pytest
我的xiaodoujiao11 天前
API 接口自动化测试详细图文教程学习系列12--Requests模块4--测试实践操作
python·学习·测试工具·pytest
Lightning-py13 天前
pytest 软断言的几种方式
pytest
Lightning-py13 天前
pytest后置处理方式
pytest