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

Pytest断言错误中断测试执行,如何跑完所有Excel数据后再标记用例结果

问题解决方法

核心原因

你当前代码在异常捕获块的末尾执行了raise e操作,会将已经捕获的断言错误重新抛出,直接终止for循环,导致剩余Excel行的数据不会被执行。

解决步骤

按照以下逻辑修改即可满足需求:

  • 进入for循环前初始化一个失败状态标记,默认值为False,用来记录是否有任意一行数据执行失败
  • 删除异常捕获块中的raise e语句,避免提前中断循环,捕获到异常时仅将失败标记修改为True即可
  • 所有Excel行都执行完成后,判断失败标记状态,若为True则主动抛出异常,将整个测试用例标记为FAILED

修改后的完整代码

import pytest
import json
import sys
import traceback
import requests
# 你原有导入的其他依赖保持不变

def test_1A():
    url_plan = getCOnfigurations()['API']['URL'] + APIResources.endpoints_plans
    classic_sum_values = [200000, 300000, 400000]
    payload_plan = open('C:/Users/aprat/PycharmProjects/RSAHealthPytest/PayLoads/plans/1A.json','r')
    json_payload_plan = json.loads(payload_plan.read())

    obj = Library.BaseClass("C:/Users/aprat/PycharmProjects/RSAHealthPytest/TestData/1A/TestData1A.xlsx","sheet1")
    col = obj.fetch_column_count()
    row = obj.fetch_row_count()
    key_age = obj.fetch_key_names()
    key_dob = obj.fetch_key_names()
    key_sum = obj.fetch_key_names()
    key_ten = obj.fetch_key_names()
    key_pr_mem_age = obj.fetch_key_names()

    # 新增:初始化失败标记
    test_failed = False

    for i in range(2, row+1):
        datadriven_json_data_plan = obj.update_request_with_data_plan1A(i,json_payload_plan,key_age,key_dob,key_pr_mem_age,key_sum,key_ten)
        a1_age = json_payload_plan['payload']['data']['insured'][0]['age']
        a1_dob = json_payload_plan['payload']['data']['insured'][0]['dob']
        prim_mem_age = json_payload_plan['payload']['data']['primary_member_age']
        tot_sum = json_payload_plan['payload']['data']['sum_insured']
        tenure = json_payload_plan['payload']['data']['tenure']
        response = requests.post(url_plan, json=datadriven_json_data_plan,)
        json_response_plan = response.json()
        print(json_response_plan)
        if int(tenure) == 1 or int(tenure) == 2 or int(tenure) == 3:
            if int(tot_sum) in classic_sum_values:
                if int(18) <= int(a1_age) <= int(50):
                    print(json_response_plan[0]['article_code'])
                    try:
                        assert int(json_response_plan[0]['premium']) > int(1)
                        assert int(json_response_plan[0]['term']) == int(tenure)
                        assert int(json_response_plan[0]['validity']) == int(tenure)
                        assert int(json_response_plan[0]['sa']) == int(tot_sum)
                    except Exception as e:
                        # 标记测试失败
                        test_failed = True
                        json_data = datadriven_json_data_plan
                        sys.stdout = open("plans_classic_1A.log", "a")
                        _, _, tb = sys.exc_info()
                        traceback.print_tb(tb)
                        tb_info = traceback.extract_tb(tb)
                        filename, line, func, text = tb_info[-1]
                        print('An error occurred on line {} in statement {}'.format(line, text))
                        print("Test failure due to assertion error")
                        print("adult1 age=" + " " + str(a1_age))
                        print("sum insured=" + " " + str(tot_sum))
                        print("tenure=" + " " + str(tenure))
                        print(json.dumps(json_data, indent=2))
                        print("**************************************************************************")
                        # 删除原有raise e代码,避免终止循环
    
    # 所有数据行执行完成后,判断是否有失败,有则整体标记用例失败
    if test_failed:
        pytest.fail("存在部分Excel行数据断言失败,请查看日志文件plans_classic_1A.log确认详情")

内容的提问来源于stack exchange,提问作者Apratim Chaudhuri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:54:01