Python Pytest 高级用法指南

pytest 是一个简单而又强大的 Python 测试框架。以下是一些高级用法,帮助你更高效地使用 pytest。

1. 参数化测试

pytest 支持参数化测试,可以让你轻松地运行相同的测试用例,但使用不同的参数。

import pytest

@pytest.mark.parametrize("num", [1, 2, 3])
def test_add(num):
    assert 1 + 1 == num

2. 自定义标记

自定义标记可以帮助你更好地组织测试。

def test_my_custom_marker():
    assert True

你可以使用 @pytest.mark.my_custom_marker 来应用这个标记。

3. 跳过测试

使用 @pytest.mark.skip 跳过测试。

def test_skipped():
    pytest.skip("跳过这个测试")

4. 测试夹具(Fixtures)

测试夹具可以重用测试数据,提高代码复用性。

@pytest.fixture
def example_data():
    return "测试数据"

def test_example_data(example_data):
    assert example_data == "测试数据"

5. 测试报告

pytest 支持多种测试报告格式,如 JUnit、JSON 等。

pytest --junitxml=report.xml

扩展阅读

想了解更多 pytest 的用法,可以阅读官方文档:pytest官方文档


python_pytest