Skip to content

Pytest 设置跳过、预期失败用例


简介

在使用 pytest 进行测试开发时,有时候可能需要跳过某些测试用例或者标记某些测试用例为预期失败。pytest 提供了一些装饰器和命令行选项来实现这些功能。


使用场景

  1. 当某些用例无法顺利通过或者尚未完成实现时,可以将其标记为跳过或预期失败,这样在整个测试运行过程中,这些用例将不会执行。
  2. 预期失败的测试用例会被执行,但不会导致整个测试运行失败。

跳过(Skip)及预期失败(xFail)的使用

  • xfail - 遇到特定情况,产生一个“期望失败”输出。

注意: 而 xFail 用于标记测试用例,以指示该测试用例是预期失败的。这意味着测试用例可以运行,但失败时不会被视为实际失败,而是被记录为已预期的失败。


跳过用例

  • skip 用于标记测试用例,以指示该测试用例应该被跳过而不执行
  • skipif:遇到特定情况跳过该测试用例。

使用场景

  • 调试时不想运行这个用例。
  • 标记无法在某些平台上运行的测试功能。
  • 在某些版本中执行,其他版本中跳过。
  • 比如:当前的外部资源不可用时跳过。

  • 如果测试数据是从数据库中取到的。

  • 连接数据库的功能如果返回结果未成功就跳过,因为执行也都报错。

  • 解决 1:添加装饰器

  • @pytest.mark.skip

  • @pytest.mark.skipif

  • 解决 2:代码中添加跳过代码

  • pytest.skip(reason)


跳过某个用例不执行

  • @pytest.mark.skip
  • @pytest.mark.skip(reason="跳过的原因描述")
import pytest

@pytest.mark.skip
def test_a():
    assert True

@pytest.mark.skip(reason="代码没有实现")
def test_b():
    assert False

运行结果:


方法中设置跳过用例

  • pytest.skip("reason")
def test_skip_example():
    print("方法中设置跳过用例")
    pytest.skip("跳过这个用例")
    # 这个断言不会被执行,因为测试会被跳过
    assert 1 == 1

执行结果:


遇到特定情况跳过该测试用例

  • @pytest.mark.skipif(条件表达式, reason="跳过原因")
import pytest

# 如果是mac系统则跳过执行
@pytest.mark.skipif(sys.platform == 'darwin', reason="does not run on mac") 
def test_case1():
    assert True

# 如果是windows系统则跳过执行
@pytest.mark.skipif(sys.platform == 'win', reason="does not run on windows") 
def test_case2():
    assert True

标记用例预期失败

  • 与 skip 类似,当用例预期结果为 fail 时,可以直接标记用例预期失败。
  • 用法:添加装饰器 @pytest.mark.xfail

代码示例:

import pytest

@pytest.mark.xfail
def test_a():
    assert  1 == 2

@pytest.mark.xfail
def test_b():
    assert  2 == 2

运行结果:


总结

  • Pytest 设置跳过。
  • Pytest 设置预期失败用例。