前言
- 前面讲解了通过 pytest 进行单元测试,是针对同步函数的:https://www.cnblogs.com/poloyy/p/15354901.html
- 但它无法再 pytest 中测试或运行任何异步函数
- 能够在测试中使用异步函数可能很有用
- 例如,当异步查询数据库时,假设想要测试向 FastAPI 应用程序发送请求,然后验证后端是否成功在数据库中写入了正确的数据,同时使用异步数据库
FastAPI 代码
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {
"message": "Tomato"}
单元测试代码
需要先安装
pip install httpx
pip install trio
pip install anyio
测试代码
import pyt