import pytest# 定义一个简单的函数def add(x, y): return x + y# 使用参数化测试同一个函数@pytest.mark.parametrize("a,b,expected", [ (1, 2, 3), (2, 3, 5), (3, 4, 7), (4, 5, 9),])def test_add(a, b, expected): assert add(a, b) == expected
在这个示例中,test_add 函数使用了 @pytest.mark.parametrize 装饰器,分别用四组不同的参数运行测试。
参数组合Pytest 也支持对参数进行组合。假设我们有两个参数列表,我们希望测试所有可能的参数组合,可以这样做:
@pytest.mark.parametrize("x", [1, 2])@pytest.mark.parametrize("y", [10, 20])def test_multiplication(x, y): assert x y in [10, 20, 20, 40]
这将会运行四次测试,分别是:

Pytest 提供了一些常用的装饰器来管理测试函数的行为,例如设置预置条件、清理操作等。
@pytest.fixture@pytest.fixture 装饰器用于定义测试前后的初始化代码(fixture)。fixture 是一种资源管理方式,用于在测试函数运行之前准备好需要的资源,并在测试函数结束之后清理这些资源。

import pytest@pytest.fixturedef sample_data(): return {"name": "Alice", "age": 30}def test_sample_data(sample_data): assert sample_data["name"] == "Alice" assert sample_data["age"] == 30
在这个示例中,sample_data 是一个 fixture,它返回一个字典。测试函数 test_sample_data 可以直接使用这个 fixture 提供的数据。
@pytest.mark.skip@pytest.mark.skip 装饰器用于跳过某些测试。这在某些情况下非常有用,例如在特定条件下不适用的测试。
@pytest.mark.skip(reason="测试暂时被跳过")def test_example(): assert 1 + 1 == 3
@pytest.mark.skipif
@pytest.mark.skipif 装饰器用于在满足特定条件时跳过测试。例如,只有在 Python 版本低于 3.6 时才跳过某个测试:
import sys@pytest.mark.skipif(sys.version_info < (3, 6), reason="需要 Python 3.6 以上版本")def test_python_version(): assert sys.version_info >= (3, 6)
@pytest.mark.xfail
@pytest.mark.xfail 装饰器用于标记已知会失败的测试。它在测试预期失败时不会被视为错误。
@pytest.mark.xfail(reason="此功能尚未实现")def test_unimplemented_feature(): assert False
结论
Pytest 的参数化和基本装饰器用法为编写灵活、高效的测试提供了强大的支持。通过参数化测试,我们可以轻松地用不同的数据集运行相同的测试函数。而通过装饰器,我们可以更好地管理测试的执行条件和环境。
熟练掌握这些功能,可以显著提高测试代码的质量和可维护性。在实际项目中,这些技术将帮助你更高效地进行测试和确保代码的可靠性。