Skip to content
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Lib/test/test_unittest/testmock/testthreadingmock.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import time
import unittest
import threading
import concurrent.futures

from test.support import threading_helper
Expand Down Expand Up @@ -196,6 +197,27 @@ def test_reset_mock_resets_wait(self):
m.wait_until_any_call_with()
m.assert_called_once()

def test_call_count_thread_safe(self):

m = ThreadingMock()

# 3k loops reliably reproduces the issue while keeping runtime ~0.6s
LOOPS = 3_000
THREADS = 10

def test_function():
for _ in range(LOOPS):
m()

threads = [threading.Thread(target=test_function) for _ in range(THREADS)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()

self.assertEqual(m.call_count, LOOPS * THREADS,
f"Expected {LOOPS * THREADS}, got {m.call_count}")


if __name__ == "__main__":
unittest.main()
2 changes: 1 addition & 1 deletion Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -1180,14 +1180,14 @@ def _mock_call(self, /, *args, **kwargs):

def _increment_mock_call(self, /, *args, **kwargs):
self.called = True
self.call_count += 1

# handle call_args
# needs to be set here so assertions on call arguments pass before
# execution in the case of awaited calls
_call = _Call((args, kwargs), two=True)
self.call_args = _call
self.call_args_list.append(_call)
self.call_count = len(self.call_args_list)

# initial stuff for method_calls:
do_method_calls = self._mock_parent is not None
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed a thread safety issue in :mod:`unittest.mock` where :attr:`~unittest.mock.Mock.call_count` could return inaccurate values when a mock was called concurrently from multiple threads. The attribute now derives its value from the length of :attr:`~unittest.mock.Mock.call_args_list` to ensure consistency.
Loading