pytest(16) mark用法

1.作用

  • 给用例分类
  • 筛选执行哪些用例
  • 钩子函数读取标记
  • 控制用例行为(跳过、超时、顺序等)

2.给用例打自定义标签

2.1 pytest.ini注册

python 复制代码
[pytest]
markers =
    mytag: 自定义标签
    device: 设备标签
    module: 模块标签

2.2 在测试用例上使用

python 复制代码
import pytest

# 打标记
@pytest.mark.mytag("示波器")
@pytest.mark.device("采集设备")
def test_1():
    assert 1 == 1

@pytest.mark.module("登录模块")
def test_2():
    assert 1 == 1

2.3执行时筛选

python 复制代码
# 只执行带 mytag 的用例
pytest -m mytag

# 执行带 device 或 module 的
pytest -m "device or module"

# 不执行 mytag
pytest -m "not mytag"

2.4钩子函数获取

python 复制代码
# conftest.py
import pytest

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()

    # 获取标记 @pytest.mark.mytag(xxx)
    tags = []
    for marker in item.iter_markers(name="mytag"):
        tags.extend(marker.args)

    print(f"用例:{item.nodeid}")
    print(f"标记内容:{tags}")
    print(f"结果:{report.outcome}")

2.5 pytest自带标记:跳过,参数化

python 复制代码
# 跳过用例
@pytest.mark.skip("暂不执行")

# 条件跳过
@pytest.mark.skipif(sys.version_info < (3,8), reason="版本太低")

# 预期失败
@pytest.mark.xfail

#  parametrize 参数化
@pytest.mark.parametrize("a,b", [(1,2), (3,4)])
相关推荐
时光不写代码6 小时前
修复 pytest-asyncio 事件循环冲突:完整解决方案
python·pytest·fastapi
上天_去_做颗惺星 EVE_BLUE8 小时前
接口自动化测试全流程:pytest 用例收集、并行执行、Allure 报告合并与上传
python·pytest
踏着七彩祥云的小丑1 天前
pytest——Mark标记
开发语言·python·pytest
lifewange2 天前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
我的xiaodoujiao4 天前
API 接口自动化测试详细图文教程学习系列9--Requests模块
python·学习·测试工具·pytest
我的xiaodoujiao4 天前
API 接口自动化测试详细图文教程学习系列10--Requests模块2--举例说明
python·学习·测试工具·pytest
超梦梦梦梦6 天前
playwright&pytest
pytest
不明觉厉二十年9 天前
pytest+pywinauto+pycharm制作mobaxterm 字符串快捷发送器 Demo
ide·pycharm·pytest
春日见10 天前
TEST文件夹:Pytest,集成测试,单元测试
服务器·人工智能·驱动开发·单元测试·计算机外设·集成测试·pytest
TRACER~8510 天前
项目实战:pandas+pytest+allure+adb
adb·pandas·pytest