Debian Codegraph @

lib-python/3/test/test_asyncio/test_runners.py

raw symbols SCIP
1 import _thread
2 import asyncio
3 import contextvars
4 import gc
5 import re
6 import signal
7 import threading
8 import unittest
9 from test.test_asyncio import utils as test_utils
10 from unittest import mock
11 from unittest.mock import patch
12 from test import support
13
14
15 def tearDownModule():
16 asyncio.set_event_loop_policy(None)
17
18
19 def interrupt_self():
20 _thread.interrupt_main()
21
22
23 class TestPolicy(asyncio.AbstractEventLoopPolicy):
24
25 def __init__(self, loop_factory):
26 self.loop_factory = loop_factory
27 self.loop = None
28
29 def get_event_loop(self):
30 # shouldn't ever be called by asyncio.run()
31 raise RuntimeError
32
33 def new_event_loop(self):
34 return self.loop_factory()
35
36 def set_event_loop(self, loop):
37 if loop is not None:
38 # we want to check if the loop is closed
39 # in BaseTest.tearDown
40 self.loop = loop
41
42
43 class BaseTest(unittest.TestCase):
44
45 def new_loop(self):
46 loop = asyncio.BaseEventLoop()
47 loop._process_events = mock.Mock()
48 # Mock waking event loop from select
49 loop._write_to_self = mock.Mock()
50 loop._write_to_self.return_value = None
51 loop._selector = mock.Mock()
52 loop._selector.select.return_value = ()
53 loop.shutdown_ag_run = False
54
55 async def shutdown_asyncgens():
56 loop.shutdown_ag_run = True
57 loop.shutdown_asyncgens = shutdown_asyncgens
58
59 return loop
60
61 def setUp(self):
62 super().setUp()
63
64 policy = TestPolicy(self.new_loop)
65 asyncio.set_event_loop_policy(policy)
66
67 def tearDown(self):
68 policy = asyncio.get_event_loop_policy()
69 if policy.loop is not None:
70 self.assertTrue(policy.loop.is_closed())
71 self.assertTrue(policy.loop.shutdown_ag_run)
72
73 asyncio.set_event_loop_policy(None)
74 super().tearDown()
75
76
77 class RunTests(BaseTest):
78
79 def test_asyncio_run_return(self):
80 async def main():
81 await asyncio.sleep(0)
82 return 42
83
84 self.assertEqual(asyncio.run(main()), 42)
85
86 def test_asyncio_run_raises(self):
87 async def main():
88 await asyncio.sleep(0)
89 raise ValueError('spam')
90
91 with self.assertRaisesRegex(ValueError, 'spam'):
92 asyncio.run(main())
93
94 def test_asyncio_run_only_coro(self):
95 for o in {1, lambda: None}:
96 with self.subTest(obj=o), \
97 self.assertRaisesRegex(ValueError,
98 'a coroutine was expected'):
99 asyncio.run(o)
100
101 def test_asyncio_run_debug(self):
102 async def main(expected):
103 loop = asyncio.get_event_loop()
104 self.assertIs(loop.get_debug(), expected)
105
106 asyncio.run(main(False), debug=False)
107 asyncio.run(main(True), debug=True)
108 with mock.patch('asyncio.coroutines._is_debug_mode', lambda: True):
109 asyncio.run(main(True))
110 asyncio.run(main(False), debug=False)
111 with mock.patch('asyncio.coroutines._is_debug_mode', lambda: False):
112 asyncio.run(main(True), debug=True)
113 asyncio.run(main(False))
114
115 def test_asyncio_run_from_running_loop(self):
116 async def main():
117 coro = main()
118 try:
119 asyncio.run(coro)
120 finally:
121 coro.close() # Suppress ResourceWarning
122
123 with self.assertRaisesRegex(RuntimeError,
124 'cannot be called from a running'):
125 asyncio.run(main())
126
127 def test_asyncio_run_cancels_hanging_tasks(self):
128 lo_task = None
129
130 async def leftover():
131 await asyncio.sleep(0.1)
132
133 async def main():
134 nonlocal lo_task
135 lo_task = asyncio.create_task(leftover())
136 return 123
137
138 self.assertEqual(asyncio.run(main()), 123)
139 self.assertTrue(lo_task.done())
140
141 def test_asyncio_run_reports_hanging_tasks_errors(self):
142 lo_task = None
143 call_exc_handler_mock = mock.Mock()
144
145 async def leftover():
146 try:
147 await asyncio.sleep(0.1)
148 except asyncio.CancelledError:
149 1 / 0
150
151 async def main():
152 loop = asyncio.get_running_loop()
153 loop.call_exception_handler = call_exc_handler_mock
154
155 nonlocal lo_task
156 lo_task = asyncio.create_task(leftover())
157 return 123
158
159 self.assertEqual(asyncio.run(main()), 123)
160 self.assertTrue(lo_task.done())
161
162 call_exc_handler_mock.assert_called_with({
163 'message': test_utils.MockPattern(r'asyncio.run.*shutdown'),
164 'task': lo_task,
165 'exception': test_utils.MockInstanceOf(ZeroDivisionError)
166 })
167
168 def test_asyncio_run_closes_gens_after_hanging_tasks_errors(self):
169 spinner = None
170 lazyboy = None
171
172 class FancyExit(Exception):
173 pass
174
175 async def fidget():
176 while True:
177 yield 1
178 await asyncio.sleep(1)
179
180 async def spin():
181 nonlocal spinner
182 spinner = fidget()
183 try:
184 async for the_meaning_of_life in spinner: # NoQA
185 pass
186 except asyncio.CancelledError:
187 1 / 0
188
189 async def main():
190 loop = asyncio.get_running_loop()
191 loop.call_exception_handler = mock.Mock()
192
193 nonlocal lazyboy
194 lazyboy = asyncio.create_task(spin())
195 raise FancyExit
196
197 with self.assertRaises(FancyExit):
198 asyncio.run(main())
199
200 self.assertTrue(lazyboy.done())
201
202 self.assertIsNone(spinner.ag_frame)
203 self.assertFalse(spinner.ag_running)
204
205 def test_asyncio_run_set_event_loop(self):
206 #See https://github.com/python/cpython/issues/93896
207
208 async def main():
209 await asyncio.sleep(0)
210 return 42
211
212 policy = asyncio.get_event_loop_policy()
213 policy.set_event_loop = mock.Mock()
214 asyncio.run(main())
215 self.assertTrue(policy.set_event_loop.called)
216
217 def test_asyncio_run_without_uncancel(self):
218 # See https://github.com/python/cpython/issues/95097
219 class Task:
220 def __init__(self, loop, coro, **kwargs):
221 self._task = asyncio.Task(coro, loop=loop, **kwargs)
222
223 def cancel(self, *args, **kwargs):
224 return self._task.cancel(*args, **kwargs)
225
226 def add_done_callback(self, *args, **kwargs):
227 return self._task.add_done_callback(*args, **kwargs)
228
229 def remove_done_callback(self, *args, **kwargs):
230 return self._task.remove_done_callback(*args, **kwargs)
231
232 @property
233 def _asyncio_future_blocking(self):
234 return self._task._asyncio_future_blocking
235
236 def result(self, *args, **kwargs):
237 return self._task.result(*args, **kwargs)
238
239 def done(self, *args, **kwargs):
240 return self._task.done(*args, **kwargs)
241
242 def cancelled(self, *args, **kwargs):
243 return self._task.cancelled(*args, **kwargs)
244
245 def exception(self, *args, **kwargs):
246 return self._task.exception(*args, **kwargs)
247
248 def get_loop(self, *args, **kwargs):
249 return self._task.get_loop(*args, **kwargs)
250
251
252 async def main():
253 interrupt_self()
254 await asyncio.Event().wait()
255
256 def new_event_loop():
257 loop = self.new_loop()
258 loop.set_task_factory(Task)
259 return loop
260
261 asyncio.set_event_loop_policy(TestPolicy(new_event_loop))
262 with self.assertRaises(asyncio.CancelledError):
263 asyncio.run(main())
264
265
266 class RunnerTests(BaseTest):
267
268 def test_non_debug(self):
269 with asyncio.Runner(debug=False) as runner:
270 self.assertFalse(runner.get_loop().get_debug())
271
272 def test_debug(self):
273 with asyncio.Runner(debug=True) as runner:
274 self.assertTrue(runner.get_loop().get_debug())
275
276 def test_custom_factory(self):
277 loop = mock.Mock()
278 with asyncio.Runner(loop_factory=lambda: loop) as runner:
279 self.assertIs(runner.get_loop(), loop)
280
281 def test_run(self):
282 async def f():
283 await asyncio.sleep(0)
284 return 'done'
285
286 with asyncio.Runner() as runner:
287 self.assertEqual('done', runner.run(f()))
288 loop = runner.get_loop()
289
290 with self.assertRaisesRegex(
291 RuntimeError,
292 "Runner is closed"
293 ):
294 runner.get_loop()
295
296 self.assertTrue(loop.is_closed())
297
298 def test_run_non_coro(self):
299 with asyncio.Runner() as runner:
300 with self.assertRaisesRegex(
301 ValueError,
302 "a coroutine was expected"
303 ):
304 runner.run(123)
305
306 def test_run_future(self):
307 with asyncio.Runner() as runner:
308 with self.assertRaisesRegex(
309 ValueError,
310 "a coroutine was expected"
311 ):
312 fut = runner.get_loop().create_future()
313 runner.run(fut)
314
315 def test_explicit_close(self):
316 runner = asyncio.Runner()
317 loop = runner.get_loop()
318 runner.close()
319 with self.assertRaisesRegex(
320 RuntimeError,
321 "Runner is closed"
322 ):
323 runner.get_loop()
324
325 self.assertTrue(loop.is_closed())
326
327 def test_double_close(self):
328 runner = asyncio.Runner()
329 loop = runner.get_loop()
330
331 runner.close()
332 self.assertTrue(loop.is_closed())
333
334 # the second call is no-op
335 runner.close()
336 self.assertTrue(loop.is_closed())
337
338 def test_second_with_block_raises(self):
339 ret = []
340
341 async def f(arg):
342 ret.append(arg)
343
344 runner = asyncio.Runner()
345 with runner:
346 runner.run(f(1))
347
348 with self.assertRaisesRegex(
349 RuntimeError,
350 "Runner is closed"
351 ):
352 with runner:
353 runner.run(f(2))
354
355 self.assertEqual([1], ret)
356
357 def test_run_keeps_context(self):
358 cvar = contextvars.ContextVar("cvar", default=-1)
359
360 async def f(val):
361 old = cvar.get()
362 await asyncio.sleep(0)
363 cvar.set(val)
364 return old
365
366 async def get_context():
367 return contextvars.copy_context()
368
369 with asyncio.Runner() as runner:
370 self.assertEqual(-1, runner.run(f(1)))
371 self.assertEqual(1, runner.run(f(2)))
372
373 self.assertEqual(2, runner.run(get_context()).get(cvar))
374
375 def test_recursive_run(self):
376 async def g():
377 pass
378
379 async def f():
380 runner.run(g())
381
382 with asyncio.Runner() as runner:
383 with self.assertWarnsRegex(
384 RuntimeWarning,
385 "coroutine .+ was never awaited",
386 ):
387 with self.assertRaisesRegex(
388 RuntimeError,
389 re.escape(
390 "Runner.run() cannot be called from a running event loop"
391 ),
392 ):
393 runner.run(f())
394 # PYPY: add gc.collect
395 support.gc_collect()
396
397 def test_interrupt_call_soon(self):
398 # The only case when task is not suspended by waiting a future
399 # or another task
400 assert threading.current_thread() is threading.main_thread()
401
402 async def coro():
403 with self.assertRaises(asyncio.CancelledError):
404 while True:
405 await asyncio.sleep(0)
406 raise asyncio.CancelledError()
407
408 with asyncio.Runner() as runner:
409 runner.get_loop().call_later(0.1, interrupt_self)
410 with self.assertRaises(KeyboardInterrupt):
411 runner.run(coro())
412
413 def test_interrupt_wait(self):
414 # interrupting when waiting a future cancels both future and main task
415 assert threading.current_thread() is threading.main_thread()
416
417 async def coro(fut):
418 with self.assertRaises(asyncio.CancelledError):
419 await fut
420 raise asyncio.CancelledError()
421
422 with asyncio.Runner() as runner:
423 fut = runner.get_loop().create_future()
424 runner.get_loop().call_later(0.1, interrupt_self)
425
426 with self.assertRaises(KeyboardInterrupt):
427 runner.run(coro(fut))
428
429 self.assertTrue(fut.cancelled())
430
431 def test_interrupt_cancelled_task(self):
432 # interrupting cancelled main task doesn't raise KeyboardInterrupt
433 assert threading.current_thread() is threading.main_thread()
434
435 async def subtask(task):
436 await asyncio.sleep(0)
437 task.cancel()
438 interrupt_self()
439
440 async def coro():
441 asyncio.create_task(subtask(asyncio.current_task()))
442 await asyncio.sleep(10)
443
444 with asyncio.Runner() as runner:
445 with self.assertRaises(asyncio.CancelledError):
446 runner.run(coro())
447
448 def test_signal_install_not_supported_ok(self):
449 # signal.signal() can throw if the "main thread" doensn't have signals enabled
450 assert threading.current_thread() is threading.main_thread()
451
452 async def coro():
453 pass
454
455 with asyncio.Runner() as runner:
456 with patch.object(
457 signal,
458 "signal",
459 side_effect=ValueError(
460 "signal only works in main thread of the main interpreter"
461 )
462 ):
463 runner.run(coro())
464
465 def test_set_event_loop_called_once(self):
466 # See https://github.com/python/cpython/issues/95736
467 async def coro():
468 pass
469
470 policy = asyncio.get_event_loop_policy()
471 policy.set_event_loop = mock.Mock()
472 runner = asyncio.Runner()
473 runner.run(coro())
474 runner.run(coro())
475
476 self.assertEqual(1, policy.set_event_loop.call_count)
477 runner.close()
478
479 def test_no_repr_is_call_on_the_task_result(self):
480 # See https://github.com/python/cpython/issues/112559.
481 class MyResult:
482 def __init__(self):
483 self.repr_count = 0
484 def __repr__(self):
485 self.repr_count += 1
486 return super().__repr__()
487
488 async def coro():
489 return MyResult()
490
491
492 with asyncio.Runner() as runner:
493 result = runner.run(coro())
494
495 self.assertEqual(0, result.repr_count)
496
497
498 if __name__ == '__main__':
499 unittest.main()