Python+Requests 接口自动化用例编写示例
使用 Python+Requests 编写接口自动化用例示例
本示例展示如何使用 Python 和 Requests 库编写简单的接口自动化用例。
- 导入 Requests 库
import requests
- 定义发送请求函数
def send_request(url, method, data=None, headers=None):
if method == 'get':
response = requests.get(url, params=data, headers=headers)
elif method == 'post':
response = requests.post(url, data=data, headers=headers)
elif method == 'put':
response = requests.put(url, data=data, headers=headers)
elif method == 'delete':
response = requests.delete(url, data=data, headers=headers)
else:
raise ValueError('Invalid method')
return response
- 定义测试用例函数
def test_case():
url = 'http://api.example.com/user'
method = 'post'
data = {
'username': 'test_user',
'password': 'password123'
}
headers = {'Content-Type': 'application/json'}
response = send_request(url, method, data=data, headers=headers)
assert response.status_code == 200
assert response.json()['status'] == 'success'
assert response.json()['data']['username'] == 'test_user'
- 运行测试用例
test_case()
- 结果输出
如果测试用例执行成功,将没有输出。如果测试用例执行失败,将会输出 AssertionError。
注意:
- 示例中的
http://api.example.com/user是一个示例 API 地址,你需要替换成实际的 API 地址。 - 示例中
test_user和password123也是示例数据,你需要替换成实际的测试数据。 - 根据实际 API 接口的返回值,你需要修改
assert语句中的断言条件。
通过以上步骤,你就可以使用 Python 和 Requests 库编写简单的接口自动化用例了。
原文地址: https://www.cveoy.top/t/topic/lfeH 著作权归作者所有。请勿转载和采集!