使用 pytest 和 HTTPX 异步测试 API
在开发 API 时,测试是确保其稳定性和正确性的关键步骤。本文将介绍如何使用 pytest 和 HTTPX 对 FastAPI 应用的 REST API 端点和 WebSocket 端点进行异步测试。
编写 REST API 端点测试
测试 FastAPI 应用所需的工具已准备就绪,所有测试本质上都是执行 HTTP 请求并检查响应是否符合预期。
简单的 GET 请求测试
以下是对 hello_world 路径操作函数的测试示例:
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. 请求 test_client 夹具,它提供一个 HTTPX 客户端
超级会员免费看
订阅专栏 解锁全文
46

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



