Debian Codegraph @

Lib/test/test_unittest/testmock/testasync.py

raw
1 import asyncio
2 import gc
3 import inspect
4 import re
5 import unittest
6 from contextlib import contextmanager
7 from test import support
8
9 support.requires_working_socket(module=True)
10
11 from asyncio import run, iscoroutinefunction
12 from unittest import IsolatedAsyncioTestCase
13 from unittest.mock import (ANY, call, AsyncMock, patch, MagicMock, Mock,
14 create_autospec, sentinel, _CallList, seal)
15
16
17 def tearDownModule():
18 asyncio.set_event_loop_policy(None)
19
20
21 class AsyncClass:
22 def __init__(self): pass
23 async def async_method(self): pass
24 def normal_method(self): pass
25
26 @classmethod
27 async def async_class_method(cls): pass
28
29 @staticmethod
30 async def async_static_method(): pass
31
32
33 class AwaitableClass:
34 def __await__(self): yield
35
36 async def async_func(): pass
37
38 async def async_func_args(a, b, *, c): pass
39
40 def normal_func(): pass
41
42 class NormalClass(object):
43 def a(self): pass
44
45
46 async_foo_name = f'{__name__}.AsyncClass'
47 normal_foo_name = f'{__name__}.NormalClass'
48
49
50 @contextmanager
51 def assertNeverAwaited(test):
52 with test.assertWarnsRegex(RuntimeWarning, "was never awaited$"):
53 yield
54 # In non-CPython implementations of Python, this is needed because timely
55 # deallocation is not guaranteed by the garbage collector.
56 gc.collect()
57
58
59 class AsyncPatchDecoratorTest(unittest.TestCase):
60 def test_is_coroutine_function_patch(self):
61 @patch.object(AsyncClass, 'async_method')
62 def test_async(mock_method):
63 self.assertTrue(iscoroutinefunction(mock_method))
64 test_async()
65
66 def test_is_async_patch(self):
67 @patch.object(AsyncClass, 'async_method')
68 def test_async(mock_method):
69 m = mock_method()
70 self.assertTrue(inspect.isawaitable(m))
71 run(m)
72
73 @patch(f'{async_foo_name}.async_method')
74 def test_no_parent_attribute(mock_method):
75 m = mock_method()
76 self.assertTrue(inspect.isawaitable(m))
77 run(m)
78
79 test_async()
80 test_no_parent_attribute()
81
82 def test_is_AsyncMock_patch(self):
83 @patch.object(AsyncClass, 'async_method')
84 def test_async(mock_method):
85 self.assertIsInstance(mock_method, AsyncMock)
86
87 test_async()
88
89 def test_is_AsyncMock_patch_staticmethod(self):
90 @patch.object(AsyncClass, 'async_static_method')
91 def test_async(mock_method):
92 self.assertIsInstance(mock_method, AsyncMock)
93
94 test_async()
95
96 def test_is_AsyncMock_patch_classmethod(self):
97 @patch.object(AsyncClass, 'async_class_method')
98 def test_async(mock_method):
99 self.assertIsInstance(mock_method, AsyncMock)
100
101 test_async()
102
103 def test_async_def_patch(self):
104 @patch(f"{__name__}.async_func", return_value=1)
105 @patch(f"{__name__}.async_func_args", return_value=2)
106 async def test_async(func_args_mock, func_mock):
107 self.assertEqual(func_args_mock._mock_name, "async_func_args")
108 self.assertEqual(func_mock._mock_name, "async_func")
109
110 self.assertIsInstance(async_func, AsyncMock)
111 self.assertIsInstance(async_func_args, AsyncMock)
112
113 self.assertEqual(await async_func(), 1)
114 self.assertEqual(await async_func_args(1, 2, c=3), 2)
115
116 run(test_async())
117 self.assertTrue(inspect.iscoroutinefunction(async_func))
118
119
120 class AsyncPatchCMTest(unittest.TestCase):
121 def test_is_async_function_cm(self):
122 def test_async():
123 with patch.object(AsyncClass, 'async_method') as mock_method:
124 self.assertTrue(iscoroutinefunction(mock_method))
125
126 test_async()
127
128 def test_is_async_cm(self):
129 def test_async():
130 with patch.object(AsyncClass, 'async_method') as mock_method:
131 m = mock_method()
132 self.assertTrue(inspect.isawaitable(m))
133 run(m)
134
135 test_async()
136
137 def test_is_AsyncMock_cm(self):
138 def test_async():
139 with patch.object(AsyncClass, 'async_method') as mock_method:
140 self.assertIsInstance(mock_method, AsyncMock)
141
142 test_async()
143
144 def test_async_def_cm(self):
145 async def test_async():
146 with patch(f"{__name__}.async_func", AsyncMock()):
147 self.assertIsInstance(async_func, AsyncMock)
148 self.assertTrue(inspect.iscoroutinefunction(async_func))
149
150 run(test_async())
151
152 def test_patch_dict_async_def(self):
153 foo = {'a': 'a'}
154 @patch.dict(foo, {'a': 'b'})
155 async def test_async():
156 self.assertEqual(foo['a'], 'b')
157
158 self.assertTrue(iscoroutinefunction(test_async))
159 run(test_async())
160
161 def test_patch_dict_async_def_context(self):
162 foo = {'a': 'a'}
163 async def test_async():
164 with patch.dict(foo, {'a': 'b'}):
165 self.assertEqual(foo['a'], 'b')
166
167 run(test_async())
168
169
170 class AsyncMockTest(unittest.TestCase):
171 def test_iscoroutinefunction_default(self):
172 mock = AsyncMock()
173 self.assertTrue(iscoroutinefunction(mock))
174
175 def test_iscoroutinefunction_function(self):
176 async def foo(): pass
177 mock = AsyncMock(foo)
178 self.assertTrue(iscoroutinefunction(mock))
179 self.assertTrue(inspect.iscoroutinefunction(mock))
180
181 def test_isawaitable(self):
182 mock = AsyncMock()
183 m = mock()
184 self.assertTrue(inspect.isawaitable(m))
185 run(m)
186 self.assertIn('assert_awaited', dir(mock))
187
188 def test_iscoroutinefunction_normal_function(self):
189 def foo(): pass
190 mock = AsyncMock(foo)
191 self.assertTrue(iscoroutinefunction(mock))
192 self.assertTrue(inspect.iscoroutinefunction(mock))
193
194 def test_future_isfuture(self):
195 loop = asyncio.new_event_loop()
196 fut = loop.create_future()
197 loop.stop()
198 loop.close()
199 mock = AsyncMock(fut)
200 self.assertIsInstance(mock, asyncio.Future)
201
202
203 class AsyncAutospecTest(unittest.TestCase):
204 def test_is_AsyncMock_patch(self):
205 @patch(async_foo_name, autospec=True)
206 def test_async(mock_method):
207 self.assertIsInstance(mock_method.async_method, AsyncMock)
208 self.assertIsInstance(mock_method, MagicMock)
209
210 @patch(async_foo_name, autospec=True)
211 def test_normal_method(mock_method):
212 self.assertIsInstance(mock_method.normal_method, MagicMock)
213
214 test_async()
215 test_normal_method()
216
217 def test_create_autospec_instance(self):
218 with self.assertRaises(RuntimeError):
219 create_autospec(async_func, instance=True)
220
221 def test_create_autospec(self):
222 spec = create_autospec(async_func_args)
223 awaitable = spec(1, 2, c=3)
224 async def main():
225 await awaitable
226
227 self.assertEqual(spec.await_count, 0)
228 self.assertIsNone(spec.await_args)
229 self.assertEqual(spec.await_args_list, [])
230 spec.assert_not_awaited()
231
232 run(main())
233
234 self.assertTrue(iscoroutinefunction(spec))
235 self.assertTrue(inspect.iscoroutinefunction(spec))
236 self.assertTrue(asyncio.iscoroutine(awaitable))
237 self.assertTrue(inspect.iscoroutine(awaitable))
238 self.assertEqual(spec.await_count, 1)
239 self.assertEqual(spec.await_args, call(1, 2, c=3))
240 self.assertEqual(spec.await_args_list, [call(1, 2, c=3)])
241 spec.assert_awaited_once()
242 spec.assert_awaited_once_with(1, 2, c=3)
243 spec.assert_awaited_with(1, 2, c=3)
244 spec.assert_awaited()
245
246 with self.assertRaises(AssertionError):
247 spec.assert_any_await(e=1)
248
249 def test_autospec_checks_signature(self):
250 spec = create_autospec(async_func_args)
251 # signature is not checked when called
252 awaitable = spec()
253 self.assertListEqual(spec.mock_calls, [])
254
255 async def main():
256 await awaitable
257
258 # but it is checked when awaited
259 with self.assertRaises(TypeError):
260 run(main())
261
262 # _checksig_ raises before running or awaiting the mock
263 self.assertListEqual(spec.mock_calls, [])
264 self.assertEqual(spec.await_count, 0)
265 self.assertIsNone(spec.await_args)
266 self.assertEqual(spec.await_args_list, [])
267 spec.assert_not_awaited()
268
269 def test_patch_with_autospec(self):
270
271 async def test_async():
272 with patch(f"{__name__}.async_func_args", autospec=True) as mock_method:
273 awaitable = mock_method(1, 2, c=3)
274 self.assertIsInstance(mock_method.mock, AsyncMock)
275
276 self.assertTrue(iscoroutinefunction(mock_method))
277 self.assertTrue(inspect.iscoroutinefunction(mock_method))
278 self.assertTrue(asyncio.iscoroutine(awaitable))
279 self.assertTrue(inspect.iscoroutine(awaitable))
280 self.assertTrue(inspect.isawaitable(awaitable))
281
282 # Verify the default values during mock setup
283 self.assertEqual(mock_method.await_count, 0)
284 self.assertEqual(mock_method.await_args_list, [])
285 self.assertIsNone(mock_method.await_args)
286 mock_method.assert_not_awaited()
287
288 await awaitable
289
290 self.assertEqual(mock_method.await_count, 1)
291 self.assertEqual(mock_method.await_args, call(1, 2, c=3))
292 self.assertEqual(mock_method.await_args_list, [call(1, 2, c=3)])
293 mock_method.assert_awaited_once()
294 mock_method.assert_awaited_once_with(1, 2, c=3)
295 mock_method.assert_awaited_with(1, 2, c=3)
296 mock_method.assert_awaited()
297
298 mock_method.reset_mock()
299 self.assertEqual(mock_method.await_count, 0)
300 self.assertIsNone(mock_method.await_args)
301 self.assertEqual(mock_method.await_args_list, [])
302
303 run(test_async())
304
305
306 class AsyncSpecTest(unittest.TestCase):
307 def test_spec_normal_methods_on_class(self):
308 def inner_test(mock_type):
309 mock = mock_type(AsyncClass)
310 self.assertIsInstance(mock.async_method, AsyncMock)
311 self.assertIsInstance(mock.normal_method, MagicMock)
312
313 for mock_type in [AsyncMock, MagicMock]:
314 with self.subTest(f"test method types with {mock_type}"):
315 inner_test(mock_type)
316
317 def test_spec_normal_methods_on_class_with_mock(self):
318 mock = Mock(AsyncClass)
319 self.assertIsInstance(mock.async_method, AsyncMock)
320 self.assertIsInstance(mock.normal_method, Mock)
321
322 def test_spec_normal_methods_on_class_with_mock_seal(self):
323 mock = Mock(AsyncClass)
324 seal(mock)
325 with self.assertRaises(AttributeError):
326 mock.normal_method
327 with self.assertRaises(AttributeError):
328 mock.async_method
329
330 def test_spec_async_attributes_instance(self):
331 async_instance = AsyncClass()
332 async_instance.async_func_attr = async_func
333 async_instance.later_async_func_attr = normal_func
334
335 mock_async_instance = Mock(spec_set=async_instance)
336
337 async_instance.later_async_func_attr = async_func
338
339 self.assertIsInstance(mock_async_instance.async_func_attr, AsyncMock)
340 # only the shape of the spec at the time of mock construction matters
341 self.assertNotIsInstance(mock_async_instance.later_async_func_attr, AsyncMock)
342
343 def test_spec_mock_type_kw(self):
344 def inner_test(mock_type):
345 async_mock = mock_type(spec=async_func)
346 self.assertIsInstance(async_mock, mock_type)
347 with assertNeverAwaited(self):
348 self.assertTrue(inspect.isawaitable(async_mock()))
349
350 sync_mock = mock_type(spec=normal_func)
351 self.assertIsInstance(sync_mock, mock_type)
352
353 for mock_type in [AsyncMock, MagicMock, Mock]:
354 with self.subTest(f"test spec kwarg with {mock_type}"):
355 inner_test(mock_type)
356
357 def test_spec_mock_type_positional(self):
358 def inner_test(mock_type):
359 async_mock = mock_type(async_func)
360 self.assertIsInstance(async_mock, mock_type)
361 with assertNeverAwaited(self):
362 self.assertTrue(inspect.isawaitable(async_mock()))
363
364 sync_mock = mock_type(normal_func)
365 self.assertIsInstance(sync_mock, mock_type)
366
367 for mock_type in [AsyncMock, MagicMock, Mock]:
368 with self.subTest(f"test spec positional with {mock_type}"):
369 inner_test(mock_type)
370
371 def test_spec_as_normal_kw_AsyncMock(self):
372 mock = AsyncMock(spec=normal_func)
373 self.assertIsInstance(mock, AsyncMock)
374 m = mock()
375 self.assertTrue(inspect.isawaitable(m))
376 run(m)
377
378 def test_spec_as_normal_positional_AsyncMock(self):
379 mock = AsyncMock(normal_func)
380 self.assertIsInstance(mock, AsyncMock)
381 m = mock()
382 self.assertTrue(inspect.isawaitable(m))
383 run(m)
384
385 def test_spec_async_mock(self):
386 @patch.object(AsyncClass, 'async_method', spec=True)
387 def test_async(mock_method):
388 self.assertIsInstance(mock_method, AsyncMock)
389
390 test_async()
391
392 def test_spec_parent_not_async_attribute_is(self):
393 @patch(async_foo_name, spec=True)
394 def test_async(mock_method):
395 self.assertIsInstance(mock_method, MagicMock)
396 self.assertIsInstance(mock_method.async_method, AsyncMock)
397
398 test_async()
399
400 def test_target_async_spec_not(self):
401 @patch.object(AsyncClass, 'async_method', spec=NormalClass.a)
402 def test_async_attribute(mock_method):
403 self.assertIsInstance(mock_method, MagicMock)
404 self.assertFalse(inspect.iscoroutine(mock_method))
405 self.assertFalse(inspect.isawaitable(mock_method))
406
407 test_async_attribute()
408
409 def test_target_not_async_spec_is(self):
410 @patch.object(NormalClass, 'a', spec=async_func)
411 def test_attribute_not_async_spec_is(mock_async_func):
412 self.assertIsInstance(mock_async_func, AsyncMock)
413 test_attribute_not_async_spec_is()
414
415 def test_spec_async_attributes(self):
416 @patch(normal_foo_name, spec=AsyncClass)
417 def test_async_attributes_coroutines(MockNormalClass):
418 self.assertIsInstance(MockNormalClass.async_method, AsyncMock)
419 self.assertIsInstance(MockNormalClass, MagicMock)
420
421 test_async_attributes_coroutines()
422
423
424 class AsyncSpecSetTest(unittest.TestCase):
425 def test_is_AsyncMock_patch(self):
426 @patch.object(AsyncClass, 'async_method', spec_set=True)
427 def test_async(async_method):
428 self.assertIsInstance(async_method, AsyncMock)
429 test_async()
430
431 def test_is_async_AsyncMock(self):
432 mock = AsyncMock(spec_set=AsyncClass.async_method)
433 self.assertTrue(iscoroutinefunction(mock))
434 self.assertIsInstance(mock, AsyncMock)
435
436 def test_is_child_AsyncMock(self):
437 mock = MagicMock(spec_set=AsyncClass)
438 self.assertTrue(iscoroutinefunction(mock.async_method))
439 self.assertFalse(iscoroutinefunction(mock.normal_method))
440 self.assertIsInstance(mock.async_method, AsyncMock)
441 self.assertIsInstance(mock.normal_method, MagicMock)
442 self.assertIsInstance(mock, MagicMock)
443
444 def test_magicmock_lambda_spec(self):
445 mock_obj = MagicMock()
446 mock_obj.mock_func = MagicMock(spec=lambda x: x)
447
448 with patch.object(mock_obj, "mock_func") as cm:
449 self.assertIsInstance(cm, MagicMock)
450
451
452 class AsyncArguments(IsolatedAsyncioTestCase):
453 async def test_add_return_value(self):
454 async def addition(self, var): pass
455
456 mock = AsyncMock(addition, return_value=10)
457 output = await mock(5)
458
459 self.assertEqual(output, 10)
460
461 async def test_add_side_effect_exception(self):
462 class CustomError(Exception): pass
463 async def addition(var): pass
464 mock = AsyncMock(addition, side_effect=CustomError('side-effect'))
465 with self.assertRaisesRegex(CustomError, 'side-effect'):
466 await mock(5)
467
468 async def test_add_side_effect_coroutine(self):
469 async def addition(var):
470 return var + 1
471 mock = AsyncMock(side_effect=addition)
472 result = await mock(5)
473 self.assertEqual(result, 6)
474
475 async def test_add_side_effect_normal_function(self):
476 def addition(var):
477 return var + 1
478 mock = AsyncMock(side_effect=addition)
479 result = await mock(5)
480 self.assertEqual(result, 6)
481
482 async def test_add_side_effect_iterable(self):
483 vals = [1, 2, 3]
484 mock = AsyncMock(side_effect=vals)
485 for item in vals:
486 self.assertEqual(await mock(), item)
487
488 with self.assertRaises(StopAsyncIteration) as e:
489 await mock()
490
491 async def test_add_side_effect_exception_iterable(self):
492 class SampleException(Exception):
493 pass
494
495 vals = [1, SampleException("foo")]
496 mock = AsyncMock(side_effect=vals)
497 self.assertEqual(await mock(), 1)
498
499 with self.assertRaises(SampleException) as e:
500 await mock()
501
502 async def test_return_value_AsyncMock(self):
503 value = AsyncMock(return_value=10)
504 mock = AsyncMock(return_value=value)
505 result = await mock()
506 self.assertIs(result, value)
507
508 async def test_return_value_awaitable(self):
509 fut = asyncio.Future()
510 fut.set_result(None)
511 mock = AsyncMock(return_value=fut)
512 result = await mock()
513 self.assertIsInstance(result, asyncio.Future)
514
515 async def test_side_effect_awaitable_values(self):
516 fut = asyncio.Future()
517 fut.set_result(None)
518
519 mock = AsyncMock(side_effect=[fut])
520 result = await mock()
521 self.assertIsInstance(result, asyncio.Future)
522
523 with self.assertRaises(StopAsyncIteration):
524 await mock()
525
526 async def test_side_effect_is_AsyncMock(self):
527 effect = AsyncMock(return_value=10)
528 mock = AsyncMock(side_effect=effect)
529
530 result = await mock()
531 self.assertEqual(result, 10)
532
533 async def test_wraps_coroutine(self):
534 value = asyncio.Future()
535
536 ran = False
537 async def inner():
538 nonlocal ran
539 ran = True
540 return value
541
542 mock = AsyncMock(wraps=inner)
543 result = await mock()
544 self.assertEqual(result, value)
545 mock.assert_awaited()
546 self.assertTrue(ran)
547
548 async def test_wraps_normal_function(self):
549 value = 1
550
551 ran = False
552 def inner():
553 nonlocal ran
554 ran = True
555 return value
556
557 mock = AsyncMock(wraps=inner)
558 result = await mock()
559 self.assertEqual(result, value)
560 mock.assert_awaited()
561 self.assertTrue(ran)
562
563 async def test_await_args_list_order(self):
564 async_mock = AsyncMock()
565 mock2 = async_mock(2)
566 mock1 = async_mock(1)
567 await mock1
568 await mock2
569 async_mock.assert_has_awaits([call(1), call(2)])
570 self.assertEqual(async_mock.await_args_list, [call(1), call(2)])
571 self.assertEqual(async_mock.call_args_list, [call(2), call(1)])
572
573
574 class AsyncMagicMethods(unittest.TestCase):
575 def test_async_magic_methods_return_async_mocks(self):
576 m_mock = MagicMock()
577 self.assertIsInstance(m_mock.__aenter__, AsyncMock)
578 self.assertIsInstance(m_mock.__aexit__, AsyncMock)
579 self.assertIsInstance(m_mock.__anext__, AsyncMock)
580 # __aiter__ is actually a synchronous object
581 # so should return a MagicMock
582 self.assertIsInstance(m_mock.__aiter__, MagicMock)
583
584 def test_sync_magic_methods_return_magic_mocks(self):
585 a_mock = AsyncMock()
586 self.assertIsInstance(a_mock.__enter__, MagicMock)
587 self.assertIsInstance(a_mock.__exit__, MagicMock)
588 self.assertIsInstance(a_mock.__next__, MagicMock)
589 self.assertIsInstance(a_mock.__len__, MagicMock)
590
591 def test_magicmock_has_async_magic_methods(self):
592 m_mock = MagicMock()
593 self.assertTrue(hasattr(m_mock, "__aenter__"))
594 self.assertTrue(hasattr(m_mock, "__aexit__"))
595 self.assertTrue(hasattr(m_mock, "__anext__"))
596
597 def test_asyncmock_has_sync_magic_methods(self):
598 a_mock = AsyncMock()
599 self.assertTrue(hasattr(a_mock, "__enter__"))
600 self.assertTrue(hasattr(a_mock, "__exit__"))
601 self.assertTrue(hasattr(a_mock, "__next__"))
602 self.assertTrue(hasattr(a_mock, "__len__"))
603
604 def test_magic_methods_are_async_functions(self):
605 m_mock = MagicMock()
606 self.assertIsInstance(m_mock.__aenter__, AsyncMock)
607 self.assertIsInstance(m_mock.__aexit__, AsyncMock)
608 # AsyncMocks are also coroutine functions
609 self.assertTrue(iscoroutinefunction(m_mock.__aenter__))
610 self.assertTrue(iscoroutinefunction(m_mock.__aexit__))
611
612 class AsyncContextManagerTest(unittest.TestCase):
613
614 class WithAsyncContextManager:
615 async def __aenter__(self, *args, **kwargs): pass
616
617 async def __aexit__(self, *args, **kwargs): pass
618
619 class WithSyncContextManager:
620 def __enter__(self, *args, **kwargs): pass
621
622 def __exit__(self, *args, **kwargs): pass
623
624 class ProductionCode:
625 # Example real-world(ish) code
626 def __init__(self):
627 self.session = None
628
629 async def main(self):
630 async with self.session.post('https://python.org') as response:
631 val = await response.json()
632 return val
633
634 def test_set_return_value_of_aenter(self):
635 def inner_test(mock_type):
636 pc = self.ProductionCode()
637 pc.session = MagicMock(name='sessionmock')
638 cm = mock_type(name='magic_cm')
639 response = AsyncMock(name='response')
640 response.json = AsyncMock(return_value={'json': 123})
641 cm.__aenter__.return_value = response
642 pc.session.post.return_value = cm
643 result = run(pc.main())
644 self.assertEqual(result, {'json': 123})
645
646 for mock_type in [AsyncMock, MagicMock]:
647 with self.subTest(f"test set return value of aenter with {mock_type}"):
648 inner_test(mock_type)
649
650 def test_mock_supports_async_context_manager(self):
651 def inner_test(mock_type):
652 called = False
653 cm = self.WithAsyncContextManager()
654 cm_mock = mock_type(cm)
655
656 async def use_context_manager():
657 nonlocal called
658 async with cm_mock as result:
659 called = True
660 return result
661
662 cm_result = run(use_context_manager())
663 self.assertTrue(called)
664 self.assertTrue(cm_mock.__aenter__.called)
665 self.assertTrue(cm_mock.__aexit__.called)
666 cm_mock.__aenter__.assert_awaited()
667 cm_mock.__aexit__.assert_awaited()
668 # We mock __aenter__ so it does not return self
669 self.assertIsNot(cm_mock, cm_result)
670
671 for mock_type in [AsyncMock, MagicMock]:
672 with self.subTest(f"test context manager magics with {mock_type}"):
673 inner_test(mock_type)
674
675
676 def test_mock_customize_async_context_manager(self):
677 instance = self.WithAsyncContextManager()
678 mock_instance = MagicMock(instance)
679
680 expected_result = object()
681 mock_instance.__aenter__.return_value = expected_result
682
683 async def use_context_manager():
684 async with mock_instance as result:
685 return result
686
687 self.assertIs(run(use_context_manager()), expected_result)
688
689 def test_mock_customize_async_context_manager_with_coroutine(self):
690 enter_called = False
691 exit_called = False
692
693 async def enter_coroutine(*args):
694 nonlocal enter_called
695 enter_called = True
696
697 async def exit_coroutine(*args):
698 nonlocal exit_called
699 exit_called = True
700
701 instance = self.WithAsyncContextManager()
702 mock_instance = MagicMock(instance)
703
704 mock_instance.__aenter__ = enter_coroutine
705 mock_instance.__aexit__ = exit_coroutine
706
707 async def use_context_manager():
708 async with mock_instance:
709 pass
710
711 run(use_context_manager())
712 self.assertTrue(enter_called)
713 self.assertTrue(exit_called)
714
715 def test_context_manager_raise_exception_by_default(self):
716 async def raise_in(context_manager):
717 async with context_manager:
718 raise TypeError()
719
720 instance = self.WithAsyncContextManager()
721 mock_instance = MagicMock(instance)
722 with self.assertRaises(TypeError):
723 run(raise_in(mock_instance))
724
725
726 class AsyncIteratorTest(unittest.TestCase):
727 class WithAsyncIterator(object):
728 def __init__(self):
729 self.items = ["foo", "NormalFoo", "baz"]
730
731 def __aiter__(self): pass
732
733 async def __anext__(self): pass
734
735 def test_aiter_set_return_value(self):
736 mock_iter = AsyncMock(name="tester")
737 mock_iter.__aiter__.return_value = [1, 2, 3]
738 async def main():
739 return [i async for i in mock_iter]
740 result = run(main())
741 self.assertEqual(result, [1, 2, 3])
742
743 def test_mock_aiter_and_anext_asyncmock(self):
744 def inner_test(mock_type):
745 instance = self.WithAsyncIterator()
746 mock_instance = mock_type(instance)
747 # Check that the mock and the real thing bahave the same
748 # __aiter__ is not actually async, so not a coroutinefunction
749 self.assertFalse(iscoroutinefunction(instance.__aiter__))
750 self.assertFalse(iscoroutinefunction(mock_instance.__aiter__))
751 # __anext__ is async
752 self.assertTrue(iscoroutinefunction(instance.__anext__))
753 self.assertTrue(iscoroutinefunction(mock_instance.__anext__))
754
755 for mock_type in [AsyncMock, MagicMock]:
756 with self.subTest(f"test aiter and anext corourtine with {mock_type}"):
757 inner_test(mock_type)
758
759
760 def test_mock_async_for(self):
761 async def iterate(iterator):
762 accumulator = []
763 async for item in iterator:
764 accumulator.append(item)
765
766 return accumulator
767
768 expected = ["FOO", "BAR", "BAZ"]
769 def test_default(mock_type):
770 mock_instance = mock_type(self.WithAsyncIterator())
771 self.assertEqual(run(iterate(mock_instance)), [])
772
773
774 def test_set_return_value(mock_type):
775 mock_instance = mock_type(self.WithAsyncIterator())
776 mock_instance.__aiter__.return_value = expected[:]
777 self.assertEqual(run(iterate(mock_instance)), expected)
778
779 def test_set_return_value_iter(mock_type):
780 mock_instance = mock_type(self.WithAsyncIterator())
781 mock_instance.__aiter__.return_value = iter(expected[:])
782 self.assertEqual(run(iterate(mock_instance)), expected)
783
784 for mock_type in [AsyncMock, MagicMock]:
785 with self.subTest(f"default value with {mock_type}"):
786 test_default(mock_type)
787
788 with self.subTest(f"set return_value with {mock_type}"):
789 test_set_return_value(mock_type)
790
791 with self.subTest(f"set return_value iterator with {mock_type}"):
792 test_set_return_value_iter(mock_type)
793
794
795 class AsyncMockAssert(unittest.TestCase):
796 def setUp(self):
797 self.mock = AsyncMock()
798
799 async def _runnable_test(self, *args, **kwargs):
800 await self.mock(*args, **kwargs)
801
802 async def _await_coroutine(self, coroutine):
803 return await coroutine
804
805 def test_assert_called_but_not_awaited(self):
806 mock = AsyncMock(AsyncClass)
807 with assertNeverAwaited(self):
808 mock.async_method()
809 self.assertTrue(iscoroutinefunction(mock.async_method))
810 mock.async_method.assert_called()
811 mock.async_method.assert_called_once()
812 mock.async_method.assert_called_once_with()
813 with self.assertRaises(AssertionError):
814 mock.assert_awaited()
815 with self.assertRaises(AssertionError):
816 mock.async_method.assert_awaited()
817
818 def test_assert_called_then_awaited(self):
819 mock = AsyncMock(AsyncClass)
820 mock_coroutine = mock.async_method()
821 mock.async_method.assert_called()
822 mock.async_method.assert_called_once()
823 mock.async_method.assert_called_once_with()
824 with self.assertRaises(AssertionError):
825 mock.async_method.assert_awaited()
826
827 run(self._await_coroutine(mock_coroutine))
828 # Assert we haven't re-called the function
829 mock.async_method.assert_called_once()
830 mock.async_method.assert_awaited()
831 mock.async_method.assert_awaited_once()
832 mock.async_method.assert_awaited_once_with()
833
834 def test_assert_called_and_awaited_at_same_time(self):
835 with self.assertRaises(AssertionError):
836 self.mock.assert_awaited()
837
838 with self.assertRaises(AssertionError):
839 self.mock.assert_called()
840
841 run(self._runnable_test())
842 self.mock.assert_called_once()
843 self.mock.assert_awaited_once()
844
845 def test_assert_called_twice_and_awaited_once(self):
846 mock = AsyncMock(AsyncClass)
847 coroutine = mock.async_method()
848 # The first call will be awaited so no warning there
849 # But this call will never get awaited, so it will warn here
850 with assertNeverAwaited(self):
851 mock.async_method()
852 with self.assertRaises(AssertionError):
853 mock.async_method.assert_awaited()
854 mock.async_method.assert_called()
855 run(self._await_coroutine(coroutine))
856 mock.async_method.assert_awaited()
857 mock.async_method.assert_awaited_once()
858
859 def test_assert_called_once_and_awaited_twice(self):
860 mock = AsyncMock(AsyncClass)
861 coroutine = mock.async_method()
862 mock.async_method.assert_called_once()
863 run(self._await_coroutine(coroutine))
864 with self.assertRaises(RuntimeError):
865 # Cannot reuse already awaited coroutine
866 run(self._await_coroutine(coroutine))
867 mock.async_method.assert_awaited()
868
869 def test_assert_awaited_but_not_called(self):
870 with self.assertRaises(AssertionError):
871 self.mock.assert_awaited()
872 with self.assertRaises(AssertionError):
873 self.mock.assert_called()
874 with self.assertRaises(TypeError):
875 # You cannot await an AsyncMock, it must be a coroutine
876 run(self._await_coroutine(self.mock))
877
878 with self.assertRaises(AssertionError):
879 self.mock.assert_awaited()
880 with self.assertRaises(AssertionError):
881 self.mock.assert_called()
882
883 def test_assert_has_calls_not_awaits(self):
884 kalls = [call('foo')]
885 with assertNeverAwaited(self):
886 self.mock('foo')
887 self.mock.assert_has_calls(kalls)
888 with self.assertRaises(AssertionError):
889 self.mock.assert_has_awaits(kalls)
890
891 def test_assert_has_mock_calls_on_async_mock_no_spec(self):
892 with assertNeverAwaited(self):
893 self.mock()
894 kalls_empty = [('', (), {})]
895 self.assertEqual(self.mock.mock_calls, kalls_empty)
896
897 with assertNeverAwaited(self):
898 self.mock('foo')
899 with assertNeverAwaited(self):
900 self.mock('baz')
901 mock_kalls = ([call(), call('foo'), call('baz')])
902 self.assertEqual(self.mock.mock_calls, mock_kalls)
903
904 def test_assert_has_mock_calls_on_async_mock_with_spec(self):
905 a_class_mock = AsyncMock(AsyncClass)
906 with assertNeverAwaited(self):
907 a_class_mock.async_method()
908 kalls_empty = [('', (), {})]
909 self.assertEqual(a_class_mock.async_method.mock_calls, kalls_empty)
910 self.assertEqual(a_class_mock.mock_calls, [call.async_method()])
911
912 with assertNeverAwaited(self):
913 a_class_mock.async_method(1, 2, 3, a=4, b=5)
914 method_kalls = [call(), call(1, 2, 3, a=4, b=5)]
915 mock_kalls = [call.async_method(), call.async_method(1, 2, 3, a=4, b=5)]
916 self.assertEqual(a_class_mock.async_method.mock_calls, method_kalls)
917 self.assertEqual(a_class_mock.mock_calls, mock_kalls)
918
919 def test_async_method_calls_recorded(self):
920 with assertNeverAwaited(self):
921 self.mock.something(3, fish=None)
922 with assertNeverAwaited(self):
923 self.mock.something_else.something(6, cake=sentinel.Cake)
924
925 self.assertEqual(self.mock.method_calls, [
926 ("something", (3,), {'fish': None}),
927 ("something_else.something", (6,), {'cake': sentinel.Cake})
928 ],
929 "method calls not recorded correctly")
930 self.assertEqual(self.mock.something_else.method_calls,
931 [("something", (6,), {'cake': sentinel.Cake})],
932 "method calls not recorded correctly")
933
934 def test_async_arg_lists(self):
935 def assert_attrs(mock):
936 names = ('call_args_list', 'method_calls', 'mock_calls')
937 for name in names:
938 attr = getattr(mock, name)
939 self.assertIsInstance(attr, _CallList)
940 self.assertIsInstance(attr, list)
941 self.assertEqual(attr, [])
942
943 assert_attrs(self.mock)
944 with assertNeverAwaited(self):
945 self.mock()
946 with assertNeverAwaited(self):
947 self.mock(1, 2)
948 with assertNeverAwaited(self):
949 self.mock(a=3)
950
951 self.mock.reset_mock()
952 assert_attrs(self.mock)
953
954 a_mock = AsyncMock(AsyncClass)
955 with assertNeverAwaited(self):
956 a_mock.async_method()
957 with assertNeverAwaited(self):
958 a_mock.async_method(1, a=3)
959
960 a_mock.reset_mock()
961 assert_attrs(a_mock)
962
963 def test_assert_awaited(self):
964 with self.assertRaises(AssertionError):
965 self.mock.assert_awaited()
966
967 run(self._runnable_test())
968 self.mock.assert_awaited()
969
970 def test_assert_awaited_once(self):
971 with self.assertRaises(AssertionError):
972 self.mock.assert_awaited_once()
973
974 run(self._runnable_test())
975 self.mock.assert_awaited_once()
976
977 run(self._runnable_test())
978 with self.assertRaises(AssertionError):
979 self.mock.assert_awaited_once()
980
981 def test_assert_awaited_with(self):
982 msg = 'Not awaited'
983 with self.assertRaisesRegex(AssertionError, msg):
984 self.mock.assert_awaited_with('foo')
985
986 run(self._runnable_test())
987 msg = 'expected await not found'
988 with self.assertRaisesRegex(AssertionError, msg):
989 self.mock.assert_awaited_with('foo')
990
991 run(self._runnable_test('foo'))
992 self.mock.assert_awaited_with('foo')
993
994 run(self._runnable_test('SomethingElse'))
995 with self.assertRaises(AssertionError):
996 self.mock.assert_awaited_with('foo')
997
998 def test_assert_awaited_once_with(self):
999 with self.assertRaises(AssertionError):
1000 self.mock.assert_awaited_once_with('foo')
1001
1002 run(self._runnable_test('foo'))
1003 self.mock.assert_awaited_once_with('foo')
1004
1005 run(self._runnable_test('foo'))
1006 with self.assertRaises(AssertionError):
1007 self.mock.assert_awaited_once_with('foo')
1008
1009 def test_assert_any_wait(self):
1010 with self.assertRaises(AssertionError):
1011 self.mock.assert_any_await('foo')
1012
1013 run(self._runnable_test('baz'))
1014 with self.assertRaises(AssertionError):
1015 self.mock.assert_any_await('foo')
1016
1017 run(self._runnable_test('foo'))
1018 self.mock.assert_any_await('foo')
1019
1020 run(self._runnable_test('SomethingElse'))
1021 self.mock.assert_any_await('foo')
1022
1023 def test_assert_has_awaits_no_order(self):
1024 calls = [call('foo'), call('baz')]
1025
1026 with self.assertRaises(AssertionError) as cm:
1027 self.mock.assert_has_awaits(calls)
1028 self.assertEqual(len(cm.exception.args), 1)
1029
1030 run(self._runnable_test('foo'))
1031 with self.assertRaises(AssertionError):
1032 self.mock.assert_has_awaits(calls)
1033
1034 run(self._runnable_test('foo'))
1035 with self.assertRaises(AssertionError):
1036 self.mock.assert_has_awaits(calls)
1037
1038 run(self._runnable_test('baz'))
1039 self.mock.assert_has_awaits(calls)
1040
1041 run(self._runnable_test('SomethingElse'))
1042 self.mock.assert_has_awaits(calls)
1043
1044 def test_awaits_asserts_with_any(self):
1045 class Foo:
1046 def __eq__(self, other): pass
1047
1048 run(self._runnable_test(Foo(), 1))
1049
1050 self.mock.assert_has_awaits([call(ANY, 1)])
1051 self.mock.assert_awaited_with(ANY, 1)
1052 self.mock.assert_any_await(ANY, 1)
1053
1054 def test_awaits_asserts_with_spec_and_any(self):
1055 class Foo:
1056 def __eq__(self, other): pass
1057
1058 mock_with_spec = AsyncMock(spec=Foo)
1059
1060 async def _custom_mock_runnable_test(*args):
1061 await mock_with_spec(*args)
1062
1063 run(_custom_mock_runnable_test(Foo(), 1))
1064 mock_with_spec.assert_has_awaits([call(ANY, 1)])
1065 mock_with_spec.assert_awaited_with(ANY, 1)
1066 mock_with_spec.assert_any_await(ANY, 1)
1067
1068 def test_assert_has_awaits_ordered(self):
1069 calls = [call('foo'), call('baz')]
1070 with self.assertRaises(AssertionError):
1071 self.mock.assert_has_awaits(calls, any_order=True)
1072
1073 run(self._runnable_test('baz'))
1074 with self.assertRaises(AssertionError):
1075 self.mock.assert_has_awaits(calls, any_order=True)
1076
1077 run(self._runnable_test('bamf'))
1078 with self.assertRaises(AssertionError):
1079 self.mock.assert_has_awaits(calls, any_order=True)
1080
1081 run(self._runnable_test('foo'))
1082 self.mock.assert_has_awaits(calls, any_order=True)
1083
1084 run(self._runnable_test('qux'))
1085 self.mock.assert_has_awaits(calls, any_order=True)
1086
1087 def test_assert_not_awaited(self):
1088 self.mock.assert_not_awaited()
1089
1090 run(self._runnable_test())
1091 with self.assertRaises(AssertionError):
1092 self.mock.assert_not_awaited()
1093
1094 def test_assert_has_awaits_not_matching_spec_error(self):
1095 async def f(x=None): pass
1096
1097 self.mock = AsyncMock(spec=f)
1098 run(self._runnable_test(1))
1099
1100 with self.assertRaisesRegex(
1101 AssertionError,
1102 '^{}$'.format(
1103 re.escape('Awaits not found.\n'
1104 'Expected: [call()]\n'
1105 'Actual: [call(1)]'))) as cm:
1106 self.mock.assert_has_awaits([call()])
1107 self.assertIsNone(cm.exception.__cause__)
1108
1109 with self.assertRaisesRegex(
1110 AssertionError,
1111 '^{}$'.format(
1112 re.escape(
1113 'Error processing expected awaits.\n'
1114 "Errors: [None, TypeError('too many positional "
1115 "arguments')]\n"
1116 'Expected: [call(), call(1, 2)]\n'
1117 'Actual: [call(1)]'))) as cm:
1118 self.mock.assert_has_awaits([call(), call(1, 2)])
1119 self.assertIsInstance(cm.exception.__cause__, TypeError)
1120
1121
1122 if __name__ == '__main__':
1123 unittest.main()