Skip to content

Commit d65b783

Browse files
mariocj89tirkarthi
andauthored
gh-61215: New mock to wait for multi-threaded events to happen (#16094)
mock: Add `ThreadingMock` class Add a new class that allows to wait for a call to happen by using `Event` objects. This mock class can be used to test and validate expectations of multithreading code. It uses two attributes for events to distinguish calls with any argument and calls with specific arguments. The calls with specific arguments need a lock to prevent two calls in parallel from creating the same event twice. The timeout is configured at class and constructor level to allow users to set a timeout, we considered passing it as an argument to the function but it could collide with a function parameter. Alternatively we also considered passing it as positional only but from an API caller perspective it was unclear what the first number meant on the function call, think `mock.wait_until_called(1, "arg1", "arg2")`, where 1 is the timeout. Lastly we also considered adding the new attributes to magic mock directly rather than having a custom mock class for multi threading scenarios, but we preferred to have specialised class that can be composed if necessary. Additionally, having added it to `MagicMock` directly would have resulted in `AsyncMock` having this logic, which would not work as expected, since when if user "waits" on a coroutine does not have the same meaning as waiting on a standard call. Co-authored-by: Karthikeyan Singaravelan <tir.karthi@gmail.com>
1 parent 0355625 commit d65b783

File tree

4 files changed

+422
-0
lines changed

4 files changed

+422
-0
lines changed

Doc/library/unittest.mock.rst

+47
Original file line numberDiff line numberDiff line change
@@ -205,8 +205,10 @@ The Mock Class
205205
import asyncio
206206
import inspect
207207
import unittest
208+
import threading
208209
from unittest.mock import sentinel, DEFAULT, ANY
209210
from unittest.mock import patch, call, Mock, MagicMock, PropertyMock, AsyncMock
211+
from unittest.mock import ThreadingMock
210212
from unittest.mock import mock_open
211213

212214
:class:`Mock` is a flexible mock object intended to replace the use of stubs and
@@ -1099,6 +1101,51 @@ object::
10991101
[call('foo'), call('bar')]
11001102

11011103

1104+
.. class:: ThreadingMock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, *, timeout=UNSET, **kwargs)
1105+
1106+
A version of :class:`MagicMock` for multithreading tests. The
1107+
:class:`ThreadingMock` object provides extra methods to wait for a call to
1108+
be invoked, rather than assert on it immediately.
1109+
1110+
The default timeout is specified by the ``timeout`` argument, or if unset by the
1111+
:attr:`ThreadingMock.DEFAULT_TIMEOUT` attribute, which defaults to blocking (``None``).
1112+
1113+
You can configure the global default timeout by setting :attr:`ThreadingMock.DEFAULT_TIMEOUT`.
1114+
1115+
.. method:: wait_until_called(*, timeout=UNSET)
1116+
1117+
Waits until the mock is called.
1118+
1119+
If a timeout was passed at the creation of the mock or if a timeout
1120+
argument is passed to this function, the function raises an
1121+
:exc:`AssertionError` if the call is not performed in time.
1122+
1123+
>>> mock = ThreadingMock()
1124+
>>> thread = threading.Thread(target=mock)
1125+
>>> thread.start()
1126+
>>> mock.wait_until_called(timeout=1)
1127+
>>> thread.join()
1128+
1129+
.. method:: wait_until_any_call(*args, **kwargs)
1130+
1131+
Waits until the the mock is called with the specified arguments.
1132+
1133+
If a timeout was passed at the creation of the mock
1134+
the function raises an :exc:`AssertionError` if the call is not performed in time.
1135+
1136+
>>> mock = ThreadingMock()
1137+
>>> thread = threading.Thread(target=mock, args=("arg1", "arg2",), kwargs={"arg": "thing"})
1138+
>>> thread.start()
1139+
>>> mock.wait_until_any_call("arg1", "arg2", arg="thing")
1140+
>>> thread.join()
1141+
1142+
.. attribute:: DEFAULT_TIMEOUT
1143+
1144+
Global default timeout in seconds to create instances of :class:`ThreadingMock`.
1145+
1146+
.. versionadded:: 3.13
1147+
1148+
11021149
Calling
11031150
~~~~~~~
11041151

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,278 @@
1+
import time
2+
import unittest
3+
import concurrent.futures
4+
5+
from unittest.mock import patch, ThreadingMock, call
6+
7+
8+
class Something:
9+
def method_1(self):
10+
pass
11+
12+
def method_2(self):
13+
pass
14+
15+
16+
class TestThreadingMock(unittest.TestCase):
17+
def _call_after_delay(self, func, /, *args, **kwargs):
18+
time.sleep(kwargs.pop("delay"))
19+
func(*args, **kwargs)
20+
21+
def setUp(self):
22+
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)
23+
24+
def tearDown(self):
25+
self._executor.shutdown()
26+
27+
def run_async(self, func, /, *args, delay=0, **kwargs):
28+
self._executor.submit(
29+
self._call_after_delay, func, *args, **kwargs, delay=delay
30+
)
31+
32+
def _make_mock(self, *args, **kwargs):
33+
return ThreadingMock(*args, **kwargs)
34+
35+
def test_spec(self):
36+
waitable_mock = self._make_mock(spec=Something)
37+
38+
with patch(f"{__name__}.Something", waitable_mock) as m:
39+
something = m()
40+
41+
self.assertIsInstance(something.method_1, ThreadingMock)
42+
self.assertIsInstance(something.method_1().method_2(), ThreadingMock)
43+
44+
with self.assertRaises(AttributeError):
45+
m.test
46+
47+
def test_side_effect(self):
48+
waitable_mock = self._make_mock()
49+
50+
with patch(f"{__name__}.Something", waitable_mock):
51+
something = Something()
52+
something.method_1.side_effect = [1]
53+
54+
self.assertEqual(something.method_1(), 1)
55+
56+
def test_instance_check(self):
57+
waitable_mock = self._make_mock()
58+
59+
with patch(f"{__name__}.Something", waitable_mock):
60+
something = Something()
61+
62+
self.assertIsInstance(something.method_1, ThreadingMock)
63+
self.assertIsInstance(something.method_1().method_2(), ThreadingMock)
64+
65+
def test_dynamic_child_mocks_are_threading_mocks(self):
66+
waitable_mock = self._make_mock()
67+
self.assertIsInstance(waitable_mock.child, ThreadingMock)
68+
69+
def test_dynamic_child_mocks_inherit_timeout(self):
70+
mock1 = self._make_mock()
71+
self.assertIs(mock1._mock_wait_timeout, None)
72+
mock2 = self._make_mock(timeout=2)
73+
self.assertEqual(mock2._mock_wait_timeout, 2)
74+
mock3 = self._make_mock(timeout=3)
75+
self.assertEqual(mock3._mock_wait_timeout, 3)
76+
77+
self.assertIs(mock1.child._mock_wait_timeout, None)
78+
self.assertEqual(mock2.child._mock_wait_timeout, 2)
79+
self.assertEqual(mock3.child._mock_wait_timeout, 3)
80+
81+
self.assertEqual(mock2.really().__mul__().complex._mock_wait_timeout, 2)
82+
83+
def test_no_name_clash(self):
84+
waitable_mock = self._make_mock()
85+
waitable_mock._event = "myevent"
86+
waitable_mock.event = "myevent"
87+
waitable_mock.timeout = "mytimeout"
88+
waitable_mock("works")
89+
waitable_mock.wait_until_called()
90+
waitable_mock.wait_until_any_call("works")
91+
92+
def test_wait_success(self):
93+
waitable_mock = self._make_mock(spec=Something)
94+
95+
with patch(f"{__name__}.Something", waitable_mock):
96+
something = Something()
97+
self.run_async(something.method_1, delay=0.01)
98+
something.method_1.wait_until_called()
99+
something.method_1.wait_until_any_call()
100+
something.method_1.assert_called()
101+
102+
def test_wait_success_with_instance_timeout(self):
103+
waitable_mock = self._make_mock(timeout=1)
104+
105+
with patch(f"{__name__}.Something", waitable_mock):
106+
something = Something()
107+
self.run_async(something.method_1, delay=0.01)
108+
something.method_1.wait_until_called()
109+
something.method_1.wait_until_any_call()
110+
something.method_1.assert_called()
111+
112+
def test_wait_failed_with_instance_timeout(self):
113+
waitable_mock = self._make_mock(timeout=0.01)
114+
115+
with patch(f"{__name__}.Something", waitable_mock):
116+
something = Something()
117+
self.run_async(something.method_1, delay=0.5)
118+
self.assertRaises(AssertionError, waitable_mock.method_1.wait_until_called)
119+
self.assertRaises(
120+
AssertionError, waitable_mock.method_1.wait_until_any_call
121+
)
122+
123+
def test_wait_success_with_timeout_override(self):
124+
waitable_mock = self._make_mock(timeout=0.01)
125+
126+
with patch(f"{__name__}.Something", waitable_mock):
127+
something = Something()
128+
self.run_async(something.method_1, delay=0.05)
129+
something.method_1.wait_until_called(timeout=1)
130+
131+
def test_wait_failed_with_timeout_override(self):
132+
waitable_mock = self._make_mock(timeout=1)
133+
134+
with patch(f"{__name__}.Something", waitable_mock):
135+
something = Something()
136+
self.run_async(something.method_1, delay=0.1)
137+
with self.assertRaises(AssertionError):
138+
something.method_1.wait_until_called(timeout=0.05)
139+
with self.assertRaises(AssertionError):
140+
something.method_1.wait_until_any_call(timeout=0.05)
141+
142+
def test_wait_success_called_before(self):
143+
waitable_mock = self._make_mock()
144+
145+
with patch(f"{__name__}.Something", waitable_mock):
146+
something = Something()
147+
something.method_1()
148+
something.method_1.wait_until_called()
149+
something.method_1.wait_until_any_call()
150+
something.method_1.assert_called()
151+
152+
def test_wait_magic_method(self):
153+
waitable_mock = self._make_mock()
154+
155+
with patch(f"{__name__}.Something", waitable_mock):
156+
something = Something()
157+
self.run_async(something.method_1.__str__, delay=0.01)
158+
something.method_1.__str__.wait_until_called()
159+
something.method_1.__str__.assert_called()
160+
161+
def test_wait_until_any_call_positional(self):
162+
waitable_mock = self._make_mock(spec=Something)
163+
164+
with patch(f"{__name__}.Something", waitable_mock):
165+
something = Something()
166+
self.run_async(something.method_1, 1, delay=0.1)
167+
self.run_async(something.method_1, 2, delay=0.2)
168+
self.run_async(something.method_1, 3, delay=0.3)
169+
self.assertNotIn(call(1), something.method_1.mock_calls)
170+
171+
something.method_1.wait_until_any_call(1)
172+
something.method_1.assert_called_with(1)
173+
self.assertNotIn(call(2), something.method_1.mock_calls)
174+
self.assertNotIn(call(3), something.method_1.mock_calls)
175+
176+
something.method_1.wait_until_any_call(3)
177+
self.assertIn(call(2), something.method_1.mock_calls)
178+
something.method_1.wait_until_any_call(2)
179+
180+
def test_wait_until_any_call_keywords(self):
181+
waitable_mock = self._make_mock(spec=Something)
182+
183+
with patch(f"{__name__}.Something", waitable_mock):
184+
something = Something()
185+
self.run_async(something.method_1, a=1, delay=0.1)
186+
self.run_async(something.method_1, b=2, delay=0.2)
187+
self.run_async(something.method_1, c=3, delay=0.3)
188+
self.assertNotIn(call(a=1), something.method_1.mock_calls)
189+
190+
something.method_1.wait_until_any_call(a=1)
191+
something.method_1.assert_called_with(a=1)
192+
self.assertNotIn(call(b=2), something.method_1.mock_calls)
193+
self.assertNotIn(call(c=3), something.method_1.mock_calls)
194+
195+
something.method_1.wait_until_any_call(c=3)
196+
self.assertIn(call(b=2), something.method_1.mock_calls)
197+
something.method_1.wait_until_any_call(b=2)
198+
199+
def test_wait_until_any_call_no_argument_fails_when_called_with_arg(self):
200+
waitable_mock = self._make_mock(timeout=0.01)
201+
202+
with patch(f"{__name__}.Something", waitable_mock):
203+
something = Something()
204+
something.method_1(1)
205+
206+
something.method_1.assert_called_with(1)
207+
with self.assertRaises(AssertionError):
208+
something.method_1.wait_until_any_call()
209+
210+
something.method_1()
211+
something.method_1.wait_until_any_call()
212+
213+
def test_wait_until_any_call_global_default(self):
214+
with patch.object(ThreadingMock, "DEFAULT_TIMEOUT"):
215+
ThreadingMock.DEFAULT_TIMEOUT = 0.01
216+
m = self._make_mock()
217+
with self.assertRaises(AssertionError):
218+
m.wait_until_any_call()
219+
with self.assertRaises(AssertionError):
220+
m.wait_until_called()
221+
222+
m()
223+
m.wait_until_any_call()
224+
assert ThreadingMock.DEFAULT_TIMEOUT != 0.01
225+
226+
def test_wait_until_any_call_change_global_and_override(self):
227+
with patch.object(ThreadingMock, "DEFAULT_TIMEOUT"):
228+
ThreadingMock.DEFAULT_TIMEOUT = 0.01
229+
230+
m1 = self._make_mock()
231+
self.run_async(m1, delay=0.1)
232+
with self.assertRaises(AssertionError):
233+
m1.wait_until_called()
234+
235+
m2 = self._make_mock(timeout=1)
236+
self.run_async(m2, delay=0.1)
237+
m2.wait_until_called()
238+
239+
m3 = self._make_mock()
240+
self.run_async(m3, delay=0.1)
241+
m3.wait_until_called(timeout=1)
242+
243+
m4 = self._make_mock()
244+
self.run_async(m4, delay=0.1)
245+
m4.wait_until_called(timeout=None)
246+
247+
m5 = self._make_mock(timeout=None)
248+
self.run_async(m5, delay=0.1)
249+
m5.wait_until_called()
250+
251+
assert ThreadingMock.DEFAULT_TIMEOUT != 0.01
252+
253+
def test_reset_mock_resets_wait(self):
254+
m = self._make_mock(timeout=0.01)
255+
256+
with self.assertRaises(AssertionError):
257+
m.wait_until_called()
258+
with self.assertRaises(AssertionError):
259+
m.wait_until_any_call()
260+
m()
261+
m.wait_until_called()
262+
m.wait_until_any_call()
263+
m.assert_called_once()
264+
265+
m.reset_mock()
266+
267+
with self.assertRaises(AssertionError):
268+
m.wait_until_called()
269+
with self.assertRaises(AssertionError):
270+
m.wait_until_any_call()
271+
m()
272+
m.wait_until_called()
273+
m.wait_until_any_call()
274+
m.assert_called_once()
275+
276+
277+
if __name__ == "__main__":
278+
unittest.main()

0 commit comments

Comments
 (0)