]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-150175: Fix ThreadingMock call_count race condition (#150176)
authorsaisneha196 <156835592+saisneha196@users.noreply.github.com>
Thu, 21 May 2026 07:38:07 +0000 (13:08 +0530)
committerGitHub <noreply@github.com>
Thu, 21 May 2026 07:38:07 +0000 (08:38 +0100)
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.

Lib/unittest/mock.py
Misc/NEWS.d/next/Library/2026-05-21-11-25-58.gh-issue-150175.8H4Caz.rst [new file with mode: 0644]

index 16f3699e89e77d1e2466f6ac93370c4430f0583e..56cdc37942d65d8735e8ad9afe788fce160d429f 100644 (file)
@@ -3113,6 +3113,10 @@ class ThreadingMixin(Base):
 
         return ret_value
 
+    def _increment_mock_call(self, /, *args, **kwargs):
+        with self._mock_calls_events_lock:
+            super()._increment_mock_call(*args, **kwargs)
+
     def wait_until_called(self, *, timeout=_timeout_unset):
         """Wait until the mock object is called.
 
diff --git a/Misc/NEWS.d/next/Library/2026-05-21-11-25-58.gh-issue-150175.8H4Caz.rst b/Misc/NEWS.d/next/Library/2026-05-21-11-25-58.gh-issue-150175.8H4Caz.rst
new file mode 100644 (file)
index 0000000..80fc80d
--- /dev/null
@@ -0,0 +1,3 @@
+Fix race condition in :class:`unittest.mock.ThreadingMock` where
+concurrent calls could lose increments to ``call_count`` and other
+attributes due to a missing lock in ``_increment_mock_call``.