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

使用pytest --doctest-modules执行非测试脚本报错,如何处理?

pytest --doctest-modules执行非测试脚本触发SystemExit错误:是否正常?如何避免?

问题描述

我有如下最小复现示例(MRE):

.
└── tests
    └── notest.py

notest.py仅包含以下代码:

import sys
sys.exit(1)

当执行命令 pytest --doctest-modules 时,出现如下错误:

ERROR collecting tests/notest.py
tests/notest.py:4: in <module>
    sys.exit(1)
E   SystemExit: 1

可见--doctest-modules会尝试执行我的非测试脚本,请问这是正常行为吗?该如何避免?

回答

这是正常行为吗?

是正常的。--doctest-modules 参数的设计逻辑就是让pytest遍历所有可导入的.py文件,查找其中的doctest测试用例。在此过程中,pytest会导入这些模块,模块顶层的代码(比如你写的sys.exit(1))会在导入阶段被执行,因此触发SystemExit异常,导致测试收集失败。

如何避免?

提供几种实用解决方案:

  • 迁移非测试文件:将notest.py这类无需pytest处理的文件移出tests目录,从根源上避免被扫描到。
  • 配置pytest忽略指定文件:在项目根目录创建pytest.ini文件,添加如下配置:
    [pytest]
    ignore = tests/notest.py
    
  • 给脚本添加执行保护:如果必须保留在测试目录中,修改脚本让顶层代码仅在直接运行时执行,导入时不触发:
    import sys
    
    if __name__ == "__main__":
        sys.exit(1)
    
  • 缩小扫描范围:运行pytest时指定具体的测试文件或目录,而非让它扫描整个tests目录,例如:
    pytest --doctest-modules tests/your_real_test.py
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:30:54