如何在Pytest中实现API测试:error非空则失败,success非空则通过
调整Pytest脚本的断言逻辑以匹配接口响应规则
需要实现的测试规则:
- 接口响应的
error数组非空时,测试用例失败 - 接口响应的
success数组非空时,测试用例通过
原测试脚本
def test_bid_submission_send(): # Act: response = post_requests(token, '/xxx/api/xxx/bidsubmissions/send', setpayload_bidsubmissions_send(powerplantId)) # Assert: assert not response.json()["error"] assert response.status_code == 200 # Validation of status code
接口响应示例
{"success":[],"error":[{"hpsId":10037,"powerPlant":{"name":"Saurdal","id":16606,"regionId":20,"priceArea":2,"timeSeries":null,"units":[]}}]}
修改后的测试脚本
def test_bid_submission_send(): # Act: response = post_requests(token, '/xxx/api/xxx/bidsubmissions/send', setpayload_bidsubmissions_send(powerplantId)) response_data = response.json() # Assert: # 验证接口请求正常返回200状态码 assert response.status_code == 200 # error数组非空时断言失败,同时输出具体错误信息便于调试 assert len(response_data["error"]) == 0, f"接口返回错误: {response_data['error']}" # success数组非空时断言通过,无成功记录则提示 assert len(response_data["success"]) > 0, "接口未返回成功提交记录"
脚本说明
- 将响应数据提前解析为
response_data变量,提升代码可读性 - 保留状态码断言,确保接口请求本身未出现服务端异常
- 用
len(response_data["error"]) == 0替代原断言,逻辑一致但更直观,同时添加错误提示文本,方便调试时定位问题 - 新增
success数组长度校验的断言,直接匹配“success非空则测试通过”的需求
内容的提问来源于stack exchange,提问作者Magnus Jensen
相关产品推荐
相关产品推荐

