test.support.warnings_helper.check_warnings() raises KeyError: 'warnings' under -X lazy_imports=all
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 36k
- PR 合併指標
- PR 指標待擷取
描述
Bug report
test.support.warnings_helper.check_warnings() raises KeyError: 'warnings'
under -X lazy_imports=all, taking down every test that uses it.
Reproducer:
./python -X lazy_imports=all -m test test_sundry test_time
Lib/test/support/warnings_helper.py:176:
# Because test_warnings swap the module, we need to look up in the
# sys.modules dictionary.
wmod = sys.modules['warnings']
warnings is not in sys.modules at interpreter startup, with or without lazy
imports, so that key is populated solely by the module-level import warnings
at the top of this same file. Reading the module out of sys.modules by
subscript means the global name is never touched, so under lazy imports the
import is never resolved and the key is never created.
41 files under Lib/test/ use check_warnings() / check_no_warnings().
One-line fix — the default argument is evaluated on every call, which resolves
the lazy import before the lookup, and the module swap done by test_warnings
still wins:
wmod = sys.modules.get('warnings', warnings)
Verified on main (d9154924138): with that change test_sundry, test_time
and test_warnings pass under -X lazy_imports=all; test___all__,
test_sundry, test_time, test_warnings and test_support still pass
without the flag.
test_sundry and test_time are not in the exclusion list proposed in
GH-151105, so this is a failure mode the planned CI would not have covered.
The same pattern appears in the tests themselves. After the helper is fixed,
test___all__ still fails at Lib/test/test___all__.py:49:
if not hasattr(sys.modules[modname], "__all__"):
with KeyError: '_osx_support' — the module is imported by
exec("import %s" % modname) a few lines above, which under lazy imports
leaves sys.modules untouched. Lines 71 and 76 do the same thing.
grep -rn 'sys\.modules\[' Lib/test/ reports 126 subscript reads. Most are
legitimate identity checks after an eager import; the ones worth auditing are
those where the key is expected to be filled by an import in the same file, or
by an execed import statement.
Related to #149640.
CPython versions tested on:
CPython main branch (d9154924138)
Operating systems tested on:
Linux
🤖 Investigated and drafted with Claude Code,
model Claude Opus 5 (1M context).
Linked PRs
- gh-156573
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
從 Lib/test/support/warnings_helper.py 的第 176 行開始,接著檢查 Lib/test/test___all__.py 中回報的 sys.modules 存取。使用 -X lazy_imports=all 和列出的測試模組執行重現程式;完成的標準是受影響的測試在啟用和未啟用延遲匯入時都通過,包括 test_support 和 test_warnings。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- testing-qa
- Issue 類型
- 缺陷
- 難度
- 2/5
- 預估耗時
- 1-3 小時
- 活躍度
- 停滯
- 描述清晰度
- 描述清楚
- 新手友好度
- 25/100