Debian Codegraph @

lib-python/3/unittest/test/testmock/testasync.py

raw symbols SCIP
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 @unittest.skip('Broken test from https://bugs.python.org/issue37251')
222 def test_create_autospec_awaitable_class(self):
223 self.assertIsInstance(create_autospec(AwaitableClass), AsyncMock)
224
225 def test_create_autospec(self):
226 spec = create_autospec(async_func_args)
227 awaitable = spec(1, 2, c=3)
228 async def main():
229 await awaitable
230
231 self.assertEqual(spec.await_count, 0)
232 self.assertIsNone(spec.await_args)
233 self.assertEqual(spec.await_args_list, [])
234 spec.assert_not_awaited()
235
236 run(main())
237
238 self.assertTrue(iscoroutinefunction(spec))
239 self.assertTrue(asyncio.iscoroutine(awaitable))
240 self.assertEqual(spec.await_count, 1)
241 self.assertEqual(spec.await_args, call(1, 2, c=3))
242 self.assertEqual(spec.await_args_list, [call(1, 2, c=3)])
243 spec.assert_awaited_once()
244 spec.assert_awaited_once_with(1, 2, c=3)
245 spec.assert_awaited_with(1, 2, c=3)
246 spec.assert_awaited()
247
248 with self.assertRaises(AssertionError):
249 spec.assert_any_await(e=1)
250
251
252 def test_patch_with_autospec(self):
253
254 async def test_async():
255 with patch(f"{__name__}.async_func_args", autospec=True) as mock_method:
256 awaitable = mock_method(1, 2, c=3)
257 self.assertIsInstance(mock_method.mock, AsyncMock)
258
259 self.assertTrue(iscoroutinefunction(mock_method))
260 self.assertTrue(asyncio.iscoroutine(awaitable))
261 self.assertTrue(inspect.isawaitable(awaitable))
262
263 # Verify the default values during mock setup
264 self.assertEqual(mock_method.await_count, 0)
265 self.assertEqual(mock_method.await_args_list, [])
266 self.assertIsNone(mock_method.await_args)
267 mock_method.assert_not_awaited()
268
269 await awaitable
270
271 self.assertEqual(mock_method.await_count, 1)
272 self.assertEqual(mock_method.await_args, call(1, 2, c=3))
273 self.assertEqual(mock_method.await_args_list, [call(1, 2, c=3)])
274 mock_method.assert_awaited_once()
275 mock_method.assert_awaited_once_with(1, 2, c=3)
276 mock_method.assert_awaited_with(1, 2, c=3)
277 mock_method.assert_awaited()
278
279 mock_method.reset_mock()
280 self.assertEqual(mock_method.await_count, 0)
281 self.assertIsNone(mock_method.await_args)
282 self.assertEqual(mock_method.await_args_list, [])
283
284 run(test_async())
285
286
287 class AsyncSpecTest(unittest.TestCase):
288 def test_spec_normal_methods_on_class(self):
289 def inner_test(mock_type):
290 mock = mock_type(AsyncClass)
291 self.assertIsInstance(mock.async_method, AsyncMock)
292 self.assertIsInstance(mock.normal_method, MagicMock)
293
294 for mock_type in [AsyncMock, MagicMock]:
295 with self.subTest(f"test method types with {mock_type}"):
296 inner_test(mock_type)
297
298 def test_spec_normal_methods_on_class_with_mock(self):
299 mock = Mock(AsyncClass)
300 self.assertIsInstance(mock.async_method, AsyncMock)
301 self.assertIsInstance(mock.normal_method, Mock)
302
303 def test_spec_normal_methods_on_class_with_mock_seal(self):
304 mock = Mock(AsyncClass)
305 seal(mock)
306 with self.assertRaises(AttributeError):
307 mock.normal_method
308 with self.assertRaises(AttributeError):
309 mock.async_method
310
311 def test_spec_mock_type_kw(self):
312 def inner_test(mock_type):
313 async_mock = mock_type(spec=async_func)
314 self.assertIsInstance(async_mock, mock_type)
315 with assertNeverAwaited(self):
316 self.assertTrue(inspect.isawaitable(async_mock()))
317 gc.collect()
318
319 sync_mock = mock_type(spec=normal_func)
320 self.assertIsInstance(sync_mock, mock_type)
321
322 for mock_type in [AsyncMock, MagicMock, Mock]:
323 with self.subTest(f"test spec kwarg with {mock_type}"):
324 inner_test(mock_type)
325
326 def test_spec_mock_type_positional(self):
327 def inner_test(mock_type):
328 async_mock = mock_type(async_func)
329 self.assertIsInstance(async_mock, mock_type)
330 with assertNeverAwaited(self):
331 self.assertTrue(inspect.isawaitable(async_mock()))
332 gc.collect()
333
334 sync_mock = mock_type(normal_func)
335 self.assertIsInstance(sync_mock, mock_type)
336
337 for mock_type in [AsyncMock, MagicMock, Mock]:
338 with self.subTest(f"test spec positional with {mock_type}"):
339 inner_test(mock_type)
340
341 def test_spec_as_normal_kw_AsyncMock(self):
342 mock = AsyncMock(spec=normal_func)
343 self.assertIsInstance(mock, AsyncMock)
344 m = mock()
345 self.assertTrue(inspect.isawaitable(m))
346 run(m)
347
348 def test_spec_as_normal_positional_AsyncMock(self):
349 mock = AsyncMock(normal_func)
350 self.assertIsInstance(mock, AsyncMock)
351 m = mock()
352 self.assertTrue(inspect.isawaitable(m))
353 run(m)
354
355 def test_spec_async_mock(self):
356 @patch.object(AsyncClass, 'async_method', spec=True)
357 def test_async(mock_method):
358 self.assertIsInstance(mock_method, AsyncMock)
359
360 test_async()
361
362 def test_spec_parent_not_async_attribute_is(self):
363 @patch(async_foo_name, spec=True)
364 def test_async(mock_method):
365 self.assertIsInstance(mock_method, MagicMock)
366 self.assertIsInstance(mock_method.async_method, AsyncMock)
367
368 test_async()
369
370 def test_target_async_spec_not(self):
371 @patch.object(AsyncClass, 'async_method', spec=NormalClass.a)
372 def test_async_attribute(mock_method):
373 self.assertIsInstance(mock_method, MagicMock)
374 self.assertFalse(inspect.iscoroutine(mock_method))
375 self.assertFalse(inspect.isawaitable(mock_method))
376
377 test_async_attribute()
378
379 def test_target_not_async_spec_is(self):
380 @patch.object(NormalClass, 'a', spec=async_func)
381 def test_attribute_not_async_spec_is(mock_async_func):
382 self.assertIsInstance(mock_async_func, AsyncMock)
383 test_attribute_not_async_spec_is()
384
385 def test_spec_async_attributes(self):
386 @patch(normal_foo_name, spec=AsyncClass)
387 def test_async_attributes_coroutines(MockNormalClass):
388 self.assertIsInstance(MockNormalClass.async_method, AsyncMock)
389 self.assertIsInstance(MockNormalClass, MagicMock)
390
391 test_async_attributes_coroutines()
392
393
394 class AsyncSpecSetTest(unittest.TestCase):
395 def test_is_AsyncMock_patch(self):
396 @patch.object(AsyncClass, 'async_method', spec_set=True)
397 def test_async(async_method):
398 self.assertIsInstance(async_method, AsyncMock)
399 test_async()
400
401 def test_is_async_AsyncMock(self):
402 mock = AsyncMock(spec_set=AsyncClass.async_method)
403 self.assertTrue(iscoroutinefunction(mock))
404 self.assertIsInstance(mock, AsyncMock)
405
406 def test_is_child_AsyncMock(self):
407 mock = MagicMock(spec_set=AsyncClass)
408 self.assertTrue(iscoroutinefunction(mock.async_method))
409 self.assertFalse(iscoroutinefunction(mock.normal_method))
410 self.assertIsInstance(mock.async_method, AsyncMock)
411 self.assertIsInstance(mock.normal_method, MagicMock)
412 self.assertIsInstance(mock, MagicMock)
413
414 def test_magicmock_lambda_spec(self):
415 mock_obj = MagicMock()
416 mock_obj.mock_func = MagicMock(spec=lambda x: x)
417
418 with patch.object(mock_obj, "mock_func") as cm:
419 self.assertIsInstance(cm, MagicMock)
420
421
422 class AsyncArguments(IsolatedAsyncioTestCase):
423 async def test_add_return_value(self):
424 async def addition(self, var): pass
425
426 mock = AsyncMock(addition, return_value=10)
427 output = await mock(5)
428
429 self.assertEqual(output, 10)
430
431 async def test_add_side_effect_exception(self):
432 class CustomError(Exception): pass
433 async def addition(var): pass
434 mock = AsyncMock(addition, side_effect=CustomError('side-effect'))
435 with self.assertRaisesRegex(CustomError, 'side-effect'):
436 await mock(5)
437
438 async def test_add_side_effect_coroutine(self):
439 async def addition(var):
440 return var + 1
441 mock = AsyncMock(side_effect=addition)
442 result = await mock(5)
443 self.assertEqual(result, 6)
444
445 async def test_add_side_effect_normal_function(self):
446 def addition(var):
447 return var + 1
448 mock = AsyncMock(side_effect=addition)
449 result = await mock(5)
450 self.assertEqual(result, 6)
451
452 async def test_add_side_effect_iterable(self):
453 vals = [1, 2, 3]
454 mock = AsyncMock(side_effect=vals)
455 for item in vals:
456 self.assertEqual(await mock(), item)
457
458 with self.assertRaises(StopAsyncIteration) as e:
459 await mock()
460
461 async def test_add_side_effect_exception_iterable(self):
462 class SampleException(Exception):
463 pass
464
465 vals = [1, SampleException("foo")]
466 mock = AsyncMock(side_effect=vals)
467 self.assertEqual(await mock(), 1)
468
469 with self.assertRaises(SampleException) as e:
470 await mock()
471
472 async def test_return_value_AsyncMock(self):
473 value = AsyncMock(return_value=10)
474 mock = AsyncMock(return_value=value)
475 result = await mock()
476 self.assertIs(result, value)
477
478 async def test_return_value_awaitable(self):
479 fut = asyncio.Future()
480 fut.set_result(None)
481 mock = AsyncMock(return_value=fut)
482 result = await mock()
483 self.assertIsInstance(result, asyncio.Future)
484
485 async def test_side_effect_awaitable_values(self):
486 fut = asyncio.Future()
487 fut.set_result(None)
488
489 mock = AsyncMock(side_effect=[fut])
490 result = await mock()
491 self.assertIsInstance(result, asyncio.Future)
492
493 with self.assertRaises(StopAsyncIteration):
494 await mock()
495
496 async def test_side_effect_is_AsyncMock(self):
497 effect = AsyncMock(return_value=10)
498 mock = AsyncMock(side_effect=effect)
499
500 result = await mock()
501 self.assertEqual(result, 10)
502
503 async def test_wraps_coroutine(self):
504 value = asyncio.Future()
505
506 ran = False
507 async def inner():
508 nonlocal ran
509 ran = True
510 return value
511
512 mock = AsyncMock(wraps=inner)
513 result = await mock()
514 self.assertEqual(result, value)
515 mock.assert_awaited()
516 self.assertTrue(ran)
517
518 async def test_wraps_normal_function(self):
519 value = 1
520
521 ran = False
522 def inner():
523 nonlocal ran
524 ran = True
525 return value
526
527 mock = AsyncMock(wraps=inner)
528 result = await mock()
529 self.assertEqual(result, value)
530 mock.assert_awaited()
531 self.assertTrue(ran)
532
533 async def test_await_args_list_order(self):
534 async_mock = AsyncMock()
535 mock2 = async_mock(2)
536 mock1 = async_mock(1)
537 await mock1
538 await mock2
539 async_mock.assert_has_awaits([call(1), call(2)])
540 self.assertEqual(async_mock.await_args_list, [call(1), call(2)])
541 self.assertEqual(async_mock.call_args_list, [call(2), call(1)])
542
543
544 class AsyncMagicMethods(unittest.TestCase):
545 def test_async_magic_methods_return_async_mocks(self):
546 m_mock = MagicMock()
547 self.assertIsInstance(m_mock.__aenter__, AsyncMock)
548 self.assertIsInstance(m_mock.__aexit__, AsyncMock)
549 self.assertIsInstance(m_mock.__anext__, AsyncMock)
550 # __aiter__ is actually a synchronous object
551 # so should return a MagicMock
552 self.assertIsInstance(m_mock.__aiter__, MagicMock)
553
554 def test_sync_magic_methods_return_magic_mocks(self):
555 a_mock = AsyncMock()
556 self.assertIsInstance(a_mock.__enter__, MagicMock)
557 self.assertIsInstance(a_mock.__exit__, MagicMock)
558 self.assertIsInstance(a_mock.__next__, MagicMock)
559 self.assertIsInstance(a_mock.__len__, MagicMock)
560
561 def test_magicmock_has_async_magic_methods(self):
562 m_mock = MagicMock()
563 self.assertTrue(hasattr(m_mock, "__aenter__"))
564 self.assertTrue(hasattr(m_mock, "__aexit__"))
565 self.assertTrue(hasattr(m_mock, "__anext__"))
566
567 def test_asyncmock_has_sync_magic_methods(self):
568 a_mock = AsyncMock()
569 self.assertTrue(hasattr(a_mock, "__enter__"))
570 self.assertTrue(hasattr(a_mock, "__exit__"))
571 self.assertTrue(hasattr(a_mock, "__next__"))
572 self.assertTrue(hasattr(a_mock, "__len__"))
573
574 def test_magic_methods_are_async_functions(self):
575 m_mock = MagicMock()
576 self.assertIsInstance(m_mock.__aenter__, AsyncMock)
577 self.assertIsInstance(m_mock.__aexit__, AsyncMock)
578 # AsyncMocks are also coroutine functions
579 self.assertTrue(iscoroutinefunction(m_mock.__aenter__))
580 self.assertTrue(iscoroutinefunction(m_mock.__aexit__))
581
582 class AsyncContextManagerTest(unittest.TestCase):
583
584 class WithAsyncContextManager:
585 async def __aenter__(self, *args, **kwargs): pass
586
587 async def __aexit__(self, *args, **kwargs): pass
588
589 class WithSyncContextManager:
590 def __enter__(self, *args, **kwargs): pass
591
592 def __exit__(self, *args, **kwargs): pass
593
594 class ProductionCode:
595 # Example real-world(ish) code
596 def __init__(self):
597 self.session = None
598
599 async def main(self):
600 async with self.session.post('https://python.org') as response:
601 val = await response.json()
602 return val
603
604 def test_set_return_value_of_aenter(self):
605 def inner_test(mock_type):
606 pc = self.ProductionCode()
607 pc.session = MagicMock(name='sessionmock')
608 cm = mock_type(name='magic_cm')
609 response = AsyncMock(name='response')
610 response.json = AsyncMock(return_value={'json': 123})
611 cm.__aenter__.return_value = response
612 pc.session.post.return_value = cm
613 result = run(pc.main())
614 self.assertEqual(result, {'json': 123})
615
616 for mock_type in [AsyncMock, MagicMock]:
617 with self.subTest(f"test set return value of aenter with {mock_type}"):
618 inner_test(mock_type)
619
620 def test_mock_supports_async_context_manager(self):
621 def inner_test(mock_type):
622 called = False
623 cm = self.WithAsyncContextManager()
624 cm_mock = mock_type(cm)
625
626 async def use_context_manager():
627 nonlocal called
628 async with cm_mock as result:
629 called = True
630 return result
631
632 cm_result = run(use_context_manager())
633 self.assertTrue(called)
634 self.assertTrue(cm_mock.__aenter__.called)
635 self.assertTrue(cm_mock.__aexit__.called)
636 cm_mock.__aenter__.assert_awaited()
637 cm_mock.__aexit__.assert_awaited()
638 # We mock __aenter__ so it does not return self
639 self.assertIsNot(cm_mock, cm_result)
640
641 for mock_type in [AsyncMock, MagicMock]:
642 with self.subTest(f"test context manager magics with {mock_type}"):
643 inner_test(mock_type)
644
645
646 def test_mock_customize_async_context_manager(self):
647 instance = self.WithAsyncContextManager()
648 mock_instance = MagicMock(instance)
649
650 expected_result = object()
651 mock_instance.__aenter__.return_value = expected_result
652
653 async def use_context_manager():
654 async with mock_instance as result:
655 return result
656
657 self.assertIs(run(use_context_manager()), expected_result)
658
659 def test_mock_customize_async_context_manager_with_coroutine(self):
660 enter_called = False
661 exit_called = False
662
663 async def enter_coroutine(*args):
664 nonlocal enter_called
665 enter_called = True
666
667 async def exit_coroutine(*args):
668 nonlocal exit_called
669 exit_called = True
670
671 instance = self.WithAsyncContextManager()
672 mock_instance = MagicMock(instance)
673
674 mock_instance.__aenter__ = enter_coroutine
675 mock_instance.__aexit__ = exit_coroutine
676
677 async def use_context_manager():
678 async with mock_instance:
679 pass
680
681 run(use_context_manager())
682 self.assertTrue(enter_called)
683 self.assertTrue(exit_called)
684
685 def test_context_manager_raise_exception_by_default(self):
686 async def raise_in(context_manager):
687 async with context_manager:
688 raise TypeError()
689
690 instance = self.WithAsyncContextManager()
691 mock_instance = MagicMock(instance)
692 with self.assertRaises(TypeError):
693 run(raise_in(mock_instance))
694
695
696 class AsyncIteratorTest(unittest.TestCase):
697 class WithAsyncIterator(object):
698 def __init__(self):
699 self.items = ["foo", "NormalFoo", "baz"]
700
701 def __aiter__(self): pass
702
703 async def __anext__(self): pass
704
705 def test_aiter_set_return_value(self):
706 mock_iter = AsyncMock(name="tester")
707 mock_iter.__aiter__.return_value = [1, 2, 3]
708 async def main():
709 return [i async for i in mock_iter]
710 result = run(main())
711 self.assertEqual(result, [1, 2, 3])
712
713 def test_mock_aiter_and_anext_asyncmock(self):
714 def inner_test(mock_type):
715 instance = self.WithAsyncIterator()
716 mock_instance = mock_type(instance)
717 # Check that the mock and the real thing bahave the same
718 # __aiter__ is not actually async, so not a coroutinefunction
719 self.assertFalse(iscoroutinefunction(instance.__aiter__))
720 self.assertFalse(iscoroutinefunction(mock_instance.__aiter__))
721 # __anext__ is async
722 self.assertTrue(iscoroutinefunction(instance.__anext__))
723 self.assertTrue(iscoroutinefunction(mock_instance.__anext__))
724
725 for mock_type in [AsyncMock, MagicMock]:
726 with self.subTest(f"test aiter and anext corourtine with {mock_type}"):
727 inner_test(mock_type)
728
729
730 def test_mock_async_for(self):
731 async def iterate(iterator):
732 accumulator = []
733 async for item in iterator:
734 accumulator.append(item)
735
736 return accumulator
737
738 expected = ["FOO", "BAR", "BAZ"]
739 def test_default(mock_type):
740 mock_instance = mock_type(self.WithAsyncIterator())
741 self.assertEqual(run(iterate(mock_instance)), [])
742
743
744 def test_set_return_value(mock_type):
745 mock_instance = mock_type(self.WithAsyncIterator())
746 mock_instance.__aiter__.return_value = expected[:]
747 self.assertEqual(run(iterate(mock_instance)), expected)
748
749 def test_set_return_value_iter(mock_type):
750 mock_instance = mock_type(self.WithAsyncIterator())
751 mock_instance.__aiter__.return_value = iter(expected[:])
752 self.assertEqual(run(iterate(mock_instance)), expected)
753
754 for mock_type in [AsyncMock, MagicMock]:
755 with self.subTest(f"default value with {mock_type}"):
756 test_default(mock_type)
757
758 with self.subTest(f"set return_value with {mock_type}"):
759 test_set_return_value(mock_type)
760
761 with self.subTest(f"set return_value iterator with {mock_type}"):
762 test_set_return_value_iter(mock_type)
763
764
765 class AsyncMockAssert(unittest.TestCase):
766 def setUp(self):
767 self.mock = AsyncMock()
768
769 async def _runnable_test(self, *args, **kwargs):
770 await self.mock(*args, **kwargs)
771
772 async def _await_coroutine(self, coroutine):
773 return await coroutine
774
775 def test_assert_called_but_not_awaited(self):
776 mock = AsyncMock(AsyncClass)
777 with assertNeverAwaited(self):
778 mock.async_method()
779 gc.collect()
780 self.assertTrue(iscoroutinefunction(mock.async_method))
781 mock.async_method.assert_called()
782 mock.async_method.assert_called_once()
783 mock.async_method.assert_called_once_with()
784 with self.assertRaises(AssertionError):
785 mock.assert_awaited()
786 with self.assertRaises(AssertionError):
787 mock.async_method.assert_awaited()
788
789 def test_assert_called_then_awaited(self):
790 mock = AsyncMock(AsyncClass)
791 mock_coroutine = mock.async_method()
792 mock.async_method.assert_called()
793 mock.async_method.assert_called_once()
794 mock.async_method.assert_called_once_with()
795 with self.assertRaises(AssertionError):
796 mock.async_method.assert_awaited()
797
798 run(self._await_coroutine(mock_coroutine))
799 # Assert we haven't re-called the function
800 mock.async_method.assert_called_once()
801 mock.async_method.assert_awaited()
802 mock.async_method.assert_awaited_once()
803 mock.async_method.assert_awaited_once_with()
804
805 def test_assert_called_and_awaited_at_same_time(self):
806 with self.assertRaises(AssertionError):
807 self.mock.assert_awaited()
808
809 with self.assertRaises(AssertionError):
810 self.mock.assert_called()
811
812 run(self._runnable_test())
813 self.mock.assert_called_once()
814 self.mock.assert_awaited_once()
815
816 def test_assert_called_twice_and_awaited_once(self):
817 mock = AsyncMock(AsyncClass)
818 coroutine = mock.async_method()
819 # The first call will be awaited so no warning there
820 # But this call will never get awaited, so it will warn here
821 with assertNeverAwaited(self):
822 mock.async_method()
823 gc.collect()
824 with self.assertRaises(AssertionError):
825 mock.async_method.assert_awaited()
826 mock.async_method.assert_called()
827 run(self._await_coroutine(coroutine))
828 mock.async_method.assert_awaited()
829 mock.async_method.assert_awaited_once()
830
831 def test_assert_called_once_and_awaited_twice(self):
832 mock = AsyncMock(AsyncClass)
833 coroutine = mock.async_method()
834 mock.async_method.assert_called_once()
835 run(self._await_coroutine(coroutine))
836 with self.assertRaises(RuntimeError):
837 # Cannot reuse already awaited coroutine
838 run(self._await_coroutine(coroutine))
839 mock.async_method.assert_awaited()
840
841 def test_assert_awaited_but_not_called(self):
842 with self.assertRaises(AssertionError):
843 self.mock.assert_awaited()
844 with self.assertRaises(AssertionError):
845 self.mock.assert_called()
846 with self.assertRaises(TypeError):
847 # You cannot await an AsyncMock, it must be a coroutine
848 run(self._await_coroutine(self.mock))
849
850 with self.assertRaises(AssertionError):
851 self.mock.assert_awaited()
852 with self.assertRaises(AssertionError):
853 self.mock.assert_called()
854
855 def test_assert_has_calls_not_awaits(self):
856 kalls = [call('foo')]
857 with assertNeverAwaited(self):
858 self.mock('foo')
859 gc.collect()
860 self.mock.assert_has_calls(kalls)
861 with self.assertRaises(AssertionError):
862 self.mock.assert_has_awaits(kalls)
863
864 def test_assert_has_mock_calls_on_async_mock_no_spec(self):
865 with assertNeverAwaited(self):
866 self.mock()
867 gc.collect()
868 kalls_empty = [('', (), {})]
869 self.assertEqual(self.mock.mock_calls, kalls_empty)
870
871 with assertNeverAwaited(self):
872 self.mock('foo')
873 with assertNeverAwaited(self):
874 self.mock('baz')
875 gc.collect()
876 mock_kalls = ([call(), call('foo'), call('baz')])
877 self.assertEqual(self.mock.mock_calls, mock_kalls)
878
879 def test_assert_has_mock_calls_on_async_mock_with_spec(self):
880 a_class_mock = AsyncMock(AsyncClass)
881 with assertNeverAwaited(self):
882 a_class_mock.async_method()
883 gc.collect()
884 kalls_empty = [('', (), {})]
885 self.assertEqual(a_class_mock.async_method.mock_calls, kalls_empty)
886 self.assertEqual(a_class_mock.mock_calls, [call.async_method()])
887
888 with assertNeverAwaited(self):
889 a_class_mock.async_method(1, 2, 3, a=4, b=5)
890 gc.collect()
891 method_kalls = [call(), call(1, 2, 3, a=4, b=5)]
892 mock_kalls = [call.async_method(), call.async_method(1, 2, 3, a=4, b=5)]
893 self.assertEqual(a_class_mock.async_method.mock_calls, method_kalls)
894 self.assertEqual(a_class_mock.mock_calls, mock_kalls)
895
896 def test_async_method_calls_recorded(self):
897 with assertNeverAwaited(self):
898 self.mock.something(3, fish=None)
899 with assertNeverAwaited(self):
900 self.mock.something_else.something(6, cake=sentinel.Cake)
901 gc.collect()
902
903 self.assertEqual(self.mock.method_calls, [
904 ("something", (3,), {'fish': None}),
905 ("something_else.something", (6,), {'cake': sentinel.Cake})
906 ],
907 "method calls not recorded correctly")
908 self.assertEqual(self.mock.something_else.method_calls,
909 [("something", (6,), {'cake': sentinel.Cake})],
910 "method calls not recorded correctly")
911
912 def test_async_arg_lists(self):
913 def assert_attrs(mock):
914 names = ('call_args_list', 'method_calls', 'mock_calls')
915 for name in names:
916 attr = getattr(mock, name)
917 self.assertIsInstance(attr, _CallList)
918 self.assertIsInstance(attr, list)
919 self.assertEqual(attr, [])
920
921 assert_attrs(self.mock)
922 with assertNeverAwaited(self):
923 self.mock()
924 with assertNeverAwaited(self):
925 self.mock(1, 2)
926 with assertNeverAwaited(self):
927 self.mock(a=3)
928 gc.collect()
929
930 self.mock.reset_mock()
931 assert_attrs(self.mock)
932
933 a_mock = AsyncMock(AsyncClass)
934 with assertNeverAwaited(self):
935 a_mock.async_method()
936 with assertNeverAwaited(self):
937 a_mock.async_method(1, a=3)
938 gc.collect()
939
940 a_mock.reset_mock()
941 assert_attrs(a_mock)
942
943 def test_assert_awaited(self):
944 with self.assertRaises(AssertionError):
945 self.mock.assert_awaited()
946
947 run(self._runnable_test())
948 self.mock.assert_awaited()
949
950 def test_assert_awaited_once(self):
951 with self.assertRaises(AssertionError):
952 self.mock.assert_awaited_once()
953
954 run(self._runnable_test())
955 self.mock.assert_awaited_once()
956
957 run(self._runnable_test())
958 with self.assertRaises(AssertionError):
959 self.mock.assert_awaited_once()
960
961 def test_assert_awaited_with(self):
962 msg = 'Not awaited'
963 with self.assertRaisesRegex(AssertionError, msg):
964 self.mock.assert_awaited_with('foo')
965
966 run(self._runnable_test())
967 msg = 'expected await not found'
968 with self.assertRaisesRegex(AssertionError, msg):
969 self.mock.assert_awaited_with('foo')
970
971 run(self._runnable_test('foo'))
972 self.mock.assert_awaited_with('foo')
973
974 run(self._runnable_test('SomethingElse'))
975 with self.assertRaises(AssertionError):
976 self.mock.assert_awaited_with('foo')
977
978 def test_assert_awaited_once_with(self):
979 with self.assertRaises(AssertionError):
980 self.mock.assert_awaited_once_with('foo')
981
982 run(self._runnable_test('foo'))
983 self.mock.assert_awaited_once_with('foo')
984
985 run(self._runnable_test('foo'))
986 with self.assertRaises(AssertionError):
987 self.mock.assert_awaited_once_with('foo')
988
989 def test_assert_any_wait(self):
990 with self.assertRaises(AssertionError):
991 self.mock.assert_any_await('foo')
992
993 run(self._runnable_test('baz'))
994 with self.assertRaises(AssertionError):
995 self.mock.assert_any_await('foo')
996
997 run(self._runnable_test('foo'))
998 self.mock.assert_any_await('foo')
999
1000 run(self._runnable_test('SomethingElse'))
1001 self.mock.assert_any_await('foo')
1002
1003 def test_assert_has_awaits_no_order(self):
1004 calls = [call('foo'), call('baz')]
1005
1006 with self.assertRaises(AssertionError) as cm:
1007 self.mock.assert_has_awaits(calls)
1008 self.assertEqual(len(cm.exception.args), 1)
1009
1010 run(self._runnable_test('foo'))
1011 with self.assertRaises(AssertionError):
1012 self.mock.assert_has_awaits(calls)
1013
1014 run(self._runnable_test('foo'))
1015 with self.assertRaises(AssertionError):
1016 self.mock.assert_has_awaits(calls)
1017
1018 run(self._runnable_test('baz'))
1019 self.mock.assert_has_awaits(calls)
1020
1021 run(self._runnable_test('SomethingElse'))
1022 self.mock.assert_has_awaits(calls)
1023
1024 def test_awaits_asserts_with_any(self):
1025 class Foo:
1026 def __eq__(self, other): pass
1027
1028 run(self._runnable_test(Foo(), 1))
1029
1030 self.mock.assert_has_awaits([call(ANY, 1)])
1031 self.mock.assert_awaited_with(ANY, 1)
1032 self.mock.assert_any_await(ANY, 1)
1033
1034 def test_awaits_asserts_with_spec_and_any(self):
1035 class Foo:
1036 def __eq__(self, other): pass
1037
1038 mock_with_spec = AsyncMock(spec=Foo)
1039
1040 async def _custom_mock_runnable_test(*args):
1041 await mock_with_spec(*args)
1042
1043 run(_custom_mock_runnable_test(Foo(), 1))
1044 mock_with_spec.assert_has_awaits([call(ANY, 1)])
1045 mock_with_spec.assert_awaited_with(ANY, 1)
1046 mock_with_spec.assert_any_await(ANY, 1)
1047
1048 def test_assert_has_awaits_ordered(self):
1049 calls = [call('foo'), call('baz')]
1050 with self.assertRaises(AssertionError):
1051 self.mock.assert_has_awaits(calls, any_order=True)
1052
1053 run(self._runnable_test('baz'))
1054 with self.assertRaises(AssertionError):
1055 self.mock.assert_has_awaits(calls, any_order=True)
1056
1057 run(self._runnable_test('bamf'))
1058 with self.assertRaises(AssertionError):
1059 self.mock.assert_has_awaits(calls, any_order=True)
1060
1061 run(self._runnable_test('foo'))
1062 self.mock.assert_has_awaits(calls, any_order=True)
1063
1064 run(self._runnable_test('qux'))
1065 self.mock.assert_has_awaits(calls, any_order=True)
1066
1067 def test_assert_not_awaited(self):
1068 self.mock.assert_not_awaited()
1069
1070 run(self._runnable_test())
1071 with self.assertRaises(AssertionError):
1072 self.mock.assert_not_awaited()
1073
1074 def test_assert_has_awaits_not_matching_spec_error(self):
1075 async def f(x=None): pass
1076
1077 self.mock = AsyncMock(spec=f)
1078 run(self._runnable_test(1))
1079
1080 with self.assertRaisesRegex(
1081 AssertionError,
1082 '^{}$'.format(
1083 re.escape('Awaits not found.\n'
1084 'Expected: [call()]\n'
1085 'Actual: [call(1)]'))) as cm:
1086 self.mock.assert_has_awaits([call()])
1087 self.assertIsNone(cm.exception.__cause__)
1088
1089 with self.assertRaisesRegex(
1090 AssertionError,
1091 '^{}$'.format(
1092 re.escape(
1093 'Error processing expected awaits.\n'
1094 "Errors: [None, TypeError('too many positional "
1095 "arguments')]\n"
1096 'Expected: [call(), call(1, 2)]\n'
1097 'Actual: [call(1)]'))) as cm:
1098 self.mock.assert_has_awaits([call(), call(1, 2)])
1099 self.assertIsInstance(cm.exception.__cause__, TypeError)
1100
1101
1102 if __name__ == '__main__':
1103 unittest.main()