如何基于pytest中前序测试函数的结果跳过后续测试函数?
问题原因
你写的代码里,@pytest.mark.skipif的条件是在pytest收集测试用例阶段就评估完成的,这时候skip_further_tests还是初始值False,所以test_one不会被标记为跳过。而test_zero是在测试运行阶段才执行的,这时候修改全局变量已经影响不到之前确定的跳过标记了。
解决方案
这里提供两种简单有效的实现方式:
方法一:在测试运行时主动判断并跳过
直接在test_one内部检查状态,调用pytest.skip()实现跳过:
import pytest skip_further_tests = False def test_zero(): global skip_further_tests skip_further_tests = True def test_one(): if skip_further_tests: pytest.skip("a previous test failed")
方法二:使用会话级fixture存储状态(更优雅,避免全局变量)
用pytest的会话级fixture来维护状态,避免全局变量的副作用:
import pytest @pytest.fixture(scope="session") def test_status(): # 用字典存储状态,方便在fixture外部修改 return {"skip_further": False} def test_zero(test_status): test_status["skip_further"] = True def test_one(test_status): if test_status["skip_further"]: pytest.skip("a previous test failed")
注意事项
测试用例的执行顺序默认是按函数名排序的,test_zero会在test_one之前运行,所以状态能正确传递。如果你的测试名称无法保证顺序,可以使用pytest-order插件(需额外安装),通过@pytest.mark.order(1)、@pytest.mark.order(2)来指定执行顺序。
内容的提问来源于stack exchange,提问作者tonitone120
相关产品推荐
相关产品推荐

