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()
相关推荐
思则变2 天前
[Pytest][Part 1]Pytest 自动化测试框架
pytest
思则变4 天前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
思则变4 天前
[Pytest][Part 3]检测python package状态
pytest
cooldream200918 天前
pytest 框架详解与实战指南
pytest·测试
慕城南风18 天前
【pytest进阶】Pytest之conftest详解
pytest
编程小白gogogo19 天前
AI自动化测试速成(Pytest框架)
pytest
慕城南风19 天前
【pytest进阶】pytest详解及进阶使用
linux·服务器·pytest
Tom Boom1 个月前
Pytest断言全解析:掌握测试验证的核心艺术
自动化测试·python·测试开发·pytest
不要一直敲门1 个月前
初学 pytest 记录
pytest