Python 接口自动化测试用例示例:Requests + Pytest
这是一份基于 Python + requests + pytest 的接口自动化用例示例:
import pytest
import requests
# 测试用例数据
test_data = [
('http://www.example.com/api/get_user_info', {'user_id': 123}, {'status': 'success', 'name': 'John Doe'}),
('http://www.example.com/api/get_user_info', {'user_id': 456}, {'status': 'success', 'name': 'Jane Smith'}),
('http://www.example.com/api/get_user_info', {'user_id': 789}, {'status': 'error', 'message': 'User not found'}),
]
# 测试用例函数
@pytest.mark.parametrize('url, params, expected', test_data)
def test_api(url, params, expected):
response = requests.get(url, params=params)
assert response.status_code == 200
assert response.json() == expected
这份代码中,我们首先定义了测试用例数据 test_data,包含了三个测试用例,每个测试用例包含了请求的 URL、请求参数和期望的响应结果。
接着,我们使用 @pytest.mark.parametrize 装饰器来标记测试用例函数 test_api,并传入测试用例数据。这样,pytest 会自动根据数据生成三个测试用例,并依次执行。
在测试用例函数中,我们使用 requests 发送 HTTP 请求,并断言响应的状态码和内容是否符合期望。如果有任何一个断言失败,pytest 会将该测试用例标记为失败。
使用 pytest 运行这份代码,可以得到如下输出:
$ pytest test_api.py
============================= test session starts ==============================
platform linux -- Python 3.7.3, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
rootdir: /home/user/projects
collected 3 items
test_api.py ... [100%]
============================== 3 passed in 0.10s ===============================
可以看到,三个测试用例都通过了,测试通过。
原文地址: https://www.cveoy.top/t/topic/lfeD 著作权归作者所有。请勿转载和采集!