📝 面试求职: 「面试试题小程序」 ,内容涵盖 测试基础、Linux操作系统、MySQL数据库、Web功能测试、接口测试、APPium移动端测试、Python知识、Selenium自动化测试相关、性能测试、性能测试、计算机网络知识、Jmeter、HR面试,命中率杠杠的。(大家刷起来…)
📝 职场经验干货:
在接口自动化测试中,断言是验证接口返回结果是否符合预期的关键步骤。通过封装断言逻辑,可以提高测试代码的可读性和可维护性,同时减少重复代码。本文将详细介绍如何在 Pytest 框架中封装常见的断言逻辑,包括状态码断言、JSON 数据断言、数据库断言等。
一、断言的基本概念
断言是验证接口返回结果是否符合预期的过程。在 Python 中,可以使用 assert 语句进行简单的断言。例如:
response = requests.get("https://api.example.com")
assert response.status_code == 200, "接口请求失败"
二、封装状态码断言
状态码断言是验证接口返回的 HTTP 状态码是否符合预期。以下是一个封装的状态码断言函数:
def assert_status_code(response, expected_status_code=200):
"""
验证接口返回的状态码是否符合预期。
:param response: 接口返回的响应对象
:param expected_status_code: 预期的状态码,默认为 200
"""
assert response.status_code == expected_status_code, f"状态码不匹配。预期:{expected_status_code},实际:{response.status_code}"
三、封装 JSON 数据断言
JSON 数据断言是验证接口返回的 JSON 数据是否符合预期。可以使用 jsonpath 库来解析 JSON 数据。以下是一个封装的 JSON 数据断言函数:
import jsonpath
def assert_json(response, jsonpath_expr, expected_value):
"""
验证接口返回的 JSON 数据是否符合预期。
:param response: 接口返回的响应对象
:param jsonpath_expr: JSONPath 表达式,用于定位 JSON 数据中的特定字段
:param expected_value: 预期的值
"""
actual_value = jsonpath.jsonpath(response.json(), jsonpath_expr)
assert actual_value[0] == expected_value, f"JSON 数据不匹配。预期:{expected_value},实际:{actual_value[0]}"
四、封装数据库断言
数据库断言是验证接口操作后的数据库状态是否符合预期。以下是一个封装的数据库断言函数:
import pymysql
def assert_db(query, expected_result):
"""
验证数据库查询结果是否符合预期。
:param query: SQL 查询语句
:param expected_result: 预期的查询结果
"""
conn = pymysql.connect(host='localhost', user='root', password='password', db='testdb')
cursor = conn.cursor()
cursor.execute(query)
result = cursor.fetchone()
cursor.close()
conn.close()
assert result == expected_result, f"数据库查询结果不匹配。预期:{expected_result},实际:{result}"
五、封装通用断言类
为了进一步提高代码的复用性,可以封装一个通用的断言类,包含多种断言方法。以下是一个示例:
class ApiAssert:
@staticmethod
def assert_status_code(response, expected_status_code=200):
assert response.status_code == expected_status_code, f"状态码不匹配。预期:{expected_status_code},实际:{response.status_code}"
@staticmethod
def assert_json(response, jsonpath_expr, expected_value):
actual_value = jsonpath.jsonpath(response.json(), jsonpath_expr)
assert actual_value[0] == expected_value, f"JSON 数据不匹配。预期:{expected_value},实际:{actual_value[0]}"
@staticmethod
def assert_db(query, expected_result):
conn = pymysql.connect(host='localhost', user='root', password='password', db='testdb')
cursor = conn.cursor()
cursor.execute(query)
result = cursor.fetchone()
cursor.close()
conn.close()
assert result == expected_result, f"数据库查询结果不匹配。预期:{expected_result},实际:{result}"
六、使用封装的断言类
在测试用例中,可以使用封装的断言类来验证接口返回结果。以下是一个示例:
import requests
def test_api():
response = requests.get("https://api.example.com")
ApiAssert.assert_status_code(response, 200)
ApiAssert.assert_json(response, "$.status", "success")
ApiAssert.assert_db("SELECT * FROM users WHERE id=1", (1, "John Doe"))
七、总结
通过封装断言逻辑,可以提高接口自动化测试的效率和可维护性。本文介绍了如何封装状态码断言、JSON 数据断言和数据库断言,并提供了一个通用的断言类。希望这些内容能帮助你在接口自动化测试中更好地实现断言封装。
最后: 下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】