unittest.mock.patch.object holds references for too long
Open
Nobody has claimed this yet.
performance
stdlib
type-bug
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with unittest.mock.patch.object and the supplied reproduction, then read linked PR gh-139937 for the current investigation. Verify the reference counts before and after repeated patch contexts and garbage collection; done means the user's object no longer remains referenced after the contexts end.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- testing
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100