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

相关推荐
糖果店的幽灵4 天前
软件测试接口测试从入门到精通:Python接口自动化 - pytest测试框架
软件测试·python·功能测试·自动化·pytest·接口测试
2601_961875244 天前
花生十三资料1200题|题库|刷题
conda·pytest·pillow·pip·web3.py·ipython·gunicorn
某人辛木4 天前
Web自动化测试
前端·python·pycharm·pytest
淡漠的蓝精灵6 天前
pytest-xdist:把 pytest 测试分发到多核 CPU 执行
其他·pytest
弹简特8 天前
【接口自动化】03-YAML详解及Parametrize数据驱动
自动化·pytest
007张三丰9 天前
软件测试专栏(11/20):测试框架开发:pytest深度解析与插件体系
运维·服务器·自动化测试·pytest·测试框架
我的xiaodoujiao10 天前
API 接口自动化测试详细图文教程学习系列25--继续处理testCase中的数据
python·学习·测试工具·pytest
xiaobai17811 天前
pytest+playwright实现UI自动化(4)-上夹具fixture
ui·自动化·pytest·playwright
弹简特11 天前
【接口自动化】02-Pytest固件fixture核心机制与Allure企业级报告实战
自动化·pytest·测试