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查看所有可用标记。

相关推荐
天才测试猿6 小时前
Python常用自动化测试框架—Pytest详解
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
慌糖15 小时前
自动化接口框架搭建分享-pytest第二部分
运维·自动化·pytest
know__ledge17 小时前
Pytest+requests进行接口自动化测试6.0(Jenkins)
elasticsearch·jenkins·pytest
慌糖2 天前
自动化接口框架搭建分享-pytest
运维·自动化·pytest
Rhys..2 天前
Gerkin+Pytest(python)实现自动化(BDD)
python·自动化·pytest
啊森要自信2 天前
【 GUI自动化测试】GUI自动化测试(一) 环境安装与测试
开发语言·python·ui·单元测试·pytest
know__ledge3 天前
Pytest+requests进行接口自动化测试5.0(5种assert断言的封装 + pymysql)
服务器·开发语言·python·测试用例·pytest
摘星编程15 天前
AI 帮我写单测:pytest 覆盖率提升 40% 的协作日志
人工智能·pytest·测试驱动开发·代码覆盖率·ai协作开发
lucia_zl17 天前
pytest并发测试,资源问题导致用例失败解决办法
pytest
鱼鱼说测试17 天前
Selenium4+Pytest自动化测试框架实战
pytest