应用测试标记

Python 测试入门

Alexander Levin

Data Scientist

测试标记概览

  • 用例 1:若条件满足则跳过测试
  • 用例 2:此测试预期会失败

  • 测试标记pytest 中测试的标签

  • 通过为测试打标(标记)来指定其行为
Python 测试入门

标记语法

  • 装饰器(Decorator):Python 中的一种设计模式,可在不修改对象结构的情况下添加新功能
  • 测试标记语法@pytest.mark 装饰器开始:
import pytest

def get_length(string):
    return len(string)

# 测试标记语法
@pytest.mark.skip
def test_get_len():
    assert get_length('123') == 3
Python 测试入门

Skip 与 Skipif 标记

  • 使用 @pytest.mark.skip:无条件跳过测试
  • 使用 @pytest.mark.skipif:当给定条件为 True 时跳过测试
Python 测试入门

Skip 标记示例

  • 使用 @pytest.mark.skip:无限期跳过测试。
import pytest
def get_length(string):
    return len(string)

# skip 标记示例
@pytest.mark.skip
def test_get_len():
    assert get_length('123') == 3
Python 测试入门

Skip 标记示例:输出

  • 跳过测试时的输出:

pytest.mark.skip 示例

Python 测试入门

Skipif 标记示例

  • 使用 @pytest.mark.skipif:当给定条件为 True 时跳过测试。
import pytest
def get_length(string):
    return len(string)

# skipif 标记示例
@pytest.mark.skipif('2 * 2 == 5')
def test_get_len():
    assert get_length('abc') == 3
Python 测试入门

Skipif 标记示例:输出

  • 条件跳过测试的输出:

pytest.mark.skipif 示例

Python 测试入门

Xfail 标记

  • 使用 @pytest.mark.xfail:当预期测试会失败时
import pytest

def gen_sequence(n):
    return list(range(1, n+1))

# xfail 标记示例
@pytest.mark.xfail
def test_gen_seq():
    assert gen_sequence(-1)
Python 测试入门

Xfail 标记:输出

  • 预期失败测试的输出:

pytest.mark.xfail 示例

Python 测试入门

总结

测试标记

  • pytest 中测试的一个属性
  • 用于为特定测试指定行为
  • 语法以 @pytest.mark.name_of_the_marker 开头
  • pytest 内置标记:
    • @pytest.mark.xfail
    • @pytest.mark.skip
    • @pytest.mark.skipif
Python 测试入门

Passons à la pratique !

Python 测试入门

Preparing Video For Download...