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 raise TypeError(f"'{cls.__module__}.{cls.__qualname__}' object does "
79 f"not support the asynchronous context manager protocol"
80 ) from None
81 result = await enter(cm)
82 self.addAsyncCleanup(exit, cm, None, None, None)
83 return result
84
85 def _callSetUp(self):
86 # Force loop to be initialized and set as the current loop
87 # so that setUp functions can use get_event_loop() and get the
88 # correct loop instance.
89 self._asyncioRunner.get_loop()
90 self._asyncioTestContext.run(self.setUp)
91 self._callAsync(self.asyncSetUp)
92
93 def _callTestMethod(self, method):
94 if self._callMaybeAsync(method) is not None:
95 warnings.warn(f'It is deprecated to return a value that is not None from a '
96 f'test case ({method})', DeprecationWarning, stacklevel=4)
97
98 def _callTearDown(self):
99 self._callAsync(self.asyncTearDown)
100 self._asyncioTestContext.run(self.tearDown)
101
102 def _callCleanup(self, function, *args, **kwargs):
103 self._callMaybeAsync(function, *args, **kwargs)
104
105 def _callAsync(self, func, /, *args, **kwargs):
106 assert self._asyncioRunner is not None, 'asyncio runner is not initialized'
107 assert inspect.iscoroutinefunction(func), f'{func!r} is not an async function'
108 return self._asyncioRunner.run(
109 func(*args, **kwargs),
110 context=self._asyncioTestContext
111 )
112
113 def _callMaybeAsync(self, func, /, *args, **kwargs):
114 assert self._asyncioRunner is not None, 'asyncio runner is not initialized'
115 if inspect.iscoroutinefunction(func):
116 return self._asyncioRunner.run(
117 func(*args, **kwargs),
118 context=self._asyncioTestContext,
119 )
120 else:
121 return self._asyncioTestContext.run(func, *args, **kwargs)
122
123 def _setupAsyncioRunner(self):
124 assert self._asyncioRunner is None, 'asyncio runner is already initialized'
125 runner = asyncio.Runner(debug=True, loop_factory=self.loop_factory)
126 self._asyncioRunner = runner
127
128 def _tearDownAsyncioRunner(self):
129 runner = self._asyncioRunner
130 runner.close()
131
132 def run(self, result=None):
133 self._setupAsyncioRunner()
134 try:
135 return super().run(result)
136 finally:
137 self._tearDownAsyncioRunner()
138
139 def debug(self):
140 self._setupAsyncioRunner()
141 super().debug()
142 self._tearDownAsyncioRunner()
143
144 def __del__(self):
145 if self._asyncioRunner is not None:
146 self._tearDownAsyncioRunner()