1.@pytest.mark.自定义标签

pytest 里,除了内置的 skip / skipif / xfail 等标记以外,我们还可以 自定义标记(marker),用来给测试用例打标签,方便分类、筛选、分组执行。

pytest.ini 示例

# pytest.ini
[pytest]
markers =
    slow: 标记为耗时测试
    api: 标记为 API 测试
    db: 标记为数据库相关测试
import pytest

@pytest.mark.slow
def test_big_data():
    assert 1 + 1 == 2

@pytest.mark.api
def test_api_call():
    assert "ok" == "ok"

@pytest.mark.db
def test_insert():
    assert True

只允许某类测试:

pytest -m slow

排除某类测试:

pytest -m "not db"

组合条件:

pytest -m "api and not slow"

2.在 conftest.py 里“注册”自定义标记(避免 UnknownMark 警告)

# conftest.py
def pytest_configure(config):
    # 等价于在 pytest.ini 里写 [pytest] markers = ...
    config.addinivalue_line("markers", "slow: 耗时测试")
    config.addinivalue_line("markers", "api: API 相关测试")
    config.addinivalue_line("markers", "needs_net: 需要网络的测试")