Skip to content

Commit 3336a28

Browse files
kumaraditya303miss-islington
authored andcommitted
gh-142651: use NonCallableMock._lock for thread safety of call_count (GH-142922)
(cherry picked from commit 728e4a0) Co-authored-by: Kumar Aditya <kumaraditya@python.org>
1 parent 80204f7 commit 3336a28

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

Lib/unittest/mock.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1178,10 +1178,16 @@ def _increment_mock_call(self, /, *args, **kwargs):
11781178
# handle call_args
11791179
# needs to be set here so assertions on call arguments pass before
11801180
# execution in the case of awaited calls
1181-
_call = _Call((args, kwargs), two=True)
1182-
self.call_args = _call
1183-
self.call_args_list.append(_call)
1184-
self.call_count = len(self.call_args_list)
1181+
with NonCallableMock._lock:
1182+
# Lock is used here so that call_args_list and call_count are
1183+
# set atomically otherwise it is possible that by the time call_count
1184+
# is set another thread may have appended to call_args_list.
1185+
# The rest of this function relies on list.append being atomic and
1186+
# skips locking.
1187+
_call = _Call((args, kwargs), two=True)
1188+
self.call_args = _call
1189+
self.call_args_list.append(_call)
1190+
self.call_count = len(self.call_args_list)
11851191

11861192
# initial stuff for method_calls:
11871193
do_method_calls = self._mock_parent is not None

0 commit comments

Comments
 (0)