pytest 是 Python 测试框架,但其不支持基于 asyncio 的异步程序(例如,测试 FastAPI 异步代码),pytest-asyncio 是一个 pytest 插件,该插件赋予 pytest 可以测试使用 asyncio 库代码的能力。
https://github.com/pytest-dev/pytest-asyncio
@pytest.mark.asyncio
async def test_some_asyncio_code():
res = await library.do_something()
assert b"expected result" == res
异步 fixture
import asyncio
import pytest
import pytest_asyncio
@pytest_asyncio.fixture
async def current_loop():
return asyncio.get_running_loop()
默认事件循环范围是函数范围。可能的循环范围包括 session、package、module、class 和 function。
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()