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

相关推荐
不拘一格的叶三少2 天前
Pytest + Playwright 自动化测试工程设计要点 & 目录结构
测试工具·pytest
努力搬砖的咸鱼3 天前
意图理解:让Agent从需求描述自动生成Pytest测试策略
人工智能·python·ai·单元测试·pytest·agent
St_rive6 天前
Pytest skip&&skipif跳过⽤例
运维·服务器·pytest
努力搬砖的咸鱼9 天前
AI Agent测试全景图:它到底改变了什么
人工智能·python·ai·集成测试·pytest·agent·ai编程
X1A0RAN10 天前
自动化流水线提效·微观篇:pytest 执行顺序优化
自动化·pytest
久久学姐18 天前
Python+Playwright+Pytest+BDD,用FSM打造高效测试框架
python·pytest·bdd·playwright·fsm
小白上线*^_^*18 天前
Pytest 自动化测试框架速通指南(二)
软件测试·pytest·python测试框架·ai测试基础
Logintern0919 天前
pytest的AST 断言重写
pytest
Tinyfacture20 天前
接口自动化之添加商品(pytest)
python·测试工具·自动化·pytest