在钩子内部如何区分 setup、call、teardown 阶段的异常?
解读
国内一线互联网公司的自动化测试面试里,这道题出现的频率极高。面试官真正想验证的是:
- 你是否真的“踩过坑”——在失败重跑、Allure 报告、钉钉告警等场景里,必须知道异常到底发生在哪一阶段,才能决定要不要重跑、截屏、清理脏数据;
- 你是否理解 pytest 的“三层执行模型”(setup → call → teardown),并能用钩子参数精准定位;
- 你是否能把“阶段”与“异常类型”解耦:同一阶段可能抛 AssertionError、WebDriverException、自定义 BusinessError,区分阶段不靠异常类型,而靠钩子被调用的时机与参数结构。
知识点
-
三层执行模型
每个测试项(item)被执行时,pytest 会依次生成三个“运行实例”:- setup:包括 fixture(scope=function 的 setUp)和 unittest 的 setUp/setUpClass
- call:真正的测试函数/方法体
- teardown:包括 fixture 的 yield 之后代码、unittest tearDown/tearDownClass
每个实例在 pytest.runner 里对应一个 CallInfo 对象,异常就保存在CallInfo.excinfo(类型为Optional[ExceptionInfo[BaseException]])。
-
钩子函数与参数
能“抓到”异常的核心钩子只有两个:pytest_runtest_makereport(item, call)
参数call就是当前阶段的 CallInfo;call.when取值"setup" | "call" | "teardown";call.excinfo存异常。pytest_runtest_logreport(report)
参数report是 TestReport,也有report.when与report.outcome(passed/failed/skipped),但异常对象已被序列化成report.longrepr,想拿到原始异常类型需回退到 makereport。
-
区分阶段的代码套路
在 makereport 里写if call.when == "setup"即可,无需关心异常类型;
若需要同时记录异常类型,可再判断call.excinfo.type;
注意:teardown 阶段即使抛异常,pytest 也会继续执行后续 teardown,并把异常合并到最终报告,因此要做“聚合”处理。 -
国内工程化落地细节
- 失败重跑(pytest-rerunfailures):只重跑 call 阶段失败,setup 失败直接标记 error 不重跑;
- 钉钉/飞书告警:setup 失败通常@责任人,call 失败@测试脚本作者,teardown 失败@运维;
- Allure 趋势报告:setup/teardown 失败归类为“环境错误”,不纳入用例通过率。
答案
在 pytest_runtest_makereport 钩子内,通过 call.when 字段即可精确区分异常发生的阶段,示例代码如下:
# conftest.py
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if call.excinfo is not None: # 有异常
when = call.when # 'setup' | 'call' | 'teardown'
exc_type = call.excinfo.type # 异常类
exc_value = call.excinfo.value # 异常实例
if when == "setup":
# 记录环境准备失败,可标记 error、不重跑
item.config.failed_setup_count = getattr(item.config, "failed_setup_count", 0) + 1
elif when == "call":
# 记录用例断言失败,可触发重跑、截屏
item.config.failed_call_count = getattr(item.config, "failed_call_count", 0) + 1
elif when == "teardown":
# 记录清理失败,可发运维告警
item.config.failed_teardown_count = getattr(item.config, "failed_teardown_count", 0) + 1
关键点:
- 用
call.when而不是异常类型; - 用
call.excinfo取到原始异常,方便后续做类型判断或重抛; - 钩子必须加
hookwrapper=True,否则拿不到call参数。
拓展思考
-
多异常聚合
teardown 阶段可能连续抛多个异常(多个 fixture 清理失败)。pytest 会把它们合并成ExceptionChain,在 makereport 里只能拿到第一个。若需全部记录,可自定义pytest_exception_interact(node, call, report)把每个异常写进日志系统或 Kafka。 -
与 fixture 的
yield异常联动
如果 fixture 的yield之后代码抛异常,它属于 teardown 阶段;但某些公司想把“fixture 清理失败”单独标记为“INFRA”级别,可在 fixture 里手动捕获并抛出自定义InfraError,然后在 makereport 里识别exc_type is InfraError并改写report.outcome = "infra",再配套自定义 Allure 标签。 -
与 CI 质量门禁对接
国内很多团队用 GitLab-CI 或云效,门禁规则是“call 失败率 >2% 阻断上线,setup 失败率 >0 直接阻断”。在 makereport 里实时累加计数器,最后通过pytest_terminal_summary把三阶段失败数写到summary.json,CI 解析即可精准阻断,避免“误伤”因 teardown 失败而阻断上线。 -
性能优化
当用例量达到万级,makereport 钩子会成为瓶颈。可只在--stage-fail-stats开关开启时才启用详细统计,减少每次函数调用的if判断开销;或把统计逻辑下沉到 Cython 扩展,提升 10%+ 执行效率。