Skip to content

unittest.mock.patch.object holds references for too long #133423

@ppwwyyxx

Description

@ppwwyyxx

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    performancePerformance or resource usagestdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions