如何让PyTest执行单个测试中所有断言(即便部分失败且无法拆分测试)
解决PyTest单测试用例全断言执行的方案
方法1:使用pytest-check插件
这是专门针对单测试内多断言全执行场景的第三方插件,操作简单直接。
操作步骤:
- 安装插件:
pip install pytest-check
- 修改测试代码,将普通
assert替换为check模块的断言方法:
import subprocess import pytest from pytest_check import check def test_executable_script(): result = subprocess.check_output([executable_script], encoding="UTF-8") check.assert_not_equal(result, "", f"Error: {result}") result_2 = subprocess.check_output([another_executable_script], encoding="UTF-8") check.assert_not_equal(result_2, "", f"Error: {result_2}")
该方式下,即便第一个断言失败,后续断言仍会执行,最终测试报告会汇总所有失败的断言信息。
方法2:手动收集断言错误(无需额外插件)
如果不想依赖第三方插件,可以手动捕获每个断言的异常,统一收集后再抛出:
import subprocess import pytest def test_executable_script(): error_list = [] # 第一个检查项 try: result = subprocess.check_output([executable_script], encoding="UTF-8") assert result != "", f"Error: {result}" except AssertionError as e: error_list.append(str(e)) # 第二个检查项 try: result_2 = subprocess.check_output([another_executable_script], encoding="UTF-8") assert result_2 != "", f"Error: {result_2}" except AssertionError as e: error_list.append(str(e)) # 最后统一抛出所有错误 if error_list: raise AssertionError("\n".join(error_list))
这种方式会把所有检查项的问题汇总展示,支持团队能一次性看到所有系统缺失项。
方法3:使用pytest-assume插件
另一款第三方插件,用法与pytest-check类似:
- 安装插件:
pip install pytest-assume
- 修改测试代码:
import subprocess import pytest def test_executable_script(): result = subprocess.check_output([executable_script], encoding="UTF-8") pytest.assume(result != "", f"Error: {result}") result_2 = subprocess.check_output([another_executable_script], encoding="UTF-8") pytest.assume(result_2 != "", f"Error: {result_2}")
执行测试后,报告会列出所有失败的assume断言内容。
内容的提问来源于stack exchange,提问作者Muhammad Sohaib Ahmed
相关产品推荐
相关产品推荐

