]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.15] gh-150175: Fix ThreadingMock call_count race condition (GH-150176) (#150182)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Tue, 26 May 2026 19:46:16 +0000 (21:46 +0200)
committerGitHub <noreply@github.com>
Tue, 26 May 2026 19:46:16 +0000 (12:46 -0700)
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 388e023fe1197c1ffed374520ed45df4ac72b8f5)

Co-authored-by: saisneha196 <156835592+saisneha196@users.noreply.github.com>
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 1cee67fa5d709463567dddec94d9de5837be88da..2f6f03c7a11ae640973abdb4be2ab6a35d29696b 100644 (file)
@@ -3121,6 +3121,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``.