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报告:

相关推荐
Lightning-py6 小时前
pytest后置处理方式
pytest
爆更小哇2 天前
Python自动化测试:pytest新手快速入门指南
python·测试工具·自动化·pytest
qq_452396232 天前
第一篇:基座选型 —— 为什么 Pytest 是自动化的终点?
自动化·pytest
时光不写代码2 天前
修复 pytest-asyncio 事件循环冲突:完整解决方案
python·pytest·fastapi
上天_去_做颗惺星 EVE_BLUE2 天前
接口自动化测试全流程:pytest 用例收集、并行执行、Allure 报告合并与上传
python·pytest
踏着七彩祥云的小丑3 天前
pytest——Mark标记
开发语言·python·pytest
lifewange4 天前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
我的xiaodoujiao6 天前
API 接口自动化测试详细图文教程学习系列9--Requests模块
python·学习·测试工具·pytest
我的xiaodoujiao6 天前
API 接口自动化测试详细图文教程学习系列10--Requests模块2--举例说明
python·学习·测试工具·pytest