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

GitHub Actions中pytest测试不通过时如何标记步骤失败

问题

在GitHub Actions工作流中执行了如下pytest测试步骤:

- name: running pytest
  run: poetry run pytest

测试执行完成后,输出显示有1个xfailed(预期失败)的测试,但工作流步骤仍被标记为成功。需求是:当存在测试未通过的情况时,让该步骤报告失败。

测试输出详情:

Run poetry run pytest
============================= test session starts ==============================
platform linux -- Python 3.9.16, pytest-7.3.1, pluggy-1.0.0
rootdir: /home/runner/work/Package/Package
plugins: cov-4.0.0
collected 271 items

tests/test_base.py ....x......................................... [ 16%]
[...]
tests/test_utils.py ......                                        [100%]

=============================== warnings summary ===============================
.venv/lib/python3.9/site-packages/pkg_resources/__init__.py:121
  /home/runner/work/package/Package/.venv/lib/python3.9/site-packages/pkg_resources/__init__.py:121: DeprecationWarning: pkg_resources is deprecated as an API
    warnings.warn("pkg_resources is deprecated as an API", DeprecationWarning)

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
============ 270 passed, 1 xfailed, 1 warning in 182.06s (0:03:02) =============
解决方案

pytest默认将xfailed(预期失败)的测试判定为“符合预期”的结果,会返回0退出码,因此GitHub Actions会认为步骤执行成功。根据需求,可通过以下方式调整:

1. 把xfail标记的测试当作普通测试

如果希望所有标记为xfail的测试一旦失败就触发步骤失败,使用--no-xfail参数,该参数会取消xfail的特殊处理,将其视为普通测试:

- name: running pytest
  run: poetry run pytest --no-xfail

这样,原本的xfailed测试会被统计为failed,pytest返回非零退出码,GitHub Actions会自动标记步骤失败。

2. 启用严格模式检测非预期通过

如果只希望处理预期失败但实际通过(xpassed)的情况,同时检测未注册的测试标记,使用--strict参数:

- name: running pytest
  run: poetry run pytest --strict

该参数会将xpassed测试判定为失败,确保只有完全符合预期的测试结果才会让步骤成功。

3. 强制让xfailed触发失败

如果需要即使是预期内的xfailed测试也触发步骤失败,可以结合使用测试报告和脚本判断结果:

- name: running pytest
  run: |
    poetry run pytest --junitxml=results.xml
    if grep -q "<testcase status=\"failed\"" results.xml || grep -q "<testcase status=\"xfailed\"" results.xml; then
      exit 1
    fi

这个脚本会生成JUnit格式的测试报告,然后检查是否存在失败或预期失败的测试,存在则返回非零码触发步骤失败。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 21:43:23