场景分析
HTTP 是一个无状态协议,其通讯过程可简要描述为:发送请求、回复响应,所以,API 测试步有不同的类型需要处理:
构造请求
断言响应
在复杂的项目场景下,可能包含更多的步骤类型,例如接口 mock、变量提取、延迟请求等
其中请求在前、响应在后,这就需要钩子在处理步骤时注意顺序。
此外,一个用例中可能需要多次调用不同的接口,而后仅进行一次断言,这就需要钩子在处理步骤时放松约束。
安装依赖
pytest 自身无法发送 HTTP 请求,也无法断言响应,需要安装第三方依赖
pip install requests responses-validator
其中:
requests :用来发送 HTTP 请求
responses-validator :用来断言 HTTP 响应
如果还需要其他步骤类型,安装对应的依赖即可。
设计用例
根据分析结论和依赖的具体用法,设计 xlsx 版 API 测试用例如下:
在这个用例中,进行了两次 HTTP 请求,并对结果进行断言,
其中一次成功,第二次失败,使用例整体的结果为:测试失败 。
实现钩子
# conftest.py
import requestsfrom responses_validator import validator
from pytest_xlsx import XlsxItem
def pytest_xlsx_run_step(item: XlsxItem): step = item.current_step action = step.get("关键字")
match action: case 'get': resp = requests.get(url=step['url'], headers=step['header'],data=step['data']) case 'post': resp = requests.post(url=step['url'], headers=step['header'], data=step['data']) case _: raise ValueError('无法识别的步骤类型')
print(f'请求成功!{action} {step["url"]}')
validator(resp, status_code=step['status_code'], text=step['text']) print('断言成功!')
return True
执行结果如下:
(.venv) C:\demo\pytest-xlsx-demo>pytest============================= test session starts ==============================platform win32 -- Python 3.12.0, pytest-8.3.4, pluggy-1.5.0rootdir: C:\demo\pytest-xlsx-democonfigfile: pytest.iniplugins: xlsx-2.0.0collected 1 item
tests\example\test_api.xlsx F [100%]
=================================== FAILURES ===================================_________________________________ Sheet1.接口测试 __________________________________xlsx content:| | 说明 | 关键字 | url | header | data | status_code | text ||-----|--------|----------|-----------------------|----------|--------|---------------|---------|| | 成功 | get | https://www.baidu.com | | | 200 | *baidu* || >>> | 失败 | post | https://www.baidu.com | | | 200 | *baidu* |src\\responses_validator\\__init__.py:49: ResponseAssertionError{'status_code': "status_code is 302 and does not match the pattern '200'."}----------------------------- Captured stdout call -----------------------------请求成功!get https://www.baidu.com断言成功!请求成功!post https://www.baidu.com=========================== short test summary info ============================FAILED tests/example/test_api.xlsx::Sheet1::接口测试============================== 1 failed in 0.26s ===============================
从结果来看,请求接口和第一次断言都成功了,第二次断言失败了。
具体原因是: status_code is 302 and does not match the pattern '200' (状态码是 302,和预期结果 200 不匹配)
小结
和此前的数学运算相比,接口测试更加添加真实的业务需求。
在真实的业务需求中,往往需要对口的第三方库进行配合,还需要熟悉业务特征,了解业务步骤。 这些最终都会反应在 xlsx 用例文件和 hook 钩子函数中。
pytest-xlsx 并不会代替你理解业务特征,也不会贸然提供一个解决方案,而是帮助你将自己的想法和理解进行落地。
能看到这里说明是真爱,关注一下吧
领取专属 10元无门槛券
私享最新 技术干货