Debian Codegraph @

tests/test_gio.py

raw
1 import contextlib
2 import os
3 import unittest
4 import warnings
5
6 import pytest
7
8 GioUnix = None
9 with contextlib.suppress(ImportError):
10 from gi.repository import GioUnix
11
12 import gi.overrides
13 from gi import PyGIWarning, PyGIDeprecationWarning
14 from gi.repository import GLib, Gio
15
16 from .helper import ignore_gi_deprecation_warnings
17
18
19 class TestGio(unittest.TestCase):
20 def test_file_enumerator(self):
21 self.assertEqual(Gio.FileEnumerator, gi.overrides.Gio.FileEnumerator)
22 f = Gio.file_new_for_path("./")
23
24 iter_info = [
25 info.get_name() for info in f.enumerate_children("standard::*", 0, None)
26 ]
27
28 next_info = []
29 enumerator = f.enumerate_children("standard::*", 0, None)
30 while True:
31 info = enumerator.next_file(None)
32 if info is None:
33 break
34 next_info.append(info.get_name())
35
36 self.assertEqual(iter_info, next_info)
37
38 def test_menu_item(self):
39 menu = Gio.Menu()
40 item = Gio.MenuItem()
41 item.set_attribute([("label", "s", "Test"), ("action", "s", "app.test")])
42 menu.append_item(item)
43 value = menu.get_item_attribute_value(0, "label", GLib.VariantType.new("s"))
44 self.assertEqual("Test", value.unpack())
45 value = menu.get_item_attribute_value(0, "action", GLib.VariantType.new("s"))
46 self.assertEqual("app.test", value.unpack())
47
48 def test_volume_monitor_warning(self):
49 with warnings.catch_warnings(record=True) as warn:
50 warnings.simplefilter("always")
51 Gio.VolumeMonitor()
52 self.assertEqual(len(warn), 1)
53 self.assertTrue(issubclass(warn[0].category, PyGIWarning))
54 self.assertRegex(
55 str(warn[0].message), ".*Gio\\.VolumeMonitor\\.get\\(\\).*"
56 )
57
58
59 class TestGioPlatform(unittest.TestCase):
60 desktopFileContent = f"""[Desktop Entry]
61 Version=1.0
62 Type=Application
63 Name=Some Application
64 Exec={GLib.find_program_in_path("true")} %u
65 Actions=act;
66 Categories=Development;Profiling;
67 GenericName=Test
68 Hidden=true
69 Keywords=test;example;
70 NoDisplay=true
71 OnlyShowIn=GNOME;
72 StartupWMClass=testTest
73 X-Bool=true
74
75 [Desktop Action act]
76 Name=Take action!
77 Exec={GLib.find_program_in_path("true")} action
78 """
79
80 def setUp(self):
81 super().setUp()
82
83 if (GLib.MAJOR_VERSION, GLib.MINOR_VERSION) < (2, 80):
84 self.skipTest("Installed Gio is not new enough for this test")
85
86 if GioUnix:
87 self.key_file = GLib.KeyFile()
88 self.key_file.load_from_data(
89 self.desktopFileContent,
90 len(self.desktopFileContent),
91 GLib.KeyFileFlags.NONE,
92 )
93
94 def assert_expected_desktop_app_info(self, app_info):
95 # All functionality is available as ordinary methods, without
96 # needing extraneous arguments
97 # https://gitlab.gnome.org/GNOME/pygobject/-/issues/719
98 self.assertEqual(app_info.get_action_name("act"), "Take action!")
99 self.assertEqual(app_info.get_boolean("X-Bool"), True)
100 self.assertEqual(app_info.get_categories(), "Development;Profiling;")
101 self.assertIsNone(app_info.get_filename())
102 self.assertEqual(app_info.get_generic_name(), "Test")
103 self.assertEqual(app_info.get_is_hidden(), True)
104 self.assertEqual(app_info.get_keywords(), ["test", "example"])
105 self.assertEqual(app_info.get_locale_string("Keywords"), "test;example;")
106 self.assertEqual(app_info.get_nodisplay(), True)
107 self.assertEqual(app_info.get_show_in("GNOME"), True)
108 self.assertEqual(app_info.get_show_in("KDE"), False)
109 # get_show_in() can be called without an argument, which means NULL
110 self.assertIn(app_info.get_show_in(), [True, False])
111 self.assertIn(app_info.get_show_in(None), [True, False])
112 self.assertEqual(app_info.get_startup_wm_class(), "testTest")
113 self.assertEqual(app_info.get_string("StartupWMClass"), "testTest")
114 self.assertEqual(app_info.get_string_list("Keywords"), ["test", "example"])
115 self.assertEqual(app_info.has_key("Keywords"), True)
116 self.assertEqual(app_info.list_actions(), ["act"])
117
118 # All functionality is also available via unbound methods:
119 # for example Cinnamon relies on this as of October 2025
120 self.assertEqual(
121 GioUnix.DesktopAppInfo.get_action_name(app_info, "act"), "Take action!"
122 )
123 self.assertEqual(
124 Gio.DesktopAppInfo.get_action_name(app_info, "act"), "Take action!"
125 )
126
127 # Exercise methods that actually launch something
128 app_info.launch_action("act")
129 app_info.launch_action("act", None)
130 self.assertTrue(
131 app_info.launch_uris_as_manager(
132 ["about:blank"],
133 None,
134 GLib.SpawnFlags.DEFAULT,
135 None,
136 None,
137 None,
138 None,
139 ),
140 )
141 self.assertTrue(
142 app_info.launch_uris_as_manager(
143 ["about:blank"],
144 None,
145 GLib.SpawnFlags.DEFAULT,
146 ),
147 )
148 self.assertTrue(
149 app_info.launch_uris_as_manager_with_fds(
150 ["about:blank"],
151 None,
152 GLib.SpawnFlags.DEFAULT,
153 None,
154 None,
155 None,
156 None,
157 -1,
158 -1,
159 -1,
160 ),
161 )
162
163 @unittest.skipIf(
164 GioUnix is None or "DesktopAppInfo" not in dir(GioUnix), "Not supported"
165 )
166 def test_desktop_app_info_can_be_created_from_gio_unix(self):
167 app_info = GioUnix.DesktopAppInfo.new_from_keyfile(self.key_file)
168 self.assertIsNotNone(app_info)
169 self.assertIsInstance(app_info, GioUnix.DesktopAppInfo)
170 self.assertIsInstance(app_info, Gio.AppInfo)
171 self.assert_expected_desktop_app_info(app_info)
172
173 @unittest.skipIf(
174 GioUnix is None or "DesktopAppInfo" not in dir(GioUnix), "Not supported"
175 )
176 def test_desktop_app_info_can_be_created_from_gio(self):
177 with warnings.catch_warnings(record=True) as warn:
178 warnings.simplefilter("always")
179 app_info = Gio.DesktopAppInfo.new_from_keyfile(self.key_file)
180
181 if (GLib.MAJOR_VERSION, GLib.MINOR_VERSION) >= (2, 86):
182 self.assertEqual(len(warn), 1)
183 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
184 self.assertEqual(
185 str(warn[0].message),
186 "Gio.DesktopAppInfo is deprecated; "
187 + "use GioUnix.DesktopAppInfo instead",
188 )
189
190 self.assertIsNotNone(app_info)
191 self.assertIsInstance(app_info, Gio.DesktopAppInfo)
192 self.assertIsInstance(app_info, Gio.AppInfo)
193
194 @unittest.skipIf(
195 GioUnix is None or "FDMessage" not in dir(GioUnix), "Not supported"
196 )
197 def test_fd_message(self):
198 message = GioUnix.FDMessage.new()
199 self.assertIsNotNone(message)
200
201 with open("/dev/null", "r+b") as devnull:
202 self.assertTrue(message.append_fd(devnull.fileno()))
203 self.assertIsNotNone(message.get_fd_list())
204 fds = message.steal_fds()
205 self.assertEqual(len(fds), 1)
206 os.close(fds[0])
207
208 @unittest.skipIf(
209 GioUnix is None or "DesktopAppInfo" not in dir(GioUnix), "Not supported"
210 )
211 def test_gio_unix_desktop_app_info_provides_platform_independent_functions(self):
212 app_info = GioUnix.DesktopAppInfo.new_from_keyfile(self.key_file)
213 self.assertEqual(app_info.get_name(), "Some Application")
214
215 @unittest.skipIf(
216 GioUnix is None or "DesktopAppInfo" not in dir(GioUnix), "Not supported"
217 )
218 @ignore_gi_deprecation_warnings
219 def test_gio_desktop_app_info_provides_platform_independent_functions(self):
220 app_info = Gio.DesktopAppInfo.new_from_keyfile(self.key_file)
221 self.assertEqual(app_info.get_name(), "Some Application")
222
223 @unittest.skipIf(
224 GioUnix is None or "DesktopAppInfo" not in dir(GioUnix), "Not supported"
225 )
226 def test_gio_unix_desktop_app_info_provides_unix_only_functions(self):
227 app_info = GioUnix.DesktopAppInfo.new_from_keyfile(self.key_file)
228 self.assertTrue(app_info.has_key("Name"))
229 self.assertEqual(app_info.get_string("Name"), "Some Application")
230
231 @unittest.skipIf(
232 GioUnix is None or "DesktopAppInfo" not in dir(GioUnix), "Not supported"
233 )
234 @ignore_gi_deprecation_warnings
235 def test_gio_desktop_app_info_provides_unix_only_functions(self):
236 app_info = Gio.DesktopAppInfo.new_from_keyfile(self.key_file)
237 self.assertTrue(app_info.has_key("Name"))
238 self.assertEqual(app_info.get_string("Name"), "Some Application")
239
240 @unittest.skipIf(GioUnix is None, "Not supported")
241 def test_deprecated_unix_function_can_be_called_from_gio(self):
242 with warnings.catch_warnings(record=True) as warn:
243 warnings.simplefilter("always")
244 mount_points = Gio.unix_mount_points_get()
245
246 if (GLib.MAJOR_VERSION, GLib.MINOR_VERSION) >= (2, 86):
247 self.assertEqual(len(warn), 1)
248 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
249 self.assertEqual(
250 str(warn[0].message),
251 "Gio.unix_mount_points_get is deprecated; "
252 + "use GioUnix.mount_points_get instead",
253 )
254
255 self.assertIsNotNone(mount_points)
256
257 if (GLib.MAJOR_VERSION, GLib.MINOR_VERSION) >= (2, 86):
258 self.assertEqual(GioUnix.mount_points_get, Gio.unix_mount_points_get)
259
260 def assert_expected_unix_stream_type(self, stream_type):
261 with open("/dev/null", "r+b") as devnull:
262 stream = stream_type.new(devnull.fileno(), False)
263 self.assertIsNotNone(stream)
264 self.assertEqual(stream.get_close_fd(), False)
265 stream.set_close_fd(False)
266 self.assertNotEqual(stream.get_fd(), -1)
267
268 @unittest.skipIf(GioUnix is None, "Not supported")
269 def test_deprecated_unix_type_can_be_used_if_equal_exists_in_gio(self):
270 with warnings.catch_warnings(record=True) as warn:
271 warnings.simplefilter("always")
272
273 input_stream = Gio.UnixInputStream
274
275 if (GLib.MAJOR_VERSION, GLib.MINOR_VERSION) >= (2, 86):
276 self.assertEqual(len(warn), 1)
277 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
278 self.assertEqual(
279 str(warn[0].message),
280 "Gio.UnixInputStream is deprecated; "
281 + "use GioUnix.InputStream instead",
282 )
283
284 self.assertIsNotNone(input_stream)
285 self.assertEqual(Gio.UnixInputStream, GioUnix.InputStream)
286 self.assertNotEqual(Gio.InputStream, GioUnix.InputStream)
287
288 self.assert_expected_unix_stream_type(Gio.UnixInputStream)
289 self.assert_expected_unix_stream_type(GioUnix.InputStream)
290
291 self.assert_expected_unix_stream_type(Gio.UnixOutputStream)
292 self.assert_expected_unix_stream_type(GioUnix.OutputStream)
293
294 @unittest.skipIf(GioUnix is None, "Not supported")
295 def test_deprecated_unix_class_can_be_used_from_gio(self):
296 with warnings.catch_warnings(record=True) as warn:
297 warnings.simplefilter("always")
298 monitor = Gio.UnixMountMonitor.get()
299
300 if (GLib.MAJOR_VERSION, GLib.MINOR_VERSION) >= (2, 86):
301 self.assertEqual(len(warn), 1)
302 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
303 self.assertEqual(
304 str(warn[0].message),
305 "Gio.UnixMountMonitor is deprecated; "
306 + "use GioUnix.MountMonitor instead",
307 )
308
309 self.assertIsNotNone(monitor)
310 self.assertEqual(Gio.UnixMountMonitor.get, GioUnix.MountMonitor.get)
311
312 @unittest.skipIf(GioUnix is None, "Not supported")
313 def test_deprecated_unix_gobject_class_can_be_used_from_gio(self):
314 with warnings.catch_warnings(record=True) as warn:
315 warnings.simplefilter("always")
316
317 input_stream_class = Gio.UnixInputStreamClass
318
319 if (GLib.MAJOR_VERSION, GLib.MINOR_VERSION) >= (2, 86):
320 self.assertEqual(len(warn), 1)
321 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
322 self.assertEqual(
323 str(warn[0].message),
324 "Gio.UnixInputStreamClass is deprecated; "
325 + "use GioUnix.InputStreamClass instead",
326 )
327
328 self.assertIsNotNone(input_stream_class)
329
330 if (GLib.MAJOR_VERSION, GLib.MINOR_VERSION) >= (2, 86):
331 self.assertEqual(Gio.UnixInputStreamClass, GioUnix.InputStreamClass)
332
333 self.assertNotEqual(Gio.InputStreamClass, GioUnix.InputStreamClass)
334
335
336 class TestGSettings(unittest.TestCase):
337 def setUp(self):
338 self.settings = Gio.Settings.new("org.gnome.test")
339 # we change the values in the tests, so set them to predictable start
340 # value
341 self.settings.reset("test-string")
342 self.settings.reset("test-array")
343 self.settings.reset("test-boolean")
344 self.settings.reset("test-enum")
345
346 def test_iter(self):
347 assert set(self.settings) == {
348 "test-tuple",
349 "test-array",
350 "test-boolean",
351 "test-string",
352 "test-enum",
353 "test-range",
354 }
355
356 def test_get_set(self):
357 for key in self.settings:
358 old_value = self.settings[key]
359 self.settings[key] = old_value
360 assert self.settings[key] == old_value
361
362 def test_native(self):
363 self.assertTrue("test-array" in self.settings.list_keys())
364
365 # get various types
366 v = self.settings.get_value("test-boolean")
367 self.assertEqual(v.get_boolean(), True)
368 self.assertEqual(self.settings.get_boolean("test-boolean"), True)
369
370 v = self.settings.get_value("test-string")
371 self.assertEqual(v.get_string(), "Hello")
372 self.assertEqual(self.settings.get_string("test-string"), "Hello")
373
374 v = self.settings.get_value("test-array")
375 self.assertEqual(v.unpack(), [1, 2])
376
377 v = self.settings.get_value("test-tuple")
378 self.assertEqual(v.unpack(), (1, 2))
379
380 v = self.settings.get_value("test-range")
381 assert v.unpack() == 123
382
383 # set a value
384 self.settings.set_string("test-string", "World")
385 self.assertEqual(self.settings.get_string("test-string"), "World")
386
387 self.settings.set_value("test-string", GLib.Variant("s", "Goodbye"))
388 self.assertEqual(self.settings.get_string("test-string"), "Goodbye")
389
390 def test_constructor(self):
391 # default constructor uses path from schema
392 self.assertEqual(self.settings.get_property("path"), "/tests/")
393
394 # optional constructor arguments
395 with_path = Gio.Settings.new_with_path("org.gnome.nopathtest", "/mypath/")
396 self.assertEqual(with_path.get_property("path"), "/mypath/")
397 self.assertEqual(with_path["np-int"], 42)
398
399 def test_dictionary_api(self):
400 self.assertEqual(len(self.settings), 6)
401 self.assertTrue("test-array" in self.settings)
402 self.assertTrue("test-array" in self.settings)
403 self.assertFalse("nonexisting" in self.settings)
404 self.assertFalse(4 in self.settings)
405 self.assertEqual(bool(self.settings), True)
406
407 def test_get(self):
408 self.assertEqual(self.settings["test-boolean"], True)
409 self.assertEqual(self.settings["test-string"], "Hello")
410 self.assertEqual(self.settings["test-enum"], "banana")
411 self.assertEqual(self.settings["test-array"], [1, 2])
412 self.assertEqual(self.settings["test-tuple"], (1, 2))
413
414 self.assertRaises(KeyError, self.settings.__getitem__, "unknown")
415 self.assertRaises(KeyError, self.settings.__getitem__, 2)
416
417 def test_set(self):
418 self.settings["test-boolean"] = False
419 self.assertEqual(self.settings["test-boolean"], False)
420 self.settings["test-string"] = "Goodbye"
421 self.assertEqual(self.settings["test-string"], "Goodbye")
422 self.settings["test-array"] = [3, 4, 5]
423 self.assertEqual(self.settings["test-array"], [3, 4, 5])
424 self.settings["test-enum"] = "pear"
425 self.assertEqual(self.settings["test-enum"], "pear")
426
427 self.assertRaises(TypeError, self.settings.__setitem__, "test-string", 1)
428 self.assertRaises(ValueError, self.settings.__setitem__, "test-enum", "plum")
429 self.assertRaises(KeyError, self.settings.__setitem__, "unknown", "moo")
430
431 def test_set_range(self):
432 self.settings["test-range"] = 7
433 assert self.settings["test-range"] == 7
434 self.settings["test-range"] = 65535
435 assert self.settings["test-range"] == 65535
436
437 with pytest.raises(ValueError, match=r".*7 - 65535.*"):
438 self.settings["test-range"] = 7 - 1
439
440 with pytest.raises(ValueError, match=r".*7 - 65535.*"):
441 self.settings["test-range"] = 65535 + 1
442
443 def test_empty(self):
444 empty = Gio.Settings.new_with_path("org.gnome.empty", "/tests/")
445 self.assertEqual(len(empty), 0)
446 self.assertEqual(bool(empty), True)
447 self.assertEqual(empty.keys(), [])
448
449 @ignore_gi_deprecation_warnings
450 def test_change_event(self):
451 changed_log = []
452 change_event_log = []
453
454 def on_changed(settings, key):
455 changed_log.append((settings, key))
456
457 def on_change_event(settings, keys, n_keys):
458 change_event_log.append((settings, keys, n_keys))
459
460 self.settings.connect("changed", on_changed)
461 self.settings.connect("change-event", on_change_event)
462 self.settings["test-string"] = "Moo"
463 self.assertEqual(changed_log, [(self.settings, "test-string")])
464 self.assertEqual(
465 change_event_log,
466 [(self.settings, [GLib.quark_from_static_string("test-string")], 1)],
467 )
468
469
470 @unittest.skipIf(os.name == "nt", "FIXME")
471 class TestGFile(unittest.TestCase):
472 def setUp(self):
473 self.file, self.io_stream = Gio.File.new_tmp("TestGFile.XXXXXX")
474
475 def tearDown(self):
476 with contextlib.suppress(GLib.GError):
477 # test_delete and test_delete_async already remove it
478 self.file.delete(None)
479
480 def test_replace_contents(self):
481 content = b"hello\0world\x7f!"
482 succ, etag = self.file.replace_contents(
483 content, None, False, Gio.FileCreateFlags.NONE, None
484 )
485 new_succ, new_content, new_etag = self.file.load_contents(None)
486
487 self.assertTrue(succ)
488 self.assertTrue(new_succ)
489 self.assertEqual(etag, new_etag)
490 self.assertEqual(content, new_content)
491
492 # https://bugzilla.gnome.org/show_bug.cgi?id=690525
493 def disabled_test_replace_contents_async(self):
494 content = b"".join(bytes(chr(i), "utf-8") for i in range(128))
495
496 def callback(f, result, d):
497 # Quit so in case of failed assertations loop doesn't keep running.
498 main_loop.quit()
499 _succ, _etag = self.file.replace_contents_finish(result)
500 _new_succ, _new_content, _new_etag = self.file.load_contents(None)
501 d["succ"], d["etag"] = self.file.replace_contents_finish(result)
502 load = self.file.load_contents(None)
503 d["new_succ"], d["new_content"], d["new_etag"] = load
504
505 data = {}
506 self.file.replace_contents_async(
507 content, None, False, Gio.FileCreateFlags.NONE, None, callback, data
508 )
509 main_loop = GLib.MainLoop()
510 main_loop.run()
511 self.assertTrue(data["succ"])
512 self.assertTrue(data["new_succ"])
513 self.assertEqual(data["etag"], data["new_etag"])
514 self.assertEqual(content, data["new_content"])
515
516 def test_tmp_exists(self):
517 # A simple test to check if Gio.File.new_tmp is working correctly.
518 self.assertTrue(self.file.query_exists(None))
519
520 def test_delete(self):
521 self.file.delete(None)
522 self.assertFalse(self.file.query_exists(None))
523
524 def test_delete_async(self):
525 def callback(f, result, data):
526 main_loop.quit()
527
528 self.file.delete_async(0, None, callback, None)
529 main_loop = GLib.MainLoop()
530 main_loop.run()
531 self.assertFalse(self.file.query_exists(None))
532
533
534 @unittest.skipIf(os.name == "nt", "crashes on Windows")
535 class TestGApplication(unittest.TestCase):
536 def test_command_line(self):
537 class App(Gio.Application):
538 args = None
539
540 def __init__(self):
541 super().__init__(flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
542
543 def do_command_line(self, cmdline):
544 self.args = cmdline.get_arguments()
545 return 42
546
547 app = App()
548 res = app.run(["spam", "eggs"])
549
550 self.assertEqual(res, 42)
551 self.assertSequenceEqual(app.args, ["spam", "eggs"])
552
553 def test_local_command_line(self):
554 class App(Gio.Application):
555 local_args = None
556
557 def __init__(self):
558 super().__init__(flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
559
560 def do_local_command_line(self, args):
561 self.local_args = args[:] # copy
562 args.remove("eggs")
563
564 # True skips do_command_line being called.
565 return True, args, 42
566
567 app = App()
568 res = app.run(["spam", "eggs"])
569
570 self.assertEqual(res, 42)
571 self.assertSequenceEqual(app.local_args, ["spam", "eggs"])
572
573 def test_local_and_remote_command_line(self):
574 class App(Gio.Application):
575 args = None
576 local_args = None
577
578 def __init__(self):
579 super().__init__(flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
580
581 def do_command_line(self, cmdline):
582 self.args = cmdline.get_arguments()
583 return 42
584
585 def do_local_command_line(self, args):
586 self.local_args = args[:] # copy
587 args.remove("eggs")
588
589 # False causes do_command_line to be called with args.
590 return False, args, 0
591
592 app = App()
593 res = app.run(["spam", "eggs"])
594
595 self.assertEqual(res, 42)
596 self.assertSequenceEqual(app.args, ["spam"])
597 self.assertSequenceEqual(app.local_args, ["spam", "eggs"])
598
599 def test_add_main_option(self):
600 stored_options = []
601
602 def on_handle_local_options(app, options):
603 stored_options.append(options)
604 return 0 # Return 0 if options have been handled
605
606 def on_activate(app):
607 pass
608
609 app = Gio.Application()
610 app.add_main_option(
611 long_name="string",
612 short_name=b"s",
613 flags=0,
614 arg=GLib.OptionArg.STRING,
615 description="some string",
616 )
617
618 app.connect("activate", on_activate)
619 app.connect("handle-local-options", on_handle_local_options)
620 app.run(["app", "-s", "test string"])
621
622 self.assertEqual(len(stored_options), 1)
623 options = stored_options[0]
624 self.assertTrue(options.contains("string"))
625 self.assertEqual(options.lookup_value("string").unpack(), "test string")
626
627 def test_add_action_entries_override(self):
628 app = Gio.Application()
629
630 app.add_action_entries(
631 [
632 ("app.new", print),
633 ("app.quit", print),
634 ]
635 )
636
637 assert app.lookup_action("app.new").get_name() == "app.new"