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()
相关推荐
摘星编程4 天前
AI 帮我写单测:pytest 覆盖率提升 40% 的协作日志
人工智能·pytest·测试驱动开发·代码覆盖率·ai协作开发
lucia_zl6 天前
pytest并发测试,资源问题导致用例失败解决办法
pytest
鱼鱼说测试6 天前
Selenium4+Pytest自动化测试框架实战
pytest
XYiFfang13 天前
【Pytest】解决Pytest中Teardown钩子的TypeError:实例方法与类方法的调用差异
python·pytest
Kingairy14 天前
Pytest 插件:pytest_runtest_protocol
python·pytest
AIZHINAN14 天前
Pytest 插件介绍和开发
测试工具·pytest·插件开发
灰阳阳17 天前
替身演员的艺术:pytest-mock 从入门到飙戏
自动化测试·python·pytest·unit testing·pytest-mock
年年测试20 天前
Playwright与PyTest结合指南
pytest
focksorCr20 天前
pytest 并发执行用例(基于受限的测试资源)
python·pytest