pytest 中如何临时禁用(跳过)某个测试?
pytest 跳过测试用 @pytest.mark.skip 装饰器(可注明原因),或用 skipif 按条件跳过,命令行可用 --deselect 精确排除。本文对比各种方式。
最常用的方式是给测试函数加装饰器 @pytest.mark.skip(reason="跳过原因");需要按条件跳过用 @pytest.mark.skipif(条件, reason=...);不想改代码可以在命令行用 --deselect 文件::测试名 排除。
无条件跳过:@pytest.mark.skip
import pytest
@pytest.mark.skip(reason="功能重构中,暂时禁用")
def test_addition():
assert 2 + 2 == 4
运行时该用例显示为 SKIPPED 并附带原因,测试报告里清晰可见——这比直接注释掉好,因为不会忘记它还存在。
条件跳过:@pytest.mark.skipif
import sys
@pytest.mark.skipif(sys.platform == "win32", reason="Windows 上不支持")
def test_posix_feature():
...
常用于"只在某平台/某 Python 版本跳过"的场景。
预期失败:@pytest.mark.xfail
如果测试对应的功能本身有 bug、明知会失败,用 xfail 比 skip 更准确:失败时记为 xfail(不计入失败),哪天修好了反而提示 XPASS。
@pytest.mark.xfail(reason="已知 bug #123")
def test_edge_case():
...
命令行临时排除
pytest --deselect test_math.py::test_addition
不改代码,临时跳过某个用例。
常见问题(FAQ)
Q:skip 和直接注释掉测试有什么区别?
A:skip 会在测试报告中留下记录(N 个用例被跳过),团队能看到;注释掉则完全消失,容易被遗忘。
Q:能跳过整个测试类或模块吗?
A:可以。类上加同样的装饰器;模块级跳过在文件顶部写 pytestmark = pytest.mark.skip(reason=...),或在模块开头调用 pytest.skip(reason=..., allow_module_level=True)。
Q:如何在运行时动态决定跳过?
A:在测试函数内部调用 pytest.skip("原因"),执行到该行即跳过本用例。