首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >pytest-asyncio 基础使用笔记

pytest-asyncio 基础使用笔记

作者头像
小田测测看
发布2026-06-17 17:01:32
发布2026-06-17 17:01:32
450
举报

一、安装与基本配置

1. 安装

代码语言:javascript
复制
pip install pytest-asyncio

2. pytest 配置(可选)

pyproject.tomlpytest.ini中添加:

代码语言:javascript
复制
[pytest]
asyncio_mode = auto  # 自动选择事件循环策略(auto/fixture/legacy)

二、测试异步函数

1. 测试普通异步函数

代码语言:javascript
复制
# test_example.py
import pytest

asyncdeffetch_data():
    return"data"

@pytest.mark.asyncio
asyncdeftest_fetch_data():
    result = await fetch_data()
    assert result == "data"

# 测试异步生成器
asyncdefasync_generator():
    yield1
    yield2

@pytest.mark.asyncio
asyncdeftest_async_generator():
    results = [i asyncfor i in async_generator()]
    assert results == [1, 2]

2. 基础异步 fixture

代码语言:javascript
复制
@pytest.fixture
async def client():
    # 异步初始化
    async with HttpClient() as client:
        yield client  # 提供给测试函数使用
        # 自动清理(无需手动关闭)

@pytest.mark.asyncio
async def test_client(client):
    response = await client.get("https://www.baidu.com")
    assert response.status == 200

3. 处理异常

代码语言:javascript
复制
async def raise_error():
    raise ValueError("Invalid input")

@pytest.mark.asyncio
async def test_raise_error():
    with pytest.raises(ValueError) as exc_info:
        await raise_error()
    assert str(exc_info.value) == "Invalid input"

4.模拟异步依赖

代码语言:javascript
复制
# 使用`unittest.mock`
from unittest.mock import MagicMock

@pytest.mark.asyncio
asyncdeftest_mocked_dependency():
    # 模拟异步函数
    async_func = MagicMock(return_value="mocked")
    result = await async_func()
    assert result == "mocked"

# 模拟异步上下文管理器
from unittest.mock import AsyncMock

@pytest.mark.asyncio
asyncdeftest_async_context_manager():
    mock = AsyncMock()
    mock.__aenter__.return_value = "mocked"
    
    asyncwith mock as result:
        assert result == "mocked"

三、其他

1. 测试异步事件循环

代码语言:javascript
复制
@pytest.mark.asyncio
async def test_event_loop(event_loop):
    # 使用 pytest-asyncio 内置的 event_loop fixture
    future = event_loop.create_future()
    event_loop.call_later(0.1, future.set_result, "done")
    result = await future
    assert result == "done"

2. 参数化异步测试

代码语言:javascript
复制
@pytest.mark.asyncio
@pytest.mark.parametrize("input, expected", [
    (1, 2),
    (3, 6),
])
async def test_async_param(input, expected):
    result = await multiply_by_two(input)
    assert result == expected

四、与其他库配合

1. FastAPI 异步测试

代码语言:javascript
复制
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/async")
asyncdefread_async():
    return {"hello": "world"}

@pytest.mark.asyncio
asyncdeftest_fastapi_app():
    client = TestClient(app)
    response = client.get("/async")
    assert response.status_code == 200

2. SQLAlchemy 异步 ORM

代码语言:javascript
复制
from sqlalchemy.ext.asyncio import create_async_engine

@pytest.fixture
async def db_session():
    engine = create_async_engine("sqlite+aiosqlite:///:memory:")
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    async with AsyncSession(engine) as session:
        yield session
        await session.rollback()

参考文档

  • [pytest-asyncio 官方文档] https://pytest-asyncio.readthedocs.io/

#Python #PythonAsyncio

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2025-06-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 编程拾光 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、安装与基本配置
    • 1. 安装
    • 2. pytest 配置(可选)
  • 二、测试异步函数
    • 1. 测试普通异步函数
    • 2. 基础异步 fixture
    • 3. 处理异常
    • 4.模拟异步依赖
  • 三、其他
    • 1. 测试异步事件循环
    • 2. 参数化异步测试
  • 四、与其他库配合
    • 1. FastAPI 异步测试
    • 2. SQLAlchemy 异步 ORM
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档