Debian Codegraph @

Lib/test/test_contextlib_async.py

raw
1 import asyncio
2 from contextlib import (
3 asynccontextmanager, AbstractAsyncContextManager,
4 AsyncExitStack, nullcontext, aclosing, contextmanager)
5 from test import support
6 import unittest
7 import traceback
8
9 from test.test_contextlib import TestBaseExitStack
10
11 support.requires_working_socket(module=True)
12
13 def tearDownModule():
14 asyncio.set_event_loop_policy(None)
15
16
17 class TestAbstractAsyncContextManager(unittest.IsolatedAsyncioTestCase):
18
19 async def test_enter(self):
20 class DefaultEnter(AbstractAsyncContextManager):
21 async def __aexit__(self, *args):
22 await super().__aexit__(*args)
23
24 manager = DefaultEnter()
25 self.assertIs(await manager.__aenter__(), manager)
26
27 async with manager as context:
28 self.assertIs(manager, context)
29
30 async def test_slots(self):
31 class DefaultAsyncContextManager(AbstractAsyncContextManager):
32 __slots__ = ()
33
34 async def __aexit__(self, *args):
35 await super().__aexit__(*args)
36
37 with self.assertRaises(AttributeError):
38 manager = DefaultAsyncContextManager()
39 manager.var = 42
40
41 async def test_async_gen_propagates_generator_exit(self):
42 # A regression test for https://bugs.python.org/issue33786.
43
44 @asynccontextmanager
45 async def ctx():
46 yield
47
48 async def gen():
49 async with ctx():
50 yield 11
51
52 g = gen()
53 async for val in g:
54 self.assertEqual(val, 11)
55 break
56 await g.aclose()
57
58 def test_exit_is_abstract(self):
59 class MissingAexit(AbstractAsyncContextManager):
60 pass
61
62 with self.assertRaises(TypeError):
63 MissingAexit()
64
65 def test_structural_subclassing(self):
66 class ManagerFromScratch:
67 async def __aenter__(self):
68 return self
69 async def __aexit__(self, exc_type, exc_value, traceback):
70 return None
71
72 self.assertTrue(issubclass(ManagerFromScratch, AbstractAsyncContextManager))
73
74 class DefaultEnter(AbstractAsyncContextManager):
75 async def __aexit__(self, *args):
76 await super().__aexit__(*args)
77
78 self.assertTrue(issubclass(DefaultEnter, AbstractAsyncContextManager))
79
80 class NoneAenter(ManagerFromScratch):
81 __aenter__ = None
82
83 self.assertFalse(issubclass(NoneAenter, AbstractAsyncContextManager))
84
85 class NoneAexit(ManagerFromScratch):
86 __aexit__ = None
87
88 self.assertFalse(issubclass(NoneAexit, AbstractAsyncContextManager))
89
90
91 class AsyncContextManagerTestCase(unittest.IsolatedAsyncioTestCase):
92
93 async def test_contextmanager_plain(self):
94 state = []
95 @asynccontextmanager
96 async def woohoo():
97 state.append(1)
98 yield 42
99 state.append(999)
100 async with woohoo() as x:
101 self.assertEqual(state, [1])
102 self.assertEqual(x, 42)
103 state.append(x)
104 self.assertEqual(state, [1, 42, 999])
105
106 async def test_contextmanager_finally(self):
107 state = []
108 @asynccontextmanager
109 async def woohoo():
110 state.append(1)
111 try:
112 yield 42
113 finally:
114 state.append(999)
115 with self.assertRaises(ZeroDivisionError):
116 async with woohoo() as x:
117 self.assertEqual(state, [1])
118 self.assertEqual(x, 42)
119 state.append(x)
120 raise ZeroDivisionError()
121 self.assertEqual(state, [1, 42, 999])
122
123 async def test_contextmanager_traceback(self):
124 @asynccontextmanager
125 async def f():
126 yield
127
128 try:
129 async with f():
130 1/0
131 except ZeroDivisionError as e:
132 frames = traceback.extract_tb(e.__traceback__)
133
134 self.assertEqual(len(frames), 1)
135 self.assertEqual(frames[0].name, 'test_contextmanager_traceback')
136 self.assertEqual(frames[0].line, '1/0')
137
138 # Repeat with RuntimeError (which goes through a different code path)
139 class RuntimeErrorSubclass(RuntimeError):
140 pass
141
142 try:
143 async with f():
144 raise RuntimeErrorSubclass(42)
145 except RuntimeErrorSubclass as e:
146 frames = traceback.extract_tb(e.__traceback__)
147
148 self.assertEqual(len(frames), 1)
149 self.assertEqual(frames[0].name, 'test_contextmanager_traceback')
150 self.assertEqual(frames[0].line, 'raise RuntimeErrorSubclass(42)')
151
152 class StopIterationSubclass(StopIteration):
153 pass
154
155 class StopAsyncIterationSubclass(StopAsyncIteration):
156 pass
157
158 for stop_exc in (
159 StopIteration('spam'),
160 StopAsyncIteration('ham'),
161 StopIterationSubclass('spam'),
162 StopAsyncIterationSubclass('spam')
163 ):
164 with self.subTest(type=type(stop_exc)):
165 try:
166 async with f():
167 raise stop_exc
168 except type(stop_exc) as e:
169 self.assertIs(e, stop_exc)
170 frames = traceback.extract_tb(e.__traceback__)
171 else:
172 self.fail(f'{stop_exc} was suppressed')
173
174 self.assertEqual(len(frames), 1)
175 self.assertEqual(frames[0].name, 'test_contextmanager_traceback')
176 self.assertEqual(frames[0].line, 'raise stop_exc')
177
178 async def test_contextmanager_no_reraise(self):
179 @asynccontextmanager
180 async def whee():
181 yield
182 ctx = whee()
183 await ctx.__aenter__()
184 # Calling __aexit__ should not result in an exception
185 self.assertFalse(await ctx.__aexit__(TypeError, TypeError("foo"), None))
186
187 async def test_contextmanager_trap_yield_after_throw(self):
188 @asynccontextmanager
189 async def whoo():
190 try:
191 yield
192 except:
193 yield
194 ctx = whoo()
195 await ctx.__aenter__()
196 with self.assertRaises(RuntimeError):
197 await ctx.__aexit__(TypeError, TypeError('foo'), None)
198 if support.check_impl_detail(cpython=True):
199 # The "gen" attribute is an implementation detail.
200 self.assertFalse(ctx.gen.ag_suspended)
201
202 async def test_contextmanager_trap_no_yield(self):
203 @asynccontextmanager
204 async def whoo():
205 if False:
206 yield
207 ctx = whoo()
208 with self.assertRaises(RuntimeError):
209 await ctx.__aenter__()
210
211 async def test_contextmanager_trap_second_yield(self):
212 @asynccontextmanager
213 async def whoo():
214 yield
215 yield
216 ctx = whoo()
217 await ctx.__aenter__()
218 with self.assertRaises(RuntimeError):
219 await ctx.__aexit__(None, None, None)
220 if support.check_impl_detail(cpython=True):
221 # The "gen" attribute is an implementation detail.
222 self.assertFalse(ctx.gen.ag_suspended)
223
224 async def test_contextmanager_non_normalised(self):
225 @asynccontextmanager
226 async def whoo():
227 try:
228 yield
229 except RuntimeError:
230 raise SyntaxError
231
232 ctx = whoo()
233 await ctx.__aenter__()
234 with self.assertRaises(SyntaxError):
235 await ctx.__aexit__(RuntimeError, None, None)
236
237 async def test_contextmanager_except(self):
238 state = []
239 @asynccontextmanager
240 async def woohoo():
241 state.append(1)
242 try:
243 yield 42
244 except ZeroDivisionError as e:
245 state.append(e.args[0])
246 self.assertEqual(state, [1, 42, 999])
247 async with woohoo() as x:
248 self.assertEqual(state, [1])
249 self.assertEqual(x, 42)
250 state.append(x)
251 raise ZeroDivisionError(999)
252 self.assertEqual(state, [1, 42, 999])
253
254 async def test_contextmanager_except_stopiter(self):
255 @asynccontextmanager
256 async def woohoo():
257 yield
258
259 class StopIterationSubclass(StopIteration):
260 pass
261
262 class StopAsyncIterationSubclass(StopAsyncIteration):
263 pass
264
265 for stop_exc in (
266 StopIteration('spam'),
267 StopAsyncIteration('ham'),
268 StopIterationSubclass('spam'),
269 StopAsyncIterationSubclass('spam')
270 ):
271 with self.subTest(type=type(stop_exc)):
272 try:
273 async with woohoo():
274 raise stop_exc
275 except Exception as ex:
276 self.assertIs(ex, stop_exc)
277 else:
278 self.fail(f'{stop_exc} was suppressed')
279
280 async def test_contextmanager_wrap_runtimeerror(self):
281 @asynccontextmanager
282 async def woohoo():
283 try:
284 yield
285 except Exception as exc:
286 raise RuntimeError(f'caught {exc}') from exc
287
288 with self.assertRaises(RuntimeError):
289 async with woohoo():
290 1 / 0
291
292 # If the context manager wrapped StopAsyncIteration in a RuntimeError,
293 # we also unwrap it, because we can't tell whether the wrapping was
294 # done by the generator machinery or by the generator itself.
295 with self.assertRaises(StopAsyncIteration):
296 async with woohoo():
297 raise StopAsyncIteration
298
299 def _create_contextmanager_attribs(self):
300 def attribs(**kw):
301 def decorate(func):
302 for k,v in kw.items():
303 setattr(func,k,v)
304 return func
305 return decorate
306 @asynccontextmanager
307 @attribs(foo='bar')
308 async def baz(spam):
309 """Whee!"""
310 yield
311 return baz
312
313 def test_contextmanager_attribs(self):
314 baz = self._create_contextmanager_attribs()
315 self.assertEqual(baz.__name__,'baz')
316 self.assertEqual(baz.foo, 'bar')
317
318 @support.requires_docstrings
319 def test_contextmanager_doc_attrib(self):
320 baz = self._create_contextmanager_attribs()
321 self.assertEqual(baz.__doc__, "Whee!")
322
323 @support.requires_docstrings
324 async def test_instance_docstring_given_cm_docstring(self):
325 baz = self._create_contextmanager_attribs()(None)
326 self.assertEqual(baz.__doc__, "Whee!")
327 async with baz:
328 pass # suppress warning
329
330 async def test_keywords(self):
331 # Ensure no keyword arguments are inhibited
332 @asynccontextmanager
333 async def woohoo(self, func, args, kwds):
334 yield (self, func, args, kwds)
335 async with woohoo(self=11, func=22, args=33, kwds=44) as target:
336 self.assertEqual(target, (11, 22, 33, 44))
337
338 async def test_recursive(self):
339 depth = 0
340 ncols = 0
341
342 @asynccontextmanager
343 async def woohoo():
344 nonlocal ncols
345 ncols += 1
346
347 nonlocal depth
348 before = depth
349 depth += 1
350 yield
351 depth -= 1
352 self.assertEqual(depth, before)
353
354 @woohoo()
355 async def recursive():
356 if depth < 10:
357 await recursive()
358
359 await recursive()
360
361 self.assertEqual(ncols, 10)
362 self.assertEqual(depth, 0)
363
364 async def test_decorator(self):
365 entered = False
366
367 @asynccontextmanager
368 async def context():
369 nonlocal entered
370 entered = True
371 yield
372 entered = False
373
374 @context()
375 async def test():
376 self.assertTrue(entered)
377
378 self.assertFalse(entered)
379 await test()
380 self.assertFalse(entered)
381
382 async def test_decorator_with_exception(self):
383 entered = False
384
385 @asynccontextmanager
386 async def context():
387 nonlocal entered
388 try:
389 entered = True
390 yield
391 finally:
392 entered = False
393
394 @context()
395 async def test():
396 self.assertTrue(entered)
397 raise NameError('foo')
398
399 self.assertFalse(entered)
400 with self.assertRaisesRegex(NameError, 'foo'):
401 await test()
402 self.assertFalse(entered)
403
404 async def test_decorating_method(self):
405
406 @asynccontextmanager
407 async def context():
408 yield
409
410
411 class Test(object):
412
413 @context()
414 async def method(self, a, b, c=None):
415 self.a = a
416 self.b = b
417 self.c = c
418
419 # these tests are for argument passing when used as a decorator
420 test = Test()
421 await test.method(1, 2)
422 self.assertEqual(test.a, 1)
423 self.assertEqual(test.b, 2)
424 self.assertEqual(test.c, None)
425
426 test = Test()
427 await test.method('a', 'b', 'c')
428 self.assertEqual(test.a, 'a')
429 self.assertEqual(test.b, 'b')
430 self.assertEqual(test.c, 'c')
431
432 test = Test()
433 await test.method(a=1, b=2)
434 self.assertEqual(test.a, 1)
435 self.assertEqual(test.b, 2)
436
437
438 class AclosingTestCase(unittest.IsolatedAsyncioTestCase):
439
440 @support.requires_docstrings
441 def test_instance_docs(self):
442 cm_docstring = aclosing.__doc__
443 obj = aclosing(None)
444 self.assertEqual(obj.__doc__, cm_docstring)
445
446 async def test_aclosing(self):
447 state = []
448 class C:
449 async def aclose(self):
450 state.append(1)
451 x = C()
452 self.assertEqual(state, [])
453 async with aclosing(x) as y:
454 self.assertEqual(x, y)
455 self.assertEqual(state, [1])
456
457 async def test_aclosing_error(self):
458 state = []
459 class C:
460 async def aclose(self):
461 state.append(1)
462 x = C()
463 self.assertEqual(state, [])
464 with self.assertRaises(ZeroDivisionError):
465 async with aclosing(x) as y:
466 self.assertEqual(x, y)
467 1 / 0
468 self.assertEqual(state, [1])
469
470 async def test_aclosing_bpo41229(self):
471 state = []
472
473 @contextmanager
474 def sync_resource():
475 try:
476 yield
477 finally:
478 state.append(1)
479
480 async def agenfunc():
481 with sync_resource():
482 yield -1
483 yield -2
484
485 x = agenfunc()
486 self.assertEqual(state, [])
487 with self.assertRaises(ZeroDivisionError):
488 async with aclosing(x) as y:
489 self.assertEqual(x, y)
490 self.assertEqual(-1, await x.__anext__())
491 1 / 0
492 self.assertEqual(state, [1])
493
494
495 class TestAsyncExitStack(TestBaseExitStack, unittest.IsolatedAsyncioTestCase):
496 class SyncAsyncExitStack(AsyncExitStack):
497 @staticmethod
498 def run_coroutine(coro):
499 loop = asyncio.get_event_loop_policy().get_event_loop()
500 t = loop.create_task(coro)
501 t.add_done_callback(lambda f: loop.stop())
502 loop.run_forever()
503
504 exc = t.exception()
505 if not exc:
506 return t.result()
507 else:
508 context = exc.__context__
509
510 try:
511 raise exc
512 except:
513 exc.__context__ = context
514 raise exc
515
516 def close(self):
517 return self.run_coroutine(self.aclose())
518
519 def __enter__(self):
520 return self.run_coroutine(self.__aenter__())
521
522 def __exit__(self, *exc_details):
523 return self.run_coroutine(self.__aexit__(*exc_details))
524
525 exit_stack = SyncAsyncExitStack
526 callback_error_internal_frames = [
527 ('__exit__', 'return self.run_coroutine(self.__aexit__(*exc_details))'),
528 ('run_coroutine', 'raise exc'),
529 ('run_coroutine', 'raise exc'),
530 ('__aexit__', 'raise exc'),
531 ('__aexit__', 'cb_suppress = cb(*exc_details)'),
532 ]
533
534 async def test_async_callback(self):
535 expected = [
536 ((), {}),
537 ((1,), {}),
538 ((1,2), {}),
539 ((), dict(example=1)),
540 ((1,), dict(example=1)),
541 ((1,2), dict(example=1)),
542 ]
543 result = []
544 async def _exit(*args, **kwds):
545 """Test metadata propagation"""
546 result.append((args, kwds))
547
548 async with AsyncExitStack() as stack:
549 for args, kwds in reversed(expected):
550 if args and kwds:
551 f = stack.push_async_callback(_exit, *args, **kwds)
552 elif args:
553 f = stack.push_async_callback(_exit, *args)
554 elif kwds:
555 f = stack.push_async_callback(_exit, **kwds)
556 else:
557 f = stack.push_async_callback(_exit)
558 self.assertIs(f, _exit)
559 for wrapper in stack._exit_callbacks:
560 self.assertIs(wrapper[1].__wrapped__, _exit)
561 self.assertNotEqual(wrapper[1].__name__, _exit.__name__)
562 self.assertIsNone(wrapper[1].__doc__, _exit.__doc__)
563
564 self.assertEqual(result, expected)
565
566 result = []
567 async with AsyncExitStack() as stack:
568 with self.assertRaises(TypeError):
569 stack.push_async_callback(arg=1)
570 with self.assertRaises(TypeError):
571 self.exit_stack.push_async_callback(arg=2)
572 with self.assertRaises(TypeError):
573 stack.push_async_callback(callback=_exit, arg=3)
574 self.assertEqual(result, [])
575
576 async def test_async_push(self):
577 exc_raised = ZeroDivisionError
578 async def _expect_exc(exc_type, exc, exc_tb):
579 self.assertIs(exc_type, exc_raised)
580 async def _suppress_exc(*exc_details):
581 return True
582 async def _expect_ok(exc_type, exc, exc_tb):
583 self.assertIsNone(exc_type)
584 self.assertIsNone(exc)
585 self.assertIsNone(exc_tb)
586 class ExitCM(object):
587 def __init__(self, check_exc):
588 self.check_exc = check_exc
589 async def __aenter__(self):
590 self.fail("Should not be called!")
591 async def __aexit__(self, *exc_details):
592 await self.check_exc(*exc_details)
593
594 async with self.exit_stack() as stack:
595 stack.push_async_exit(_expect_ok)
596 self.assertIs(stack._exit_callbacks[-1][1], _expect_ok)
597 cm = ExitCM(_expect_ok)
598 stack.push_async_exit(cm)
599 self.assertIs(stack._exit_callbacks[-1][1].__self__, cm)
600 stack.push_async_exit(_suppress_exc)
601 self.assertIs(stack._exit_callbacks[-1][1], _suppress_exc)
602 cm = ExitCM(_expect_exc)
603 stack.push_async_exit(cm)
604 self.assertIs(stack._exit_callbacks[-1][1].__self__, cm)
605 stack.push_async_exit(_expect_exc)
606 self.assertIs(stack._exit_callbacks[-1][1], _expect_exc)
607 stack.push_async_exit(_expect_exc)
608 self.assertIs(stack._exit_callbacks[-1][1], _expect_exc)
609 1/0
610
611 async def test_enter_async_context(self):
612 class TestCM(object):
613 async def __aenter__(self):
614 result.append(1)
615 async def __aexit__(self, *exc_details):
616 result.append(3)
617
618 result = []
619 cm = TestCM()
620
621 async with AsyncExitStack() as stack:
622 @stack.push_async_callback # Registered first => cleaned up last
623 async def _exit():
624 result.append(4)
625 self.assertIsNotNone(_exit)
626 await stack.enter_async_context(cm)
627 self.assertIs(stack._exit_callbacks[-1][1].__self__, cm)
628 result.append(2)
629
630 self.assertEqual(result, [1, 2, 3, 4])
631
632 async def test_enter_async_context_errors(self):
633 class LacksEnterAndExit:
634 pass
635 class LacksEnter:
636 async def __aexit__(self, *exc_info):
637 pass
638 class LacksExit:
639 async def __aenter__(self):
640 pass
641
642 async with self.exit_stack() as stack:
643 with self.assertRaisesRegex(TypeError, 'asynchronous context manager'):
644 await stack.enter_async_context(LacksEnterAndExit())
645 with self.assertRaisesRegex(TypeError, 'asynchronous context manager'):
646 await stack.enter_async_context(LacksEnter())
647 with self.assertRaisesRegex(TypeError, 'asynchronous context manager'):
648 await stack.enter_async_context(LacksExit())
649 self.assertFalse(stack._exit_callbacks)
650
651 async def test_async_exit_exception_chaining(self):
652 # Ensure exception chaining matches the reference behaviour
653 async def raise_exc(exc):
654 raise exc
655
656 saved_details = None
657 async def suppress_exc(*exc_details):
658 nonlocal saved_details
659 saved_details = exc_details
660 return True
661
662 try:
663 async with self.exit_stack() as stack:
664 stack.push_async_callback(raise_exc, IndexError)
665 stack.push_async_callback(raise_exc, KeyError)
666 stack.push_async_callback(raise_exc, AttributeError)
667 stack.push_async_exit(suppress_exc)
668 stack.push_async_callback(raise_exc, ValueError)
669 1 / 0
670 except IndexError as exc:
671 self.assertIsInstance(exc.__context__, KeyError)
672 self.assertIsInstance(exc.__context__.__context__, AttributeError)
673 # Inner exceptions were suppressed
674 self.assertIsNone(exc.__context__.__context__.__context__)
675 else:
676 self.fail("Expected IndexError, but no exception was raised")
677 # Check the inner exceptions
678 inner_exc = saved_details[1]
679 self.assertIsInstance(inner_exc, ValueError)
680 self.assertIsInstance(inner_exc.__context__, ZeroDivisionError)
681
682 async def test_async_exit_exception_explicit_none_context(self):
683 # Ensure AsyncExitStack chaining matches actual nested `with` statements
684 # regarding explicit __context__ = None.
685
686 class MyException(Exception):
687 pass
688
689 @asynccontextmanager
690 async def my_cm():
691 try:
692 yield
693 except BaseException:
694 exc = MyException()
695 try:
696 raise exc
697 finally:
698 exc.__context__ = None
699
700 @asynccontextmanager
701 async def my_cm_with_exit_stack():
702 async with self.exit_stack() as stack:
703 await stack.enter_async_context(my_cm())
704 yield stack
705
706 for cm in (my_cm, my_cm_with_exit_stack):
707 with self.subTest():
708 try:
709 async with cm():
710 raise IndexError()
711 except MyException as exc:
712 self.assertIsNone(exc.__context__)
713 else:
714 self.fail("Expected IndexError, but no exception was raised")
715
716 async def test_instance_bypass_async(self):
717 class Example(object): pass
718 cm = Example()
719 cm.__aenter__ = object()
720 cm.__aexit__ = object()
721 stack = self.exit_stack()
722 with self.assertRaisesRegex(TypeError, 'asynchronous context manager'):
723 await stack.enter_async_context(cm)
724 stack.push_async_exit(cm)
725 self.assertIs(stack._exit_callbacks[-1][1], cm)
726
727
728 class TestAsyncNullcontext(unittest.IsolatedAsyncioTestCase):
729 async def test_async_nullcontext(self):
730 class C:
731 pass
732 c = C()
733 async with nullcontext(c) as c_in:
734 self.assertIs(c_in, c)
735
736
737 if __name__ == '__main__':
738 unittest.main()