Debian Codegraph @

Lib/test/test_asyncio/test_eager_task_factory.py

raw
1 """Tests for base_events.py"""
2
3 import asyncio
4 import contextvars
5 import unittest
6
7 from unittest import mock
8 from asyncio import tasks
9 from test.test_asyncio import utils as test_utils
10 from test.support.script_helper import assert_python_ok
11
12 MOCK_ANY = mock.ANY
13
14
15 def tearDownModule():
16 asyncio.set_event_loop_policy(None)
17
18
19 class EagerTaskFactoryLoopTests:
20
21 Task = None
22
23 def run_coro(self, coro):
24 """
25 Helper method to run the `coro` coroutine in the test event loop.
26 It helps with making sure the event loop is running before starting
27 to execute `coro`. This is important for testing the eager step
28 functionality, since an eager step is taken only if the event loop
29 is already running.
30 """
31
32 async def coro_runner():
33 self.assertTrue(asyncio.get_event_loop().is_running())
34 return await coro
35
36 return self.loop.run_until_complete(coro)
37
38 def setUp(self):
39 super().setUp()
40 self.loop = asyncio.new_event_loop()
41 self.eager_task_factory = asyncio.create_eager_task_factory(self.Task)
42 self.loop.set_task_factory(self.eager_task_factory)
43 self.set_event_loop(self.loop)
44
45 def test_eager_task_factory_set(self):
46 self.assertIsNotNone(self.eager_task_factory)
47 self.assertIs(self.loop.get_task_factory(), self.eager_task_factory)
48
49 async def noop(): pass
50
51 async def run():
52 t = self.loop.create_task(noop())
53 self.assertIsInstance(t, self.Task)
54 await t
55
56 self.run_coro(run())
57
58 def test_await_future_during_eager_step(self):
59
60 async def set_result(fut, val):
61 fut.set_result(val)
62
63 async def run():
64 fut = self.loop.create_future()
65 t = self.loop.create_task(set_result(fut, 'my message'))
66 # assert the eager step completed the task
67 self.assertTrue(t.done())
68 return await fut
69
70 self.assertEqual(self.run_coro(run()), 'my message')
71
72 def test_eager_completion(self):
73
74 async def coro():
75 return 'hello'
76
77 async def run():
78 t = self.loop.create_task(coro())
79 # assert the eager step completed the task
80 self.assertTrue(t.done())
81 return await t
82
83 self.assertEqual(self.run_coro(run()), 'hello')
84
85 def test_block_after_eager_step(self):
86
87 async def coro():
88 await asyncio.sleep(0.1)
89 return 'finished after blocking'
90
91 async def run():
92 t = self.loop.create_task(coro())
93 self.assertFalse(t.done())
94 result = await t
95 self.assertTrue(t.done())
96 return result
97
98 self.assertEqual(self.run_coro(run()), 'finished after blocking')
99
100 def test_cancellation_after_eager_completion(self):
101
102 async def coro():
103 return 'finished without blocking'
104
105 async def run():
106 t = self.loop.create_task(coro())
107 t.cancel()
108 result = await t
109 # finished task can't be cancelled
110 self.assertFalse(t.cancelled())
111 return result
112
113 self.assertEqual(self.run_coro(run()), 'finished without blocking')
114
115 def test_cancellation_after_eager_step_blocks(self):
116
117 async def coro():
118 await asyncio.sleep(0.1)
119 return 'finished after blocking'
120
121 async def run():
122 t = self.loop.create_task(coro())
123 t.cancel('cancellation message')
124 self.assertGreater(t.cancelling(), 0)
125 result = await t
126
127 with self.assertRaises(asyncio.CancelledError) as cm:
128 self.run_coro(run())
129
130 self.assertEqual('cancellation message', cm.exception.args[0])
131
132 def test_current_task(self):
133 captured_current_task = None
134
135 async def coro():
136 nonlocal captured_current_task
137 captured_current_task = asyncio.current_task()
138 # verify the task before and after blocking is identical
139 await asyncio.sleep(0.1)
140 self.assertIs(asyncio.current_task(), captured_current_task)
141
142 async def run():
143 t = self.loop.create_task(coro())
144 self.assertIs(captured_current_task, t)
145 await t
146
147 self.run_coro(run())
148 captured_current_task = None
149
150 def test_all_tasks_with_eager_completion(self):
151 captured_all_tasks = None
152
153 async def coro():
154 nonlocal captured_all_tasks
155 captured_all_tasks = asyncio.all_tasks()
156
157 async def run():
158 t = self.loop.create_task(coro())
159 self.assertIn(t, captured_all_tasks)
160 self.assertNotIn(t, asyncio.all_tasks())
161
162 self.run_coro(run())
163
164 def test_all_tasks_with_blocking(self):
165 captured_eager_all_tasks = None
166
167 async def coro(fut1, fut2):
168 nonlocal captured_eager_all_tasks
169 captured_eager_all_tasks = asyncio.all_tasks()
170 await fut1
171 fut2.set_result(None)
172
173 async def run():
174 fut1 = self.loop.create_future()
175 fut2 = self.loop.create_future()
176 t = self.loop.create_task(coro(fut1, fut2))
177 self.assertIn(t, captured_eager_all_tasks)
178 self.assertIn(t, asyncio.all_tasks())
179 fut1.set_result(None)
180 await fut2
181 self.assertNotIn(t, asyncio.all_tasks())
182
183 self.run_coro(run())
184
185 def test_context_vars(self):
186 cv = contextvars.ContextVar('cv', default=0)
187
188 coro_first_step_ran = False
189 coro_second_step_ran = False
190
191 async def coro():
192 nonlocal coro_first_step_ran
193 nonlocal coro_second_step_ran
194 self.assertEqual(cv.get(), 1)
195 cv.set(2)
196 self.assertEqual(cv.get(), 2)
197 coro_first_step_ran = True
198 await asyncio.sleep(0.1)
199 self.assertEqual(cv.get(), 2)
200 cv.set(3)
201 self.assertEqual(cv.get(), 3)
202 coro_second_step_ran = True
203
204 async def run():
205 cv.set(1)
206 t = self.loop.create_task(coro())
207 self.assertTrue(coro_first_step_ran)
208 self.assertFalse(coro_second_step_ran)
209 self.assertEqual(cv.get(), 1)
210 await t
211 self.assertTrue(coro_second_step_ran)
212 self.assertEqual(cv.get(), 1)
213
214 self.run_coro(run())
215
216 def test_staggered_race_with_eager_tasks(self):
217 # See https://github.com/python/cpython/issues/124309
218
219 async def fail():
220 await asyncio.sleep(0)
221 raise ValueError("no good")
222
223 async def blocked():
224 fut = asyncio.Future()
225 await fut
226
227 async def run():
228 winner, index, excs = await asyncio.staggered.staggered_race(
229 [
230 lambda: blocked(),
231 lambda: asyncio.sleep(1, result="sleep1"),
232 lambda: fail()
233 ],
234 delay=0.25
235 )
236 self.assertEqual(winner, 'sleep1')
237 self.assertEqual(index, 1)
238 self.assertIsNone(excs[index])
239 self.assertIsInstance(excs[0], asyncio.CancelledError)
240 self.assertIsInstance(excs[2], ValueError)
241
242 self.run_coro(run())
243
244 def test_staggered_race_with_eager_tasks_no_delay(self):
245 # See https://github.com/python/cpython/issues/124309
246 async def fail():
247 raise ValueError("no good")
248
249 async def run():
250 winner, index, excs = await asyncio.staggered.staggered_race(
251 [
252 lambda: fail(),
253 lambda: asyncio.sleep(1, result="sleep1"),
254 lambda: asyncio.sleep(0, result="sleep0"),
255 ],
256 delay=None
257 )
258 self.assertEqual(winner, 'sleep1')
259 self.assertEqual(index, 1)
260 self.assertIsNone(excs[index])
261 self.assertIsInstance(excs[0], ValueError)
262 self.assertEqual(len(excs), 2)
263
264 self.run_coro(run())
265
266
267 class PyEagerTaskFactoryLoopTests(EagerTaskFactoryLoopTests, test_utils.TestCase):
268 Task = tasks._PyTask
269
270
271 @unittest.skipUnless(hasattr(tasks, '_CTask'),
272 'requires the C _asyncio module')
273 class CEagerTaskFactoryLoopTests(EagerTaskFactoryLoopTests, test_utils.TestCase):
274 Task = getattr(tasks, '_CTask', None)
275
276 def test_issue105987(self):
277 code = """if 1:
278 from _asyncio import _swap_current_task
279
280 class DummyTask:
281 pass
282
283 class DummyLoop:
284 pass
285
286 l = DummyLoop()
287 _swap_current_task(l, DummyTask())
288 t = _swap_current_task(l, None)
289 """
290
291 _, out, err = assert_python_ok("-c", code)
292 self.assertFalse(err)
293
294 def test_issue122332(self):
295 async def coro():
296 pass
297
298 async def run():
299 task = self.loop.create_task(coro())
300 await task
301 self.assertIsNone(task.get_coro())
302
303 self.run_coro(run())
304
305 def test_name(self):
306 name = None
307 async def coro():
308 nonlocal name
309 name = asyncio.current_task().get_name()
310
311 async def main():
312 task = self.loop.create_task(coro(), name="test name")
313 self.assertEqual(name, "test name")
314 await task
315
316 self.run_coro(coro())
317
318 class AsyncTaskCounter:
319 def __init__(self, loop, *, task_class, eager):
320 self.suspense_count = 0
321 self.task_count = 0
322
323 def CountingTask(*args, eager_start=False, **kwargs):
324 if not eager_start:
325 self.task_count += 1
326 kwargs["eager_start"] = eager_start
327 return task_class(*args, **kwargs)
328
329 if eager:
330 factory = asyncio.create_eager_task_factory(CountingTask)
331 else:
332 def factory(loop, coro, **kwargs):
333 return CountingTask(coro, loop=loop, **kwargs)
334 loop.set_task_factory(factory)
335
336 def get(self):
337 return self.task_count
338
339
340 async def awaitable_chain(depth):
341 if depth == 0:
342 return 0
343 return 1 + await awaitable_chain(depth - 1)
344
345
346 async def recursive_taskgroups(width, depth):
347 if depth == 0:
348 return
349
350 async with asyncio.TaskGroup() as tg:
351 futures = [
352 tg.create_task(recursive_taskgroups(width, depth - 1))
353 for _ in range(width)
354 ]
355
356
357 async def recursive_gather(width, depth):
358 if depth == 0:
359 return
360
361 await asyncio.gather(
362 *[recursive_gather(width, depth - 1) for _ in range(width)]
363 )
364
365
366 class BaseTaskCountingTests:
367
368 Task = None
369 eager = None
370 expected_task_count = None
371
372 def setUp(self):
373 super().setUp()
374 self.loop = asyncio.new_event_loop()
375 self.counter = AsyncTaskCounter(self.loop, task_class=self.Task, eager=self.eager)
376 self.set_event_loop(self.loop)
377
378 def test_awaitables_chain(self):
379 observed_depth = self.loop.run_until_complete(awaitable_chain(100))
380 self.assertEqual(observed_depth, 100)
381 self.assertEqual(self.counter.get(), 0 if self.eager else 1)
382
383 def test_recursive_taskgroups(self):
384 num_tasks = self.loop.run_until_complete(recursive_taskgroups(5, 4))
385 self.assertEqual(self.counter.get(), self.expected_task_count)
386
387 def test_recursive_gather(self):
388 self.loop.run_until_complete(recursive_gather(5, 4))
389 self.assertEqual(self.counter.get(), self.expected_task_count)
390
391
392 class BaseNonEagerTaskFactoryTests(BaseTaskCountingTests):
393 eager = False
394 expected_task_count = 781 # 1 + 5 + 5^2 + 5^3 + 5^4
395
396
397 class BaseEagerTaskFactoryTests(BaseTaskCountingTests):
398 eager = True
399 expected_task_count = 0
400
401
402 class NonEagerTests(BaseNonEagerTaskFactoryTests, test_utils.TestCase):
403 Task = asyncio.Task
404
405
406 class EagerTests(BaseEagerTaskFactoryTests, test_utils.TestCase):
407 Task = asyncio.Task
408
409
410 class NonEagerPyTaskTests(BaseNonEagerTaskFactoryTests, test_utils.TestCase):
411 Task = tasks._PyTask
412
413
414 class EagerPyTaskTests(BaseEagerTaskFactoryTests, test_utils.TestCase):
415 Task = tasks._PyTask
416
417
418 @unittest.skipUnless(hasattr(tasks, '_CTask'),
419 'requires the C _asyncio module')
420 class NonEagerCTaskTests(BaseNonEagerTaskFactoryTests, test_utils.TestCase):
421 Task = getattr(tasks, '_CTask', None)
422
423
424 @unittest.skipUnless(hasattr(tasks, '_CTask'),
425 'requires the C _asyncio module')
426 class EagerCTaskTests(BaseEagerTaskFactoryTests, test_utils.TestCase):
427 Task = getattr(tasks, '_CTask', None)
428
429 if __name__ == '__main__':
430 unittest.main()