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

Python 3.11 ExceptionGroup的doctest测试文档编写问题求助

解决Python 3.11 ExceptionGroup的doctest测试问题

为什么直接复制输出无效

这不是Python版本的bug,而是doctest的严格匹配机制与ExceptionGroup的结构化输出共同导致的:

  • doctest默认会逐字符匹配输出内容,包括ExceptionGroup用来展示层级的|和+符号。
  • 实际抛出异常的Traceback包含动态内容(如文件路径、行号),每次运行都会变化,直接复制的静态测试用例必然和实际输出不匹配。

实现Traceback省略的两种方法

方法1:启用ELLIPSIS选项并调整测试用例

doctest的ELLIPSIS选项允许用...代替任意长度的动态内容,只需保留ExceptionGroup的核心结构:

  1. 编写测试用例时,用...替换Traceback的动态部分,保留|和+的结构:
>>> def raise_group():
...     raise ExceptionGroup("errors", [ValueError("invalid value"), TypeError("wrong type")])
>>> raise_group()
Traceback (most recent call last):
    ...
ExceptionGroup: errors (2 sub-exceptions)
+-----------------------------+
| ValueError: invalid value   |
+-----------------------------+
| TypeError: wrong type       |
+-----------------------------+
  1. 运行doctest时启用ELLIPSIS选项:
    • 命令行方式:python -m doctest -o ELLIPSIS your_script.py
    • 代码内调用:
      import doctest
      doctest.testmod(optionflags=doctest.ELLIPSIS)
      

方法2:捕获异常后手动验证(更可靠)

避开输出格式的干扰,直接捕获ExceptionGroup并验证其属性:

>>> try:
...     raise_group()
... except ExceptionGroup as eg:
...     assert eg.args[0] == "errors"  # 验证组消息
...     assert len(eg.exceptions) == 2  # 验证子异常数量
...     assert isinstance(eg.exceptions[0], ValueError)
...     assert str(eg.exceptions[0]) == "invalid value"
...     assert isinstance(eg.exceptions[1], TypeError)
...     assert str(eg.exceptions[1]) == "wrong type"

这种方法不依赖输出格式,即使Python后续版本调整ExceptionGroup的展示样式,测试依然有效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 16:55:02