使用introcs包做Python单元测试时如何在断言失败后执行后续用例
问题描述
使用Introcs包测试Python代码时,程序基础运行无异常,但执行完第一个测试用例后就会终止,弹出Quitting with Error提示,测试代码如下:
import introcs from Assignment import func_test print("Testing function"+"\n") test1=func_test("Hello") introcs.assert_equals(True,test1) test2=func_test("Hello World") introcs.assert_equals(True,test2)
上述场景中test2会被跳过,程序触发错误后直接退出。需求为:func_test是根据传入字符串返回布尔值的函数,需要保证无论单个测试用例返回的布尔值是否符合断言预期,都能执行完所有测试用例,而非某一个用例失败就直接跳过后续所有用例。
解决方法
introcs.assert_equals断言失败时会直接抛出终止进程的错误,默认不会继续执行后续代码,有两种可落地的修改方案:
方案1:手动捕获断言异常,汇总结果后统一退出
用异常捕获包裹每个测试用例的断言逻辑,把失败的用例信息暂存,等所有用例执行完之后再统一输出结果、触发退出,修改后的代码如下:
import introcs from Assignment import func_test print("Testing function"+"\n") failed_cases = [] # 执行第一个测试用例 test1 = func_test("Hello") try: introcs.assert_equals(True, test1) print("test1 执行通过") except AssertionError: failed_cases.append(f"test1 失败:预期返回True,实际返回{test1}") # 执行第二个测试用例 test2 = func_test("Hello World") try: introcs.assert_equals(True, test2) print("test2 执行通过") except AssertionError: failed_cases.append(f"test2 失败:预期返回True,实际返回{test2}") # 统一输出测试结果 print("\n===== 测试全部执行完毕 =====") if failed_cases: print(f"失败用例共{len(failed_cases)}个:") for case in failed_cases: print(f"- {case}") raise SystemExit("存在未通过的测试用例") else: print("所有测试用例均通过")
方案2:使用introcs自带的测试运行器
introcs内置了批量执行测试用例的能力,把每个测试用例封装为test开头的无参数函数,调用introcs.test()方法即可自动执行所有用例,不会因为单个用例失败中断流程,最终会统一汇总测试结果,代码示例如下:
import introcs from Assignment import func_test def test_hello_input(): introcs.assert_equals(True, func_test("Hello")) def test_hello_world_input(): introcs.assert_equals(True, func_test("Hello World")) if __name__ == "__main__": introcs.test()
两种方案都能满足跑完所有测试用例的需求,测试用例数量多的情况下优先选方案2,写法更简洁不需要重复写异常捕获逻辑。
内容的提问来源于stack exchange,提问作者gautam
相关产品推荐
相关产品推荐

