Debian Codegraph @

tests/test_events.py

raw
1 import os
2 import sys
3 import pytest
4 import unittest
5
6 try:
7 if sys.platform != "win32":
8 try:
9 # cpython <= 3.13
10 from test.test_asyncio.test_events import (
11 UnixEventLoopTestsMixin as GLibEventLoopTestsMixin,
12 )
13 except:
14 # cpython >= 3.14
15 from test.test_asyncio.test_events import (
16 EventLoopTestsMixin as GLibEventLoopTestsMixin,
17 )
18 else:
19 from test.test_asyncio.test_events import EventLoopTestsMixin
20
21 # There is Mixin for the ProactorEventLoop, so copy the skips
22 class GLibEventLoopTestsMixin(EventLoopTestsMixin):
23 def test_reader_callback(self):
24 raise unittest.SkipTest("IocpEventLoop does not have add_reader()")
25
26 def test_reader_callback_cancel(self):
27 raise unittest.SkipTest("IocpEventLoop does not have add_reader()")
28
29 def test_writer_callback(self):
30 raise unittest.SkipTest("IocpEventLoop does not have add_writer()")
31
32 def test_writer_callback_cancel(self):
33 raise unittest.SkipTest("IocpEventLoop does not have add_writer()")
34
35 def test_remove_fds_after_closing(self):
36 raise unittest.SkipTest("IocpEventLoop does not have add_reader()")
37
38 from test.test_asyncio.test_subprocess import SubprocessMixin
39 from test.test_asyncio.utils import TestCase
40 except:
41 assert "CI" not in os.environ, "Could not find asyncio test suite in CI!"
42
43 class GLibEventLoopTestsMixin:
44 def test_unix_event_loop_tests_missing(self):
45 import warnings
46
47 warnings.warn("No EventLoopTestsMixin found, not running tests!")
48 self.skipTest("No EventLoopTestsMixin found, not running tests!")
49
50 class SubprocessMixin:
51 def test_subprocess_mixin_tests_missing(self):
52 import warnings
53
54 warnings.warn("SubprocessMixin is unavailable, not running tests!")
55 self.skipTest("SubprocessMixin is unavailable, not running tests!")
56
57 from unittest import TestCase
58
59 import gi
60 import gi.events
61 import asyncio
62 import signal
63 import socket
64 import threading
65 from gi.repository import GLib, Gio
66
67 try:
68 from gi.repository import Gtk
69 except ImportError:
70 Gtk = None
71
72
73 GTK4 = Gtk and Gtk._version == "4.0"
74
75
76 class GLibEventLoopTests(GLibEventLoopTestsMixin, TestCase):
77 def __init__(self, *args):
78 super().__init__(*args)
79 self.loop = None
80
81 def setUp(self):
82 # Ensure a previous test did not leave an event loop around
83 assert gi.events.GLibEventLoopPolicy._get_event_loop() is None, (
84 "A previous test appears to have left an EventLoop open"
85 )
86
87 super().setUp()
88
89 def _cleanup_glib_event_loop(self, loop):
90 if not loop.is_closed():
91 loop.close()
92 raise AssertionError("Loop was no closed by the test")
93
94 def create_event_loop(self):
95 loop = gi.events.GLibEventLoop(GLib.MainContext())
96
97 self.addCleanup(self._cleanup_glib_event_loop, loop)
98
99 return loop
100
101
102 class SubprocessWatcherTests(SubprocessMixin, TestCase):
103 def setUp(self):
104 super().setUp()
105 policy = gi.events.GLibEventLoopPolicy()
106 asyncio.set_event_loop_policy(policy)
107 self.loop = policy.get_event_loop()
108
109 def tearDown(self):
110 asyncio.set_event_loop_policy(None)
111 self.loop.close()
112 super().tearDown()
113
114 def test_subprocess_read_pipe_cancelled(self):
115 raise unittest.SkipTest(
116 "GLib event loop can not be run with plain asyncio.run()"
117 )
118
119 def test_subprocess_read_write_pipe_cancelled(self):
120 raise unittest.SkipTest(
121 "GLib event loop can not be run with plain asyncio.run()"
122 )
123
124 def test_subprocess_write_pipe_cancelled(self):
125 raise unittest.SkipTest(
126 "GLib event loop can not be run with plain asyncio.run()"
127 )
128
129
130 class GLibEventLoopPolicyTests(unittest.TestCase):
131 def create_policy(self):
132 return gi.events.GLibEventLoopPolicy()
133
134 def test_get_event_loop(self):
135 policy = self.create_policy()
136 loop = policy.get_event_loop()
137 self.assertIsInstance(loop, gi.events.GLibEventLoop)
138 self.assertIs(loop, policy.get_event_loop())
139 loop.close()
140
141 def test_new_event_loop(self):
142 policy = self.create_policy()
143 loop = policy.new_event_loop()
144 self.assertIsInstance(loop, gi.events.GLibEventLoop)
145 loop.close()
146
147 # Attaching a loop to the main thread fails
148 with self.assertRaises(RuntimeError):
149 policy.set_event_loop(loop)
150
151 def test_application(self):
152 task_completed = False
153
154 async def task():
155 nonlocal task_completed
156 await asyncio.sleep(1)
157 task_completed = True
158
159 def activate(app):
160 app.hold()
161 app.create_asyncio_task(task())
162 GLib.timeout_add(500, app.release)
163
164 app = Gio.Application()
165 app.connect("activate", activate)
166 with self.create_policy():
167 app.run()
168
169 self.assertTrue(task_completed)
170
171 def test_implicit_close(self):
172 """Verify that implicitly closing the EventLoop (from __del__) works."""
173 task_completed = False
174
175 async def task():
176 nonlocal task_completed
177 await asyncio.sleep(1)
178 task_completed = True
179
180 policy = self.create_policy()
181 loop = policy.new_event_loop()
182
183 loop.run_until_complete(task())
184
185 self.assertTrue(task_completed)
186
187 with pytest.warns(ResourceWarning, match="unclosed event loop"):
188 del loop
189
190 # For some reason, PyPy needs two collect() steps
191 import gc
192
193 gc.collect()
194 gc.collect()
195
196 def test_nested_context_iteration(self):
197 policy = self.create_policy()
198 loop = policy.new_event_loop()
199
200 called = False
201
202 def cb():
203 nonlocal called
204 called = True
205
206 async def run():
207 nonlocal loop, called
208
209 loop.call_soon(cb)
210 self.assertEqual(called, False)
211
212 # Iterating the main context does not cause cb to be called
213 while loop._context.iteration(False):
214 pass
215 self.assertEqual(called, False)
216
217 # Awaiting on anything *does* cause the cb to fire
218 await asyncio.sleep(0)
219 self.assertEqual(called, True)
220
221 loop.run_until_complete(run())
222 loop.close()
223
224 def test_thread_event_loop(self):
225 policy = self.create_policy()
226 loop = policy.new_event_loop()
227
228 res = []
229
230 def thread_func(res):
231 try:
232 # We cannot get an event loop for the current thread
233 with self.assertRaises(RuntimeError):
234 policy.get_event_loop()
235
236 # We can attach our loop
237 policy.set_event_loop(loop)
238 # Now we can get it, and it is the same
239 self.assertIs(policy.get_event_loop(), loop)
240
241 # Simple call_soon test
242 results = []
243
244 def callback(arg1, arg2):
245 results.append((arg1, arg2))
246 loop.stop()
247
248 loop.call_soon(callback, "hello", "world")
249 loop.run_forever()
250 self.assertEqual(results, [("hello", "world")])
251
252 # We can detach it again
253 policy.set_event_loop(None)
254
255 # Which means we have none and get a runtime error
256 with self.assertRaises(RuntimeError):
257 policy.get_event_loop()
258 except:
259 res += sys.exc_info()
260
261 # Initially, the thread has no event loop
262 thread = threading.Thread(target=lambda: thread_func(res))
263 thread.start()
264 thread.join()
265
266 if res:
267 t, v, tb = res
268 raise t(v).with_traceback(tb)
269
270 loop.close()
271
272 def test_outside_context_iteration(self):
273 """Iterating the main context from the outside, does not cause the
274 EventLoop to dispatch.
275 """
276 policy = self.create_policy()
277 loop = policy.new_event_loop()
278
279 called = False
280
281 def cb():
282 nonlocal called
283 called = True
284
285 loop.call_soon(cb)
286 while loop._context.iteration(False):
287 pass
288 loop.close()
289 self.assertEqual(called, False)
290
291 def test_inside_context_iteration(self):
292 """Iterating the main context from the inside, does not cause the
293 EventLoop to dispatch.
294 """
295 policy = self.create_policy()
296 loop = policy.get_event_loop()
297
298 done = asyncio.Future(loop=loop)
299
300 called = False
301
302 def cb():
303 nonlocal called
304 called = True
305
306 def ctx_iterate():
307 nonlocal called
308
309 loop.call_soon(cb)
310 while loop._context.iteration(False):
311 pass
312 self.assertEqual(called, False)
313
314 # If we by-pass the override, then the callback is called
315 while super(GLib.MainContext, loop._context).iteration(False):
316 pass
317 self.assertEqual(called, True)
318
319 # It'll also be called (again) before run_until_complete finishes
320 called = False
321 loop.call_soon(cb)
322
323 done.set_result(True)
324
325 return GLib.SOURCE_REMOVE
326
327 GLib.idle_add(ctx_iterate)
328 loop.run_until_complete(done)
329 loop.close()
330 self.assertEqual(called, True)
331
332 @unittest.skipUnless(Gtk, "no Gtk")
333 def test_recursive_stop(self):
334 """Calling stop() on the EventLoop will quit it, even if iteration
335 is done recursively.
336 """
337 policy = self.create_policy()
338 asyncio.set_event_loop_policy(policy)
339 self.addCleanup(asyncio.set_event_loop_policy, None)
340 loop = policy.get_event_loop()
341
342 if not GTK4:
343
344 def main_gtk():
345 GLib.idle_add(loop.stop)
346 Gtk.main()
347
348 GLib.idle_add(main_gtk)
349 Gtk.main()
350
351 def main_glib():
352 GLib.idle_add(loop.stop)
353 GLib.MainLoop().run()
354
355 GLib.idle_add(main_glib)
356 GLib.MainLoop().run()
357
358 loop.close()
359
360 def test_glib_task_prio(self):
361 """Check that we can set a task priority."""
362 policy = self.create_policy()
363 loop = policy.new_event_loop()
364
365 order = []
366
367 async def run_prio(priority):
368 # Note that asyncio.sleep(0) is a special case that not sleep
369 nonlocal order
370 await asyncio.sleep(0)
371 order.append(priority)
372 await asyncio.sleep(0)
373 order.append(priority)
374 await asyncio.sleep(0)
375 order.append(priority)
376
377 async def run():
378 t1 = asyncio.create_task(run_prio(GLib.PRIORITY_DEFAULT_IDLE))
379 t1.set_priority(GLib.PRIORITY_DEFAULT_IDLE)
380 t2 = asyncio.create_task(run_prio(GLib.PRIORITY_DEFAULT))
381 t2.set_priority(GLib.PRIORITY_DEFAULT)
382 t3 = asyncio.create_task(run_prio(GLib.PRIORITY_HIGH))
383 t3.set_priority(GLib.PRIORITY_HIGH)
384
385 pending = (t1, t2, t3)
386 while pending:
387 _, pending = await asyncio.wait(pending)
388
389 loop.run_until_complete(run())
390 loop.close()
391
392 # Check that the order was correct
393 self.assertEqual(
394 order,
395 [GLib.PRIORITY_HIGH] * 3
396 + [GLib.PRIORITY_DEFAULT] * 3
397 + [GLib.PRIORITY_DEFAULT_IDLE] * 3,
398 )
399
400 @unittest.skipIf(sys.platform == "win32", "add reader/writer not implemented")
401 def test_source_fileobj_fd(self):
402 """Regression test for
403 https://gitlab.gnome.org/GNOME/pygobject/-/issues/689
404 """
405
406 class Echo:
407 def __init__(self, sock, expect_bytes):
408 self.sock = sock
409 self.sent_bytes = 0
410 self.expect_bytes = expect_bytes
411 self.done = asyncio.Future()
412 self.data = b""
413
414 def send(self):
415 if self.done.done():
416 return
417 if self.sent_bytes < len(self.data):
418 self.sent_bytes += self.sock.send(self.data[self.sent_bytes :])
419 if self.sent_bytes >= self.expect_bytes:
420 self.done.set_result(None)
421 self.sock.shutdown(socket.SHUT_WR)
422
423 def recv(self):
424 if self.done.done():
425 return
426 self.data += self.sock.recv(self.expect_bytes)
427 if len(self.data) >= self.expect_bytes:
428 self.sock.shutdown(socket.SHUT_RD)
429
430 async def run():
431 loop = asyncio.get_running_loop()
432 s1, s2 = socket.socketpair()
433 sample = b"Hello!"
434 e = Echo(s1, len(sample))
435 # register using file object and file descriptor
436 loop.add_reader(s1, e.recv)
437 loop.add_writer(s1.fileno(), e.send)
438 s2.sendall(sample)
439 await asyncio.wait_for(e.done, timeout=2.0)
440 echo = b""
441 for _ in range(len(sample)):
442 echo += s2.recv(len(sample))
443 if len(echo) == len(sample):
444 break
445 # remove using file object and file descriptor
446 loop.remove_reader(s1)
447 loop.remove_writer(s1.fileno())
448 s1.close()
449 s2.close()
450 # check if the data was echoed correctly
451 self.assertEqual(sample, echo)
452
453 policy = self.create_policy()
454 loop = policy.get_event_loop()
455 loop.run_until_complete(run())
456 loop.close()
457
458 @unittest.skipIf(
459 sys.version_info < (3, 12),
460 "Older python versions do not have the loop_factory parameter",
461 )
462 def test_asyncio_run(self):
463 coro_state = 0
464
465 async def coro():
466 nonlocal coro_state
467 coro_state = 1
468
469 await asyncio.sleep(1)
470 coro_state = 2
471
472 # asyncio.run registered a SIGINT handler to quit
473 if sys.platform == "win32":
474 signal.raise_signal(signal.SIGINT)
475 else:
476 os.kill(os.getpid(), signal.SIGINT)
477
478 # The signal is processed when we return to the mainloop
479 await asyncio.sleep(0)
480 coro_state = 3
481
482 with self.assertRaises(KeyboardInterrupt):
483 asyncio.run(coro(), loop_factory=gi.events.GLibEventLoop)
484
485 # This works fine a second time as the first loop is unregistered (and closed)
486 with self.assertRaises(KeyboardInterrupt):
487 asyncio.run(coro(), loop_factory=gi.events.GLibEventLoop)
488
489 self.assertEqual(coro_state, 2)
490
491 def test_eventloop_context(self):
492 # Main thread has only the implicit default main context
493 self.assertIsNone(GLib.MainContext.get_thread_default())
494
495 loop = gi.events.GLibEventLoop(main_context=GLib.MainContext())
496
497 def check_loop_cannot_run(check_loop):
498 with self.assertRaises(RuntimeError), check_loop:
499 pass
500
501 with self.assertRaises(RuntimeError):
502 future = loop_samectx.create_future()
503 future.set_result(True)
504 loop_samectx.run_until_complete(future)
505
506 def check_loop_can_run(check_loop):
507 with check_loop:
508 pass
509
510 future = loop_samectx.create_future()
511 future.set_result(True)
512 loop_samectx.run_until_complete(future)
513
514 with loop:
515 # Entering the context manager sets the thread default
516 self.assertEqual(
517 hash(loop._context), hash(GLib.MainContext.get_thread_default())
518 )
519
520 loop_samectx = gi.events.GLibEventLoop()
521 self.assertEqual(hash(loop._context), hash(loop_samectx._context))
522 check_loop_cannot_run(loop_samectx)
523
524 # We can do the same excercise with another main context
525 loop_otherctx = gi.events.GLibEventLoop(GLib.MainContext())
526 check_loop_cannot_run(loop_otherctx)
527
528 # But, once we are outside it works fine.
529 check_loop_can_run(loop_samectx)
530 check_loop_can_run(loop_otherctx)