FastAPI 的单元测试
- 对于服务端来说,通常会对功能进行单元测试,也称白盒测试
- FastAPI 集成了第三方库,让我们可以快捷的编写单元测试
- FastAPI 的单元测试是基于 Pytest + Request 的
Pytest 学习
https://www.cnblogs.com/poloyy/tag/Pytest/
TestClient 简单的栗子
#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# blog: https://www.cnblogs.com/poloyy/
# time: 2021/9/29 10:55 下午
# file: 37_pytest.py
"""
import uvicorn
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/")
async def read_main():
return {
"msg": "Hello World"}
# 声明一个 TestClient,把 FastAPI() 实例对象传进去
client = TestClient(app)
# 测试用
def test_read_main():
# 请求 127.0.0.1:8080/
response = client.get("/")
assert response.status_code == 200
assert response.json() == {
"msg": "Hello World"}
if __name__ == '__main__':
uvicorn.run(app="37_pytest:app", reload=True, host="127.0.0.1", port=8080)
在该文件夹下的命令行敲
pytest 37_pytest.py
运行结果
![](https://img-blog.csdnimg.cn/img_convert/47c1839d1eccd0920aa337dfae989f01.png)