Pytest Xfail/跳过测试


在本章中,我们将了解 Pytest 中的 Skip 和 Xfail 测试。

现在,考虑以下情况:

  • 由于某些原因,测试在一段时间内不相关。
  • 正在实施一项新功能,我们已经为该功能添加了测试。

在这些情况下,我们可以选择使测试失败或跳过测试。

Pytest 将执行 xfailed 测试,但它不会被视为部分失败或通过测试。即使测试失败,也不会打印这些测试的详细信息(请记住,pytest 通常会打印失败的测试详细信息)。我们可以使用以下标记进行 xfail 测试:

@pytest.mark.xfail

跳过测试意味着不会执行测试。我们可以使用 以下标记:

@pytest.mark.skip

稍后,当测试变得相关时,我们可以删除标记。

Edit the test_compare.py 我们已经必须包含 xfail 和 skip 标记:

import pytest
@pytest.mark.xfail
@pytest.mark.great
def test_greater():
    num = 100
    assert num > 100

@pytest.mark.xfail
@pytest.mark.great
def test_greater_equal():
    num = 100
    assert num >= 100

@pytest.mark.skip
@pytest.mark.others
def test_less():
    num = 100
    assert num < 200

使用以下命令执行测试:

pytest test_compare.py -v

上述命令执行后会产生如下结果:

test_compare.py::test_greater xfail
test_compare.py::test_greater_equal XPASS
test_compare.py::test_less SKIPPED
============================ 1 skipped, 1 xfailed, 1 xpassed in 0.06 seconds
============================