Skip to content

Commit 43f71b0

Browse files
[3.13] gh-150175: Fix ThreadingMock call_count race condition (GH-150176) (#150180)
gh-150175: Fix ThreadingMock call_count race condition (GH-150176) ThreadingMock._increment_mock_call() was not thread-safe. Multiple threads calling the mock simultaneously could lose increments due to race conditions on call_count and other attributes. Fix by overriding _increment_mock_call in ThreadingMixin and wrapping it with the existing _mock_calls_events_lock. (cherry picked from commit 388e023) Co-authored-by: saisneha196 <156835592+saisneha196@users.noreply.github.com>
1 parent 43b6b48 commit 43f71b0

2 files changed

Lines changed: 7 additions & 0 deletions

File tree

Lib/unittest/mock.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3102,6 +3102,10 @@ def _mock_call(self, *args, **kwargs):
31023102

31033103
return ret_value
31043104

3105+
def _increment_mock_call(self, /, *args, **kwargs):
3106+
with self._mock_calls_events_lock:
3107+
super()._increment_mock_call(*args, **kwargs)
3108+
31053109
def wait_until_called(self, *, timeout=_timeout_unset):
31063110
"""Wait until the mock object is called.
31073111
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix race condition in :class:`unittest.mock.ThreadingMock` where
2+
concurrent calls could lose increments to ``call_count`` and other
3+
attributes due to a missing lock in ``_increment_mock_call``.

0 commit comments

Comments
 (0)