Debian Codegraph @

Lib/unittest/async_case.py

raw
1 import asyncio
2 import contextvars
3 import inspect
4 import warnings
5
6 from .case import TestCase
7
8 __unittest = True
9
10 class IsolatedAsyncioTestCase(TestCase):
11 # Names intentionally have a long prefix
12 # to reduce a chance of clashing with user-defined attributes
13 # from inherited test case
14 #
15 # The class doesn't call loop.run_until_complete(self.setUp()) and family
16 # but uses a different approach:
17 # 1. create a long-running task that reads self.setUp()
18 # awaitable from queue along with a future
19 # 2. await the awaitable object passing in and set the result
20 # into the future object
21 # 3. Outer code puts the awaitable and the future object into a queue
22 # with waiting for the future
23 # The trick is necessary because every run_until_complete() call
24 # creates a new task with embedded ContextVar context.
25 # To share contextvars between setUp(), test and tearDown() we need to execute
26 # them inside the same task.
27
28 # Note: the test case modifies event loop policy if the policy was not instantiated
29 # yet, unless loop_factory=asyncio.EventLoop is set.
30 # asyncio.get_event_loop_policy() creates a default policy on demand but never
31 # returns None
32 # I believe this is not an issue in user level tests but python itself for testing
33 # should reset a policy in every test module
34 # by calling asyncio.set_event_loop_policy(None) in tearDownModule()
35 # or set loop_factory=asyncio.EventLoop
36
37 loop_factory = None
38
39 def __init__(self, methodName='runTest'):
40 super().__init__(methodName)
41 self._asyncioRunner = None
42 self._asyncioTestContext = contextvars.copy_context()
43
44 async def asyncSetUp(self):
45 pass
46
47 async def asyncTearDown(self):
48 pass
49
50 def addAsyncCleanup(self, func, /, *args, **kwargs):
51 # A trivial trampoline to addCleanup()
52 # the function exists because it has a different semantics
53 # and signature:
54 # addCleanup() accepts regular functions
55 # but addAsyncCleanup() accepts coroutines
56 #
57 # We intentionally don't add inspect.iscoroutinefunction() check
58 # for func argument because there is no way
59 # to check for async function reliably:
60 # 1. It can be "async def func()" itself
61 # 2. Class can implement "async def __call__()" method
62 # 3. Regular "def func()" that returns awaitable object
63 self.addCleanup(*(func, *args), **kwargs)
64
65 async def enterAsyncContext(self, cm):
66 """Enters the supplied asynchronous context manager.
67
68 If successful, also adds its __aexit__ method as a cleanup
69 function and returns the result of the __aenter__ method.
70 """
71 # We look up the special methods on the type to match the with
72 # statement.
73 cls = type(cm)
74 try:
75 enter = cls.__aenter__
76 exit = cls.__aexit__
77 except AttributeError:
78 msg = (f"'{cls.__module__}.{cls.__qualname__}' object does "
79 "not support the asynchronous context manager protocol")
80 try:
81 cls.__enter__
82 cls.__exit__
83 except AttributeError:
84 pass
85 else:
86 msg += (" but it supports the context manager protocol. "
87 "Did you mean to use enterContext()?")
88 raise TypeError(msg) from None
89 result = await enter(cm)
90 self.addAsyncCleanup(exit, cm, None, None, None)
91 return result
92
93 def _callSetUp(self):
94 # Force loop to be initialized and set as the current loop
95 # so that setUp functions can use get_event_loop() and get the
96 # correct loop instance.
97 self._asyncioRunner.get_loop()
98 self._asyncioTestContext.run(self.setUp)
99 self._callAsync(self.asyncSetUp)
100
101 def _callTestMethod(self, method):
102 result = self._callMaybeAsync(method)
103 if result is not None:
104 msg = (
105 f'It is deprecated to return a value that is not None '
106 f'from a test case ({method} returned {type(result).__name__!r})',
107 )
108 warnings.warn(msg, DeprecationWarning, stacklevel=4)
109
110 def _callTearDown(self):
111 self._callAsync(self.asyncTearDown)
112 self._asyncioTestContext.run(self.tearDown)
113
114 def _callCleanup(self, function, *args, **kwargs):
115 self._callMaybeAsync(function, *args, **kwargs)
116
117 def _callAsync(self, func, /, *args, **kwargs):
118 assert self._asyncioRunner is not None, 'asyncio runner is not initialized'
119 assert inspect.iscoroutinefunction(func), f'{func!r} is not an async function'
120 return self._asyncioRunner.run(
121 func(*args, **kwargs),
122 context=self._asyncioTestContext
123 )
124
125 def _callMaybeAsync(self, func, /, *args, **kwargs):
126 assert self._asyncioRunner is not None, 'asyncio runner is not initialized'
127 if inspect.iscoroutinefunction(func):
128 return self._asyncioRunner.run(
129 func(*args, **kwargs),
130 context=self._asyncioTestContext,
131 )
132 else:
133 return self._asyncioTestContext.run(func, *args, **kwargs)
134
135 def _setupAsyncioRunner(self):
136 assert self._asyncioRunner is None, 'asyncio runner is already initialized'
137 runner = asyncio.Runner(debug=True, loop_factory=self.loop_factory)
138 self._asyncioRunner = runner
139
140 def _tearDownAsyncioRunner(self):
141 runner = self._asyncioRunner
142 runner.close()
143
144 def run(self, result=None):
145 self._setupAsyncioRunner()
146 try:
147 return super().run(result)
148 finally:
149 self._tearDownAsyncioRunner()
150
151 def debug(self):
152 self._setupAsyncioRunner()
153 super().debug()
154 self._tearDownAsyncioRunner()
155
156 def __del__(self):
157 if self._asyncioRunner is not None:
158 self._tearDownAsyncioRunner()