使用 pytest 和 HTTPX 异步测试 API
在开发 API 时,测试是确保其稳定性和正确性的关键步骤。本文将介绍如何使用 pytest 和 HTTPX 异步测试 FastAPI 应用程序的不同类型端点,包括 REST API 端点、涉及数据库的端点以及 WebSocket 端点。
1. 编写 REST API 端点测试
测试 FastAPI 应用程序所需的工具已准备就绪,所有测试都可归结为执行 HTTP 请求并检查响应是否符合预期。
1.1 测试 hello_world 路径操作函数
以下是一个简单的测试示例:
# chapter09_app_test.py
import pytest
import httpx
from fastapi import status
@pytest.mark.asyncio
async def test_hello_world(test_client: httpx.AsyncClient):
response = await test_client.get("/")
assert response.status_code == status.HTTP_200_OK
json = response.json()
assert json == {"hello": "world"}
操作步骤如下:
1. 定义异步测试函数,并使用 pytest.mark.asyncio 装饰器。
2. 请求
超级会员免费看
订阅专栏 解锁全文
46

被折叠的 条评论
为什么被折叠?



