PyTest 中的 `pytest.mark` 可以用于哪些场景?如何自定义一个标记(mark)并实现其逻辑?

PyTest 中的 pytest.mark 是一个非常强大的功能,可以用于多种场景,比如标记测试用例、分类测试、参数化测试以及跳过某些测试等。以下是其常见用途和自定义标记的实现方法:

1. pytest.mark 的常见用途

标记测试用例

可以为一组测试用例添加标记,方便后续运行或筛选。例如,标记某些用例为冒烟测试或回归测试:

import pytest

@pytest.mark.smoke
def test_login():
    assert True

@pytest.mark.regression
def test_logout():
    assert True

运行标记为 smoke 的测试用例:

pytest -m smoke

跳过测试

可以使用 pytest.mark.skip 或 pytest.mark.skipif 跳过某些测试:

import pytest

@pytest.mark.skip(reason="Not implemented yet")
def test_unimplemented():
    assert False

@pytest.mark.skipif(1 < 2, reason="1 is always less than 2")
def test_skipped_if_true():
    assert False

参数化测试

使用 pytest.mark.parametrize 可以为测试用例提供多组输入参数:

import pytest

@pytest.mark.parametrize("input, expected", [(1, 2), (3, 4)])
def test_increment(input, expected):
    assert input + 1 == expected

预期失败测试

使用 pytest.mark.xfail 标记预期会失败的测试用例,但不会中断测试流程:

import pytest

@pytest.mark.xfail
def test_expected_failure():
    assert False

2. 自定义标记的实现方法

定义自定义标记

在 pytest.ini 文件中定义自定义标记,以避免运行时警告:

[pytest]
markers =
    slow: marks tests as slow (deselect with '-m "not slow"')
    high_priority: marks tests as high priority

使用自定义标记

在测试代码中使用自定义标记:

import pytest

@pytest.mark.slow
def test_long_running():
    import time
    time.sleep(10)
    assert True

@pytest.mark.high_priority
def test_important_feature():
    assert True

运行标记为 high_priority 的测试用例:

pytest -m high_priority

实现标记的逻辑

可以通过 pytest_collection_modifyitems 钩子函数实现标记的逻辑。例如,为标记为 slow 的测试用例添加超时限制:

import pytest

def pytest_collection_modifyitems(config, items):
    for item in items:
        if "slow" in item.keywords:
            item.add_marker(pytest.mark.timeout(10))  # 设置超时时间为10秒

标记的参数化

自定义标记也可以携带参数,例如实现一个动态标记:

import pytest

@pytest.mark.custom_mark(priority="high")
def test_custom_mark_logic():
    assert True

然后在钩子函数中解析参数:

def pytest_collection_modifyitems(config, items):
    for item in items:
        for mark in item.iter_markers(name="custom_mark"):
            priority = mark.kwargs.get("priority", "low")
            if priority == "high":
                item.add_marker(pytest.mark.high_priority)

总结

pytest.mark 是一个非常灵活的工具,能够满足各种测试场景的需求,包括分类、筛选、跳过和参数化测试等。通过自定义标记,可以进一步扩展其功能,为测试框架添加领域特定的逻辑。