You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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, "接口未返回成功提交记录"

脚本说明

  1. 将响应数据提前解析为response_data变量,提升代码可读性
  2. 保留状态码断言,确保接口请求本身未出现服务端异常
  3. 用len(response_data["error"]) == 0替代原断言,逻辑一致但更直观,同时添加错误提示文本,方便调试时定位问题
  4. 新增success数组长度校验的断言,直接匹配“success非空则测试通过”的需求

内容的提问来源于stack exchange,提问作者Magnus Jensen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 10:05:00