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

如何阻止非断言失败的错误测试用例写入pytest_cache的lastfailed文件

实现方案

核心思路是通过pytest的钩子函数,在测试会话结束时过滤lastfailed缓存内容,仅保留真正断言失败的测试用例写入缓存。

步骤1:创建conftest.py配置文件

在项目根目录新建conftest.py,写入以下代码:

import pytest

@pytest.hookimpl(tryfirst=True)
def pytest_runtest_makereport(item, call):
    # 将测试用例各阶段的执行报告挂载到用例对象上,方便后续过滤
    if not hasattr(item, "report"):
        setattr(item, "report", [])
    item.report.append(call.get_result())

@pytest.hookimpl(tryfirst=True)
def pytest_sessionfinish(session, exitstatus):
    # 读取默认生成的lastfailed缓存
    last_failed_cache = session.config.cache.get("cache/lastfailed", {})
    if not last_failed_cache:
        return

    filtered_failed = {}
    # 遍历所有测试用例的执行结果
    for test_item in session.items:
        node_id = test_item.nodeid
        if node_id not in last_failed_cache:
            continue

        # 筛选出测试执行阶段(排除setup/teardown阶段)的报告
        call_reports = [rep for rep in test_item.report if rep.when == "call"]
        if not call_reports:
            continue
        call_report = call_reports[0]

        # 仅保留测试执行阶段失败、且失败原因是AssertionError的用例
        if call_report.outcome == "failed" and "AssertionError" in str(call_report.longrepr):
            filtered_failed[node_id] = True

    # 把过滤后的结果写回lastfailed缓存
    session.config.cache.set("cache/lastfailed", filtered_failed)

步骤2:验证效果

运行你提供的测试代码后,查看.pytest_cache/v/cache/lastfailed文件,只会记录断言失败的test_two,fixture报错导致运行错误的test_one会被过滤掉。
下次执行pytest --lf时,只会重跑test_two,符合预期。

注意事项

  • 该逻辑不会修改测试执行的最终结果展示,控制台仍会正常显示fixture错误、运行时错误等异常状态,仅过滤lastfailed缓存的写入内容。
  • 如果你的测试中有自定义断言异常继承自AssertionError,也会被判定为合法的断言失败加入缓存,若要排除可以调整"AssertionError" in str(call_report.longrepr)的判断逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:15:03