You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pytest中添加测试优先级并在Azure DevOps的Tests标签中展示

实现方案

1. 所需依赖安装

  • 核心依赖为 pytest-azurepipelines 插件,是Azure官方适配pytest的工具,支持输出Azure DevOps原生识别的TRX测试报告,可传递测试优先级等自定义属性
  • 安装命令:pip install pytest-azurepipelines pytest
  • 若你习惯使用 pytest-trx 生成TRX报告,方案也完全兼容,无需调整后续配置

2. 测试用例打优先级标记

首先在项目根目录的pytest.ini中注册自定义优先级marker,避免运行时出现未注册marker警告:

[pytest]
markers =
    severity: 标记测试用例优先级,对应Azure DevOps Priority字段,取值为1-4的整数,1为最高优先级,4为最低

之后直接在测试用例上添加标记即可:

import pytest

@pytest.mark.severity(1)
def test_high_priority_feature():
    assert 1 == 1

@pytest.mark.severity(3)
def test_medium_priority_feature():
    assert 2 == 2

3. 同步优先级到测试报告

在项目根目录的conftest.py中添加pytest钩子函数,自动将用例的severity标记值写入TRX报告的对应优先级字段:

def pytest_runtest_makereport(item, call):
    if call.when == "call":
        # 读取用例的severity标记
        severity_marker = item.get_closest_marker("severity")
        if severity_marker:
            priority = severity_marker.args[0]
            # 将优先级写入测试结果属性,适配TRX格式的Priority字段
            if hasattr(item, "execution_properties"):
                item.execution_properties["Priority"] = priority

4. Azure DevOps Pipeline配置

Pipeline中运行测试和发布报告的示例配置如下:

steps:
- task: UsePythonVersion@0
  inputs:
    versionSpec: '3.9'
  displayName: '使用指定Python版本'

- script: |
    pip install -r requirements.txt
    pytest --trx-results=test-results.trx
  displayName: '运行pytest测试'

- task: PublishTestResults@2
  inputs:
    testResultsFormat: 'TRX'
    testResultsFiles: '**/test-results.trx'
    mergeTestResults: true
    testRunTitle: '自动化测试执行结果'
  displayName: '发布测试结果到Azure DevOps'

注意事项

  • Azure DevOps Tests标签页的Priority字段仅支持1-4的整数值,优先级从高到低对应1到4,标记时不要传入字符串类型的优先级(如"高""中"),否则无法正常识别
  • 无需额外安装其他第三方插件,上述方案即可实现优先级字段的正常展示

内容的提问来源于stack exchange,提问作者Diggy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 03:15:03