pytest-asyncio 插件介绍及使用
简介:
默认情况下,pytest
不支持异步测试函数(async def
),会直接跳过或报错。而 pytest-asyncio
插件可以在 pytest
中直接写 async def test_xxx()
函数,并正常运行它们。
准备:
安装插件
pip install pytest-asyncio
若未安装插件运行异步函数,则会出现该情况:
PytestUnhandledCoroutineWarning: async def functions are not natively supported and have been skipped.
运行方式:
1、在 pytest.ini
中配置参数(推荐)
[pytest]
asyncio_mode = auto
2、使用 --asyncio-mode=auto
(推荐)
pytest test_async_fixture.py -v --asyncio-mode=auto
自动检测并兼容同步和异步测试,这样你不需要为每个测试函数添加
@pytest.mark.asyncio
装饰器。
3、手动添加 @pytest.mark.asyncio
不操作1或2的步骤,也可以使用 @pytest.mark.asyncio
@pytest.mark.asyncio
async def test_with_async_fixture():
assert 1 == 1
@pytest.mark.asyncio
是 基于pytest-asyncio
插件的功能,它并不是pytest
自带的原生功能。
示例:
1、异步调用外部服务(如使用 httpx.AsyncClient
)
import httpx
import pytest
async def test_async_http_call():
async with httpx.AsyncClient() as client:
response = await client.get("https://example.com")
assert response.status_code == 200
通过 httpx.AsyncClient
发起异步 HTTP 请求,只有在 pytest-asyncio
的支持下才能正常运行。
2、异步 fixture 支持
import pytest
@pytest.fixture
async def async_fixture():
await asyncio.sleep(0.1)
return "data"
async def test_with_async_fixture(async_fixture):
assert async_fixture == "data"
3、并发运行多个异步任务
async def test_concurrent_tasks():
async def task(n):
await asyncio.sleep(1)
return n * n
results = await asyncio.gather(task(1), task(2), task(3))
assert results == [1, 4, 9]
评论区