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()
相关推荐
姚青&5 天前
PyCharm 配置与界面化运行
pytest
姚青&5 天前
Pytest 测试用例断言
测试用例·pytest
姚青&5 天前
Pytest 命名规则
pytest
姚青&5 天前
Pytest 测试用例结构
测试用例·pytest
姚青&6 天前
Pytest 简介、安装与环境准备
pytest
测试渣6 天前
持续集成中的自动化测试框架优化实战指南
python·ci/cd·单元测试·自动化·pytest
小凯123457 天前
pytest框架-详解(学习pytest框架这一篇就够了)
python·学习·pytest
逻极7 天前
pytest 入门指南:Python 测试框架从零到一(2025 实战版)
开发语言·python·pytest