pytest 软断言的几种方式

特性 原生 assert Pytest 9.0+ subtests pytest-assume pytest-check pytest-essentials
失败行为 立即停止 仅子测试失败,不影响其他 继续执行,汇总所有失败 继续执行,汇总所有失败 继续执行,但可配置最终状态
依赖/安装 (Pytest 9.0+内置) 需要安装 pytest-assume 需要安装 pytest-check 需要安装pytest-essentials
代码风格 原生 assert 语句 原生 assert 语句 需调用 pytest.assume() 函数 上下文管理器或特定方法 创建软断言实例
适用场景 简单、独立的断言 官方推荐,需在一个用例中执行多个独立检查 需要失败后继续执行的简单场景 需要详细错误报告的复杂断言 允许灵活控制当软断言失败时,测试用例的最终状态
详细错误报告 否,信息较简略 是,可自定义信息 是,可自定义信息
Allure集成 仅首失败 部分支持 较好 较好 官方支持

使用示例:

python 复制代码
def test_native_assert():
    assert 1 == 2   # 失败,函数立即停止
    assert 2 == 2   # 不会执行
    assert 1 == 3

def test_subtests(subtests): #将 pytest 升级到 9.0 或更高版本 或 安装 pytest-subtests 插件; allure报告不显示2个失败
    with subtests.test("第一次检查"):
        assert 1 == 2       # 失败,但不会终止
    with subtests.test("第二次检查"):
        assert 2 == 2       # 会执行,成功
    with subtests.test("第三次检查"):
        assert 1 == 3       # 失败
def test_assume():#需要安装 pytest-assume,allure报告显示2个失败
    pytest.assume(1 == 2)   # 失败,记录错误但继续
    pytest.assume(2 == 2)   # 会执行,成功
    pytest.assume(1 == 3)   # 失败


from pytest_check import check
def test_check():#需要安装 pytest-check, allure报告显示2个失败
    with check:
        assert 1 == 2       # 失败,继续执行
    with check:
        assert 2 == 2       # 成功
    with check:
        assert 1 == 3       # 失败

from pytest_essentials import SoftAssert
@pytest.mark.soft_assert_level("failed")
def test_soft_assert_example():#需要安装pytest-essentials, allure报告可显示多个错误,标记failed,报告显示failed,默认warning
    sa = SoftAssert()  # 创建软断言实例

    # 使用软断言方法进行检查
    sa.assert_equal(1, 2, "第一次检查: 1 不应该等于 2")
    sa.assert_true(False, "第二次检查: 这个条件应该为 True")
    sa.assert_equal(2, 2, "第三次检查: 2 应该等于 2")
    sa.assert_equal(1, 3, "第四次检查: 1 不应该等于 3")

Allure报告:

相关推荐
nbwenren6 天前
2026实测:Gemini 3.1 Pro 从需求文档到 pytest 测试用例一条龙教程
测试用例·pytest
我的xiaodoujiao6 天前
API 接口自动化测试详细图文教程学习系列16--项目实战演练3
python·学习·测试工具·pytest
我的xiaodoujiao6 天前
API 接口自动化测试详细图文教程学习系列15--项目实战演练2
python·学习·测试工具·pytest
技术钱7 天前
PyTest配置与API测试用例
servlet·测试用例·pytest
weixin_419658319 天前
pytest 零基础入门实战指南
python·pycharm·pytest
姚青&12 天前
软件测试基础概念
单元测试·pytest
爆更小哇15 天前
pytest集成Allure报告教程
python·测试工具·pytest·接口测试·allure
gCode Teacher 格码致知15 天前
Python提高:pytest的简单案例-由Deepseek产生
python·pytest
gCode Teacher 格码致知16 天前
Python提高: unittest和 pytest的使用方法-由Deepseek产生
开发语言·python·pytest