Debian Codegraph @

tests/test_async.py

raw
1 import sys
2 import pytest
3 import platform
4 import unittest
5
6 import asyncio
7 from gi.repository import GLib, Gio
8 from gi.events import GLibEventLoopPolicy
9
10
11 class TestAsync(unittest.TestCase):
12 def setUp(self):
13 policy = GLibEventLoopPolicy()
14 asyncio.set_event_loop_policy(policy)
15 self.addCleanup(asyncio.set_event_loop_policy, None)
16 self.loop = policy.get_event_loop()
17 self.addCleanup(self.loop.close)
18
19 def test_async_enumerate(self):
20 f = Gio.file_new_for_path("./")
21
22 called = False
23
24 def cb():
25 nonlocal called
26 called = True
27
28 async def run():
29 nonlocal called, self
30
31 self.loop.call_soon(cb)
32
33 iter_info = [
34 info.get_name()
35 for info in await f.enumerate_children_async(
36 "standard::*", 0, GLib.PRIORITY_DEFAULT
37 )
38 ]
39
40 # The await runs the mainloop and cb is called.
41 self.assertEqual(called, True)
42
43 next_info = []
44 enumerator = f.enumerate_children("standard::*", 0, None)
45 while True:
46 info = enumerator.next_file(None)
47 if info is None:
48 break
49 next_info.append(info.get_name())
50
51 self.assertEqual(iter_info, next_info)
52
53 self.loop.run_until_complete(run())
54
55 def test_async_cancellation(self):
56 """Cancellation raises G_IO_ERROR_CANCELLED."""
57 f = Gio.file_new_for_path("./")
58
59 async def run():
60 nonlocal self
61
62 # cancellable created implicitly
63 res = f.enumerate_children_async("standard::*", 0, GLib.PRIORITY_DEFAULT)
64 res.cancel()
65 with self.assertRaisesRegex(GLib.GError, "Operation was cancelled"):
66 await res
67
68 # cancellable passed explicitly
69 cancel = Gio.Cancellable()
70 res = f.enumerate_children_async(
71 "standard::*", 0, GLib.PRIORITY_DEFAULT, cancel
72 )
73 self.assertEqual(res.cancellable, cancel)
74 cancel.cancel()
75 with self.assertRaisesRegex(GLib.GError, "Operation was cancelled"):
76 await res
77
78 self.loop.run_until_complete(run())
79
80 def test_cancel_async_task(self):
81 # Regression test for https://gitlab.gnome.org/GNOME/pygobject/-/issues/755
82 async def _long_task(proc):
83 await proc.wait_async()
84
85 async def run():
86 nonlocal self
87
88 # Create a process which waits for input on stdin, without ever
89 # actually providing any such input. This process won't exit unless
90 # we explicitly kill it.
91 flags = (
92 Gio.SubprocessFlags.STDOUT_SILENCE
93 | Gio.SubprocessFlags.STDERR_SILENCE
94 | Gio.SubprocessFlags.STDIN_PIPE
95 )
96 proc = Gio.Subprocess.new([sys.executable], flags)
97
98 try:
99 # Create a task which waits for said process to exit; but since
100 # the process won't actually do so we've created a task which
101 # indefinitely awaits on a Gio cancellable.
102 res = asyncio.create_task(_long_task(proc))
103 # Briefly yield control to make sure the task we just created
104 # starts running on the loop and polls on a Gio task.
105 await asyncio.sleep(0.1)
106 # Now cancel the task while it's awaiting on a Gio task; this
107 # will now hit the async_cancel implementation on the C side.
108 #
109 # Also, explicitly assert that the task was really cancelled
110 # (.cancel() returns True), and hasn't already finished by this
111 # time (.cancel() returns False). This makes sure that we're
112 # really testing the cancellation here.
113 assert res.cancel(), "Test invalid, task already finished"
114 finally:
115 proc.force_exit()
116
117 self.loop.run_until_complete(run())
118
119 def test_async_task_cancellation(self):
120 """Cancellation works on wrapping task."""
121 f = Gio.file_new_for_path("./")
122
123 async def run():
124 nonlocal self, task
125
126 # Queue cancellation of ourselves with default idle priority
127 GLib.idle_add(lambda: task.cancel("custom cancellation message") and False)
128
129 cancel = Gio.Cancellable()
130
131 try:
132 # Start low priority task which will be cancelled (lower than default idle)
133 async_call = f.enumerate_children_async(
134 "standard::*", 0, GLib.PRIORITY_LOW, cancel
135 )
136 await async_call
137
138 self.fail("await did not raise!")
139 except asyncio.CancelledError:
140 self.assertTrue(cancel.is_cancelled())
141
142 gio_exception = async_call.exception()
143 self.assertIsInstance(gio_exception, GLib.GError)
144 self.assertTrue(
145 gio_exception.matches(
146 Gio.io_error_quark(), Gio.IOErrorEnum.CANCELLED
147 )
148 )
149
150 # re-raise cancellation
151 raise
152
153 task = self.loop.create_task(run())
154 with self.assertRaisesRegex(
155 asyncio.CancelledError,
156 "" if sys.version_info < (3, 11) else "custom cancellation message",
157 ):
158 self.loop.run_until_complete(task)
159
160 def test_not_completed(self):
161 """Querying an uncompleted task raises exceptions."""
162 f = Gio.file_new_for_path("./")
163
164 async def run():
165 nonlocal self
166
167 # cancellable created implicitly
168 res = f.enumerate_children_async("standard::*", 0, GLib.PRIORITY_DEFAULT)
169 with self.assertRaises(asyncio.InvalidStateError):
170 res.result()
171
172 with self.assertRaises(asyncio.InvalidStateError):
173 res.exception()
174
175 # And, await it
176 await res
177
178 self.loop.run_until_complete(run())
179
180 def test_async_cancel_completed(self):
181 """Cancelling a completed task just cancels the cancellable."""
182 f = Gio.file_new_for_path("./")
183
184 async def run():
185 nonlocal self
186
187 res = f.enumerate_children_async("standard::*", 0, GLib.PRIORITY_DEFAULT)
188 await res
189 assert not res.cancellable.is_cancelled()
190 res.cancel()
191 assert res.cancellable.is_cancelled()
192
193 self.loop.run_until_complete(run())
194
195 def test_async_completed_add_cb(self):
196 """Adding a done cb to a completed future queues it with call_soon."""
197 f = Gio.file_new_for_path("./")
198
199 called = False
200
201 def cb():
202 nonlocal called
203 called = True
204
205 async def run():
206 nonlocal called, self
207
208 res = f.enumerate_children_async("standard::*", 0, GLib.PRIORITY_DEFAULT)
209 await res
210 self.loop.call_soon(cb)
211
212 # Python await is smart and does not iterate the EventLoop
213 await res
214 assert not called
215
216 # So create a new future and wait on that
217 fut = asyncio.Future()
218
219 def done_cb(res):
220 nonlocal fut
221 fut.set_result(res.result())
222
223 res.add_done_callback(done_cb)
224 await fut
225 assert called
226
227 self.loop.run_until_complete(run())
228
229 @pytest.mark.xfail(
230 platform.python_implementation() == "PyPy",
231 reason="Exception reporting does not work in pypy",
232 )
233 def test_deleting_failed_logs(self):
234 f = Gio.file_new_for_path("./")
235
236 async def run():
237 nonlocal self
238
239 res = f.enumerate_children_async("standard::*", 0, GLib.PRIORITY_DEFAULT)
240 res.cancel()
241 # Cancellation in Gio is not immediate, so sleep for a bit
242 await asyncio.sleep(0.5)
243
244 exc = None
245 msg = None
246
247 def handler(loop, context):
248 nonlocal exc, msg
249 msg = context["message"]
250 exc = context["exception"]
251
252 self.loop.set_exception_handler(handler)
253 self.loop.run_until_complete(run())
254
255 self.assertRegex(msg, ".*exception was never retrieved")
256 self.assertIsInstance(exc, GLib.GError)
257 assert exc.matches(Gio.io_error_quark(), Gio.IOErrorEnum.CANCELLED)
258
259 def test_no_running_loop(self):
260 f = Gio.file_new_for_path("./")
261
262 res = f.enumerate_children_async("standard::*", 0, GLib.PRIORITY_DEFAULT)
263 self.assertIsNone(res)
264
265 def test_wrong_default_context(self):
266 f = Gio.file_new_for_path("./")
267
268 async def run(): # noqa: RUF029
269 nonlocal self
270
271 ctx = GLib.MainContext.new()
272 GLib.MainContext.push_thread_default(ctx)
273 try:
274 res = f.enumerate_children_async(
275 "standard::*", 0, GLib.PRIORITY_DEFAULT
276 )
277 self.assertIsNone(res)
278 finally:
279 GLib.MainContext.pop_thread_default(ctx)
280
281 self.loop.run_until_complete(run())