Pytest 标记测试用例
简介
在测试过程中,有时候需要对测试用例进行标记,以便在运行测试时选择性地执行或跳过某些测试。
Pytest 提供了一种灵活的测试标记功能,可以通过自定义的标记标签来对测试用例进行分类和标记。
标记测试用例的优点
- 组织和分类测试:标记测试用例可以将它们分组归类,便于组织和管理测试。
- 例如,可以为功能测试、性能测试、回归测试等不同类型的测试案例创建不同的标记,使测试套件更加可读和易于维护。
- 灵活选择测试:通过标记测试用例,可以在运行测试时选择性地执行或跳过特定的测试用例。这对于执行特定类型或特定条件下的测试非常有用,提高了测试效率。
使用步骤
- 在测试用例方法上加
@pytest.mark.标签名
。 - 命令行执行用例时使用
-m 标签名
来指定要执行的测试用例。
实战案例
场景:测试 double 方法,给不同的测试场景分类。
import pytest
def double(a):
return a * 2
@pytest.mark.int
def test_double_int():
assert 2 == double(1)
@pytest.mark.minus
def test_double1_minus():
assert -2 == double(-1)
@pytest.mark.float
def test_double_float():
assert 0.2 == double(0.1)
@pytest.mark.minus
def test_double2_minus():
assert -0.2 == double(-0.1)
@pytest.mark.zero
def test_double_0():
assert 0 == double(0)
@pytest.mark.bignum
def test_double_bignum():
assert 200 == double(100)
@pytest.mark.str
def test_double_str():
assert 'aa' == double('a')
@pytest.mark.str
def test_double_str1():
assert 'a$a$' == double('a$')
执行标记为 str
的测试用例:
pytest test_command_param.py -m "str"
运行结果:
总结
- 标记测试用例的优点。
- 标记测试用例的方法。