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

如何在pytest-bdd中正确使用@pytest.mark.xfail标记?

问题原因

pytest的标记是作用于测试用例函数层级,你将@pytest.mark.xfail添加在单个step定义函数上不会生效,pytest-bdd会为每个Scenario自动生成独立的测试用例函数,标记需要绑定到这个生成的测试用例上才会生效。

解决方法

方法1:在feature文件中添加tag(最便捷)

直接在对应Scenario上方添加@xfail标签,pytest-bdd会自动将feature文件中的标签映射为pytest的标记:

@xfail
Scenario: Validate the API response where availableLicense should not be greater than the totalLicense.
Given Send valid input
Then validate the availableLicense count should not be greater than totalLicense.

如果需要配置xfail的参数(比如设置严格模式、添加原因),可以在pytest配置文件中对xfail标签做自定义映射,或者使用方法2。

方法2:在Python代码中给Scenario绑定标记

在定义Scenario对应的测试函数时,直接添加@pytest.mark.xfail装饰器即可,step定义不需要做任何修改:

import pytest
from pytest_bdd import scenario, given, then

# 给对应Scenario的测试函数加xfail标记
@pytest.mark.xfail(reason="已知许可证计数逻辑待修复,预期校验失败", strict=False)
@scenario("example.feature", "Validate the API response where availableLicense should not be greater than the totalLicense.")
def test_validate_license_count():
    pass

# 原step定义保持不变,不需要加xfail装饰器
@given('Send valid input')
def valid_data(context, url,token_url, api_key):
    context.response = api_req('get',url, token_url, api_key)

@then('validate the availableLicense count should not be greater than totalLicense.')
def validate_license_count(context):
      <some logic>
      assert avail_license <= total_license
补充说明
  • 配置strict=True时,如果该用例实际运行通过(显示XPASS状态),会被判定为测试失败
  • 建议添加reason参数标注预期失败的原因,方便后续维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 21:45:04