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

如何为通过的pytest测试设置自定义状态标识(不抛异常)

pytest自定义测试结果问题

我知道可以自定义pytest的测试结果,但在给已通过的测试设置特殊状态时遇到了麻烦。比如我想实现这样的逻辑(伪代码):

def test_speed():
    duration = timeit(my_function())
    if duration > 60:
        set_pytest_flag(it_passed_but_took_a_while)

之后我在conftest.py里写了如下代码:

CUSTOM_STATUS_TIME = "_time"

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    """为测试项的setup、call、teardown阶段生成测试报告"""
    report = (yield).get_result()
    
    if report.passed and call.info.it_passed_but_took_a_while:
        # 测试中出现的问题并非验证失败导致
        # 可能是测试代码本身的问题,给报告添加自定义属性标记为`time`类型
        setattr(report, CUSTOM_STATUS_TIME, True)


def pytest_report_teststatus(report, config):
    """自定义测试状态的报告展示"""
    if getattr(report, CUSTOM_STATUS_TIME, False):
        return "time", "T", ("TIME", {"yellow": True})

我想要的效果是:测试本身通过,但同时给用户提示该测试耗时过长。注:这里只是以耗时为例,实际会基于其他业务逻辑设置这个特殊标识。

我的核心疑问是:能不能在测试执行过程中,给report或者call对象设置某个自定义值,让钩子函数能读取到,而且不需要抛出异常?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 04:55:14