如何使用 skip 和 xfail 处理无法成功的测试¶
你可以标记那些在特定平台上无法运行或预期会失败的测试函数,以便 pytest 能够相应地处理它们,并在保持测试套件 绿色(通过)状态的同时,提供测试会话的摘要。
skip 表示你预期测试仅在满足某些条件时才会通过,否则 pytest 应该完全跳过该测试。常见的例子包括在非 Windows 平台上跳过仅限 Windows 的测试,或者跳过当前不可用的外部资源(例如数据库)相关的测试。
xfail 表示你预期测试由于某种原因会失败。常见的例子包括尚未实现的功能的测试,或尚未修复的错误。当一个预期失败的测试(标记为 pytest.mark.xfail)实际上通过了,这被称为 xpass,并将显示在测试摘要中。
pytest 会分别计数并列出 skip 和 xfail 的测试。默认情况下,不会显示关于跳过/预期失败测试的详细信息,以避免输出冗余。你可以使用 -r 选项来查看与测试进度中显示的“短代码”对应的详细信息。
pytest -rxXs # show extra info on xfailed, xpassed, and skipped tests
有关 -r 选项的更多详细信息,可以通过运行 pytest -h 查看。
(参见 内置配置文件选项)
跳过测试函数¶
跳过测试函数最简单的方法是用 skip 装饰器标记它,并可选择传入一个 reason(原因)参数。
@pytest.mark.skip(reason="no way of currently testing this")
def test_the_unknown(): ...
或者,也可以在测试执行或设置期间通过调用 pytest.skip(reason) 函数来强制跳过。
def test_function():
if not valid_config():
pytest.skip("unsupported configuration")
当无法在导入时评估跳过条件时,这种强制跳过的方法非常有用。
也可以在模块级别使用 pytest.skip(reason, allow_module_level=True) 来跳过整个模块。
import sys
import pytest
if not sys.platform.startswith("win"):
pytest.skip("skipping windows-only tests", allow_module_level=True)
参考: pytest.mark.skip
skipif¶
如果你希望有条件地跳过某些测试,可以使用 skipif。以下是一个标记测试函数,使其在 Python 3.13 之前的解释器上运行时被跳过的示例。
import sys
@pytest.mark.skipif(sys.version_info < (3, 13), reason="requires python3.13 or higher")
def test_function(): ...
如果条件在收集期间评估为 True,则测试函数将被跳过,并在使用 -rs 时在摘要中显示指定的原因。
你可以在模块之间共享 skipif 标记。请参考这个测试模块:
# content of test_mymodule.py
import mymodule
minversion = pytest.mark.skipif(
mymodule.__versioninfo__ < (1, 1), reason="at least mymodule-1.1 required"
)
@minversion
def test_function(): ...
你可以导入该标记并在另一个测试模块中重用它。
# test_myothermodule.py
from test_mymodule import minversion
@minversion
def test_anotherfunction(): ...
对于大型测试套件,通常最好创建一个专门的文件来定义标记,然后在整个测试套件中统一应用它们。
或者,你可以使用 条件字符串 代替布尔值,但它们不容易在模块间共享,因此主要为了向后兼容性而支持。
跳过类或模块的所有测试函数¶
你可以在类上使用 skipif 标记(就像使用其他标记一样)。
@pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows")
class TestPosixCalls:
def test_function(self):
"will not be setup or run under 'win32' platform"
如果条件为 True,此标记将导致该类的每个测试方法都产生跳过结果。
如果你想跳过模块的所有测试函数,可以使用 pytestmark 全局变量。
# test_module.py
pytestmark = pytest.mark.skipif(...)
如果测试函数应用了多个 skipif 装饰器,只要其中任何一个跳过条件为真,它就会被跳过。
跳过文件或目录¶
有时你可能需要跳过整个文件或目录,例如,如果测试依赖于 Python 特定版本的功能,或者包含你不希望 pytest 运行的代码。在这种情况下,你必须在收集过程中排除这些文件和目录。更多信息请参阅 自定义测试收集。
在缺少导入依赖项时跳过¶
你可以通过在模块级别、测试内部或测试设置函数中使用 pytest.importorskip 来在缺少导入时跳过测试。
docutils = pytest.importorskip("docutils")
如果此处无法导入 docutils,将导致测试跳过。你也可以根据库的版本号进行跳过。
docutils = pytest.importorskip("docutils", minversion="0.3")
版本号将从指定模块的 __version__ 属性中读取。
摘要¶
以下是在不同情况下跳过模块中测试的快速指南:
无条件跳过模块中的所有测试
pytestmark = pytest.mark.skip("all tests still WIP")
根据某些条件跳过模块中的所有测试
pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="tests for linux only")
如果缺少某些导入,则跳过模块中的所有测试
pexpect = pytest.importorskip("pexpect")
XFail:将测试函数标记为预期失败¶
你可以使用 xfail 标记来表明你预期测试会失败。
@pytest.mark.xfail
def test_function(): ...
此测试仍会运行,但在失败时不会报告回溯。相反,终端报告会将其列在“预期失败”(XFAIL)或“意外通过”(XPASS)部分中。
或者,你也可以在测试函数内部或其设置函数中强制将测试标记为 XFAIL。
def test_function():
if not valid_config():
pytest.xfail("failing configuration (but should work)")
def test_function2():
import slow_module
if slow_module.slow_function():
pytest.xfail("slow_module taking too long")
这两个示例展示了你不希望在模块级别检查条件的情况,即条件在装饰器应用时无法评估的情况。
这将使 test_function 变为 XFAIL。注意,与标记不同,在 pytest.xfail() 调用之后,代码不会继续执行,这是因为它在内部是通过引发已知异常来实现的。
condition 参数¶
如果测试仅在特定条件下预期失败,你可以将该条件作为第一个参数传递。
@pytest.mark.xfail(sys.platform == "win32", reason="bug in a 3rd party library")
def test_function(): ...
注意,你还必须传递一个原因(参见 pytest.mark.xfail 的参数描述)。
reason 参数¶
你可以使用 reason 参数指定预期失败的原因。
@pytest.mark.xfail(reason="known parser issue")
def test_function(): ...
raises 参数¶
如果你想更具体地说明测试失败的原因,可以在 raises 参数中指定单个异常或异常元组。
@pytest.mark.xfail(raises=RuntimeError)
def test_function(): ...
那么,如果测试失败且异常不在 raises 中,它将被报告为常规失败。
run 参数¶
如果一个测试应该被标记为 xfail 并被报告为这样,但不应该被实际执行,请将 run 参数设置为 False。
@pytest.mark.xfail(run=False)
def test_function(): ...
这对于那些会导致解释器崩溃且应稍后调查的 xfail 测试特别有用。
strict 参数¶
默认情况下,XFAIL 和 XPASS 都不会导致测试套件失败。你可以通过将 strict 仅关键字参数设置为 True 来更改此行为。
@pytest.mark.xfail(strict=True)
def test_function(): ...
这将导致该测试的 XPASS(“意外通过”)结果导致整个测试套件失败。
你可以使用 strict_xfail ini 选项来更改 strict 参数的默认值。
[pytest]
xfail_strict = true
[pytest]
strict_xfail = true
忽略 xfail¶
通过在命令行指定:
pytest --runxfail
你可以强制运行并报告一个标记为 xfail 的测试,就好像它从未被标记过一样。这也使得 pytest.xfail() 不产生任何效果。
示例¶
这是一个包含多种用法的简单测试文件。
from __future__ import annotations
import pytest
xfail = pytest.mark.xfail
@xfail
def test_hello():
assert 0
@xfail(run=False)
def test_hello2():
assert 0
@xfail("hasattr(os, 'sep')")
def test_hello3():
assert 0
@xfail(reason="bug 110")
def test_hello4():
assert 0
@xfail('pytest.__version__[0] != "17"')
def test_hello5():
assert 0
def test_hello6():
pytest.xfail("reason")
@xfail(raises=IndexError)
def test_hello7():
x = []
x[1] = 1
使用 report-on-xfail 选项运行它会得到以下输出:
! pytest -rx xfail_demo.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-6.x.y, py-1.x.y, pluggy-1.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR/example
collected 7 items
xfail_demo.py xxxxxxx [100%]
========================= short test summary info ==========================
XFAIL xfail_demo.py::test_hello
XFAIL xfail_demo.py::test_hello2
reason: [NOTRUN]
XFAIL xfail_demo.py::test_hello3
condition: hasattr(os, 'sep')
XFAIL xfail_demo.py::test_hello4
bug 110
XFAIL xfail_demo.py::test_hello5
condition: pytest.__version__[0] != "17"
XFAIL xfail_demo.py::test_hello6
reason: reason
XFAIL xfail_demo.py::test_hello7
============================ 7 xfailed in 0.12s ============================
带参数化的 Skip/xfail¶
在使用 parametrize 时,可以将 skip 和 xfail 等标记应用于单个测试实例。
import sys
import pytest
@pytest.mark.parametrize(
("n", "expected"),
[
(1, 2),
pytest.param(1, 0, marks=pytest.mark.xfail),
pytest.param(1, 3, marks=pytest.mark.xfail(reason="some bug")),
(2, 3),
(3, 4),
(4, 5),
pytest.param(
10, 11, marks=pytest.mark.skipif(sys.version_info >= (3, 0), reason="py2k")
),
],
)
def test_increment(n, expected):
assert n + 1 == expected