Debian Codegraph @

tests/test_glib.py

raw
1 import contextlib
2 import os
3 import sys
4 import unittest
5 import os.path
6 import warnings
7 import subprocess
8
9 import pytest
10 from gi.repository import GLib
11 from gi import PyGIDeprecationWarning
12
13
14 PLATFORM_SPLIT_VERSION = (2, 88)
15
16
17 GLibUnix = None
18 with contextlib.suppress(ImportError):
19 from gi.repository import GLibUnix
20
21
22 class TestGLib(unittest.TestCase):
23 @pytest.mark.xfail()
24 def test_pytest_capture_error_in_closure(self):
25 # this test is supposed to fail
26 ml = GLib.MainLoop()
27
28 def callback():
29 ml.quit()
30 raise Exception("expected")
31
32 GLib.idle_add(callback)
33 ml.run()
34
35 @unittest.skipIf(os.name == "nt", "no bash on Windows")
36 def test_find_program_in_path(self):
37 bash_path = GLib.find_program_in_path("bash")
38 self.assertTrue(bash_path.endswith(os.path.sep + "bash"))
39 self.assertTrue(os.path.exists(bash_path))
40
41 self.assertEqual(GLib.find_program_in_path("non existing"), None)
42
43 def test_markup_escape_text(self):
44 self.assertEqual(GLib.markup_escape_text("a&bä"), "a&bä")
45 self.assertEqual(GLib.markup_escape_text(b"a&b\x05"), "a&b")
46
47 # with explicit length argument
48 self.assertEqual(GLib.markup_escape_text(b"a\x05\x01\x02", 2), "a")
49
50 def test_progname(self):
51 GLib.set_prgname("moo")
52 self.assertEqual(GLib.get_prgname(), "moo")
53
54 def test_appname(self):
55 GLib.set_application_name("moo")
56 self.assertEqual(GLib.get_application_name(), "moo")
57
58 def test_xdg_dirs(self):
59 d = GLib.get_user_data_dir()
60 self.assertTrue(os.path.sep in d, d)
61 d = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DESKTOP)
62 self.assertTrue(os.path.sep in d, d)
63 with warnings.catch_warnings():
64 warnings.simplefilter("ignore", PyGIDeprecationWarning)
65
66 # also works with backwards compatible enum names
67 self.assertEqual(
68 GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_MUSIC),
69 GLib.get_user_special_dir(GLib.USER_DIRECTORY_MUSIC),
70 )
71
72 for d in GLib.get_system_config_dirs():
73 self.assertTrue(os.path.sep in d, d)
74 for d in GLib.get_system_data_dirs():
75 self.assertTrue(isinstance(d, str), d)
76
77 def test_main_depth(self):
78 self.assertEqual(GLib.main_depth(), 0)
79
80 def test_filenames(self):
81 self.assertEqual(GLib.filename_display_name("foo"), "foo")
82 self.assertEqual(GLib.filename_display_basename("bar/foo"), "foo")
83
84 def glibfsencode(f):
85 # the annotations of filename_from_utf8() was changed in
86 # https://bugzilla.gnome.org/show_bug.cgi?id=756128
87 if isinstance(f, bytes):
88 return f
89 if os.name == "nt":
90 return f.encode("utf-8", "surrogatepass")
91 return os.fsencode(f)
92
93 # this is locale dependent, so we cannot completely verify the result
94 res = GLib.filename_from_utf8("aäb")
95 res = glibfsencode(res)
96 self.assertTrue(isinstance(res, bytes))
97 self.assertGreaterEqual(len(res), 3)
98
99 # with explicit length argument
100 res = GLib.filename_from_utf8("aäb", 1)
101 res = glibfsencode(res)
102 self.assertEqual(res, b"a")
103
104 def test_uri_extract(self):
105 res = GLib.uri_list_extract_uris("""# some comment
106 http://example.com
107 https://my.org/q?x=1&y=2
108 http://gnome.org/new""")
109 self.assertEqual(
110 res,
111 ["http://example.com", "https://my.org/q?x=1&y=2", "http://gnome.org/new"],
112 )
113
114 def test_current_time(self):
115 with warnings.catch_warnings(record=True) as warn:
116 warnings.simplefilter("always")
117 tm = GLib.get_current_time()
118 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
119
120 self.assertTrue(isinstance(tm, float))
121 self.assertGreater(tm, 1350000000.0)
122
123 @unittest.skipIf(sys.platform == "darwin", "fails on OSX")
124 def test_main_loop(self):
125 # note we do not test run() here, as we use this in countless other
126 # tests
127 ml = GLib.MainLoop()
128 self.assertFalse(ml.is_running())
129
130 context = ml.get_context()
131 self.assertEqual(context, GLib.MainContext.default())
132 self.assertTrue(context.is_owner() in [True, False])
133 self.assertTrue(context.pending() in [True, False])
134 self.assertFalse(context.iteration(False))
135
136 def test_main_loop_with_context(self):
137 context = GLib.MainContext()
138 ml = GLib.MainLoop(context)
139 self.assertFalse(ml.is_running())
140 self.assertEqual(ml.get_context(), context)
141
142 def test_main_context(self):
143 # constructor
144 context = GLib.MainContext()
145 self.assertTrue(context.is_owner() in [True, False])
146 self.assertFalse(context.pending())
147 self.assertFalse(context.iteration(False))
148
149 # GLib API
150 context = GLib.MainContext.default()
151 self.assertTrue(context.is_owner() in [True, False])
152 self.assertTrue(context.pending() in [True, False])
153 self.assertTrue(context.iteration(False) in [True, False])
154
155 # backwards compatible API
156 context = GLib.main_context_default()
157 self.assertTrue(context.is_owner() in [True, False])
158 self.assertTrue(context.pending() in [True, False])
159 self.assertTrue(context.iteration(False) in [True, False])
160
161 def test_main_context_query(self):
162 context = GLib.MainContext()
163 assert context.acquire()
164
165 timeout_msec, fds = context.query(0)
166
167 assert timeout_msec == 0
168 assert len(fds) == 1
169
170 @unittest.skipIf(os.name == "nt", "hangs")
171 def test_io_add_watch_no_data(self):
172 (r, w) = os.pipe()
173 call_data = []
174
175 def cb(fd, condition):
176 call_data.append((fd, condition, os.read(fd, 1)))
177 if len(call_data) == 2:
178 ml.quit()
179 return True
180
181 # io_add_watch() takes an IOChannel, calling with an fd is deprecated
182 with warnings.catch_warnings(record=True) as warn:
183 warnings.simplefilter("always")
184 GLib.io_add_watch(r, GLib.IOCondition.IN, cb, priority=GLib.PRIORITY_HIGH)
185 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
186
187 def write():
188 os.write(w, b"a")
189 GLib.idle_add(lambda: os.write(w, b"b") and False)
190
191 ml = GLib.MainLoop()
192 GLib.idle_add(write)
193 GLib.timeout_add(2000, ml.quit)
194 ml.run()
195
196 self.assertEqual(
197 call_data, [(r, GLib.IOCondition.IN, b"a"), (r, GLib.IOCondition.IN, b"b")]
198 )
199
200 @unittest.skipIf(os.name == "nt", "hangs")
201 def test_io_add_watch_with_data(self):
202 (r, w) = os.pipe()
203 call_data = []
204
205 def cb(fd, condition, data):
206 call_data.append((fd, condition, os.read(fd, 1), data))
207 if len(call_data) == 2:
208 ml.quit()
209 return True
210
211 # io_add_watch() takes an IOChannel, calling with an fd is deprecated
212 with warnings.catch_warnings(record=True) as warn:
213 warnings.simplefilter("always")
214 GLib.io_add_watch(
215 r, GLib.IOCondition.IN, cb, "moo", priority=GLib.PRIORITY_HIGH
216 )
217 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
218
219 def write():
220 os.write(w, b"a")
221 GLib.idle_add(lambda: os.write(w, b"b") and False)
222
223 ml = GLib.MainLoop()
224 GLib.idle_add(write)
225 GLib.timeout_add(2000, ml.quit)
226 ml.run()
227
228 self.assertEqual(
229 call_data,
230 [
231 (r, GLib.IOCondition.IN, b"a", "moo"),
232 (r, GLib.IOCondition.IN, b"b", "moo"),
233 ],
234 )
235
236 @unittest.skipIf(os.name == "nt", "hangs")
237 def test_io_add_watch_with_multiple_data(self):
238 (r, w) = os.pipe()
239 call_data = []
240
241 def cb(fd, condition, *user_data):
242 call_data.append((fd, condition, os.read(fd, 1), user_data))
243 ml.quit()
244 return True
245
246 # io_add_watch() takes an IOChannel, calling with an fd is deprecated
247 with warnings.catch_warnings(record=True) as warn:
248 warnings.simplefilter("always")
249 GLib.io_add_watch(r, GLib.IOCondition.IN, cb, "moo", "foo")
250 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
251
252 ml = GLib.MainLoop()
253 GLib.idle_add(lambda: os.write(w, b"a") and False)
254 GLib.timeout_add(2000, ml.quit)
255 ml.run()
256
257 self.assertEqual(call_data, [(r, GLib.IOCondition.IN, b"a", ("moo", "foo"))])
258
259 @unittest.skipIf(sys.platform == "darwin", "fails")
260 @unittest.skipIf(os.name == "nt", "no shell on Windows")
261 def test_io_add_watch_pyfile(self):
262 call_data = []
263
264 cmd = subprocess.Popen(
265 "echo hello; echo world", shell=True, bufsize=0, stdout=subprocess.PIPE
266 )
267
268 def cb(file, condition):
269 call_data.append((file, condition, file.readline()))
270 if len(call_data) == 2:
271 # avoid having to wait for the full timeout
272 ml.quit()
273 return True
274
275 # io_add_watch() takes an IOChannel, calling with a Python file is deprecated
276 with warnings.catch_warnings(record=True) as warn:
277 warnings.simplefilter("always")
278 GLib.io_add_watch(cmd.stdout, GLib.IOCondition.IN, cb)
279 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
280
281 ml = GLib.MainLoop()
282 GLib.timeout_add(2000, ml.quit)
283 ml.run()
284
285 cmd.wait()
286
287 self.assertEqual(
288 call_data,
289 [
290 (cmd.stdout, GLib.IOCondition.IN, b"hello\n"),
291 (cmd.stdout, GLib.IOCondition.IN, b"world\n"),
292 ],
293 )
294
295 def test_glib_version(self):
296 with warnings.catch_warnings():
297 warnings.simplefilter("ignore", PyGIDeprecationWarning)
298
299 (major, minor, micro) = GLib.glib_version
300 self.assertGreaterEqual(major, 2)
301 self.assertGreaterEqual(minor, 0)
302 self.assertGreaterEqual(micro, 0)
303
304 def test_pyglib_version(self):
305 with warnings.catch_warnings():
306 warnings.simplefilter("ignore", PyGIDeprecationWarning)
307
308 (major, minor, micro) = GLib.pyglib_version
309 self.assertGreaterEqual(major, 3)
310 self.assertGreaterEqual(minor, 0)
311 self.assertGreaterEqual(micro, 0)
312
313 def test_timezone_constructor(self):
314 with warnings.catch_warnings():
315 warnings.simplefilter("ignore", DeprecationWarning)
316 timezone = GLib.TimeZone("+05:21")
317 self.assertEqual(timezone.get_offset(0), ((5 * 60) + 21) * 60)
318
319 def test_source_attach_implicit_context(self):
320 context = GLib.MainContext.default()
321 source = GLib.Idle()
322 source_id = source.attach()
323 self.assertEqual(context, source.get_context())
324 self.assertTrue(GLib.Source.remove(source_id))
325
326
327 class TestGLibPlatform(unittest.TestCase):
328 @classmethod
329 def setUpClass(cls):
330 # TODO: Make this more dynamic in case we'll support Win32
331 cls.platform_glib = GLibUnix
332
333 if cls.platform_glib:
334 cls.platform_full_name = cls.platform_glib._namespace
335 cls.platform_name = f"{cls.platform_full_name[len(GLib._namespace) :]}"
336
337 unittest.TestCase.setUpClass()
338
339 def assertPlatformTypeFallback(self, symbol_name):
340 self.assertIn(symbol_name, dir(GLib))
341
342 platform_symbol_name = symbol_name
343 if symbol_name.startswith(f"{self.platform_name}"):
344 platform_symbol_name = symbol_name[len(self.platform_name) :]
345 elif symbol_name.startswith(f"{self.platform_name.lower()}_"):
346 platform_symbol_name = symbol_name[len(self.platform_name) + 1 :]
347
348 with warnings.catch_warnings(record=True) as warn:
349 symbol = getattr(GLib, symbol_name)
350 self.assertIsNotNone(symbol)
351
352 platform_symbol = getattr(self.platform_glib, platform_symbol_name)
353 self.assertIsNotNone(platform_symbol)
354 self.maybeAssertDeprecationWarning(warn, symbol_name, platform_symbol_name)
355
356 if (GLib.MAJOR_VERSION, GLib.MINOR_VERSION) >= PLATFORM_SPLIT_VERSION:
357 self.assertEqual(platform_symbol, symbol)
358
359 def maybeAssertDeprecationWarning(self, warn, symbol_name, new_symbol_name):
360 if (GLib.MAJOR_VERSION, GLib.MINOR_VERSION) >= PLATFORM_SPLIT_VERSION:
361 self.assertDeprecationWarning(
362 warn,
363 "GLib",
364 self.platform_full_name,
365 symbol_name,
366 new_symbol_name,
367 )
368
369 def assertDeprecationWarning(
370 self, warn, namespace, new_namespace, symbol_name, new_symbol_name
371 ):
372 self.assertGreaterEqual(len(warn), 1)
373 self.assertTrue(
374 any(issubclass(w.category, PyGIDeprecationWarning) for w in warn)
375 )
376
377 expected_message = (
378 f"{namespace}.{symbol_name} is deprecated; "
379 + f"use {new_namespace}.{new_symbol_name} instead"
380 )
381 if len(warn) == 1:
382 self.assertEqual(expected_message, str(warn[0].message))
383 return
384
385 self.assertIn(
386 expected_message,
387 [str(w.message) for w in warn],
388 )
389
390 @unittest.skipIf(GLibUnix is None, "Not supported")
391 def test_fallback_unix_pipe(self):
392 self.assertPlatformTypeFallback("UnixPipe")
393
394 @unittest.skipIf(GLibUnix is None, "Not supported")
395 def test_fallback_unix_pipe_end(self):
396 self.assertPlatformTypeFallback("UnixPipeEnd")
397
398 @unittest.skipIf(GLibUnix is None, "Not supported")
399 def test_fallback_closefrom(self):
400 self.assertPlatformTypeFallback("closefrom")
401
402 @unittest.skipIf(GLibUnix is None, "Not supported")
403 def test_fallback_unix_error_quark(self):
404 self.assertPlatformTypeFallback("unix_error_quark")
405
406 @unittest.skipIf(GLibUnix is None, "Not supported")
407 def test_fallback_unix_fd_add_full(self):
408 self.assertPlatformTypeFallback("unix_fd_add_full")
409
410 @unittest.skipIf(
411 GLibUnix is None or (GLib.MAJOR_VERSION, GLib.MINOR_VERSION) < (2, 87),
412 "Not supported",
413 )
414 def test_fallback_unix_fd_query_path(self):
415 self.assertPlatformTypeFallback("unix_fd_query_path")
416
417 @unittest.skipIf(GLibUnix is None, "Not supported")
418 def test_fallback_unix_fd_source_new(self):
419 self.assertPlatformTypeFallback("unix_fd_source_new")
420
421 @unittest.skipIf(GLibUnix is None, "Not supported")
422 def test_fallback_fdwalk_set_cloexec(self):
423 self.assertPlatformTypeFallback("fdwalk_set_cloexec")
424
425 @unittest.skipIf(GLibUnix is None, "Not supported")
426 def test_fallback_unix_get_passwd_entry(self):
427 self.assertPlatformTypeFallback("unix_get_passwd_entry")
428
429 @unittest.skipIf(GLibUnix is None, "Not supported")
430 def test_fallback_unix_open_pipe(self):
431 self.assertPlatformTypeFallback("unix_open_pipe")
432
433 @unittest.skipIf(GLibUnix is None, "Not supported")
434 def test_fallback_unix_set_fd_nonblocking(self):
435 self.assertPlatformTypeFallback("unix_set_fd_nonblocking")
436
437 @unittest.skipIf(
438 GLibUnix is None
439 or (GLib.MAJOR_VERSION, GLib.MINOR_VERSION) < PLATFORM_SPLIT_VERSION,
440 "Not supported",
441 )
442 def test_fallback_unix_signal_add(self):
443 self.assertPlatformTypeFallback("unix_signal_add")
444
445 @unittest.skipIf(GLibUnix is None, "Not supported")
446 def test_fallback_unix_signal_add_full(self):
447 self.assertPlatformTypeFallback(
448 "unix_signal_add"
449 if "signal_add" in dir(GLibUnix)
450 else "unix_signal_add_full"
451 )
452
453 @unittest.skipIf(GLibUnix is None, "Not supported")
454 def test_fallback_unix_signal_source_new(self):
455 self.assertPlatformTypeFallback("unix_signal_source_new")
456
457 @unittest.skipIf(GLibUnix is None, "Not supported")
458 def test_glib_unix_pipe(self):
459 pipe = GLibUnix.Pipe()
460 self.assertEqual(pipe.fds, [0, 0])
461
462 @unittest.skipIf(GLibUnix is None, "Not supported")
463 def test_glib_unix_pipe_fallback(self):
464 with warnings.catch_warnings(record=True) as warn:
465 pipe = GLib.UnixPipe()
466 self.maybeAssertDeprecationWarning(warn, "UnixPipe", "Pipe")
467 self.assertEqual(pipe.fds, [0, 0])
468
469 @unittest.skipIf(GLibUnix is None, "Not supported")
470 def test_glib_unix_error_quark(self):
471 self.assertGreater(GLibUnix.error_quark(), 0)
472
473 @unittest.skipIf(GLibUnix is None, "Not supported")
474 def test_glib_unix_error_quark_fallback(self):
475 with warnings.catch_warnings(record=True) as warn:
476 self.assertGreater(GLib.unix_error_quark(), 0)
477 self.maybeAssertDeprecationWarning(warn, "unix_error_quark", "error_quark")
478
479 @unittest.skipIf(
480 GLibUnix is None
481 or (GLib.MAJOR_VERSION, GLib.MINOR_VERSION) < PLATFORM_SPLIT_VERSION,
482 "Not supported",
483 )
484 def test_glib_unix_signal_add_full_deprecation(self):
485 with warnings.catch_warnings(record=True) as warn:
486 self.assertIsNotNone(GLibUnix.signal_add_full)
487 self.assertDeprecationWarning(
488 warn, "GLibUnix", "GLibUnix", "signal_add_full", "signal_add"
489 )
490
491 @unittest.skipIf(GLibUnix is None, "Not supported")
492 def test_glib_unix_signal_add_full_wrapper_deprecation(self):
493 with warnings.catch_warnings(record=True) as warn:
494 self.assertIsNotNone(GLib.unix_signal_add_full)
495 new_namespace = "GLibUnix" if "signal_add" in dir(GLibUnix) else "GLib"
496 new_symbol = (
497 "signal_add" if "signal_add" in dir(GLibUnix) else "unix_signal_add"
498 )
499 self.assertDeprecationWarning(
500 warn, "GLib", new_namespace, "unix_signal_add_full", new_symbol
501 )