Python Requests 接口自动化用例示例
以下是一个基于 Python 和 Requests 的接口自动化用例示例:
import requests
import json
# 设置测试数据
url = 'http://api.example.com/login'
headers = {'Content-Type': 'application/json'}
data = {'username': 'testuser', 'password': 'testpass'}
# 发送POST请求
response = requests.post(url, headers=headers, data=json.dumps(data))
# 验证响应状态码和返回结果
assert response.status_code == 200
assert response.json()['success'] == True
assert response.json()['message'] == 'Login successful'
# 设置下一个测试数据
url = 'http://api.example.com/user/profile'
headers = {'Authorization': 'Bearer ' + response.json()['token']}
# 发送GET请求
response = requests.get(url, headers=headers)
# 验证响应状态码和返回结果
assert response.status_code == 200
assert response.json()['username'] == 'testuser'
assert response.json()['email'] == 'testuser@example.com'
这个示例测试了一个登录接口和一个获取用户信息的接口。首先,发送一个 POST 请求来登录,然后使用响应中返回的令牌进行身份验证,发送一个 GET 请求来获取用户信息。最后,使用断言来验证响应状态码和返回结果是否符合预期。
原文地址: https://www.cveoy.top/t/topic/lfeA 著作权归作者所有。请勿转载和采集!