用 pytest xfail(strict=True) 管理已知缺陷并阻止过期标记
问题场景
在持续迭代的项目里,某些缺陷已经确认,但修复要排期。若直接跳过相关测试,回归覆盖会静默丢失;若让测试一直失败,CI 又会被长期染红,其他真实失败反而被淹没。pytest 的 xfail 用于表达“这个用例预期失败”:失败时记为 xfailed,不阻断流水线;而 strict=True 让它在“意外通过”时变成失败,提示缺陷可能已修复,必须移除过期标记。
关键是把预期失败限定在具体参数上,并写明原因,而不是整组跳过测试。
最小示例
示例模块有一个已知缺陷:连续空格只被替换成多个连字符。
# calc.py
def slugify(title: str) -> str:
return title.strip().lower().replace(' ', '-')
测试用参数化区分正常用例和缺陷用例:
# test_calc.py
import pytest
from calc import slugify
@pytest.mark.parametrize(
'raw, expected',
[
pytest.param('Hello World', 'hello-world', id='single-space'),
pytest.param(
'Hello World',
'hello-world',
id='double-space',
marks=pytest.mark.xfail(
strict=True,
reason='BUG-123:连续空格未折叠为单个连字符',
),
),
],
)
def test_slugify(raw, expected):
assert slugify(raw) == expected
这里 single-space 应通过;double-space 会得到 hello--world,断言失败,因此被记为 xfailed。strict=True 只作用于这个参数,不会影响同组的其他用例。
运行与验证
安装 pytest 后执行:
python -m pytest -q -rxX
预期摘要中应看到一个通过、一个 xfailed,且 -rxX 会显示 xfail 原因和 XPASS 信息。若去掉 strict=True,用例意外通过时只会记为 xpass,默认不阻断 CI,容易让过期标记长期存在。
修复实现后,例如:
# calc.py
import re
def slugify(title: str) -> str:
return re.sub(r'\s+', '-', title.strip().lower())
再次运行测试,double-space 会变成 XPASS。由于 strict 生效,pytest 会把它计为失败并返回非零退出码。此时不应改回非 strict,也不应删除测试,而应移除该参数的 xfail 标记,把它保留为普通回归用例。
CI 门禁配置
CI 只需正常执行 pytest 并保留退出码。示意步骤:
# .github/workflows/test.yml
name: test
on: [push, pull_request]
jobs:
pytest:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- run: python -m pip install -r requirements-dev.txt
- run: python -m pytest -q -rxX
其他 CI 平台等价命令也是 python -m pytest -q -rxX。不要把命令改成 || true,也不要在流水线里忽略测试退出码;否则 strict 产生的失败不会成为门禁。若项目统一要求,可在配置中设置 xfail_strict = true,但参数级 strict=True 更清晰,能避免影响其他标记。
边界与限制
- xfail 适合“缺陷已确认、暂时无法修复”的用例;原因必须可追踪,例如关联缺陷编号,避免写“先这样”。
- strict 只能防止标记过期,不能证明缺陷存在。修复后应人工确认并移除标记,不能依赖自动删除。
- 只标记受缺陷影响的具体参数或最小用例,避免把整组正常测试标成 xfail。
- 如果失败来自 fixture 初始化、环境缺失或导入错误,不应靠 xfail 掩盖;这类问题通常应按错误处理。
- XPASS 是待处理信号而非噪音。CI 失败后应更新实现或移除标记,再提交。
- 定期用
pytest --runxfail可查看忽略 xfail 后的真实结果,适合排查,但日常门禁仍应保留 strict 行为。
- 点赞
- 收藏
- 关注作者
评论(0)