当使用 --tb=line 时,如何为失败用例自动打印局部变量?

解读

--tb=line 会把异常回溯压缩成“文件名:行号: 异常名”这一行,省掉了帧详情,也就看不到局部变量。国内很多公司为了日志简洁、CI 日志不超限,会强制加 --tb=line 或 --tb=no,但调试时又希望“失败时能看到局部变量”。面试官想确认两点:

  1. 你知道 --tb=line 的副作用;
  2. 你能用 pytest 的钩子和内置机制“按需”把局部变量打出来,而不是简单地换成 --tb=long。

知识点

  1. pytest 的终端回溯样式由 --tb 控制,line/no/short/long/native/auto 互斥。
  2. 局部变量属于帧信息,只有进入 Traceback 对象才能拿到;--tb=line 直接跳过帧打印,因此必须额外钩子介入。
  3. pytest_runtest_makereport 钩子能在用例 outcome == 'failed' 时拿到 excinfo(ExceptionInfo),其 .tb 属性就是回溯链。
  4. 用 traceback 标准库可以 walk_tb,再通过 frame.f_locals 读取局部变量;为了可读性,一般用 pprint 或 json.dumps(…, ensure_ascii=False) 打印。
  5. 打印时机:
    • 直接 print → 会被 --tb=line 的简洁输出“淹没”;
    • 改用 terminalreporter 的 write_line/section,能确保在失败汇总区域高亮输出,符合国内“日志规范”要求。
  6. 兼容性:本地开发可加 --tb=long,CI 强制 --tb=line,但钩子始终生效,做到“一套代码,两种模式”。
  7. 注意:局部变量可能含敏感字段(密码、token),生产 CI 需脱敏或关闭,面试时可主动提到“数据合规”。

答案

在项目根目录的 conftest.py 中实现钩子,即可在 --tb=line 模式下自动打印失败用例的局部变量,且不影响简洁的回溯行:

# conftest.py
import sys, traceback, pprint
from _pytest.reports import TestReport
from _pytest.terminal import TerminalReporter

def pytest_runtest_makereport(item, call):
    # 只关心调用阶段的失败
    if call.when == "call" and call.excinfo is not None:
        # 把局部变量收集成字符串
        tb = call.excinfo.tb
        locals_lines = []
        while tb:
            frame = tb.tb_frame
            locals_lines.append(f"\n--- Frame: {frame.f_code.co_name}  {frame.f_code.co_filename}:{frame.f_lineno} ---")
            for k, v in frame.f_locals.items():
                # 简单脱敏示例
                if 'pwd' in k.lower() or 'token' in k.lower():
                    v = "***"
                locals_lines.append(f"{k} = {pprint.pformat(v, width=120)}")
            tb = tb.tb_next
        # 挂到 report 上,供后续钩子取用
        item._failed_locals = "\n".join(locals_lines)

def pytest_terminal_summary(terminalreporter: TerminalReporter, exitstatus, config):
    # 只在终端模式下追加
    if not hasattr(terminalreporter, '_tw'):
        return
    reports: list[TestReport] = terminalreporter.getreports('failed')
    for rep in reports:
        item = rep.item
        locals_text = getattr(item, '_failed_locals', None)
        if locals_text:
            terminalreporter.section(f"局部变量捕获:{rep.nodeid}", sep=">", blue=True)
            terminalreporter.write_line(locals_text)

运行命令:

pytest -q --tb=line

失败时终端仍只显示一行回溯,但在最底部会多出一个 “>局部变量捕获:test_xx.py::test_xxx” 区块,完整打印各帧局部变量,达到“简洁+调试”两全。

拓展思考

  1. 分布式执行:当使用 pytest-xdist 时,worker 子进程里产生的失败需通过 pytest-testreport 协议把 locals_text 序列化回 master,可在 pytest_report_to_serializable 钩子中追加自定义字段,再在 master 端反序列化打印。
  2. 大对象截断:局部变量可能是 numpy 数组、pandas DataFrame,全部 pprint 会撑爆日志,可在 conftest.py 中加阈值,只打印前 N 项或类型摘要。
  3. 与 allure/pytest-html 集成:把 locals_text 作为附件或 extra 信息,生成离线报告时同样可见,满足国内“测试报告归档”审计要求。
  4. 安全合规:金融、医疗类项目需符合《个人信息保护法》,建议加白名单机制,只有指定测试标记(如 @pytest.mark.debug_locals)才启用打印,CI 默认关闭。
  5. 性能:walk_tb 发生在失败路径,对成功用例零损耗;若担心极端场景(递归 1w 层),可限制最大帧深度。