pytest中mark的使用

在pytest中,mark(标记)是用于对测试用例进行分类、筛选或附加元数据的重要功能。以下是其核心使用方法:

1. ‌基本标记定义与使用‌

‌注册标记‌:在pytest.ini中预先定义标记(避免运行时警告):

python 复制代码
[pytest]
markers =
    smoke: 冒烟测试用例
    slow: 执行耗时较长的用例

‌标记测试函数/类‌:

python 复制代码
@pytest.mark.smoke
def test_login():
    assert True

@pytest.mark.slow
class TestPerformance:
    def test_response_time(self):
        assert True

2. ‌常用内置标记‌

‌跳过测试‌:

python 复制代码
@pytest.mark.skip(reason="功能暂未完成")
def test_unimplemented():
    pass

‌预期失败‌:

python 复制代码
@pytest.mark.xfail(reason="已知兼容性问题")
def test_legacy_feature():
    assert False

3. ‌参数化标记(数据驱动)‌

python 复制代码
@pytest.mark.parametrize("input,expected", [(1, 2), (3, 4)])
def test_add_one(input, expected):
    assert input + 1 == expected

4. ‌自定义标记的筛选‌

命令行执行特定标记的测试:

bash 复制代码
pytest -m "smoke"          # 只运行冒烟测试
pytest -m "not slow"       # 排除耗时用例
pytest -m "smoke or slow"  # 组合逻辑

5. ‌动态添加标记‌

通过钩子函数动态标记(如根据执行时间):

python 复制代码
def pytest_collection_modifyitems(items):
    for item in items:
        if "api" in item.nodeid:
            item.add_marker(pytest.mark.api)

注意事项:

未注册的自定义标记会触发警告,需在pytest.ini中声明。

标记支持继承(类标记会应用到所有方法)。

可通过pytest --markers查看所有可用标记。

相关推荐
努力搬砖的咸鱼15 小时前
AI Agent测试全景图:它到底改变了什么
人工智能·python·ai·集成测试·pytest·agent·ai编程
X1A0RAN2 天前
自动化流水线提效·微观篇:pytest 执行顺序优化
自动化·pytest
久久学姐10 天前
Python+Playwright+Pytest+BDD,用FSM打造高效测试框架
python·pytest·bdd·playwright·fsm
小白上线*^_^*10 天前
Pytest 自动化测试框架速通指南(二)
软件测试·pytest·python测试框架·ai测试基础
Logintern0911 天前
pytest的AST 断言重写
pytest
Tinyfacture12 天前
接口自动化之添加商品(pytest)
python·测试工具·自动化·pytest
ji_shuke14 天前
从零深入:基于 Playwright + Pytest + Allure 的企业级 Web 端到端自动化测试框架实战
前端·自动化测试·docker·jenkins·pytest·allure·playwright
祉猷并茂,雯华若锦15 天前
Selenium+Pytest自动化测试框架实战
selenium·测试工具·pytest
祉猷并茂,雯华若锦16 天前
Pytest+Selenium自动化测试:失败自动截图集成Allure报告
selenium·测试工具·pytest
我的xiaodoujiao19 天前
API 接口自动化测试详细图文教程学习系列32--Allure测试报告2
python·学习·测试工具·pytest