You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pytest中实现前置测试用例失败时跳过指定后续测试用例

测试用例失败后跳过指定后续用例的实现方案

可以通过pytest的fixture结合标记功能实现需求,核心思路是跟踪前置用例的执行状态,以此决定后续用例是否跳过。

实现代码

import pytest

class TestExample:
    @pytest.fixture(scope="class")
    def abc_test_result(self):
        # 用字典存储状态,方便在测试方法中修改
        return {"passed": True}

    def test_abc(self, abc_test_result):
        print("Hello")
        # 模拟测试失败场景,实际替换为你的测试逻辑
        assert 1 == 2, "test_abc执行失败"
        # 若测试通过,更新状态
        abc_test_result["passed"] = True

    @pytest.mark.skipif(
        lambda self, res: not res["passed"],
        reason="test_abc执行失败,跳过当前用例"
    )
    def test_xyz(self, abc_test_result):
        print("Hi")

    @pytest.mark.skipif(
        lambda self, res: not res["passed"],
        reason="test_abc执行失败,跳过当前用例"
    )
    def test_aaa(self, abc_test_result):
        print("World")

    def test_sample(self):
        print("Python")

关键说明

  • 定义abc_test_result fixture存储test_abc的执行状态,作用域设为class确保同一测试类内共享状态
  • 在test_abc中,若测试失败(断言触发异常),状态会保持初始的False;若测试通过则更新为True
  • 给test_xyz和test_aaa添加skipif标记,根据abc_test_result的状态判断是否跳过
  • test_sample不受状态影响,无论前置用例结果如何都会执行

内容的提问来源于stack exchange,提问作者Shastransu Suprabh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 23:05:17