Debian Codegraph @

tests/test_gdbus.py

raw
1 import asyncio
2 import unittest
3
4 import pytest
5 from gi.events import GLibEventLoopPolicy
6 from gi.repository import GLib
7 from gi.repository import Gio
8
9
10 try:
11 Gio.bus_get_sync(Gio.BusType.SESSION, None)
12 except GLib.Error:
13 has_dbus = False
14 else:
15 has_dbus = True
16
17
18 class TestDBusNodeInfo(unittest.TestCase):
19 def test_new_for_xml(self):
20 info = Gio.DBusNodeInfo.new_for_xml("""
21 <!DOCTYPE node PUBLIC '-//freedesktop//DTD D-BUS Object Introspection 1.0//EN'
22 'http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd'>
23 <node>
24 <interface name='org.freedesktop.DBus.Introspectable'>
25 <method name='Introspect'>
26 <arg name='data' direction='out' type='s'/>
27 </method>
28 </interface>
29 </node>
30 """)
31
32 interfaces = info.interfaces
33 del info
34 assert len(interfaces) == 1
35 assert interfaces[0].name == "org.freedesktop.DBus.Introspectable"
36 methods = interfaces[0].methods
37 del interfaces
38 assert len(methods) == 1
39 assert methods[0].name == "Introspect"
40 out_args = methods[0].out_args
41 assert len(out_args)
42 del methods
43 assert out_args[0].name == "data"
44
45
46 @unittest.skipUnless(has_dbus, "no dbus running")
47 class TestGDBusClient(unittest.TestCase):
48 def setUp(self):
49 self.bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
50
51 self.dbus_proxy = Gio.DBusProxy.new_sync(
52 self.bus,
53 Gio.DBusProxyFlags.NONE,
54 None,
55 "org.freedesktop.DBus",
56 "/org/freedesktop/DBus",
57 "org.freedesktop.DBus",
58 None,
59 )
60
61 def test_native_calls_sync(self):
62 result = self.dbus_proxy.call_sync(
63 "ListNames", None, Gio.DBusCallFlags.NO_AUTO_START, 500, None
64 )
65 self.assertTrue(isinstance(result, GLib.Variant))
66 result = result.unpack()[0] # result is always a tuple
67 self.assertTrue(len(result) > 1)
68 self.assertTrue("org.freedesktop.DBus" in result)
69
70 result = self.dbus_proxy.call_sync(
71 "GetNameOwner",
72 GLib.Variant("(s)", ("org.freedesktop.DBus",)),
73 Gio.DBusCallFlags.NO_AUTO_START,
74 500,
75 None,
76 )
77 self.assertTrue(isinstance(result, GLib.Variant))
78 self.assertEqual(type(result.unpack()[0]), str)
79
80 def test_native_calls_sync_errors(self):
81 # error case: invalid argument types
82 try:
83 self.dbus_proxy.call_sync(
84 "GetConnectionUnixProcessID",
85 None,
86 Gio.DBusCallFlags.NO_AUTO_START,
87 500,
88 None,
89 )
90 self.fail("call with invalid arguments should raise an exception")
91 except Exception as e:
92 self.assertTrue("InvalidArgs" in str(e))
93
94 # error case: invalid argument
95 try:
96 self.dbus_proxy.call_sync(
97 "GetConnectionUnixProcessID",
98 GLib.Variant("(s)", (" unknown",)),
99 Gio.DBusCallFlags.NO_AUTO_START,
100 500,
101 None,
102 )
103 self.fail("call with invalid arguments should raise an exception")
104 except Exception as e:
105 self.assertTrue("NameHasNoOwner" in str(e))
106
107 # error case: unknown method
108 try:
109 self.dbus_proxy.call_sync(
110 "UnknownMethod", None, Gio.DBusCallFlags.NO_AUTO_START, 500, None
111 )
112 self.fail("call for unknown method should raise an exception")
113 except Exception as e:
114 self.assertTrue("UnknownMethod" in str(e))
115
116 def test_native_calls_async(self):
117 def call_done(obj, result, user_data):
118 try:
119 user_data["result"] = obj.call_finish(result)
120 finally:
121 user_data["main_loop"].quit()
122
123 main_loop = GLib.MainLoop()
124 data = {"main_loop": main_loop}
125 self.dbus_proxy.call(
126 "ListNames",
127 None,
128 Gio.DBusCallFlags.NO_AUTO_START,
129 500,
130 None,
131 call_done,
132 data,
133 )
134 main_loop.run()
135
136 self.assertTrue(isinstance(data["result"], GLib.Variant))
137 result = data["result"].unpack()[0] # result is always a tuple
138 self.assertTrue(len(result) > 1)
139 self.assertTrue("org.freedesktop.DBus" in result)
140
141 def test_native_calls_async_errors(self):
142 def call_done(obj, result, user_data):
143 try:
144 obj.call_finish(result)
145 self.fail("call_finish() for unknown method should raise an exception")
146 except Exception as e:
147 self.assertTrue("UnknownMethod" in str(e))
148 finally:
149 user_data["main_loop"].quit()
150
151 main_loop = GLib.MainLoop()
152 data = {"main_loop": main_loop}
153 self.dbus_proxy.call(
154 "UnknownMethod",
155 None,
156 Gio.DBusCallFlags.NO_AUTO_START,
157 500,
158 None,
159 call_done,
160 data,
161 )
162 main_loop.run()
163
164 def test_python_calls_sync(self):
165 # single value return tuples get unboxed to the one element
166 result = self.dbus_proxy.ListNames("()")
167 self.assertTrue(isinstance(result, list))
168 self.assertTrue(len(result) > 1)
169 self.assertTrue("org.freedesktop.DBus" in result)
170
171 result = self.dbus_proxy.GetNameOwner("(s)", "org.freedesktop.DBus")
172 self.assertEqual(type(result), str)
173
174 # empty return tuples get unboxed to None
175 self.assertEqual(self.dbus_proxy.ReloadConfig("()"), None)
176
177 # multiple return values remain a tuple; unfortunately D-BUS itself
178 # does not have any method returning multiple results, so try talking
179 # to notification-daemon (and don't fail the test if it does not exist)
180 try:
181 nd = Gio.DBusProxy.new_sync(
182 self.bus,
183 Gio.DBusProxyFlags.NONE,
184 None,
185 "org.freedesktop.Notifications",
186 "/org/freedesktop/Notifications",
187 "org.freedesktop.Notifications",
188 None,
189 )
190 result = nd.GetServerInformation("()")
191 self.assertTrue(isinstance(result, tuple))
192 self.assertEqual(len(result), 4)
193 for i in result:
194 self.assertEqual(type(i), str)
195 except Exception as e:
196 if "Error.ServiceUnknown" not in str(e):
197 raise
198
199 # test keyword argument; timeout=0 will fail immediately
200 try:
201 self.dbus_proxy.GetConnectionUnixProcessID("(s)", "1", timeout=0)
202 self.fail("call with timeout=0 should raise an exception")
203 except Exception as e:
204 # FIXME: this is not very precise, but in some environments we
205 # do not always get an actual timeout
206 self.assertTrue(isinstance(e, GLib.GError), str(e))
207
208 def test_python_calls_sync_noargs(self):
209 # methods without arguments don't need an explicit signature
210 result = self.dbus_proxy.ListNames()
211 self.assertTrue(isinstance(result, list))
212 self.assertTrue(len(result) > 1)
213 self.assertTrue("org.freedesktop.DBus" in result)
214
215 def test_python_calls_sync_errors(self):
216 # error case: invalid argument types
217 try:
218 self.dbus_proxy.GetConnectionUnixProcessID("()")
219 self.fail("call with invalid arguments should raise an exception")
220 except Exception as e:
221 self.assertTrue("InvalidArgs" in str(e), str(e))
222
223 try:
224 self.dbus_proxy.GetConnectionUnixProcessID(None, "foo")
225 self.fail("call with None signature should raise an exception")
226 except TypeError as e:
227 self.assertTrue("signature" in str(e), str(e))
228
229 def test_python_calls_async(self):
230 def call_done(obj, result, user_data):
231 user_data["result"] = result
232 user_data["main_loop"].quit()
233
234 main_loop = GLib.MainLoop()
235 data = {"main_loop": main_loop}
236 self.dbus_proxy.ListNames("()", result_handler=call_done, user_data=data)
237 main_loop.run()
238
239 result = data["result"]
240 self.assertEqual(type(result), type([]))
241 self.assertTrue(len(result) > 1)
242 self.assertTrue("org.freedesktop.DBus" in result)
243
244 def test_python_calls_async_error_result(self):
245 # when only specifying a result handler, this will get the error
246 def call_done(obj, result, user_data):
247 user_data["result"] = result
248 user_data["main_loop"].quit()
249
250 main_loop = GLib.MainLoop()
251 data = {"main_loop": main_loop}
252 self.dbus_proxy.ListNames(
253 "(s)", "invalid_argument", result_handler=call_done, user_data=data
254 )
255 main_loop.run()
256
257 self.assertTrue(isinstance(data["result"], Exception))
258 self.assertTrue("InvalidArgs" in str(data["result"]), str(data["result"]))
259
260 def test_python_calls_async_error(self):
261 # when specifying an explicit error handler, this will get the error
262 def call_done(obj, result, user_data):
263 user_data["main_loop"].quit()
264 self.fail("result handler should not be called")
265
266 def call_error(obj, error, user_data):
267 user_data["error"] = error
268 user_data["main_loop"].quit()
269
270 main_loop = GLib.MainLoop()
271 data = {"main_loop": main_loop}
272 self.dbus_proxy.ListNames(
273 "(s)",
274 "invalid_argument",
275 result_handler=call_done,
276 error_handler=call_error,
277 user_data=data,
278 )
279 main_loop.run()
280
281 self.assertTrue(isinstance(data["error"], Exception))
282 self.assertTrue("InvalidArgs" in str(data["error"]), str(data["error"]))
283
284 def test_instantiate_custom_proxy(self):
285 class SomeProxy(Gio.DBusProxy):
286 def __init__(self):
287 Gio.DBusProxy.__init__(self)
288
289 SomeProxy()
290
291
292 class TestDBusConnection:
293 @unittest.skipUnless(has_dbus, "no dbus running")
294 def test_register_object(self):
295 object_path = "/pygobject/Test"
296 interface_xml = """
297 <node>
298 <interface name='org.pygobject.Test'>
299 <method name='test' />
300 </interface>
301 </node>"""
302 interface_info = Gio.DBusNodeInfo.new_for_xml(interface_xml).interfaces[0]
303 bus = Gio.bus_get_sync(Gio.BusType.SESSION)
304
305 for args in (
306 (object_path, interface_info),
307 (object_path, interface_info, None, None, None),
308 ):
309 reg_id = bus.register_object(*args)
310 bus.unregister_object(reg_id)
311
312 for kwargs in (
313 {"object_path": object_path, "interface_info": interface_info},
314 {
315 "object_path": object_path,
316 "interface_info": interface_info,
317 "method_call_closure": None,
318 "get_property_closure": None,
319 "set_property_closure": None,
320 },
321 ):
322 reg_id = bus.register_object(**kwargs)
323 bus.unregister_object(reg_id)
324
325 @unittest.skipUnless(has_dbus, "no dbus running")
326 @pytest.mark.xfail()
327 def test_connection_invocation_ref_count(self):
328 """Invocation object should not leak a reference."""
329 invocation, errors = self.run_server(self.client_call)
330
331 assert not errors
332 assert invocation
333 assert invocation.ref_count == 1
334
335 def run_server(self, client_callback):
336 self.invocation = None
337 self.errors = []
338 self.loop = GLib.MainLoop()
339
340 def on_name_acquired(bus, name):
341 client_callback(bus)
342
343 self.reg_id = None
344 bus = Gio.bus_get_sync(Gio.BusType.SESSION)
345 owner_id = Gio.bus_own_name(
346 Gio.BusType.SESSION,
347 "org.pygobject.Test",
348 Gio.BusNameOwnerFlags.NONE,
349 self.on_bus_acquired,
350 on_name_acquired,
351 self.on_name_lost,
352 )
353 try:
354 self.loop.run()
355 finally:
356 Gio.bus_unown_name(owner_id)
357 if self.reg_id:
358 bus.unregister_object(self.reg_id)
359
360 return (self.invocation, self.errors)
361
362 def on_name_lost(self, _bus, name):
363 self.errors.append(f"Name {name} lost")
364 self.loop.quit()
365
366 def on_bus_acquired(self, bus, name):
367 interface_xml = """
368 <node>
369 <interface name='org.pygobject.Test'>
370 <method name='test' />
371 </interface>
372 </node>"""
373 self.reg_id = bus.register_object(
374 "/pygobject/Test",
375 Gio.DBusNodeInfo.new_for_xml(interface_xml).interfaces[0],
376 self.on_incoming_method_call,
377 None,
378 None,
379 )
380
381 def on_incoming_method_call(
382 self,
383 bus,
384 sender,
385 object_path,
386 interface_name,
387 method_name,
388 parameters,
389 invocation,
390 ):
391 invocation.return_value(GLib.Variant("()", ()))
392 self.invocation = invocation
393
394 def client_call(self, bus):
395 def call_done(obj, result):
396 try:
397 obj.call_finish(result)
398 finally:
399 self.loop.quit()
400
401 bus.call(
402 "org.pygobject.Test",
403 "/pygobject/Test",
404 "org.pygobject.Test",
405 "test",
406 parameters=None,
407 reply_type=None,
408 flags=Gio.DBusCallFlags.NONE,
409 timeout_msec=5000,
410 callback=call_done,
411 )
412
413
414 @unittest.skipUnless(has_dbus, "no dbus running")
415 class AsyncDBusTests(unittest.TestCase):
416 def setUp(self):
417 policy = GLibEventLoopPolicy()
418 asyncio.set_event_loop_policy(policy)
419 self.addCleanup(asyncio.set_event_loop_policy, None)
420 self.loop = policy.get_event_loop()
421 self.addCleanup(self.loop.close)
422
423 def test_async_bus_get(self):
424 async def run():
425 bus = await Gio.bus_get(Gio.BusType.SESSION)
426 self.assertIsInstance(bus, Gio.DBusConnection)
427
428 self.loop.run_until_complete(run())
429
430 def test_async_proxy(self):
431 async def run():
432 proxy = await Gio.DBusProxy.new_for_bus(
433 Gio.BusType.SESSION,
434 Gio.DBusProxyFlags.DO_NOT_LOAD_PROPERTIES,
435 None,
436 "org.freedesktop.DBus",
437 "/org/freedesktop/DBus",
438 "org.freedesktop.DBus",
439 )
440 self.assertIsInstance(proxy, Gio.DBusProxy)
441
442 self.loop.run_until_complete(run())