pytest assert 封装

该博客内容展示了如何封装pytest的assert断言,以便在断言失败时提供更清晰的错误信息。定义了assert_equal、assert_not_equal、assert_in和assert_true等函数,这些函数在断言失败时会打印出实际结果和预期结果的对比,便于调试。

由于pytest 自带的assert 断言失败的时候,是不会打印出失败的实际结果和预期结果值,给查看的时候带来不变,所以进行封装格式化打印

import logging

import pytest

from common.baselogger import logger


def assert_equal(actual, expected):
    assert actual == expected, "实际结果为:{0}, 预期结果为:{1}".format(actual, expected)


def assert_not_equal(a, b):
    assert a != b, "{0}等于{1}".format(a, b)


def assert_in(a, b):
    assert a in b, "{0}不包含{1}".format(b, a)


def assert_true(value):
    assert value, "{0} 为假".format(value)

### 使用 Pytest 封装 Requests 的示例及最佳实践 #### 1. 基础封装 为了提高代码的可重用性和可维护性,可以将 `requests` 库的功能封装在一个基础类中。以下是基于引用中的内容构建的一个简单封装[^3]: ```python import requests class BaseRequest: def __init__(self, base_url="http://example.com"): """ 初始化会话并设置基础URL。 :param base_url: API的基础地址,默认为 http://example.com """ self.base_url = base_url self.session = requests.Session() def send_request(self, method, endpoint, **kwargs): """ 发送HTTP请求。 :param method: 请求方法 (GET, POST, PUT, DELETE 等) :param endpoint: 接口路径 :param kwargs: 额外的关键字参数传递给 requests.request() :return: 返回Response对象 """ url = f"{self.base_url}{endpoint}" response = self.session.request(method, url, **kwargs) return response def assert_status_code(self, response, expected_status_code=200): """ 断言状态码是否匹配预期值。 :param response: Response 对象 :param expected_status_code: 预期的状态码,默认为200 """ assert response.status_code == expected_status_code, \ f"Expected status code {expected_status_code}, but got {response.status_code}" def assert_response_data(self, response, expected_data=None): """ 断言返回的数据是否与预期数据一致。 :param response: Response 对象 :param expected_data: 预期的JSON数据结构 """ if expected_data is not None: actual_data = response.json() assert actual_data == expected_data, \ f"Expected data {expected_data}, but got {actual_data}" ``` --- #### 2. 结合 Pytest 编写测试用例 通过继承或实例化上述封装好的 `BaseRequest` 类,在 Pytest 中编写具体的测试用例。 ##### 示例测试用例 ```python from api_client import BaseRequest # 假设上面的类保存在api_client.py中 def test_get_user_info(): client = BaseRequest(base_url="https://jsonplaceholder.typicode.com") response = client.send_request("GET", "/users/1") # 断言状态码 client.assert_status_code(response) # 断言返回数据 expected_data = { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz" } client.assert_response_data(response, expected_data) def test_create_post(): client = BaseRequest(base_url="https://jsonplaceholder.typicode.com") payload = {"title": "foo", "body": "bar", "userId": 1} response = client.send_request("POST", "/posts", json=payload) # 断言状态码 client.assert_status_code(response, 201) # 断言返回数据 created_post = response.json() assert created_post["title"] == payload["title"] assert created_post["body"] == payload["body"] assert created_post["userId"] == payload["userId"] ``` --- #### 3. 最佳实践建议 - **使用 Session 提高效率** 在封装中使用 `Session` 而不是每次重新创建连接,这样可以减少 TCP 握手次数,提升性能[^3]。 - **统一异常处理机制** 如果接口调用失败(如超时、网络错误),可以在 `send_request` 方法中捕获异常并记录日志,或者抛出自定义异常以便于调试。 - **灵活配置 URL 和 Header** 支持动态传入不同的 `base_url` 或者自定义头部信息,增强灵活性[^4]。 - **集成 Allure 报告工具** 利用 Allure 工具生成美观的测试报告,便于团队协作和问题追踪[^2]。 - **分离环境变量** 不同环境下可能有不同的基础 URL 或认证信息,推荐使用 `.env` 文件存储这些敏感信息,并通过 Python-dotenv 加载到程序中。 --- #### 4. 执行测试脚本 可以通过命令行直接运行测试脚本,也可以利用 pytest 的全局配置文件简化操作流程[^4]。 ```bash pytest -v --html=./report.html tests/ ``` 如果需要指定特定标签的用例执行,则可在 pytest.ini 中预先定义好 marker 并标注对应的测试函数。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值