📝 面试求职: 「面试试题小程序」 ,内容涵盖 测试基础、Linux操作系统、MySQL数据库、Web功能测试、接口测试、APPium移动端测试、Python知识、Selenium自动化测试相关、性能测试、性能测试、计算机网络知识、Jmeter、HR面试,命中率杠杠的。(大家刷起来…)
📝 职场经验干货:
在接口自动化测试中,断言是验证接口返回结果是否符合预期的关键步骤。通过封装自定义断言逻辑,可以提高测试代码的可读性和可维护性,同时减少重复代码。本文将详细介绍如何在接口自动化框架中封装自定义断言逻辑,包括常见的断言类型、断言方法的封装以及在测试用例中的应用。
一、自定义断言的必要性
在接口自动化测试中,直接使用 assert 语句进行断言虽然简单,但会导致测试用例中重复编写类似的代码。通过封装自定义断言逻辑,可以:
减少代码重复:将重复的断言逻辑抽象到封装方法中,提高代码复用性。
提高可维护性:当断言逻辑发生变化时,只需修改封装方法,而无需修改每个测试用例。
增强测试的可读性:封装方法可以提供更直观的断言方式,使测试用例更加清晰易懂。
二、封装自定义断言类
(一)安装依赖库
首先,需要安装 jsonschema 库,用于验证 JSON 数据的结构和类型。
pip install jsonschema
(二)封装自定义断言类
创建一个 assertions.py 文件,封装自定义断言逻辑。
import jsonschema
from jsonschema import validate
class Assertions:
@staticmethod
def assert_status_code(response, expected_status_code):
"""
验证接口返回的状态码是否符合预期。
:param response: 接口返回的响应对象
:param expected_status_code: 预期的状态码
"""
assert response.status_code == expected_status_code, f"状态码不匹配。预期:{expected_status_code},实际:{response.status_code}"
@staticmethod
def assert_json(response, schema):
"""
验证接口返回的 JSON 数据是否符合指定的 schema。
:param response: 接口返回的响应对象
:param schema: JSON Schema
"""
try:
validate(instance=response.json(), schema=schema)
except jsonschema.exceptions.ValidationError as e:
raise AssertionError(f"JSON 数据验证失败:{e}")
@staticmethod
def assert_json_key(response, key, expected_value):
"""
验证接口返回的 JSON 数据中某个键的值是否符合预期。
:param response: 接口返回的响应对象
:param key: JSON 数据中的键
:param expected_value: 预期的值
"""
data = response.json()
assert key in data, f"键 '{key}' 不存在于 JSON 数据中"
assert data[key] == expected_value, f"键 '{key}' 的值不匹配。预期:{expected_value},实际:{data[key]}"
@staticmethod
def assert_json_path(response, json_path, expected_value):
"""
验证接口返回的 JSON 数据中某个路径的值是否符合预期。
:param response: 接口返回的响应对象
:param json_path: JSONPath 表达式
:param expected_value: 预期的值
"""
from jsonpath_ng import jsonpath, parse
data = response.json()
json_expr = parse(json_path)
match = json_expr.find(data)
assert match, f"路径 '{json_path}' 未找到"
assert match[0].value == expected_value, f"路径 '{json_path}' 的值不匹配。预期:{expected_value},实际:{match[0].value}"
@staticmethod
def assert_response_time(response, max_time):
"""
验证接口响应时间是否在指定范围内。
:param response: 接口返回的响应对象
:param max_time: 最大响应时间(秒)
"""
assert response.elapsed.total_seconds() <= max_time, f"响应时间超出预期。最大允许时间:{max_time} 秒,实际响应时间:{response.elapsed.total_seconds()} 秒"
三、使用封装的断言类
(一)示例:验证接口返回的状态码
import requests
from assertions import Assertions
def test_get_user_info():
response = requests.get("https://api.example.com/users/123")
Assertions.assert_status_code(response, 200)
(二)示例:验证接口返回的 JSON 数据
import requests
from assertions import Assertions
user_schema = {
"type": "object",
"properties": {
"id": {"type": "integer"},
"name": {"type": "string"},
"email": {"type": "string"}
},
"required": ["id", "name", "email"]
}
def test_get_user_info():
response = requests.get("https://api.example.com/users/123")
Assertions.assert_status_code(response, 200)
Assertions.assert_json(response, user_schema)
(三)示例:验证接口返回的 JSON 数据中的某个键值
import requests
from assertions import Assertions
def test_get_user_info():
response = requests.get("https://api.example.com/users/123")
Assertions.assert_status_code(response, 200)
Assertions.assert_json_key(response, "name", "John Doe")
(四)示例:验证接口返回的 JSON 数据中的某个路径值
import requests
from assertions import Assertions
def test_get_user_info():
response = requests.get("https://api.example.com/users/123")
Assertions.assert_status_code(response, 200)
Assertions.assert_json_path(response, "$.name", "John Doe")
(五)示例:验证接口响应时间
import requests
from assertions import Assertions
def test_get_user_info():
response = requests.get("https://api.example.com/users/123")
Assertions.assert_status_code(response, 200)
Assertions.assert_response_time(response, 2) # 响应时间不超过 2 秒
四、总结
通过封装自定义断言逻辑,可以显著提高接口自动化测试的代码复用性和可维护性。本文详细介绍了如何在接口自动化框架中封装常见的断言类型,包括状态码断言、JSON 数据断言、键值断言、路径值断言和响应时间断言,并提供了详细的代码示例。希望这些内容能帮助你在接口自动化测试中更加高效地实现断言封装。
最后: 下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】