Skip to content

Commit ba116c3

Browse files
committed
Fix ThreadingMock call_count race condition
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. Reproducer: m = unittest.mock.ThreadingMock() # Run 50 threads each calling m() 10000 times # Expected: 500000, Got: ~460000 (missing calls)
1 parent cb3b4b9 commit ba116c3

1 file changed

Lines changed: 4 additions & 0 deletions

File tree

Lib/unittest/mock.py

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

31143114
return ret_value
31153115

3116+
def _increment_mock_call(self, /, *args, **kwargs):
3117+
with self._mock_calls_events_lock:
3118+
super()._increment_mock_call(*args, **kwargs)
3119+
31163120
def wait_until_called(self, *, timeout=_timeout_unset):
31173121
"""Wait until the mock object is called.
31183122

0 commit comments

Comments
 (0)