FastAPI(43)- 基于 pytest + requests 进行单元测试

 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
运行结果

TestClient 的源码解析

<
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小菠萝测试笔记

来支持下测试小锅锅

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值