From: Kumar Aditya Date: Tue, 10 Mar 2026 12:11:12 +0000 (+0530) Subject: gh-142651: use `NonCallableMock._lock` for thread safety of `call_count` (#142922) X-Git-Tag: v3.15.0a7~1 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=728e4a075e3dae7e04edf90ad137a35073deb141;p=thirdparty%2FPython%2Fcpython.git gh-142651: use `NonCallableMock._lock` for thread safety of `call_count` (#142922) --- diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py index 34fd49bf56fb..64a01a0b713c 100644 --- a/Lib/unittest/mock.py +++ b/Lib/unittest/mock.py @@ -1184,10 +1184,16 @@ class CallableMixin(Base): # 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) + with NonCallableMock._lock: + # Lock is used here so that call_args_list and call_count are + # set atomically otherwise it is possible that by the time call_count + # is set another thread may have appended to call_args_list. + # The rest of this function relies on list.append being atomic and + # skips locking. + _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