unittest.mock.patch.object holds references for too long
未关闭
还没有人认领这个 Issue。
performance
stdlib
type-bug
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 36k
- PR 合并指标
- PR 指标待抓取
描述
Bug report
Bug description:
import sys
from unittest import mock
import json
def main():
obj = 'asdfa' * 2000
print("BEGIN", sys.getrefcount(obj))
for i in range(10):
with mock.patch.object(json, 'dumps', return_value=3):
from json import dumps
dumps(obj)
del dumps
print("END", sys.getrefcount(obj))
import gc; gc.collect()
print("AFTERGC", sys.getrefcount(obj))
if __name__ == '__main__':
main()
The code prints:
BEGIN 2
END 12
AFTERGC 2
Because it is the user's data that is leaked, the leaked object could be huge and could cause non-trivial problems.
CPython versions tested on:
3.13
Operating systems tested on:
Linux
Linked PRs
- gh-139937
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 unittest.mock.patch.object 和提供的复现开始,然后阅读链接的 PR gh-139937 以了解当前的调查。验证重复 patch 上下文以及垃圾回收前后的引用计数;当上下文结束后用户的对象不再被引用时,即表示完成。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- testing
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 25/100