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

相关推荐
11路没有终点20 小时前
pytest 参数化与 Mark 标记
pytest
2601_9622962821 小时前
五种Python自动化测试框架汇总,附学习方法
自动化测试·pytest·unittest·robotframework·python框架
11路没有终点2 天前
pytest Fixture 进阶:conftest 与依赖注入
pytest
2601_962387825 天前
web自动化测试实战教程【selenium/unittest/pytest】【共193课
selenium·pytest·devops·web自动化测试·unittest
weixin_440730505 天前
使用pytest中方法控制执行步骤(test_begin.py、test_end.py,@pytest.mark.run(order=1))
开发语言·python·pytest
2601_962297255 天前
Python、Pytest、Allure、Selenium和Jenkins实现自动化测试集成实例
python·selenium·jenkins·pytest·allure
2601_962077606 天前
从零搭建Python接口自动化测试框架:pytest+requests实战指南
python·pytest·接口自动化·requests·框架搭建
weixin_440730506 天前
pytest结合allure生成html测试报告(step、story、severity、screenshot)
前端·html·pytest·allure报告
拜托多多指教6 天前
【Pytest框架学习】分层架构
python·pytest
2601_962299886 天前
python脚本如何单元测试
python·单元测试·pytest·unittest·mock对象