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
    评论
您好,关于使用 Python pytest requests 进行接口测试的具体方法,可以按照以下步骤进行: 1. 安装必要的库 在 Python 环境下安装 pytestrequests 库,可以使用以下命令: ```python pip install pytest pip install requests ``` 2. 创建测试文件和测试用例 在项目中建立一个文件夹,命名为tests(如果没有该文件夹的话),在tests文件夹下创建一个测试文件,命名为test_example.py,用于编写测试用例。 在test_example.py 文件中,先导入 pytestrequests 库,然后编写测试用例函数。例如: ```python import pytest import requests def test_get_example(): url = 'http://example.com/api/get' headers = {'Content-Type': 'application/json'} response = requests.get(url, headers=headers) assert response.status_code == 200 assert 'Example' in response.json() ``` 这是一个简单的 get 请求测试用例,使用 requests 库发送请求,并通过 assert 断言判断返回结果是否正确。 3. 运行测试 在项目根目录下,使用以下命令启动 pytest 运行测试用例: ```python pytest ``` 如果测试全部通过,控制台会显示如下信息: ```python ============================= test session starts ============================= ... collected 1 item test_example.py . [100%] ============================== 1 passed in 0.23s ============================== ``` 如果测试未通过,会显示具体的错误信息,如: ```python ============================= test session starts ============================= ... collected 1 item test_example.py F [100%] ================================== FAILURES =================================== ______________________________ test_get_example ______________________________ def test_get_example(): url = 'http://example.com/api/get' headers = {'Content-Type': 'application/json'} response = requests.get(url, headers=headers) assert response.status_code == 200 > assert 'Example' in response.json() test_example.py:9: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ response = <Response [500]> def json(self, **kwargs): r"""If Response's content is json, return the json-encoded content. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. """ if not self.encoding and len(self.content) > 3: encodings = guess_json_utf(self.content) if encodings: try: return json.loads(self.content.decode(encodings[0]), **kwargs) except UnicodeDecodeError: pass return json.loads(self.text, **kwargs) def test_get_example(): url = 'http://example.com/api/get' headers = {'Content-Type': 'application/json'} response = requests.get(url, headers=headers) assert response.status_code == 200 > assert 'Example' in response.json() E AssertionError: assert 'Example' in None E + where None = <Response [500]>.json() test_example.py:10: AssertionError =========================== short test summary info ============================ FAILED test_example.py::test_get_example - AssertionError: assert 'Example' in... ========================= 1 failed, 1 passed in 0.45s ========================== ``` 4. 高级用法 pytest 还提供了更多功能强大的测试用例编写和运行方式,例如: - 参数化测试:使用@pytest.mark.parametrize标记来测试相同的功能,在不同的情况下运行测试。 - 报告和输出控制:控制台和报告可以被似于```pytest -v -s --html=report.html```的命令来控制和配置。 - 使用 Fixture:pytest fixtures 将测试运行的环境和外部应用程序配置隔离开来,使测试用例更加可靠。 希望这些信息能对您有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小菠萝测试笔记

来支持下测试小锅锅

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

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

打赏作者

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

抵扣说明:

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

余额充值