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)])
相关推荐
边吃番茄边敲代码3 天前
从本地工具到 MCP:给 Agent 接入独立工具服务,并补齐自动化测试
人工智能·python·功能测试·ai·单元测试·pytest
SugarAbsinthe3 天前
【Agent开发实习小记】从人工逐条验证到自动化验收:新 API 接入前的效率瓶颈
人工智能·python·自动化·pytest
X1A0RAN4 天前
pytest 动态报告:数据可视化篇 —— 用 Golang + Echo 打造自动化测试任务可视化平台
信息可视化·golang·pytest
吨吨ai4 天前
Codex 实战:用 Git 分支 + pytest 构建可回滚的 AI 开发流程(2026年8月27日)
人工智能·git·pytest
冷凝娇6 天前
【Pytest】2026 学习总结
学习·pytest
测试老哥9 天前
Pytest自动化测试框架tep环境变量、fixtures、用例三者之间的关系
自动化测试·软件测试·python·测试工具·测试用例·pytest·职场发展
小小测试开发9 天前
Agent 安全测试:pytest 原生红队框架 RAMPART 实战解析
人工智能·pytest
不拘一格的叶三少13 天前
Pytest + Playwright 自动化测试工程设计要点 & 目录结构
测试工具·pytest