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