Debian Codegraph @

tests/test_gi.py

raw
1 import sys
2
3 import unittest
4 import tempfile
5 import types
6 import shutil
7 import os
8 import gc
9 import weakref
10 import warnings
11 import pickle
12 import platform
13 import enum
14
15 import gi
16 import gi.overrides
17 from gi import PyGIWarning
18 from gi import PyGIDeprecationWarning
19 from gi.repository import GObject, GLib, Gio
20 from gi.repository import GIMarshallingTests
21 import pytest
22
23 from .helper import capture_exceptions, capture_glib_warnings, capture_output
24 import contextlib
25
26
27 CONSTANT_UTF8 = "const ♥ utf8"
28 CONSTANT_UCS4 = "const ♥ utf8"
29
30
31 class Number:
32 def __init__(self, value):
33 self.value = value
34
35 def __int__(self):
36 return int(self.value)
37
38 def __float__(self):
39 return float(self.value)
40
41
42 class Sequence:
43 def __init__(self, sequence):
44 self.sequence = sequence
45
46 def __len__(self):
47 return len(self.sequence)
48
49 def __getitem__(self, key):
50 return self.sequence[key]
51
52
53 class TestConstant(unittest.TestCase):
54 def test_constant_utf8(self):
55 self.assertEqual(CONSTANT_UTF8, GIMarshallingTests.CONSTANT_UTF8)
56
57 def test_constant_number(self):
58 self.assertEqual(42, GIMarshallingTests.CONSTANT_NUMBER)
59
60 def test_min_max_int(self):
61 self.assertEqual(GLib.MAXINT32, 2**31 - 1)
62 self.assertEqual(GLib.MININT32, -(2**31))
63 self.assertEqual(GLib.MAXUINT32, 2**32 - 1)
64
65 self.assertEqual(GLib.MAXINT64, 2**63 - 1)
66 self.assertEqual(GLib.MININT64, -(2**63))
67 self.assertEqual(GLib.MAXUINT64, 2**64 - 1)
68
69
70 class TestBoolean(unittest.TestCase):
71 def test_boolean_return(self):
72 self.assertEqual(True, GIMarshallingTests.boolean_return_true())
73 self.assertEqual(False, GIMarshallingTests.boolean_return_false())
74
75 def test_boolean_in(self):
76 GIMarshallingTests.boolean_in_true(True)
77 GIMarshallingTests.boolean_in_false(False)
78
79 GIMarshallingTests.boolean_in_true(1)
80 GIMarshallingTests.boolean_in_false(0)
81
82 def test_boolean_in_other_types(self):
83 GIMarshallingTests.boolean_in_true([""])
84 GIMarshallingTests.boolean_in_false([])
85 GIMarshallingTests.boolean_in_false(None)
86
87 def test_boolean_out(self):
88 self.assertEqual(True, GIMarshallingTests.boolean_out_true())
89 self.assertEqual(False, GIMarshallingTests.boolean_out_false())
90
91 def test_boolean_inout(self):
92 self.assertEqual(False, GIMarshallingTests.boolean_inout_true_false(True))
93 self.assertEqual(True, GIMarshallingTests.boolean_inout_false_true(False))
94
95
96 class TestInt8(unittest.TestCase):
97 MAX = GLib.MAXINT8
98 MIN = GLib.MININT8
99
100 def test_int8_return(self):
101 self.assertEqual(self.MAX, GIMarshallingTests.int8_return_max())
102 self.assertEqual(self.MIN, GIMarshallingTests.int8_return_min())
103
104 def test_int8_in(self):
105 max = Number(self.MAX)
106 min = Number(self.MIN)
107
108 GIMarshallingTests.int8_in_max(max)
109 GIMarshallingTests.int8_in_min(min)
110
111 max.value += 1
112 min.value -= 1
113
114 self.assertRaises(OverflowError, GIMarshallingTests.int8_in_max, max)
115 self.assertRaises(OverflowError, GIMarshallingTests.int8_in_min, min)
116
117 self.assertRaises(TypeError, GIMarshallingTests.int8_in_max, "self.MAX")
118
119 def test_int8_out(self):
120 self.assertEqual(self.MAX, GIMarshallingTests.int8_out_max())
121 self.assertEqual(self.MIN, GIMarshallingTests.int8_out_min())
122
123 def test_int8_inout(self):
124 self.assertEqual(
125 self.MIN, GIMarshallingTests.int8_inout_max_min(Number(self.MAX))
126 )
127 self.assertEqual(
128 self.MAX, GIMarshallingTests.int8_inout_min_max(Number(self.MIN))
129 )
130
131
132 class TestUInt8(unittest.TestCase):
133 MAX = GLib.MAXUINT8
134
135 def test_uint8_return(self):
136 self.assertEqual(self.MAX, GIMarshallingTests.uint8_return())
137
138 def test_uint8_in(self):
139 number = Number(self.MAX)
140
141 GIMarshallingTests.uint8_in(number)
142 GIMarshallingTests.uint8_in(b"\xff")
143
144 number.value += 1
145 self.assertRaises(OverflowError, GIMarshallingTests.uint8_in, number)
146 self.assertRaises(OverflowError, GIMarshallingTests.uint8_in, Number(-1))
147
148 self.assertRaises(TypeError, GIMarshallingTests.uint8_in, "self.MAX")
149
150 def test_uint8_out(self):
151 self.assertEqual(self.MAX, GIMarshallingTests.uint8_out())
152
153 def test_uint8_inout(self):
154 self.assertEqual(0, GIMarshallingTests.uint8_inout(Number(self.MAX)))
155
156
157 class TestInt16(unittest.TestCase):
158 MAX = GLib.MAXINT16
159 MIN = GLib.MININT16
160
161 def test_int16_return(self):
162 self.assertEqual(self.MAX, GIMarshallingTests.int16_return_max())
163 self.assertEqual(self.MIN, GIMarshallingTests.int16_return_min())
164
165 def test_int16_in(self):
166 max = Number(self.MAX)
167 min = Number(self.MIN)
168
169 GIMarshallingTests.int16_in_max(max)
170 GIMarshallingTests.int16_in_min(min)
171
172 max.value += 1
173 min.value -= 1
174
175 self.assertRaises(OverflowError, GIMarshallingTests.int16_in_max, max)
176 self.assertRaises(OverflowError, GIMarshallingTests.int16_in_min, min)
177
178 self.assertRaises(TypeError, GIMarshallingTests.int16_in_max, "self.MAX")
179
180 def test_int16_out(self):
181 self.assertEqual(self.MAX, GIMarshallingTests.int16_out_max())
182 self.assertEqual(self.MIN, GIMarshallingTests.int16_out_min())
183
184 def test_int16_inout(self):
185 self.assertEqual(
186 self.MIN, GIMarshallingTests.int16_inout_max_min(Number(self.MAX))
187 )
188 self.assertEqual(
189 self.MAX, GIMarshallingTests.int16_inout_min_max(Number(self.MIN))
190 )
191
192
193 class TestUInt16(unittest.TestCase):
194 MAX = GLib.MAXUINT16
195
196 def test_uint16_return(self):
197 self.assertEqual(self.MAX, GIMarshallingTests.uint16_return())
198
199 def test_uint16_in(self):
200 number = Number(self.MAX)
201
202 GIMarshallingTests.uint16_in(number)
203
204 number.value += 1
205
206 self.assertRaises(OverflowError, GIMarshallingTests.uint16_in, number)
207 self.assertRaises(OverflowError, GIMarshallingTests.uint16_in, Number(-1))
208
209 self.assertRaises(TypeError, GIMarshallingTests.uint16_in, "self.MAX")
210
211 def test_uint16_out(self):
212 self.assertEqual(self.MAX, GIMarshallingTests.uint16_out())
213
214 def test_uint16_inout(self):
215 self.assertEqual(0, GIMarshallingTests.uint16_inout(Number(self.MAX)))
216
217
218 class TestInt32(unittest.TestCase):
219 MAX = GLib.MAXINT32
220 MIN = GLib.MININT32
221
222 def test_int32_return(self):
223 self.assertEqual(self.MAX, GIMarshallingTests.int32_return_max())
224 self.assertEqual(self.MIN, GIMarshallingTests.int32_return_min())
225
226 def test_int32_in(self):
227 max = Number(self.MAX)
228 min = Number(self.MIN)
229
230 GIMarshallingTests.int32_in_max(max)
231 GIMarshallingTests.int32_in_min(min)
232
233 max.value += 1
234 min.value -= 1
235
236 self.assertRaises(OverflowError, GIMarshallingTests.int32_in_max, max)
237 self.assertRaises(OverflowError, GIMarshallingTests.int32_in_min, min)
238
239 self.assertRaises(TypeError, GIMarshallingTests.int32_in_max, "self.MAX")
240
241 def test_int32_out(self):
242 self.assertEqual(self.MAX, GIMarshallingTests.int32_out_max())
243 self.assertEqual(self.MIN, GIMarshallingTests.int32_out_min())
244
245 def test_int32_inout(self):
246 self.assertEqual(
247 self.MIN, GIMarshallingTests.int32_inout_max_min(Number(self.MAX))
248 )
249 self.assertEqual(
250 self.MAX, GIMarshallingTests.int32_inout_min_max(Number(self.MIN))
251 )
252
253
254 class TestUInt32(unittest.TestCase):
255 MAX = GLib.MAXUINT32
256
257 def test_uint32_return(self):
258 self.assertEqual(self.MAX, GIMarshallingTests.uint32_return())
259
260 def test_uint32_in(self):
261 number = Number(self.MAX)
262
263 GIMarshallingTests.uint32_in(number)
264
265 number.value += 1
266
267 self.assertRaises(OverflowError, GIMarshallingTests.uint32_in, number)
268 self.assertRaises(OverflowError, GIMarshallingTests.uint32_in, Number(-1))
269
270 self.assertRaises(TypeError, GIMarshallingTests.uint32_in, "self.MAX")
271
272 def test_uint32_out(self):
273 self.assertEqual(self.MAX, GIMarshallingTests.uint32_out())
274
275 def test_uint32_inout(self):
276 self.assertEqual(0, GIMarshallingTests.uint32_inout(Number(self.MAX)))
277
278
279 class TestInt64(unittest.TestCase):
280 MAX = 2**63 - 1
281 MIN = -(2**63)
282
283 def test_int64_return(self):
284 self.assertEqual(self.MAX, GIMarshallingTests.int64_return_max())
285 self.assertEqual(self.MIN, GIMarshallingTests.int64_return_min())
286
287 def test_int64_in(self):
288 max = Number(self.MAX)
289 min = Number(self.MIN)
290
291 GIMarshallingTests.int64_in_max(max)
292 GIMarshallingTests.int64_in_min(min)
293
294 max.value += 1
295 min.value -= 1
296
297 self.assertRaises(OverflowError, GIMarshallingTests.int64_in_max, max)
298 self.assertRaises(OverflowError, GIMarshallingTests.int64_in_min, min)
299
300 self.assertRaises(TypeError, GIMarshallingTests.int64_in_max, "self.MAX")
301
302 def test_int64_out(self):
303 self.assertEqual(self.MAX, GIMarshallingTests.int64_out_max())
304 self.assertEqual(self.MIN, GIMarshallingTests.int64_out_min())
305
306 def test_int64_inout(self):
307 self.assertEqual(
308 self.MIN, GIMarshallingTests.int64_inout_max_min(Number(self.MAX))
309 )
310 self.assertEqual(
311 self.MAX, GIMarshallingTests.int64_inout_min_max(Number(self.MIN))
312 )
313
314
315 class TestUInt64(unittest.TestCase):
316 MAX = 2**64 - 1
317
318 def test_uint64_return(self):
319 self.assertEqual(self.MAX, GIMarshallingTests.uint64_return())
320
321 def test_uint64_in(self):
322 number = Number(self.MAX)
323
324 GIMarshallingTests.uint64_in(number)
325
326 number.value += 1
327
328 self.assertRaises(OverflowError, GIMarshallingTests.uint64_in, number)
329 self.assertRaises(OverflowError, GIMarshallingTests.uint64_in, Number(-1))
330
331 self.assertRaises(TypeError, GIMarshallingTests.uint64_in, "self.MAX")
332
333 def test_uint64_out(self):
334 self.assertEqual(self.MAX, GIMarshallingTests.uint64_out())
335
336 def test_uint64_inout(self):
337 self.assertEqual(0, GIMarshallingTests.uint64_inout(Number(self.MAX)))
338
339
340 class TestShort(unittest.TestCase):
341 MAX = GLib.MAXSHORT
342 MIN = GLib.MINSHORT
343
344 def test_short_return(self):
345 self.assertEqual(self.MAX, GIMarshallingTests.short_return_max())
346 self.assertEqual(self.MIN, GIMarshallingTests.short_return_min())
347
348 def test_short_in(self):
349 max = Number(self.MAX)
350 min = Number(self.MIN)
351
352 GIMarshallingTests.short_in_max(max)
353 GIMarshallingTests.short_in_min(min)
354
355 max.value += 1
356 min.value -= 1
357
358 self.assertRaises(OverflowError, GIMarshallingTests.short_in_max, max)
359 self.assertRaises(OverflowError, GIMarshallingTests.short_in_min, min)
360
361 self.assertRaises(TypeError, GIMarshallingTests.short_in_max, "self.MAX")
362
363 def test_short_out(self):
364 self.assertEqual(self.MAX, GIMarshallingTests.short_out_max())
365 self.assertEqual(self.MIN, GIMarshallingTests.short_out_min())
366
367 def test_short_inout(self):
368 self.assertEqual(
369 self.MIN, GIMarshallingTests.short_inout_max_min(Number(self.MAX))
370 )
371 self.assertEqual(
372 self.MAX, GIMarshallingTests.short_inout_min_max(Number(self.MIN))
373 )
374
375
376 class TestUShort(unittest.TestCase):
377 MAX = GLib.MAXUSHORT
378
379 def test_ushort_return(self):
380 self.assertEqual(self.MAX, GIMarshallingTests.ushort_return())
381
382 def test_ushort_in(self):
383 number = Number(self.MAX)
384
385 GIMarshallingTests.ushort_in(number)
386
387 number.value += 1
388
389 self.assertRaises(OverflowError, GIMarshallingTests.ushort_in, number)
390 self.assertRaises(OverflowError, GIMarshallingTests.ushort_in, Number(-1))
391
392 self.assertRaises(TypeError, GIMarshallingTests.ushort_in, "self.MAX")
393
394 def test_ushort_out(self):
395 self.assertEqual(self.MAX, GIMarshallingTests.ushort_out())
396
397 def test_ushort_inout(self):
398 self.assertEqual(0, GIMarshallingTests.ushort_inout(Number(self.MAX)))
399
400
401 class TestInt(unittest.TestCase):
402 MAX = GLib.MAXINT
403 MIN = GLib.MININT
404
405 def test_int_return(self):
406 self.assertEqual(self.MAX, GIMarshallingTests.int_return_max())
407 self.assertEqual(self.MIN, GIMarshallingTests.int_return_min())
408
409 def test_int_in(self):
410 max = Number(self.MAX)
411 min = Number(self.MIN)
412
413 GIMarshallingTests.int_in_max(max)
414 GIMarshallingTests.int_in_min(min)
415
416 max.value += 1
417 min.value -= 1
418
419 self.assertRaises(OverflowError, GIMarshallingTests.int_in_max, max)
420 self.assertRaises(OverflowError, GIMarshallingTests.int_in_min, min)
421
422 self.assertRaises(TypeError, GIMarshallingTests.int_in_max, "self.MAX")
423
424 def test_int_out(self):
425 self.assertEqual(self.MAX, GIMarshallingTests.int_out_max())
426 self.assertEqual(self.MIN, GIMarshallingTests.int_out_min())
427
428 def test_int_inout(self):
429 self.assertEqual(
430 self.MIN, GIMarshallingTests.int_inout_max_min(Number(self.MAX))
431 )
432 self.assertEqual(
433 self.MAX, GIMarshallingTests.int_inout_min_max(Number(self.MIN))
434 )
435 self.assertRaises(
436 TypeError, GIMarshallingTests.int_inout_min_max, Number(self.MIN), 42
437 )
438
439
440 class TestUInt(unittest.TestCase):
441 MAX = GLib.MAXUINT
442
443 def test_uint_return(self):
444 self.assertEqual(self.MAX, GIMarshallingTests.uint_return())
445
446 def test_uint_in(self):
447 number = Number(self.MAX)
448
449 GIMarshallingTests.uint_in(number)
450
451 number.value += 1
452
453 self.assertRaises(OverflowError, GIMarshallingTests.uint_in, number)
454 self.assertRaises(OverflowError, GIMarshallingTests.uint_in, Number(-1))
455
456 self.assertRaises(TypeError, GIMarshallingTests.uint_in, "self.MAX")
457
458 def test_uint_out(self):
459 self.assertEqual(self.MAX, GIMarshallingTests.uint_out())
460
461 def test_uint_inout(self):
462 self.assertEqual(0, GIMarshallingTests.uint_inout(Number(self.MAX)))
463
464
465 class TestLong(unittest.TestCase):
466 MAX = GLib.MAXLONG
467 MIN = GLib.MINLONG
468
469 def test_long_return(self):
470 self.assertEqual(self.MAX, GIMarshallingTests.long_return_max())
471 self.assertEqual(self.MIN, GIMarshallingTests.long_return_min())
472
473 def test_long_in(self):
474 max = Number(self.MAX)
475 min = Number(self.MIN)
476
477 GIMarshallingTests.long_in_max(max)
478 GIMarshallingTests.long_in_min(min)
479
480 max.value += 1
481 min.value -= 1
482
483 self.assertRaises(OverflowError, GIMarshallingTests.long_in_max, max)
484 self.assertRaises(OverflowError, GIMarshallingTests.long_in_min, min)
485
486 self.assertRaises(TypeError, GIMarshallingTests.long_in_max, "self.MAX")
487
488 def test_long_out(self):
489 self.assertEqual(self.MAX, GIMarshallingTests.long_out_max())
490 self.assertEqual(self.MIN, GIMarshallingTests.long_out_min())
491
492 def test_long_inout(self):
493 self.assertEqual(
494 self.MIN, GIMarshallingTests.long_inout_max_min(Number(self.MAX))
495 )
496 self.assertEqual(
497 self.MAX, GIMarshallingTests.long_inout_min_max(Number(self.MIN))
498 )
499
500
501 class TestULong(unittest.TestCase):
502 MAX = GLib.MAXULONG
503
504 def test_ulong_return(self):
505 self.assertEqual(self.MAX, GIMarshallingTests.ulong_return())
506
507 def test_ulong_in(self):
508 number = Number(self.MAX)
509
510 GIMarshallingTests.ulong_in(number)
511
512 number.value += 1
513
514 self.assertRaises(OverflowError, GIMarshallingTests.ulong_in, number)
515 self.assertRaises(OverflowError, GIMarshallingTests.ulong_in, Number(-1))
516
517 self.assertRaises(TypeError, GIMarshallingTests.ulong_in, "self.MAX")
518
519 def test_ulong_out(self):
520 self.assertEqual(self.MAX, GIMarshallingTests.ulong_out())
521
522 def test_ulong_inout(self):
523 self.assertEqual(0, GIMarshallingTests.ulong_inout(Number(self.MAX)))
524
525
526 class TestSSize(unittest.TestCase):
527 MAX = GLib.MAXSSIZE
528 MIN = GLib.MINSSIZE
529
530 def test_ssize_return(self):
531 self.assertEqual(self.MAX, GIMarshallingTests.ssize_return_max())
532 self.assertEqual(self.MIN, GIMarshallingTests.ssize_return_min())
533
534 def test_ssize_in(self):
535 max = Number(self.MAX)
536 min = Number(self.MIN)
537
538 GIMarshallingTests.ssize_in_max(max)
539 GIMarshallingTests.ssize_in_min(min)
540
541 max.value += 1
542 min.value -= 1
543
544 self.assertRaises(OverflowError, GIMarshallingTests.ssize_in_max, max)
545 self.assertRaises(OverflowError, GIMarshallingTests.ssize_in_min, min)
546
547 self.assertRaises(TypeError, GIMarshallingTests.ssize_in_max, "self.MAX")
548
549 def test_ssize_out(self):
550 self.assertEqual(self.MAX, GIMarshallingTests.ssize_out_max())
551 self.assertEqual(self.MIN, GIMarshallingTests.ssize_out_min())
552
553 def test_ssize_inout(self):
554 self.assertEqual(
555 self.MIN, GIMarshallingTests.ssize_inout_max_min(Number(self.MAX))
556 )
557 self.assertEqual(
558 self.MAX, GIMarshallingTests.ssize_inout_min_max(Number(self.MIN))
559 )
560
561
562 class TestSize(unittest.TestCase):
563 MAX = GLib.MAXSIZE
564
565 def test_size_return(self):
566 self.assertEqual(self.MAX, GIMarshallingTests.size_return())
567
568 def test_size_in(self):
569 number = Number(self.MAX)
570
571 GIMarshallingTests.size_in(number)
572
573 number.value += 1
574
575 self.assertRaises(OverflowError, GIMarshallingTests.size_in, number)
576 self.assertRaises(OverflowError, GIMarshallingTests.size_in, Number(-1))
577
578 self.assertRaises(TypeError, GIMarshallingTests.size_in, "self.MAX")
579
580 def test_size_out(self):
581 self.assertEqual(self.MAX, GIMarshallingTests.size_out())
582
583 def test_size_inout(self):
584 self.assertEqual(0, GIMarshallingTests.size_inout(Number(self.MAX)))
585
586
587 class TestTimet(unittest.TestCase):
588 def test_time_t_return(self):
589 self.assertEqual(1234567890, GIMarshallingTests.time_t_return())
590
591 def test_time_t_in(self):
592 GIMarshallingTests.time_t_in(1234567890)
593 self.assertRaises(TypeError, GIMarshallingTests.time_t_in, "hello")
594
595 def test_time_t_out(self):
596 self.assertEqual(1234567890, GIMarshallingTests.time_t_out())
597
598 def test_time_t_inout(self):
599 self.assertEqual(0, GIMarshallingTests.time_t_inout(1234567890))
600
601
602 class TestFloat(unittest.TestCase):
603 MAX = GLib.MAXFLOAT
604 MIN = GLib.MINFLOAT
605
606 def test_float_return(self):
607 self.assertAlmostEqual(self.MAX, GIMarshallingTests.float_return())
608
609 def test_float_in(self):
610 GIMarshallingTests.float_in(Number(self.MAX))
611
612 self.assertRaises(TypeError, GIMarshallingTests.float_in, "self.MAX")
613
614 def test_float_out(self):
615 self.assertAlmostEqual(self.MAX, GIMarshallingTests.float_out())
616
617 def test_float_inout(self):
618 self.assertAlmostEqual(
619 self.MIN, GIMarshallingTests.float_inout(Number(self.MAX))
620 )
621
622
623 class TestDouble(unittest.TestCase):
624 MAX = GLib.MAXDOUBLE
625 MIN = GLib.MINDOUBLE
626
627 def test_double_return(self):
628 self.assertAlmostEqual(self.MAX, GIMarshallingTests.double_return())
629
630 def test_double_in(self):
631 GIMarshallingTests.double_in(Number(self.MAX))
632
633 self.assertRaises(TypeError, GIMarshallingTests.double_in, "self.MAX")
634
635 def test_double_out(self):
636 self.assertAlmostEqual(self.MAX, GIMarshallingTests.double_out())
637
638 def test_double_inout(self):
639 self.assertAlmostEqual(
640 self.MIN, GIMarshallingTests.double_inout(Number(self.MAX))
641 )
642
643
644 class TestGType(unittest.TestCase):
645 def test_gtype_name(self):
646 self.assertEqual("void", GObject.TYPE_NONE.name)
647 self.assertEqual("gchararray", GObject.TYPE_STRING.name)
648
649 def check_readonly(gtype):
650 gtype.name = "foo"
651
652 errors = (AttributeError,)
653 if platform.python_implementation() == "PyPy":
654 # https://foss.heptapod.net/pypy/pypy/-/issues/2788
655 errors = (AttributeError, TypeError)
656
657 self.assertRaises(errors, check_readonly, GObject.TYPE_NONE)
658 self.assertRaises(errors, check_readonly, GObject.TYPE_STRING)
659
660 def test_gtype_return(self):
661 self.assertEqual(GObject.TYPE_NONE, GIMarshallingTests.gtype_return())
662 self.assertEqual(GObject.TYPE_STRING, GIMarshallingTests.gtype_string_return())
663
664 def test_gtype_in(self):
665 GIMarshallingTests.gtype_in(GObject.TYPE_NONE)
666 GIMarshallingTests.gtype_string_in(GObject.TYPE_STRING)
667 self.assertRaises(TypeError, GIMarshallingTests.gtype_in, "foo")
668 self.assertRaises(TypeError, GIMarshallingTests.gtype_string_in, "foo")
669
670 def test_gtype_out(self):
671 self.assertEqual(GObject.TYPE_NONE, GIMarshallingTests.gtype_out())
672 self.assertEqual(GObject.TYPE_STRING, GIMarshallingTests.gtype_string_out())
673
674 def test_gtype_inout(self):
675 self.assertEqual(
676 GObject.TYPE_INT, GIMarshallingTests.gtype_inout(GObject.TYPE_NONE)
677 )
678
679
680 class TestUtf8(unittest.TestCase):
681 def test_utf8_as_uint8array_in(self):
682 data = CONSTANT_UTF8
683 if not isinstance(data, bytes):
684 data = data.encode("utf-8")
685 GIMarshallingTests.utf8_as_uint8array_in(data)
686
687 def test_utf8_as_string_array_in(self):
688 data = CONSTANT_UTF8
689 with pytest.raises(
690 TypeError,
691 match=r"Unable to marshal str as an array, use \.encode\(\) to convert to bytes",
692 ):
693 GIMarshallingTests.utf8_as_uint8array_in(data)
694
695 def test_utf8_none_return(self):
696 self.assertEqual(CONSTANT_UTF8, GIMarshallingTests.utf8_none_return())
697
698 def test_utf8_full_return(self):
699 self.assertEqual(CONSTANT_UTF8, GIMarshallingTests.utf8_full_return())
700
701 def test_extra_utf8_full_return_invalid(self):
702 with pytest.raises(UnicodeDecodeError):
703 GIMarshallingTests.extra_utf8_full_return_invalid()
704
705 def test_extra_utf8_full_out_invalid(self):
706 with pytest.raises(UnicodeDecodeError):
707 GIMarshallingTests.extra_utf8_full_out_invalid()
708
709 def test_utf8_none_in(self):
710 GIMarshallingTests.utf8_none_in(CONSTANT_UTF8)
711 self.assertRaises(TypeError, GIMarshallingTests.utf8_none_in, 42)
712 self.assertRaises(TypeError, GIMarshallingTests.utf8_none_in, None)
713
714 def test_utf8_none_out(self):
715 self.assertEqual(CONSTANT_UTF8, GIMarshallingTests.utf8_none_out())
716
717 def test_utf8_full_out(self):
718 self.assertEqual(CONSTANT_UTF8, GIMarshallingTests.utf8_full_out())
719
720 def test_utf8_dangling_out(self):
721 GIMarshallingTests.utf8_dangling_out()
722
723 def test_utf8_none_inout(self):
724 self.assertEqual("", GIMarshallingTests.utf8_none_inout(CONSTANT_UTF8))
725
726 def test_utf8_full_inout(self):
727 self.assertEqual("", GIMarshallingTests.utf8_full_inout(CONSTANT_UTF8))
728
729
730 class TestFilename(unittest.TestCase):
731 def setUp(self):
732 self.workdir = tempfile.mkdtemp()
733
734 def tearDown(self):
735 shutil.rmtree(self.workdir)
736
737 def tests_filename_list_return(self):
738 assert GIMarshallingTests.filename_list_return() == []
739
740 @unittest.skipIf(os.name == "nt", "fixme")
741 def test_filename_in(self):
742 fname = os.path.join(self.workdir, "testäø.txt")
743
744 try:
745 os.path.exists(fname)
746 except ValueError:
747 # non-unicode fs encoding
748 return
749
750 self.assertRaises(GLib.GError, GLib.file_get_contents, fname)
751
752 with open(fname.encode("UTF-8"), "wb") as f:
753 f.write(b"hello world!\n\x01\x02")
754
755 (result, contents) = GLib.file_get_contents(fname)
756 self.assertEqual(result, True)
757 self.assertEqual(contents, b"hello world!\n\x01\x02")
758
759 def test_filename_in_nullable(self):
760 self.assertTrue(GIMarshallingTests.filename_copy(None) is None)
761 self.assertRaises(TypeError, GIMarshallingTests.filename_exists, None)
762
763 @unittest.skipIf(os.name == "nt", "fixme")
764 def test_filename_out(self):
765 self.assertRaises(GLib.GError, GLib.Dir.make_tmp, "test")
766 name = "testäø.XXXXXX"
767
768 try:
769 os.path.exists(name)
770 except ValueError:
771 # non-unicode fs encoding
772 return
773
774 dirname = GLib.Dir.make_tmp(name)
775 self.assertTrue(os.path.sep + "testäø." in dirname, dirname)
776 self.assertTrue(os.path.isdir(dirname))
777 os.rmdir(dirname)
778
779 def test_wrong_types(self):
780 self.assertRaises(TypeError, GIMarshallingTests.filename_copy, 23)
781 self.assertRaises(TypeError, GIMarshallingTests.filename_copy, [])
782
783 def test_null(self):
784 self.assertTrue(GIMarshallingTests.filename_copy(None) is None)
785 self.assertRaises(TypeError, GIMarshallingTests.filename_exists, None)
786
787 def test_round_trip(self):
788 self.assertEqual(GIMarshallingTests.filename_copy("foo"), "foo")
789 self.assertEqual(GIMarshallingTests.filename_copy(b"foo"), "foo")
790
791 def test_contains_null(self):
792 self.assertRaises(
793 (ValueError, TypeError), GIMarshallingTests.filename_copy, b"foo\x00"
794 )
795 self.assertRaises(
796 (ValueError, TypeError), GIMarshallingTests.filename_copy, "foo\x00"
797 )
798
799 def test_win32_surrogates(self):
800 if os.name != "nt":
801 return
802
803 copy = GIMarshallingTests.filename_copy
804 glib_repr = GIMarshallingTests.filename_to_glib_repr
805
806 self.assertEqual(copy("\ud83d"), "\ud83d")
807 self.assertEqual(copy("\x61\udc00"), "\x61\udc00")
808 self.assertEqual(copy("\ud800\udc01"), "\U00010001")
809 self.assertEqual(copy("\ud83d\x20\udca9"), "\ud83d\x20\udca9")
810
811 self.assertEqual(glib_repr("\ud83d"), b"\xed\xa0\xbd")
812 self.assertEqual(glib_repr("\ud800\udc01"), b"\xf0\x90\x80\x81")
813
814 self.assertEqual(glib_repr("\ud800\udbff"), b"\xed\xa0\x80\xed\xaf\xbf")
815 self.assertEqual(glib_repr("\ud800\ue000"), b"\xed\xa0\x80\xee\x80\x80")
816 self.assertEqual(glib_repr("\ud7ff\udc00"), b"\xed\x9f\xbf\xed\xb0\x80")
817 self.assertEqual(glib_repr("\x61\udc00"), b"\x61\xed\xb0\x80")
818 self.assertEqual(glib_repr("\udc00"), b"\xed\xb0\x80")
819
820 def test_win32_bytes_py3(self):
821 if os.name != "nt":
822 return
823
824 values = [
825 b"foo",
826 b"\xff\xff",
827 b"\xc3\xb6\xc3\xa4\xc3\xbc",
828 b"\xed\xa0\xbd",
829 b"\xf0\x90\x80\x81",
830 ]
831
832 for v in values:
833 try:
834 uni = v.decode(sys.getfilesystemencoding(), "surrogatepass")
835 except UnicodeDecodeError:
836 continue
837 self.assertEqual(GIMarshallingTests.filename_copy(v), uni)
838
839 def test_unix_various(self):
840 if os.name == "nt":
841 return
842
843 copy = GIMarshallingTests.filename_copy
844 glib_repr = GIMarshallingTests.filename_to_glib_repr
845
846 try:
847 os.fsdecode(b"\xff\xfe")
848 except UnicodeDecodeError:
849 self.assertRaises(UnicodeDecodeError, copy, b"\xff\xfe")
850 else:
851 str_path = copy(b"\xff\xfe")
852 self.assertTrue(isinstance(str_path, str))
853 self.assertEqual(str_path, os.fsdecode(b"\xff\xfe"))
854 self.assertEqual(copy(str_path), str_path)
855 self.assertEqual(glib_repr(b"\xff\xfe"), b"\xff\xfe")
856 self.assertEqual(glib_repr(str_path), b"\xff\xfe")
857
858 # if getfilesystemencoding is ASCII, then we should fail like
859 # os.fsencode
860 try:
861 byte_path = os.fsencode("ä")
862 except UnicodeEncodeError:
863 self.assertRaises(UnicodeEncodeError, copy, "ä")
864 else:
865 self.assertEqual(copy("ä"), "ä")
866 self.assertEqual(glib_repr("ä"), byte_path)
867
868 @unittest.skip("glib can't handle non-unicode paths")
869 def test_win32_surrogates_exists(self):
870 if os.name != "nt":
871 return
872
873 path = os.path.join(self.workdir, "\ud83d")
874 with open(path, "wb"):
875 self.assertTrue(os.path.exists(path))
876 self.assertTrue(GIMarshallingTests.filename_exists(path))
877 os.unlink(path)
878
879 def test_path_exists_various_types(self):
880 wd = self.workdir
881 wdb = os.fsencode(wd)
882
883 paths = [(wdb, b"foo-1"), (wd, "foo-2"), (wd, "öäü-3")]
884
885 if sys.platform != "darwin":
886 with contextlib.suppress(UnicodeDecodeError):
887 # depends on the code page
888 paths.append((wd, os.fsdecode(b"\xff\xfe-4")))
889
890 if os.name != "nt":
891 paths.append((wdb, b"\xff\xfe-5"))
892
893 def valid_path(p):
894 try:
895 os.path.exists(p)
896 except ValueError:
897 return False
898 return True
899
900 for d, path in paths:
901 if not valid_path(path):
902 continue
903 path = os.path.join(d, path)
904 with open(path, "wb"):
905 self.assertTrue(GIMarshallingTests.filename_exists(path))
906
907
908 class TestArray(unittest.TestCase):
909 def test_array_bool_in(self):
910 GIMarshallingTests.array_bool_in([True, False, True, True])
911
912 def test_array_bool_out(self):
913 assert GIMarshallingTests.array_bool_out() == [True, False, True, True]
914
915 def test_array_int64_in(self):
916 GIMarshallingTests.array_int64_in([-1, 0, 1, 2])
917
918 def test_array_uint64_in(self):
919 GIMarshallingTests.array_uint64_in([GLib.MAXUINT64, 0, 1, 2])
920
921 def test_array_unichar_in(self):
922 GIMarshallingTests.array_unichar_in(list(CONSTANT_UCS4))
923 GIMarshallingTests.array_unichar_in(CONSTANT_UCS4)
924
925 def test_array_unichar_out(self):
926 result = list(CONSTANT_UCS4)
927 assert GIMarshallingTests.array_unichar_out() == result
928
929 def test_array_zero_terminated_return_unichar(self):
930 assert GIMarshallingTests.array_zero_terminated_return_unichar() == list(
931 CONSTANT_UCS4
932 )
933
934 def test_array_fixed_int_return(self):
935 self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.array_fixed_int_return())
936
937 def test_array_fixed_short_return(self):
938 self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.array_fixed_short_return())
939
940 def test_array_fixed_int_in(self):
941 GIMarshallingTests.array_fixed_int_in(Sequence([-1, 0, 1, 2]))
942
943 self.assertRaises(
944 TypeError, GIMarshallingTests.array_fixed_int_in, Sequence([-1, "0", 1, 2])
945 )
946
947 self.assertRaises(TypeError, GIMarshallingTests.array_fixed_int_in, 42)
948 self.assertRaises(TypeError, GIMarshallingTests.array_fixed_int_in, None)
949
950 def test_array_fixed_short_in(self):
951 GIMarshallingTests.array_fixed_short_in(Sequence([-1, 0, 1, 2]))
952
953 def test_array_fixed_out(self):
954 self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.array_fixed_out())
955
956 def test_array_fixed_inout(self):
957 self.assertEqual(
958 [2, 1, 0, -1], GIMarshallingTests.array_fixed_inout([-1, 0, 1, 2])
959 )
960
961 def test_array_return(self):
962 self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.array_return())
963
964 def test_array_return_etc(self):
965 self.assertEqual(([5, 0, 1, 9], 14), GIMarshallingTests.array_return_etc(5, 9))
966
967 def test_array_in(self):
968 GIMarshallingTests.array_in(Sequence([-1, 0, 1, 2]))
969 GIMarshallingTests.array_in_guint64_len(Sequence([-1, 0, 1, 2]))
970 GIMarshallingTests.array_in_guint8_len(Sequence([-1, 0, 1, 2]))
971
972 def test_array_in_len_before(self):
973 GIMarshallingTests.array_in_len_before(Sequence([-1, 0, 1, 2]))
974
975 def test_array_in_len_zero_terminated(self):
976 GIMarshallingTests.array_in_len_zero_terminated(Sequence([-1, 0, 1, 2]))
977
978 def test_array_uint8_in(self):
979 GIMarshallingTests.array_uint8_in(Sequence([97, 98, 99, 100]))
980 GIMarshallingTests.array_uint8_in(b"abcd")
981
982 def test_array_string_in(self):
983 GIMarshallingTests.array_string_in(["foo", "bar"])
984
985 def test_array_out(self):
986 self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.array_out())
987
988 def test_array_out_etc(self):
989 self.assertEqual(([-5, 0, 1, 9], 4), GIMarshallingTests.array_out_etc(-5, 9))
990
991 def test_array_inout(self):
992 self.assertEqual(
993 [-2, -1, 0, 1, 2], GIMarshallingTests.array_inout(Sequence([-1, 0, 1, 2]))
994 )
995
996 def test_array_inout_etc(self):
997 self.assertEqual(
998 ([-5, -1, 0, 1, 9], 4),
999 GIMarshallingTests.array_inout_etc(-5, Sequence([-1, 0, 1, 2]), 9),
1000 )
1001
1002 def test_method_array_in(self):
1003 object_ = GIMarshallingTests.Object()
1004 object_.method_array_in(Sequence([-1, 0, 1, 2]))
1005
1006 def test_method_array_out(self):
1007 object_ = GIMarshallingTests.Object()
1008 self.assertEqual([-1, 0, 1, 2], object_.method_array_out())
1009
1010 def test_method_array_inout(self):
1011 object_ = GIMarshallingTests.Object()
1012 self.assertEqual(
1013 [-2, -1, 0, 1, 2], object_.method_array_inout(Sequence([-1, 0, 1, 2]))
1014 )
1015
1016 def test_method_array_return(self):
1017 object_ = GIMarshallingTests.Object()
1018 self.assertEqual([-1, 0, 1, 2], object_.method_array_return())
1019
1020 def test_array_enum_in(self):
1021 GIMarshallingTests.array_enum_in(
1022 [
1023 GIMarshallingTests.Enum.VALUE1,
1024 GIMarshallingTests.Enum.VALUE2,
1025 GIMarshallingTests.Enum.VALUE3,
1026 ]
1027 )
1028
1029 def test_array_boxed_struct_in(self):
1030 struct1 = GIMarshallingTests.BoxedStruct()
1031 struct1.long_ = 1
1032 struct2 = GIMarshallingTests.BoxedStruct()
1033 struct2.long_ = 2
1034 struct3 = GIMarshallingTests.BoxedStruct()
1035 struct3.long_ = 3
1036
1037 GIMarshallingTests.array_struct_in([struct1, struct2, struct3])
1038
1039 def test_array_boxed_struct_in_item_marshal_failure(self):
1040 struct1 = GIMarshallingTests.BoxedStruct()
1041 struct1.long_ = 1
1042 struct2 = GIMarshallingTests.BoxedStruct()
1043 struct2.long_ = 2
1044
1045 self.assertRaises(
1046 TypeError,
1047 GIMarshallingTests.array_struct_in,
1048 [struct1, struct2, "not_a_struct"],
1049 )
1050
1051 def test_array_boxed_struct_value_in(self):
1052 struct1 = GIMarshallingTests.BoxedStruct()
1053 struct1.long_ = 1
1054 struct2 = GIMarshallingTests.BoxedStruct()
1055 struct2.long_ = 2
1056 struct3 = GIMarshallingTests.BoxedStruct()
1057 struct3.long_ = 3
1058
1059 GIMarshallingTests.array_struct_value_in([struct1, struct2, struct3])
1060
1061 def test_array_boxed_struct_value_in_item_marshal_failure(self):
1062 struct1 = GIMarshallingTests.BoxedStruct()
1063 struct1.long_ = 1
1064 struct2 = GIMarshallingTests.BoxedStruct()
1065 struct2.long_ = 2
1066
1067 self.assertRaises(
1068 TypeError,
1069 GIMarshallingTests.array_struct_value_in,
1070 [struct1, struct2, "not_a_struct"],
1071 )
1072
1073 def test_array_boxed_struct_take_in(self):
1074 struct1 = GIMarshallingTests.BoxedStruct()
1075 struct1.long_ = 1
1076 struct2 = GIMarshallingTests.BoxedStruct()
1077 struct2.long_ = 2
1078 struct3 = GIMarshallingTests.BoxedStruct()
1079 struct3.long_ = 3
1080
1081 GIMarshallingTests.array_struct_take_in([struct1, struct2, struct3])
1082
1083 self.assertEqual(1, struct1.long_)
1084
1085 def test_array_boxed_struct_return(self):
1086 (struct1, struct2, struct3) = (
1087 GIMarshallingTests.array_zero_terminated_return_struct()
1088 )
1089 self.assertEqual(GIMarshallingTests.BoxedStruct, type(struct1))
1090 self.assertEqual(GIMarshallingTests.BoxedStruct, type(struct2))
1091 self.assertEqual(GIMarshallingTests.BoxedStruct, type(struct3))
1092 self.assertEqual(42, struct1.long_)
1093 self.assertEqual(43, struct2.long_)
1094 self.assertEqual(44, struct3.long_)
1095
1096 def test_array_simple_struct_in(self):
1097 struct1 = GIMarshallingTests.SimpleStruct()
1098 struct1.long_ = 1
1099 struct2 = GIMarshallingTests.SimpleStruct()
1100 struct2.long_ = 2
1101 struct3 = GIMarshallingTests.SimpleStruct()
1102 struct3.long_ = 3
1103
1104 GIMarshallingTests.array_simple_struct_in([struct1, struct2, struct3])
1105
1106 def test_array_simple_struct_in_item_marshal_failure(self):
1107 struct1 = GIMarshallingTests.SimpleStruct()
1108 struct1.long_ = 1
1109 struct2 = GIMarshallingTests.SimpleStruct()
1110 struct2.long_ = 2
1111
1112 self.assertRaises(
1113 TypeError,
1114 GIMarshallingTests.array_simple_struct_in,
1115 [struct1, struct2, "not_a_struct"],
1116 )
1117
1118 def test_array_multi_array_key_value_in(self):
1119 GIMarshallingTests.multi_array_key_value_in(["one", "two", "three"], [1, 2, 3])
1120
1121 def test_array_in_nonzero_nonlen(self):
1122 GIMarshallingTests.array_in_nonzero_nonlen(1, b"abcd")
1123
1124 def test_array_fixed_out_struct(self):
1125 struct1, struct2 = GIMarshallingTests.array_fixed_out_struct()
1126
1127 self.assertEqual(7, struct1.long_)
1128 self.assertEqual(6, struct1.int8)
1129 self.assertEqual(6, struct2.long_)
1130 self.assertEqual(7, struct2.int8)
1131
1132 def test_array_zero_terminated_return(self):
1133 self.assertEqual(
1134 ["0", "1", "2"], GIMarshallingTests.array_zero_terminated_return()
1135 )
1136
1137 def test_array_zero_terminated_return_null(self):
1138 self.assertEqual([], GIMarshallingTests.array_zero_terminated_return_null())
1139
1140 def test_array_zero_terminated_in(self):
1141 GIMarshallingTests.array_zero_terminated_in(Sequence(["0", "1", "2"]))
1142
1143 def test_array_zero_terminated_out(self):
1144 self.assertEqual(
1145 ["0", "1", "2"], GIMarshallingTests.array_zero_terminated_out()
1146 )
1147
1148 def test_array_zero_terminated_inout(self):
1149 self.assertEqual(
1150 ["-1", "0", "1", "2"],
1151 GIMarshallingTests.array_zero_terminated_inout(["0", "1", "2"]),
1152 )
1153
1154 def test_init_function(self):
1155 self.assertEqual((True, []), GIMarshallingTests.init_function([]))
1156 self.assertEqual((True, []), GIMarshallingTests.init_function(["hello"]))
1157 self.assertEqual(
1158 (True, ["hello"]), GIMarshallingTests.init_function(["hello", "world"])
1159 )
1160
1161 def test_enum_array_return_type(self):
1162 self.assertEqual(
1163 GIMarshallingTests.enum_array_return_type(),
1164 [
1165 GIMarshallingTests.ExtraEnum.VALUE1,
1166 GIMarshallingTests.ExtraEnum.VALUE2,
1167 GIMarshallingTests.ExtraEnum.VALUE3,
1168 ],
1169 )
1170
1171 def test_array_fixed_caller_allocated_out(self):
1172 self.assertEqual(
1173 GIMarshallingTests.array_fixed_caller_allocated_out(),
1174 [
1175 -1,
1176 0,
1177 1,
1178 2,
1179 ],
1180 )
1181
1182 def test_array_fixed_caller_allocated_struct_out(self):
1183 array = GIMarshallingTests.array_fixed_caller_allocated_struct_out()
1184 self.assertEqual(len(array), 4)
1185
1186 self.assertIsInstance(array[0], GIMarshallingTests.SimpleStruct)
1187 self.assertEqual(array[0].long_, -2)
1188 self.assertEqual(array[0].int8, -1)
1189
1190 self.assertIsInstance(array[1], GIMarshallingTests.SimpleStruct)
1191 self.assertEqual(array[1].long_, 1)
1192 self.assertEqual(array[1].int8, 2)
1193
1194 self.assertIsInstance(array[2], GIMarshallingTests.SimpleStruct)
1195 self.assertEqual(array[2].long_, 3)
1196 self.assertEqual(array[2].int8, 4)
1197
1198 self.assertIsInstance(array[3], GIMarshallingTests.SimpleStruct)
1199 self.assertEqual(array[3].long_, 5)
1200 self.assertEqual(array[3].int8, 6)
1201
1202
1203 class TestLengthArray(unittest.TestCase):
1204 def test_length_array_utf8_none_inout(self):
1205 assert GIMarshallingTests.length_array_utf8_none_inout(
1206 ["🅰", "β", "c", "d"]
1207 ) == ["a", "b", "¢", "🔠"]
1208
1209 def test_length_array_utf8_full_inout(self):
1210 assert GIMarshallingTests.length_array_utf8_full_inout(
1211 ["🅰", "β", "c", "d"]
1212 ) == ["a", "b", "¢", "🔠"]
1213
1214 def test_length_array_utf8_optional_inout(self):
1215 assert GIMarshallingTests.length_array_utf8_optional_inout(
1216 ["🅰", "β", "c", "d"]
1217 ) == ["a", "b", "¢", "🔠"]
1218
1219 def test_length_array_utf8_optional_inout_none_arg(self):
1220 assert GIMarshallingTests.length_array_utf8_optional_inout(None) == ["a", "b"]
1221
1222 def test_length_array_utf8_optional_inout_no_arg(self):
1223 assert GIMarshallingTests.length_array_utf8_optional_inout() == ["a", "b"]
1224
1225
1226 class TestGStrv(unittest.TestCase):
1227 def test_gstrv_return(self):
1228 self.assertEqual(["0", "1", "2"], GIMarshallingTests.gstrv_return())
1229
1230 def test_gstrv_in(self):
1231 GIMarshallingTests.gstrv_in(Sequence(["0", "1", "2"]))
1232
1233 def test_gstrv_out(self):
1234 self.assertEqual(["0", "1", "2"], GIMarshallingTests.gstrv_out())
1235
1236 def test_gstrv_inout(self):
1237 self.assertEqual(
1238 ["-1", "0", "1", "2"], GIMarshallingTests.gstrv_inout(["0", "1", "2"])
1239 )
1240
1241
1242 class TestArrayGVariant(unittest.TestCase):
1243 def test_array_gvariant_none_in(self):
1244 v = [GLib.Variant("i", 27), GLib.Variant("s", "Hello")]
1245 returned = [
1246 GLib.Variant.unpack(r) for r in GIMarshallingTests.array_gvariant_none_in(v)
1247 ]
1248 self.assertEqual([27, "Hello"], returned)
1249
1250 def test_array_gvariant_container_in(self):
1251 v = [GLib.Variant("i", 27), GLib.Variant("s", "Hello")]
1252 returned = [
1253 GLib.Variant.unpack(r)
1254 for r in GIMarshallingTests.array_gvariant_container_in(v)
1255 ]
1256 self.assertEqual([27, "Hello"], returned)
1257
1258 def test_array_gvariant_full_in(self):
1259 v = [GLib.Variant("i", 27), GLib.Variant("s", "Hello")]
1260 returned = [
1261 GLib.Variant.unpack(r) for r in GIMarshallingTests.array_gvariant_full_in(v)
1262 ]
1263 self.assertEqual([27, "Hello"], returned)
1264
1265 def test_bytearray_gvariant(self):
1266 v = GLib.Variant.new_bytestring(b"foo")
1267 self.assertEqual(v.get_bytestring(), b"foo")
1268
1269
1270 class TestGArray(unittest.TestCase):
1271 def test_garray_bool_none_in(self):
1272 GIMarshallingTests.garray_bool_none_in([True, False, True, True])
1273
1274 def test_garray_unichar_none_in(self):
1275 GIMarshallingTests.garray_unichar_none_in(CONSTANT_UCS4)
1276 GIMarshallingTests.garray_unichar_none_in(list(CONSTANT_UCS4))
1277
1278 def test_garray_int_none_return(self):
1279 self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.garray_int_none_return())
1280
1281 def test_garray_uint64_none_return(self):
1282 self.assertEqual(
1283 [0, GLib.MAXUINT64], GIMarshallingTests.garray_uint64_none_return()
1284 )
1285
1286 def test_garray_enum_none_return(self):
1287 self.assertEqual(
1288 [
1289 GIMarshallingTests.GEnum.VALUE1,
1290 GIMarshallingTests.GEnum.VALUE2,
1291 GIMarshallingTests.GEnum.VALUE3,
1292 ],
1293 GIMarshallingTests.garray_enum_none_return(),
1294 )
1295
1296 def test_garray_utf8_none_return(self):
1297 self.assertEqual(["0", "1", "2"], GIMarshallingTests.garray_utf8_none_return())
1298
1299 def test_garray_utf8_container_return(self):
1300 self.assertEqual(
1301 ["0", "1", "2"], GIMarshallingTests.garray_utf8_container_return()
1302 )
1303
1304 def test_garray_utf8_full_return(self):
1305 self.assertEqual(["0", "1", "2"], GIMarshallingTests.garray_utf8_full_return())
1306
1307 def test_garray_int_none_in(self):
1308 GIMarshallingTests.garray_int_none_in(Sequence([-1, 0, 1, 2]))
1309
1310 self.assertRaises(
1311 TypeError, GIMarshallingTests.garray_int_none_in, Sequence([-1, "0", 1, 2])
1312 )
1313
1314 self.assertRaises(TypeError, GIMarshallingTests.garray_int_none_in, 42)
1315 self.assertRaises(TypeError, GIMarshallingTests.garray_int_none_in, None)
1316
1317 def test_garray_uint64_none_in(self):
1318 GIMarshallingTests.garray_uint64_none_in(Sequence([0, GLib.MAXUINT64]))
1319
1320 def test_garray_utf8_none_in(self):
1321 GIMarshallingTests.garray_utf8_none_in(Sequence(["0", "1", "2"]))
1322
1323 def test_garray_utf8_none_out(self):
1324 self.assertEqual(["0", "1", "2"], GIMarshallingTests.garray_utf8_none_out())
1325
1326 def test_garray_utf8_container_out(self):
1327 self.assertEqual(
1328 ["0", "1", "2"], GIMarshallingTests.garray_utf8_container_out()
1329 )
1330
1331 def test_garray_utf8_full_out(self):
1332 self.assertEqual(["0", "1", "2"], GIMarshallingTests.garray_utf8_full_out())
1333
1334 def test_garray_utf8_full_out_caller_allocated(self):
1335 self.assertEqual(
1336 ["0", "1", "2"], GIMarshallingTests.garray_utf8_full_out_caller_allocated()
1337 )
1338
1339 def test_garray_utf8_none_inout(self):
1340 self.assertEqual(
1341 ["-2", "-1", "0", "1"],
1342 GIMarshallingTests.garray_utf8_none_inout(Sequence(("0", "1", "2"))),
1343 )
1344
1345 def test_garray_utf8_container_inout(self):
1346 self.assertEqual(
1347 ["-2", "-1", "0", "1"],
1348 GIMarshallingTests.garray_utf8_container_inout(["0", "1", "2"]),
1349 )
1350
1351 def test_garray_utf8_full_inout(self):
1352 self.assertEqual(
1353 ["-2", "-1", "0", "1"],
1354 GIMarshallingTests.garray_utf8_full_inout(["0", "1", "2"]),
1355 )
1356
1357
1358 class TestGPtrArray(unittest.TestCase):
1359 def test_gptrarray_utf8_none_return(self):
1360 self.assertEqual(
1361 ["0", "1", "2"], GIMarshallingTests.gptrarray_utf8_none_return()
1362 )
1363
1364 def test_gptrarray_utf8_container_return(self):
1365 self.assertEqual(
1366 ["0", "1", "2"], GIMarshallingTests.gptrarray_utf8_container_return()
1367 )
1368
1369 def test_gptrarray_utf8_full_return(self):
1370 self.assertEqual(
1371 ["0", "1", "2"], GIMarshallingTests.gptrarray_utf8_full_return()
1372 )
1373
1374 def test_gptrarray_utf8_none_in(self):
1375 GIMarshallingTests.gptrarray_utf8_none_in(Sequence(["0", "1", "2"]))
1376
1377 def test_gptrarray_utf8_none_out(self):
1378 self.assertEqual(["0", "1", "2"], GIMarshallingTests.gptrarray_utf8_none_out())
1379
1380 def test_gptrarray_utf8_container_out(self):
1381 self.assertEqual(
1382 ["0", "1", "2"], GIMarshallingTests.gptrarray_utf8_container_out()
1383 )
1384
1385 def test_gptrarray_utf8_full_out(self):
1386 self.assertEqual(["0", "1", "2"], GIMarshallingTests.gptrarray_utf8_full_out())
1387
1388 def test_gptrarray_utf8_none_inout(self):
1389 self.assertEqual(
1390 ["-2", "-1", "0", "1"],
1391 GIMarshallingTests.gptrarray_utf8_none_inout(Sequence(("0", "1", "2"))),
1392 )
1393
1394 def test_gptrarray_utf8_container_inout(self):
1395 self.assertEqual(
1396 ["-2", "-1", "0", "1"],
1397 GIMarshallingTests.gptrarray_utf8_container_inout(["0", "1", "2"]),
1398 )
1399
1400 def test_gptrarray_utf8_full_inout(self):
1401 self.assertEqual(
1402 ["-2", "-1", "0", "1"],
1403 GIMarshallingTests.gptrarray_utf8_full_inout(["0", "1", "2"]),
1404 )
1405
1406
1407 class TestGBytes(unittest.TestCase):
1408 def test_gbytes_create(self):
1409 b = GLib.Bytes.new(b"\x00\x01\xff")
1410 self.assertEqual(3, b.get_size())
1411 self.assertEqual(b"\x00\x01\xff", b.get_data())
1412
1413 def test_gbytes_create_take(self):
1414 b = GLib.Bytes.new_take(b"\x00\x01\xff")
1415 self.assertEqual(3, b.get_size())
1416 self.assertEqual(b"\x00\x01\xff", b.get_data())
1417
1418 def test_gbytes_full_return(self):
1419 b = GIMarshallingTests.gbytes_full_return()
1420 self.assertEqual(4, b.get_size())
1421 self.assertEqual(b"\x00\x31\xff\x33", b.get_data())
1422
1423 def test_gbytes_none_in(self):
1424 b = GIMarshallingTests.gbytes_full_return()
1425 GIMarshallingTests.gbytes_none_in(b)
1426
1427 def test_compare(self):
1428 a1 = GLib.Bytes.new(b"\x00\x01\xff")
1429 a2 = GLib.Bytes.new(b"\x00\x01\xff")
1430 b = GLib.Bytes.new(b"\x00\x01\xfe")
1431
1432 self.assertTrue(a1.equal(a2))
1433 self.assertTrue(a2.equal(a1))
1434 self.assertFalse(a1.equal(b))
1435 self.assertFalse(b.equal(a2))
1436
1437 self.assertEqual(0, a1.compare(a2))
1438 self.assertLess(0, a1.compare(b))
1439 self.assertGreater(0, b.compare(a1))
1440
1441
1442 class TestGByteArray(unittest.TestCase):
1443 def test_new(self):
1444 ba = GLib.ByteArray.new()
1445 self.assertEqual(b"", ba)
1446
1447 ba = GLib.ByteArray.new_take(b"\x01\x02\xff")
1448 self.assertEqual(b"\x01\x02\xff", ba)
1449
1450 def test_bytearray_full_return(self):
1451 self.assertEqual(b"\x001\xff3", GIMarshallingTests.bytearray_full_return())
1452
1453 def test_bytearray_none_in(self):
1454 b = b"\x00\x31\xff\x33"
1455 ba = GLib.ByteArray.new_take(b)
1456
1457 # b should always have the same value even
1458 # though the generated GByteArray is being modified
1459 GIMarshallingTests.bytearray_none_in(b)
1460 GIMarshallingTests.bytearray_none_in(b)
1461
1462 # The GByteArray is just a bytes
1463 # thus it will not reflect any changes
1464 GIMarshallingTests.bytearray_none_in(ba)
1465 GIMarshallingTests.bytearray_none_in(ba)
1466
1467
1468 class TestGList(unittest.TestCase):
1469 def test_glist_int_none_return(self):
1470 self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.glist_int_none_return())
1471
1472 def test_glist_uint32_none_return(self):
1473 self.assertEqual(
1474 [0, GLib.MAXUINT32], GIMarshallingTests.glist_uint32_none_return()
1475 )
1476
1477 def test_glist_utf8_none_return(self):
1478 self.assertEqual(["0", "1", "2"], GIMarshallingTests.glist_utf8_none_return())
1479
1480 def test_glist_utf8_container_return(self):
1481 self.assertEqual(
1482 ["0", "1", "2"], GIMarshallingTests.glist_utf8_container_return()
1483 )
1484
1485 def test_glist_utf8_full_return(self):
1486 self.assertEqual(["0", "1", "2"], GIMarshallingTests.glist_utf8_full_return())
1487
1488 def test_glist_int_none_in(self):
1489 GIMarshallingTests.glist_int_none_in(Sequence((-1, 0, 1, 2)))
1490
1491 self.assertRaises(
1492 TypeError, GIMarshallingTests.glist_int_none_in, Sequence((-1, "0", 1, 2))
1493 )
1494
1495 self.assertRaises(TypeError, GIMarshallingTests.glist_int_none_in, 42)
1496 self.assertRaises(TypeError, GIMarshallingTests.glist_int_none_in, None)
1497
1498 def test_glist_int_none_in_error_getitem(self):
1499 class FailingSequence(Sequence):
1500 def __getitem__(self, key):
1501 raise Exception
1502
1503 self.assertRaises(
1504 Exception,
1505 GIMarshallingTests.glist_int_none_in,
1506 FailingSequence((-1, 0, 1, 2)),
1507 )
1508
1509 def test_glist_uint32_none_in(self):
1510 GIMarshallingTests.glist_uint32_none_in(Sequence((0, GLib.MAXUINT32)))
1511
1512 def test_glist_utf8_none_in(self):
1513 GIMarshallingTests.glist_utf8_none_in(Sequence(("0", "1", "2")))
1514
1515 def test_glist_utf8_none_out(self):
1516 self.assertEqual(["0", "1", "2"], GIMarshallingTests.glist_utf8_none_out())
1517
1518 def test_glist_utf8_container_out(self):
1519 self.assertEqual(["0", "1", "2"], GIMarshallingTests.glist_utf8_container_out())
1520
1521 def test_glist_utf8_full_out(self):
1522 self.assertEqual(["0", "1", "2"], GIMarshallingTests.glist_utf8_full_out())
1523
1524 def test_glist_utf8_none_inout(self):
1525 self.assertEqual(
1526 ["-2", "-1", "0", "1"],
1527 GIMarshallingTests.glist_utf8_none_inout(Sequence(("0", "1", "2"))),
1528 )
1529
1530 def test_glist_utf8_container_inout(self):
1531 self.assertEqual(
1532 ["-2", "-1", "0", "1"],
1533 GIMarshallingTests.glist_utf8_container_inout(("0", "1", "2")),
1534 )
1535
1536 def test_glist_utf8_full_inout(self):
1537 self.assertEqual(
1538 ["-2", "-1", "0", "1"],
1539 GIMarshallingTests.glist_utf8_full_inout(("0", "1", "2")),
1540 )
1541
1542
1543 class TestGSList(unittest.TestCase):
1544 def test_gslist_int_none_return(self):
1545 self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.gslist_int_none_return())
1546
1547 def test_gslist_utf8_none_return(self):
1548 self.assertEqual(["0", "1", "2"], GIMarshallingTests.gslist_utf8_none_return())
1549
1550 def test_gslist_utf8_container_return(self):
1551 self.assertEqual(
1552 ["0", "1", "2"], GIMarshallingTests.gslist_utf8_container_return()
1553 )
1554
1555 def test_gslist_utf8_full_return(self):
1556 self.assertEqual(["0", "1", "2"], GIMarshallingTests.gslist_utf8_full_return())
1557
1558 def test_gslist_int_none_in(self):
1559 GIMarshallingTests.gslist_int_none_in(Sequence((-1, 0, 1, 2)))
1560
1561 self.assertRaises(
1562 TypeError, GIMarshallingTests.gslist_int_none_in, Sequence((-1, "0", 1, 2))
1563 )
1564
1565 self.assertRaises(TypeError, GIMarshallingTests.gslist_int_none_in, 42)
1566 self.assertRaises(TypeError, GIMarshallingTests.gslist_int_none_in, None)
1567
1568 def test_gslist_int_none_in_error_getitem(self):
1569 class FailingSequence(Sequence):
1570 def __getitem__(self, key):
1571 raise Exception
1572
1573 self.assertRaises(
1574 Exception,
1575 GIMarshallingTests.gslist_int_none_in,
1576 FailingSequence((-1, 0, 1, 2)),
1577 )
1578
1579 def test_gslist_utf8_none_in(self):
1580 GIMarshallingTests.gslist_utf8_none_in(Sequence(("0", "1", "2")))
1581
1582 def test_gslist_utf8_none_out(self):
1583 self.assertEqual(["0", "1", "2"], GIMarshallingTests.gslist_utf8_none_out())
1584
1585 def test_gslist_utf8_container_out(self):
1586 self.assertEqual(
1587 ["0", "1", "2"], GIMarshallingTests.gslist_utf8_container_out()
1588 )
1589
1590 def test_gslist_utf8_full_out(self):
1591 self.assertEqual(["0", "1", "2"], GIMarshallingTests.gslist_utf8_full_out())
1592
1593 def test_gslist_utf8_none_inout(self):
1594 self.assertEqual(
1595 ["-2", "-1", "0", "1"],
1596 GIMarshallingTests.gslist_utf8_none_inout(Sequence(("0", "1", "2"))),
1597 )
1598
1599 def test_gslist_utf8_container_inout(self):
1600 self.assertEqual(
1601 ["-2", "-1", "0", "1"],
1602 GIMarshallingTests.gslist_utf8_container_inout(("0", "1", "2")),
1603 )
1604
1605 def test_gslist_utf8_full_inout(self):
1606 self.assertEqual(
1607 ["-2", "-1", "0", "1"],
1608 GIMarshallingTests.gslist_utf8_full_inout(("0", "1", "2")),
1609 )
1610
1611
1612 class TestGHashTable(unittest.TestCase):
1613 @unittest.skip("broken")
1614 def test_ghashtable_double_in(self):
1615 GIMarshallingTests.ghashtable_double_in(
1616 {"-1": -0.1, "0": 0.0, "1": 0.1, "2": 0.2}
1617 )
1618
1619 @unittest.skip("broken")
1620 def test_ghashtable_float_in(self):
1621 GIMarshallingTests.ghashtable_float_in(
1622 {"-1": -0.1, "0": 0.0, "1": 0.1, "2": 0.2}
1623 )
1624
1625 @unittest.skip("broken")
1626 def test_ghashtable_int64_in(self):
1627 GIMarshallingTests.ghashtable_int64_in(
1628 {"-1": GLib.MAXUINT32 + 1, "0": 0, "1": 1, "2": 2}
1629 )
1630
1631 @unittest.skip("broken")
1632 def test_ghashtable_uint64_in(self):
1633 GIMarshallingTests.ghashtable_uint64_in(
1634 {"-1": GLib.MAXUINT32 + 1, "0": 0, "1": 1, "2": 2}
1635 )
1636
1637 def test_ghashtable_int_none_return(self):
1638 self.assertEqual(
1639 {-1: 1, 0: 0, 1: -1, 2: -2}, GIMarshallingTests.ghashtable_int_none_return()
1640 )
1641
1642 def test_ghashtable_int_none_return2(self):
1643 self.assertEqual(
1644 {"-1": "1", "0": "0", "1": "-1", "2": "-2"},
1645 GIMarshallingTests.ghashtable_utf8_none_return(),
1646 )
1647
1648 def test_ghashtable_int_container_return(self):
1649 self.assertEqual(
1650 {"-1": "1", "0": "0", "1": "-1", "2": "-2"},
1651 GIMarshallingTests.ghashtable_utf8_container_return(),
1652 )
1653
1654 def test_ghashtable_int_full_return(self):
1655 self.assertEqual(
1656 {"-1": "1", "0": "0", "1": "-1", "2": "-2"},
1657 GIMarshallingTests.ghashtable_utf8_full_return(),
1658 )
1659
1660 def test_ghashtable_int_none_in(self):
1661 GIMarshallingTests.ghashtable_int_none_in({-1: 1, 0: 0, 1: -1, 2: -2})
1662
1663 self.assertRaises(
1664 TypeError,
1665 GIMarshallingTests.ghashtable_int_none_in,
1666 {-1: 1, "0": 0, 1: -1, 2: -2},
1667 )
1668 self.assertRaises(
1669 TypeError,
1670 GIMarshallingTests.ghashtable_int_none_in,
1671 {-1: 1, 0: "0", 1: -1, 2: -2},
1672 )
1673
1674 self.assertRaises(
1675 TypeError,
1676 GIMarshallingTests.ghashtable_int_none_in,
1677 "{-1: 1, 0: 0, 1: -1, 2: -2}",
1678 )
1679 self.assertRaises(TypeError, GIMarshallingTests.ghashtable_int_none_in, None)
1680
1681 def test_ghashtable_utf8_none_in(self):
1682 GIMarshallingTests.ghashtable_utf8_none_in(
1683 {"-1": "1", "0": "0", "1": "-1", "2": "-2"}
1684 )
1685
1686 def test_ghashtable_utf8_none_out(self):
1687 self.assertEqual(
1688 {"-1": "1", "0": "0", "1": "-1", "2": "-2"},
1689 GIMarshallingTests.ghashtable_utf8_none_out(),
1690 )
1691
1692 def test_ghashtable_utf8_container_out(self):
1693 self.assertEqual(
1694 {"-1": "1", "0": "0", "1": "-1", "2": "-2"},
1695 GIMarshallingTests.ghashtable_utf8_container_out(),
1696 )
1697
1698 def test_ghashtable_utf8_full_out(self):
1699 self.assertEqual(
1700 {"-1": "1", "0": "0", "1": "-1", "2": "-2"},
1701 GIMarshallingTests.ghashtable_utf8_full_out(),
1702 )
1703
1704 def test_ghashtable_utf8_none_inout(self):
1705 i = {"-1": "1", "0": "0", "1": "-1", "2": "-2"}
1706 self.assertEqual(
1707 {"-1": "1", "0": "0", "1": "1"},
1708 GIMarshallingTests.ghashtable_utf8_none_inout(i),
1709 )
1710
1711 def test_ghashtable_utf8_container_inout(self):
1712 i = {"-1": "1", "0": "0", "1": "-1", "2": "-2"}
1713 self.assertEqual(
1714 {"-1": "1", "0": "0", "1": "1"},
1715 GIMarshallingTests.ghashtable_utf8_container_inout(i),
1716 )
1717
1718 def test_ghashtable_utf8_full_inout(self):
1719 i = {"-1": "1", "0": "0", "1": "-1", "2": "-2"}
1720 self.assertEqual(
1721 {"-1": "1", "0": "0", "1": "1"},
1722 GIMarshallingTests.ghashtable_utf8_full_inout(i),
1723 )
1724
1725 def test_ghashtable_enum_none_in(self):
1726 GIMarshallingTests.ghashtable_enum_none_in(
1727 {
1728 1: GIMarshallingTests.ExtraEnum.VALUE1,
1729 2: GIMarshallingTests.ExtraEnum.VALUE2,
1730 3: GIMarshallingTests.ExtraEnum.VALUE3,
1731 }
1732 )
1733
1734 def test_ghashtable_enum_none_return(self):
1735 self.assertEqual(
1736 {
1737 1: GIMarshallingTests.ExtraEnum.VALUE1,
1738 2: GIMarshallingTests.ExtraEnum.VALUE2,
1739 3: GIMarshallingTests.ExtraEnum.VALUE3,
1740 },
1741 GIMarshallingTests.ghashtable_enum_none_return(),
1742 )
1743
1744
1745 class TestGValue(unittest.TestCase):
1746 def test_gvalue_return(self):
1747 self.assertEqual(42, GIMarshallingTests.gvalue_return())
1748
1749 def test_gvalue_in(self):
1750 GIMarshallingTests.gvalue_in(42)
1751 value = GObject.Value(GObject.TYPE_INT, 42)
1752 GIMarshallingTests.gvalue_in(value)
1753
1754 def test_gvalue_in_with_modification(self):
1755 value = GObject.Value(GObject.TYPE_INT, 42)
1756 GIMarshallingTests.gvalue_in_with_modification(value)
1757 self.assertEqual(value.get_int(), 24)
1758
1759 def test_gvalue_int64_in(self):
1760 value = GObject.Value(GObject.TYPE_INT64, GLib.MAXINT64)
1761 GIMarshallingTests.gvalue_int64_in(value)
1762
1763 def test_gvalue_in_with_type(self):
1764 value = GObject.Value(GObject.TYPE_STRING, "foo")
1765 GIMarshallingTests.gvalue_in_with_type(value, GObject.TYPE_STRING)
1766
1767 value = GObject.Value(
1768 GIMarshallingTests.Flags.__gtype__, GIMarshallingTests.Flags.VALUE1
1769 )
1770 GIMarshallingTests.gvalue_in_with_type(value, GObject.TYPE_FLAGS)
1771
1772 def test_gvalue_in_enum(self):
1773 # It is unclear what GIMarshallingTests expects here, since
1774 # GIMarshallingTests.Enum is an unregistered type.
1775 # https://gitlab.gnome.org/GNOME/gobject-introspection-tests/-/issues/8
1776 value = GObject.Value(
1777 GIMarshallingTests.GEnum.__gtype__, GIMarshallingTests.GEnum.VALUE3
1778 )
1779 GIMarshallingTests.gvalue_in_enum(value)
1780
1781 def test_gvalue_out(self):
1782 self.assertEqual(42, GIMarshallingTests.gvalue_out())
1783
1784 def test_gvalue_int64_out(self):
1785 self.assertEqual(GLib.MAXINT64, GIMarshallingTests.gvalue_int64_out())
1786
1787 def test_gvalue_out_caller_allocates(self):
1788 self.assertEqual(42, GIMarshallingTests.gvalue_out_caller_allocates())
1789
1790 def test_gvalue_inout(self):
1791 self.assertEqual("42", GIMarshallingTests.gvalue_inout(42))
1792 value = GObject.Value(int, 42)
1793 self.assertEqual("42", GIMarshallingTests.gvalue_inout(value))
1794
1795 def test_gvalue_flat_array_in(self):
1796 # the function already asserts the correct values
1797 GIMarshallingTests.gvalue_flat_array([42, "42", True])
1798
1799 def test_gvalue_flat_array_in_item_marshal_failure(self):
1800 # Tests the failure to marshal 2^256 to a GValue mid-way through the array marshaling.
1801 self.assertRaises(
1802 OverflowError, GIMarshallingTests.gvalue_flat_array, [42, 2**256, True]
1803 )
1804
1805 self.assertRaises(
1806 OverflowError,
1807 GIMarshallingTests.gvalue_flat_array,
1808 [GLib.MAXINT + 1, "42", True],
1809 )
1810 self.assertRaises(
1811 OverflowError,
1812 GIMarshallingTests.gvalue_flat_array,
1813 [GLib.MININT - 1, "42", True],
1814 )
1815
1816 # FIXME: https://gitlab.gnome.org/GNOME/pygobject/-/issues/582#note_1764164
1817 exc_prefix = "Item 0: " if sys.version_info[:2] < (3, 12) else ""
1818
1819 with pytest.raises(
1820 OverflowError,
1821 match=exc_prefix
1822 + f"{GLib.MAXINT + 1:d} not in range {GLib.MININT:d} to {GLib.MAXINT:d}",
1823 ):
1824 GIMarshallingTests.gvalue_flat_array([GLib.MAXINT + 1, "42", True])
1825
1826 min_, max_ = GLib.MININT, GLib.MAXINT
1827
1828 with pytest.raises(
1829 OverflowError,
1830 match=exc_prefix
1831 + f"{GLib.MAXUINT64 * 2:d} not in range {min_:d} to {max_:d}",
1832 ):
1833 GIMarshallingTests.gvalue_flat_array([GLib.MAXUINT64 * 2, "42", True])
1834
1835 def test_gvalue_flat_array_out(self):
1836 values = GIMarshallingTests.return_gvalue_flat_array()
1837 self.assertEqual(values, [42, "42", True])
1838
1839 def test_gvalue_gobject_ref_counts_simple(self):
1840 obj = GObject.Object()
1841 grefcount = obj.__grefcount__
1842 value = GObject.Value(GObject.TYPE_OBJECT, obj)
1843 del value
1844 gc.collect()
1845 assert obj.__grefcount__ == grefcount
1846
1847 def test_gvalue_gobject_ref_counts(self):
1848 # Tests a GObject held by a GValue
1849 obj = GObject.Object()
1850 ref = weakref.ref(obj)
1851 grefcount = obj.__grefcount__
1852
1853 value = GObject.Value()
1854 value.init(GObject.TYPE_OBJECT)
1855
1856 # TYPE_OBJECT will inc ref count as it should
1857 value.set_object(obj)
1858 self.assertEqual(obj.__grefcount__, grefcount + 1)
1859
1860 # multiple set_object should not inc ref count
1861 value.set_object(obj)
1862 self.assertEqual(obj.__grefcount__, grefcount + 1)
1863
1864 # get_object will re-use the same wrapper as obj
1865 res = value.get_object()
1866 self.assertEqual(obj, res)
1867 self.assertEqual(obj.__grefcount__, grefcount + 1)
1868
1869 # multiple get_object should not inc ref count
1870 res = value.get_object()
1871 self.assertEqual(obj.__grefcount__, grefcount + 1)
1872
1873 # deletion of the result and value holder should bring the
1874 # refcount back to where we started
1875 del res
1876 del value
1877 gc.collect()
1878 self.assertEqual(obj.__grefcount__, grefcount)
1879
1880 del obj
1881 gc.collect()
1882 self.assertEqual(ref(), None)
1883
1884 @unittest.skipUnless(hasattr(sys, "getrefcount"), "no sys.getrefcount")
1885 def test_gvalue_boxed_ref_counts(self):
1886 # Tests a boxed type wrapping a python object pointer (TYPE_PYOBJECT)
1887 # held by a GValue
1888 class Obj:
1889 pass
1890
1891 obj = Obj()
1892 ref = weakref.ref(obj)
1893 refcount = sys.getrefcount(obj)
1894
1895 value = GObject.Value()
1896 value.init(GObject.TYPE_PYOBJECT)
1897
1898 # boxed TYPE_PYOBJECT will inc ref count as it should
1899 value.set_boxed(obj)
1900 self.assertEqual(sys.getrefcount(obj), refcount + 1)
1901
1902 # multiple set_boxed should not inc ref count
1903 value.set_boxed(obj)
1904 self.assertEqual(sys.getrefcount(obj), refcount + 1)
1905
1906 res = value.get_boxed()
1907 self.assertEqual(obj, res)
1908 self.assertEqual(sys.getrefcount(obj), refcount + 2)
1909
1910 # multiple get_boxed should not inc ref count
1911 res = value.get_boxed()
1912 self.assertEqual(sys.getrefcount(obj), refcount + 2)
1913
1914 # deletion of the result and value holder should bring the
1915 # refcount back to where we started
1916 del res
1917 del value
1918 gc.collect()
1919 self.assertEqual(sys.getrefcount(obj), refcount)
1920
1921 del obj
1922 gc.collect()
1923 self.assertEqual(ref(), None)
1924
1925 @unittest.skip("broken")
1926 def test_gvalue_flat_array_round_trip(self):
1927 self.assertEqual(
1928 [42, "42", True],
1929 GIMarshallingTests.gvalue_flat_array_round_trip(42, "42", True),
1930 )
1931
1932 def test_gvalue_float(self):
1933 GIMarshallingTests.gvalue_float(GObject.Float(3.14), 3.14)
1934
1935
1936 class TestGClosure(unittest.TestCase):
1937 def test_in(self):
1938 GIMarshallingTests.gclosure_in(lambda: 42)
1939
1940 def test_in_partial(self):
1941 from functools import partial
1942
1943 called_args = []
1944 called_kwargs = {}
1945
1946 def callback(*args, **kwargs):
1947 called_args.extend(args)
1948 called_kwargs.update(kwargs)
1949 return 42
1950
1951 func = partial(callback, 1, 2, 3, foo=42)
1952 GIMarshallingTests.gclosure_in(func)
1953 assert called_args == [1, 2, 3]
1954 assert called_kwargs["foo"] == 42
1955
1956 def test_pass(self):
1957 # test passing a closure between two C calls
1958 closure = GIMarshallingTests.gclosure_return()
1959 GIMarshallingTests.gclosure_in(closure)
1960
1961 def test_type_error(self):
1962 self.assertRaises(TypeError, GIMarshallingTests.gclosure_in, 42)
1963 self.assertRaises(TypeError, GIMarshallingTests.gclosure_in, None)
1964
1965
1966 class TestCallbacks(unittest.TestCase):
1967 def test_return_value_only(self):
1968 def cb():
1969 return 5
1970
1971 self.assertEqual(GIMarshallingTests.callback_return_value_only(cb), 5)
1972
1973 def test_one_out_arg(self):
1974 def cb():
1975 return 5.5
1976
1977 self.assertAlmostEqual(GIMarshallingTests.callback_one_out_parameter(cb), 5.5)
1978
1979 def test_multiple_out_args(self):
1980 def cb():
1981 return (5.5, 42.0)
1982
1983 res = GIMarshallingTests.callback_multiple_out_parameters(cb)
1984 self.assertAlmostEqual(res[0], 5.5)
1985 self.assertAlmostEqual(res[1], 42.0)
1986
1987 def test_return_and_one_out_arg(self):
1988 def cb():
1989 return (5, 42.0)
1990
1991 res = GIMarshallingTests.callback_return_value_and_one_out_parameter(cb)
1992 self.assertEqual(res[0], 5)
1993 self.assertAlmostEqual(res[1], 42.0)
1994
1995 def test_return_and_multiple_out_arg(self):
1996 def cb():
1997 return (5, 42, -1000)
1998
1999 self.assertEqual(
2000 GIMarshallingTests.callback_return_value_and_multiple_out_parameters(cb),
2001 (5, 42, -1000),
2002 )
2003
2004
2005 class TestPointer(unittest.TestCase):
2006 def test_pointer_in_return(self):
2007 self.assertEqual(GIMarshallingTests.pointer_in_return(42), 42)
2008
2009
2010 class TestEnum(unittest.TestCase):
2011 def test_enum(self):
2012 self.assertTrue(issubclass(GIMarshallingTests.Enum, int))
2013 self.assertTrue(
2014 isinstance(GIMarshallingTests.Enum.VALUE1, GIMarshallingTests.Enum)
2015 )
2016 self.assertTrue(
2017 isinstance(GIMarshallingTests.Enum.VALUE2, GIMarshallingTests.Enum)
2018 )
2019 self.assertTrue(
2020 isinstance(GIMarshallingTests.Enum.VALUE3, GIMarshallingTests.Enum)
2021 )
2022 self.assertEqual(42, GIMarshallingTests.Enum.VALUE3)
2023
2024 def test_enum_in(self):
2025 GIMarshallingTests.enum_in(GIMarshallingTests.Enum.VALUE3)
2026 GIMarshallingTests.enum_in(42)
2027
2028 self.assertRaises(TypeError, GIMarshallingTests.enum_in, 43)
2029 self.assertRaises(
2030 TypeError, GIMarshallingTests.enum_in, "GIMarshallingTests.Enum.VALUE3"
2031 )
2032
2033 def test_enum_return(self):
2034 enum = GIMarshallingTests.enum_returnv()
2035 self.assertTrue(isinstance(enum, GIMarshallingTests.Enum))
2036 self.assertEqual(enum, GIMarshallingTests.Enum.VALUE3)
2037
2038 def test_enum_out(self):
2039 enum = GIMarshallingTests.enum_out()
2040 self.assertTrue(isinstance(enum, GIMarshallingTests.Enum))
2041 self.assertEqual(enum, GIMarshallingTests.Enum.VALUE3)
2042
2043 def test_enum_inout(self):
2044 enum = GIMarshallingTests.enum_inout(GIMarshallingTests.Enum.VALUE3)
2045 self.assertTrue(isinstance(enum, GIMarshallingTests.Enum))
2046 self.assertEqual(enum, GIMarshallingTests.Enum.VALUE1)
2047
2048 def test_enum_second(self):
2049 # check for the bug where different non-gtype enums share the same class
2050 self.assertNotEqual(GIMarshallingTests.Enum, GIMarshallingTests.SecondEnum)
2051
2052 # check that values are not being shared between different enums
2053 self.assertTrue(hasattr(GIMarshallingTests.SecondEnum, "SECONDVALUE1"))
2054 self.assertRaises(
2055 AttributeError, getattr, GIMarshallingTests.Enum, "SECONDVALUE1"
2056 )
2057 self.assertTrue(hasattr(GIMarshallingTests.Enum, "VALUE1"))
2058 self.assertRaises(
2059 AttributeError, getattr, GIMarshallingTests.SecondEnum, "VALUE1"
2060 )
2061
2062 def test_enum_has_no_gtype(self):
2063 # GIMarshallingTests.Enum is not registered with the GType system
2064 self.assertFalse(hasattr(GIMarshallingTests.Enum, "__gtype__"))
2065 self.assertFalse(isinstance(GIMarshallingTests.Enum, GObject.GEnum))
2066
2067 def test_enum_add_type_error(self):
2068 with self.assertRaises(TypeError):
2069 gi._gi.enum_add(
2070 self,
2071 "Flags",
2072 GIMarshallingTests.Flags.__gtype__,
2073 GIMarshallingTests.Flags.__info__,
2074 )
2075
2076 def test_enum_add_module_type_error(self):
2077 with self.assertRaises(TypeError):
2078 gi._gi.flags_add(
2079 "self",
2080 "GEnum",
2081 GIMarshallingTests.GEnum.__gtype__,
2082 GIMarshallingTests.GEnum.__info__,
2083 )
2084
2085 def test_type_module_name(self):
2086 self.assertEqual(GIMarshallingTests.Enum.__name__, "Enum")
2087 self.assertEqual(
2088 GIMarshallingTests.Enum.__module__, "gi.repository.GIMarshallingTests"
2089 )
2090
2091 def test_hash(self):
2092 assert hash(GIMarshallingTests.Enum.VALUE1) == hash(
2093 GIMarshallingTests.Enum(GIMarshallingTests.Enum.VALUE1)
2094 )
2095
2096 def test_repr(self):
2097 self.assertEqual(repr(GIMarshallingTests.Enum.VALUE3), "<Enum.VALUE3: 42>")
2098
2099 def test_enum_field_set(self):
2100 option = GLib.OptionEntry()
2101 # GLib.OptionEntry.arg is of type GLib.OptionArg, which is not
2102 # registered with the GObject type system by libglib.
2103 option.arg = GLib.OptionArg.NONE
2104
2105
2106 class TestEnumVFuncResults(unittest.TestCase):
2107 class EnumTester(GIMarshallingTests.Object):
2108 def do_vfunc_return_enum(self):
2109 return GIMarshallingTests.Enum.VALUE2
2110
2111 def do_vfunc_out_enum(self):
2112 return GIMarshallingTests.Enum.VALUE3
2113
2114 def test_vfunc_return_enum(self):
2115 tester = self.EnumTester()
2116 self.assertEqual(tester.vfunc_return_enum(), GIMarshallingTests.Enum.VALUE2)
2117
2118 def test_vfunc_out_enum(self):
2119 tester = self.EnumTester()
2120 self.assertEqual(tester.vfunc_out_enum(), GIMarshallingTests.Enum.VALUE3)
2121
2122
2123 class TestGEnum(unittest.TestCase):
2124 def test_genum(self):
2125 self.assertTrue(issubclass(GIMarshallingTests.GEnum, GObject.GEnum))
2126 self.assertTrue(
2127 isinstance(GIMarshallingTests.GEnum.VALUE1, GIMarshallingTests.GEnum)
2128 )
2129 self.assertTrue(
2130 isinstance(GIMarshallingTests.GEnum.VALUE2, GIMarshallingTests.GEnum)
2131 )
2132 self.assertTrue(
2133 isinstance(GIMarshallingTests.GEnum.VALUE3, GIMarshallingTests.GEnum)
2134 )
2135 self.assertEqual(42, GIMarshallingTests.GEnum.VALUE3)
2136
2137 def test_pickle(self):
2138 v = GIMarshallingTests.GEnum.VALUE3
2139 new_v = pickle.loads(pickle.dumps(v))
2140 assert new_v == v
2141 assert isinstance(new_v, GIMarshallingTests.GEnum)
2142
2143 def test_value_nick_and_name(self):
2144 self.assertEqual(GIMarshallingTests.GEnum.VALUE1.value_nick, "value1")
2145 self.assertEqual(GIMarshallingTests.GEnum.VALUE2.value_nick, "value2")
2146 self.assertEqual(GIMarshallingTests.GEnum.VALUE3.value_nick, "value3")
2147
2148 self.assertEqual(
2149 GIMarshallingTests.GEnum.VALUE1.value_name,
2150 "GI_MARSHALLING_TESTS_GENUM_VALUE1",
2151 )
2152 self.assertEqual(
2153 GIMarshallingTests.GEnum.VALUE2.value_name,
2154 "GI_MARSHALLING_TESTS_GENUM_VALUE2",
2155 )
2156 self.assertEqual(
2157 GIMarshallingTests.GEnum.VALUE3.value_name,
2158 "GI_MARSHALLING_TESTS_GENUM_VALUE3",
2159 )
2160
2161 def test_genum_in(self):
2162 GIMarshallingTests.genum_in(GIMarshallingTests.GEnum.VALUE3)
2163 GIMarshallingTests.genum_in(42)
2164 GIMarshallingTests.GEnum.in_(42)
2165
2166 self.assertRaises(TypeError, GIMarshallingTests.genum_in, 43)
2167 self.assertRaises(
2168 TypeError, GIMarshallingTests.genum_in, "GIMarshallingTests.GEnum.VALUE3"
2169 )
2170
2171 def test_genum_return(self):
2172 genum = GIMarshallingTests.genum_returnv()
2173 self.assertTrue(isinstance(genum, GIMarshallingTests.GEnum))
2174 self.assertEqual(genum, GIMarshallingTests.GEnum.VALUE3)
2175
2176 def test_genum_out(self):
2177 genum = GIMarshallingTests.genum_out()
2178 genum = GIMarshallingTests.GEnum.out()
2179 self.assertTrue(isinstance(genum, GIMarshallingTests.GEnum))
2180 self.assertEqual(genum, GIMarshallingTests.GEnum.VALUE3)
2181
2182 def test_genum_inout(self):
2183 genum = GIMarshallingTests.genum_inout(GIMarshallingTests.GEnum.VALUE3)
2184 self.assertTrue(isinstance(genum, GIMarshallingTests.GEnum))
2185 self.assertEqual(genum, GIMarshallingTests.GEnum.VALUE1)
2186
2187 def test_type_module_name(self):
2188 self.assertEqual(GIMarshallingTests.GEnum.__name__, "GEnum")
2189 self.assertEqual(
2190 GIMarshallingTests.GEnum.__module__, "gi.repository.GIMarshallingTests"
2191 )
2192
2193 def test_enum_values_property(self):
2194 with warnings.catch_warnings():
2195 warnings.simplefilter("ignore", PyGIDeprecationWarning)
2196
2197 assert GIMarshallingTests.GEnum.__enum_values__ == {
2198 0: GIMarshallingTests.GEnum.VALUE1,
2199 1: GIMarshallingTests.GEnum.VALUE2,
2200 42: GIMarshallingTests.GEnum.VALUE3,
2201 }
2202
2203 def test_hash(self):
2204 assert hash(GIMarshallingTests.GEnum.VALUE3) == hash(
2205 GIMarshallingTests.GEnum(GIMarshallingTests.GEnum.VALUE3)
2206 )
2207
2208 def test_repr(self):
2209 self.assertEqual(repr(GIMarshallingTests.GEnum.VALUE3), "<GEnum.VALUE3: 42>")
2210
2211
2212 class TestGFlags(unittest.TestCase):
2213 def test_flags(self):
2214 self.assertTrue(issubclass(GIMarshallingTests.Flags, GObject.GFlags))
2215 self.assertTrue(
2216 isinstance(GIMarshallingTests.Flags.VALUE1, GIMarshallingTests.Flags)
2217 )
2218 self.assertTrue(
2219 isinstance(GIMarshallingTests.Flags.VALUE2, GIMarshallingTests.Flags)
2220 )
2221 self.assertTrue(
2222 isinstance(GIMarshallingTests.Flags.VALUE3, GIMarshallingTests.Flags)
2223 )
2224 # __or__() operation should still return an instance, not an int.
2225 self.assertTrue(
2226 isinstance(
2227 GIMarshallingTests.Flags.VALUE1 | GIMarshallingTests.Flags.VALUE2,
2228 GIMarshallingTests.Flags,
2229 )
2230 )
2231 self.assertEqual(1 << 1, GIMarshallingTests.Flags.VALUE2)
2232
2233 def test_value_nick_and_name(self):
2234 self.assertEqual(GIMarshallingTests.Flags.VALUE1.first_value_nick, "value1")
2235 self.assertEqual(GIMarshallingTests.Flags.VALUE2.first_value_nick, "value2")
2236 self.assertEqual(GIMarshallingTests.Flags.VALUE3.first_value_nick, "value3")
2237
2238 self.assertEqual(
2239 GIMarshallingTests.Flags.VALUE1.first_value_name,
2240 "GI_MARSHALLING_TESTS_FLAGS_VALUE1",
2241 )
2242 self.assertEqual(
2243 GIMarshallingTests.Flags.VALUE2.first_value_name,
2244 "GI_MARSHALLING_TESTS_FLAGS_VALUE2",
2245 )
2246 self.assertEqual(
2247 GIMarshallingTests.Flags.VALUE3.first_value_name,
2248 "GI_MARSHALLING_TESTS_FLAGS_VALUE3",
2249 )
2250
2251 def test_flags_in(self):
2252 GIMarshallingTests.flags_in(GIMarshallingTests.Flags.VALUE2)
2253 GIMarshallingTests.Flags.in_(GIMarshallingTests.Flags.VALUE2)
2254 # result of __or__() operation should still be valid instance, not an int.
2255 GIMarshallingTests.flags_in(
2256 GIMarshallingTests.Flags.VALUE2 | GIMarshallingTests.Flags.VALUE2
2257 )
2258 GIMarshallingTests.flags_in_zero(Number(0))
2259 GIMarshallingTests.Flags.in_zero(Number(0))
2260
2261 GIMarshallingTests.flags_in(1 << 1)
2262 self.assertRaises(
2263 TypeError, GIMarshallingTests.flags_in, "GIMarshallingTests.Flags.VALUE2"
2264 )
2265
2266 def test_flags_return(self):
2267 flags = GIMarshallingTests.flags_returnv()
2268 self.assertTrue(isinstance(flags, GIMarshallingTests.Flags))
2269 self.assertEqual(flags, GIMarshallingTests.Flags.VALUE2)
2270
2271 def test_flags_return_method(self):
2272 flags = GIMarshallingTests.Flags.returnv()
2273 self.assertTrue(isinstance(flags, GIMarshallingTests.Flags))
2274 self.assertEqual(flags, GIMarshallingTests.Flags.VALUE2)
2275
2276 def test_flags_out(self):
2277 flags = GIMarshallingTests.flags_out()
2278 self.assertTrue(isinstance(flags, GIMarshallingTests.Flags))
2279 self.assertEqual(flags, GIMarshallingTests.Flags.VALUE2)
2280
2281 def test_flags_inout(self):
2282 flags = GIMarshallingTests.flags_inout(GIMarshallingTests.Flags.VALUE2)
2283 self.assertTrue(isinstance(flags, GIMarshallingTests.Flags))
2284 self.assertEqual(flags, GIMarshallingTests.Flags.VALUE1)
2285
2286 def test_type_module_name(self):
2287 self.assertEqual(GIMarshallingTests.Flags.__name__, "Flags")
2288 self.assertEqual(
2289 GIMarshallingTests.Flags.__module__, "gi.repository.GIMarshallingTests"
2290 )
2291
2292 def test_flags_values_property(self):
2293 flags_values = {
2294 1: GIMarshallingTests.Flags.VALUE1,
2295 2: GIMarshallingTests.Flags.VALUE2,
2296 4: GIMarshallingTests.Flags.VALUE3,
2297 }
2298
2299 # Since Python 3.11 only primary values are considered.
2300 # See https://docs.python.org/3/whatsnew/3.11.html#enum
2301 if sys.version_info[:2] < (3, 11):
2302 flags_values[3] = GIMarshallingTests.Flags.MASK
2303
2304 with warnings.catch_warnings():
2305 warnings.simplefilter("ignore", PyGIDeprecationWarning)
2306
2307 assert GIMarshallingTests.Flags.__flags_values__ == flags_values
2308
2309 def test_repr(self):
2310 self.assertEqual(repr(GIMarshallingTests.Flags.VALUE2), "<Flags.VALUE2: 2>")
2311 self.assertIn(
2312 repr(GIMarshallingTests.Flags.VALUE2 | GIMarshallingTests.Flags.VALUE3),
2313 {"<Flags.VALUE2|VALUE3: 6>", "<Flags.VALUE3|VALUE2: 6>"},
2314 )
2315
2316 def test_hash(self):
2317 assert hash(GIMarshallingTests.Flags.VALUE2) == hash(
2318 GIMarshallingTests.Flags(GIMarshallingTests.Flags.VALUE2)
2319 )
2320
2321 def test_flags_large_in(self):
2322 GIMarshallingTests.extra_flags_large_in(GIMarshallingTests.ExtraFlags.VALUE2)
2323
2324
2325 class TestNoTypeFlags(unittest.TestCase):
2326 def test_flags(self):
2327 self.assertTrue(issubclass(GIMarshallingTests.NoTypeFlags, enum.IntFlag))
2328 self.assertTrue(
2329 isinstance(
2330 GIMarshallingTests.NoTypeFlags.VALUE1, GIMarshallingTests.NoTypeFlags
2331 )
2332 )
2333 self.assertTrue(
2334 isinstance(
2335 GIMarshallingTests.NoTypeFlags.VALUE2, GIMarshallingTests.NoTypeFlags
2336 )
2337 )
2338 self.assertTrue(
2339 isinstance(
2340 GIMarshallingTests.NoTypeFlags.VALUE3, GIMarshallingTests.NoTypeFlags
2341 )
2342 )
2343 # __or__() operation should still return an instance, not an int.
2344 self.assertTrue(
2345 isinstance(
2346 GIMarshallingTests.NoTypeFlags.VALUE1
2347 | GIMarshallingTests.NoTypeFlags.VALUE2,
2348 GIMarshallingTests.NoTypeFlags,
2349 )
2350 )
2351 self.assertEqual(1 << 1, GIMarshallingTests.NoTypeFlags.VALUE2)
2352
2353 def test_flags_in(self):
2354 GIMarshallingTests.no_type_flags_in(GIMarshallingTests.NoTypeFlags.VALUE2)
2355 GIMarshallingTests.no_type_flags_in(
2356 GIMarshallingTests.NoTypeFlags.VALUE2
2357 | GIMarshallingTests.NoTypeFlags.VALUE2
2358 )
2359 GIMarshallingTests.no_type_flags_in_zero(Number(0))
2360
2361 GIMarshallingTests.no_type_flags_in(1 << 1)
2362 self.assertRaises(
2363 TypeError,
2364 GIMarshallingTests.no_type_flags_in,
2365 "GIMarshallingTests.NoTypeFlags.VALUE2",
2366 )
2367
2368 def test_flags_return(self):
2369 flags = GIMarshallingTests.no_type_flags_returnv()
2370 self.assertTrue(isinstance(flags, GIMarshallingTests.NoTypeFlags))
2371 self.assertEqual(flags, GIMarshallingTests.NoTypeFlags.VALUE2)
2372
2373 def test_flags_out(self):
2374 flags = GIMarshallingTests.no_type_flags_out()
2375 self.assertTrue(isinstance(flags, GIMarshallingTests.NoTypeFlags))
2376 self.assertEqual(flags, GIMarshallingTests.NoTypeFlags.VALUE2)
2377
2378 def test_flags_inout(self):
2379 flags = GIMarshallingTests.no_type_flags_inout(
2380 GIMarshallingTests.NoTypeFlags.VALUE2
2381 )
2382 self.assertTrue(isinstance(flags, GIMarshallingTests.NoTypeFlags))
2383 self.assertEqual(flags, GIMarshallingTests.NoTypeFlags.VALUE1)
2384
2385 def test_flags_has_no_gtype(self):
2386 self.assertFalse(hasattr(GIMarshallingTests.NoTypeFlags, "__gtype__"))
2387 self.assertFalse(issubclass(GIMarshallingTests.NoTypeFlags, GObject.GFlags))
2388
2389 def test_type_module_name(self):
2390 self.assertEqual(GIMarshallingTests.NoTypeFlags.__name__, "NoTypeFlags")
2391 self.assertEqual(
2392 GIMarshallingTests.NoTypeFlags.__module__,
2393 "gi.repository.GIMarshallingTests",
2394 )
2395
2396 def test_repr(self):
2397 self.assertEqual(
2398 repr(GIMarshallingTests.NoTypeFlags.VALUE2), "<NoTypeFlags.VALUE2: 2>"
2399 )
2400
2401 def test_flags_add_module_type_error(self):
2402 with self.assertRaises(TypeError):
2403 gi._gi.flags_add(
2404 "self",
2405 "Flags",
2406 GIMarshallingTests.Flags.__gtype__,
2407 GIMarshallingTests.Flags.__info__,
2408 )
2409
2410
2411 class TestStructure(unittest.TestCase):
2412 def test_simple_struct(self):
2413 self.assertTrue(issubclass(GIMarshallingTests.SimpleStruct, GObject.GPointer))
2414
2415 struct = GIMarshallingTests.SimpleStruct()
2416 self.assertTrue(isinstance(struct, GIMarshallingTests.SimpleStruct))
2417
2418 self.assertEqual(0, struct.long_)
2419 self.assertEqual(0, struct.int8)
2420
2421 struct.long_ = 6
2422 struct.int8 = 7
2423
2424 self.assertEqual(6, struct.long_)
2425 self.assertEqual(7, struct.int8)
2426
2427 del struct
2428
2429 def test_nested_struct(self):
2430 struct = GIMarshallingTests.NestedStruct()
2431
2432 self.assertTrue(
2433 isinstance(struct.simple_struct, GIMarshallingTests.SimpleStruct)
2434 )
2435
2436 struct.simple_struct.long_ = 42
2437 self.assertEqual(42, struct.simple_struct.long_)
2438
2439 del struct
2440
2441 def test_not_simple_struct(self):
2442 struct = GIMarshallingTests.NotSimpleStruct()
2443 self.assertEqual(None, struct.pointer)
2444
2445 def test_simple_struct_return(self):
2446 struct = GIMarshallingTests.simple_struct_returnv()
2447
2448 self.assertTrue(isinstance(struct, GIMarshallingTests.SimpleStruct))
2449 self.assertEqual(6, struct.long_)
2450 self.assertEqual(7, struct.int8)
2451
2452 del struct
2453
2454 def test_simple_struct_in(self):
2455 struct = GIMarshallingTests.SimpleStruct()
2456 struct.long_ = 6
2457 struct.int8 = 7
2458
2459 GIMarshallingTests.SimpleStruct.inv(struct)
2460
2461 del struct
2462
2463 struct = GIMarshallingTests.NestedStruct()
2464
2465 self.assertRaises(TypeError, GIMarshallingTests.SimpleStruct.inv, struct)
2466
2467 del struct
2468
2469 self.assertRaises(TypeError, GIMarshallingTests.SimpleStruct.inv, None)
2470
2471 def test_simple_struct_method(self):
2472 struct = GIMarshallingTests.SimpleStruct()
2473 struct.long_ = 6
2474 struct.int8 = 7
2475
2476 struct.method()
2477
2478 del struct
2479
2480 self.assertRaises(TypeError, GIMarshallingTests.SimpleStruct.method)
2481
2482 def test_pointer_struct(self):
2483 self.assertTrue(issubclass(GIMarshallingTests.PointerStruct, GObject.GPointer))
2484
2485 struct = GIMarshallingTests.PointerStruct()
2486 self.assertTrue(isinstance(struct, GIMarshallingTests.PointerStruct))
2487
2488 del struct
2489
2490 def test_pointer_struct_return(self):
2491 struct = GIMarshallingTests.pointer_struct_returnv()
2492
2493 self.assertTrue(isinstance(struct, GIMarshallingTests.PointerStruct))
2494 self.assertEqual(42, struct.long_)
2495
2496 del struct
2497
2498 def test_pointer_struct_in(self):
2499 struct = GIMarshallingTests.PointerStruct()
2500 struct.long_ = 42
2501
2502 struct.inv()
2503
2504 del struct
2505
2506 def test_boxed_struct(self):
2507 self.assertTrue(issubclass(GIMarshallingTests.BoxedStruct, GObject.GBoxed))
2508
2509 struct = GIMarshallingTests.BoxedStruct()
2510 self.assertTrue(isinstance(struct, GIMarshallingTests.BoxedStruct))
2511
2512 self.assertEqual(0, struct.long_)
2513 self.assertEqual(None, struct.string_)
2514 self.assertEqual([], struct.g_strv)
2515
2516 del struct
2517
2518 def test_boxed_struct_new(self):
2519 struct = GIMarshallingTests.BoxedStruct.new()
2520 self.assertTrue(isinstance(struct, GIMarshallingTests.BoxedStruct))
2521 self.assertEqual(struct.long_, 0)
2522 self.assertEqual(struct.string_, None)
2523
2524 del struct
2525
2526 def test_boxed_struct_copy(self):
2527 struct = GIMarshallingTests.BoxedStruct()
2528 struct.long_ = 42
2529 struct.string_ = "hello"
2530
2531 new_struct = struct.copy()
2532 self.assertTrue(isinstance(new_struct, GIMarshallingTests.BoxedStruct))
2533 self.assertEqual(new_struct.long_, 42)
2534 self.assertEqual(new_struct.string_, "hello")
2535
2536 del new_struct
2537 del struct
2538
2539 def test_boxed_struct_return(self):
2540 struct = GIMarshallingTests.boxed_struct_returnv()
2541
2542 self.assertTrue(isinstance(struct, GIMarshallingTests.BoxedStruct))
2543 self.assertEqual(42, struct.long_)
2544 self.assertEqual("hello", struct.string_)
2545 self.assertEqual(["0", "1", "2"], struct.g_strv)
2546
2547 del struct
2548
2549 def test_boxed_struct_in(self):
2550 struct = GIMarshallingTests.BoxedStruct()
2551 struct.long_ = 42
2552
2553 struct.inv()
2554
2555 del struct
2556
2557 def test_boxed_struct_out(self):
2558 struct = GIMarshallingTests.boxed_struct_out()
2559
2560 self.assertTrue(isinstance(struct, GIMarshallingTests.BoxedStruct))
2561 self.assertEqual(42, struct.long_)
2562
2563 del struct
2564
2565 def test_boxed_struct_inout(self):
2566 in_struct = GIMarshallingTests.BoxedStruct()
2567 in_struct.long_ = 42
2568
2569 out_struct = GIMarshallingTests.boxed_struct_inout(in_struct)
2570
2571 self.assertTrue(isinstance(out_struct, GIMarshallingTests.BoxedStruct))
2572 self.assertEqual(0, out_struct.long_)
2573
2574 del in_struct
2575 del out_struct
2576
2577 def test_pointer_array_struct_with_guint8(self):
2578 out_struct = GIMarshallingTests.PointerArrayStruct.with_uint8_array()
2579
2580 with capture_glib_warnings(allow_warnings=True):
2581 assert out_struct.array == list(map(ord, "0123456789"))
2582
2583 def test_struct_field_assignment(self):
2584 struct = GIMarshallingTests.BoxedStruct()
2585
2586 struct.long_ = 42
2587 struct.string_ = "hello"
2588 self.assertEqual(struct.long_, 42)
2589 self.assertEqual(struct.string_, "hello")
2590
2591 def test_union_init(self):
2592 with warnings.catch_warnings(record=True) as warn:
2593 warnings.simplefilter("always")
2594 GIMarshallingTests.Union(42)
2595
2596 self.assertTrue(issubclass(warn[0].category, DeprecationWarning))
2597
2598 with warnings.catch_warnings(record=True) as warn:
2599 warnings.simplefilter("always")
2600 GIMarshallingTests.Union(f=42)
2601
2602 self.assertTrue(issubclass(warn[0].category, DeprecationWarning))
2603
2604 def test_union(self):
2605 union = GIMarshallingTests.Union()
2606
2607 self.assertTrue(isinstance(union, GIMarshallingTests.Union))
2608
2609 new_union = union.copy()
2610 self.assertTrue(isinstance(new_union, GIMarshallingTests.Union))
2611
2612 del union
2613 del new_union
2614
2615 def test_union_return(self):
2616 union = GIMarshallingTests.union_returnv()
2617
2618 self.assertTrue(isinstance(union, GIMarshallingTests.Union))
2619 self.assertEqual(42, union.long_)
2620
2621 del union
2622
2623 def test_union_in(self):
2624 union = GIMarshallingTests.Union()
2625 union.long_ = 42
2626
2627 union.inv()
2628
2629 del union
2630
2631 def test_union_method(self):
2632 union = GIMarshallingTests.Union()
2633 union.long_ = 42
2634
2635 union.method()
2636
2637 del union
2638
2639 self.assertRaises(TypeError, GIMarshallingTests.Union.method)
2640
2641 def test_repr(self):
2642 self.assertRegex(
2643 repr(GIMarshallingTests.PointerStruct()),
2644 r"<GIMarshallingTests.PointerStruct object at 0x[^\s]+ "
2645 r"\((void|GIMarshallingTestsPointerStruct) at 0x[^\s]+\)>",
2646 )
2647
2648 self.assertRegex(
2649 repr(GIMarshallingTests.SimpleStruct()),
2650 r"<GIMarshallingTests.SimpleStruct object at 0x[^\s]+ "
2651 r"\((void|GIMarshallingTestsSimpleStruct) at 0x[^\s]+\)>",
2652 )
2653
2654 self.assertRegex(
2655 repr(GIMarshallingTests.Union()),
2656 r"<GIMarshallingTests.Union object at 0x[^\s]+ "
2657 r"\(GIMarshallingTestsUnion at 0x[^\s]+\)>",
2658 )
2659
2660 self.assertRegex(
2661 repr(GIMarshallingTests.BoxedStruct()),
2662 r"<GIMarshallingTests.BoxedStruct object at 0x[^\s]+ "
2663 r"\(GIMarshallingTestsBoxedStruct at 0x[^\s]+\)>",
2664 )
2665
2666
2667 class TestGObject(unittest.TestCase):
2668 def test_object(self):
2669 self.assertTrue(issubclass(GIMarshallingTests.Object, GObject.GObject))
2670
2671 object_ = GIMarshallingTests.Object()
2672 self.assertTrue(isinstance(object_, GIMarshallingTests.Object))
2673 self.assertEqual(object_.__grefcount__, 1)
2674
2675 def test_object_new(self):
2676 object_ = GIMarshallingTests.Object.new(42)
2677 self.assertTrue(isinstance(object_, GIMarshallingTests.Object))
2678 self.assertEqual(object_.__grefcount__, 1)
2679
2680 def test_object_int(self):
2681 object_ = GIMarshallingTests.Object(int=42)
2682 self.assertEqual(object_.int_, 42)
2683
2684 # FIXME: Don't work yet.
2685 # object_.int_ = 0
2686 # self.assertEqual(object_.int_, 0)
2687
2688 def test_object_static_method(self):
2689 GIMarshallingTests.Object.static_method()
2690
2691 def test_object_method(self):
2692 GIMarshallingTests.Object(int=42).method()
2693 self.assertRaises(
2694 TypeError, GIMarshallingTests.Object.method, GObject.GObject()
2695 )
2696 self.assertRaises(TypeError, GIMarshallingTests.Object.method)
2697
2698 def test_sub_object(self):
2699 self.assertTrue(
2700 issubclass(GIMarshallingTests.SubObject, GIMarshallingTests.Object)
2701 )
2702
2703 object_ = GIMarshallingTests.SubObject()
2704 self.assertTrue(isinstance(object_, GIMarshallingTests.SubObject))
2705
2706 def test_sub_object_new(self):
2707 self.assertRaises(TypeError, GIMarshallingTests.SubObject.new, 42)
2708
2709 def test_sub_object_static_method(self):
2710 object_ = GIMarshallingTests.SubObject()
2711 object_.static_method()
2712
2713 def test_sub_object_method(self):
2714 object_ = GIMarshallingTests.SubObject(int=42)
2715 object_.method()
2716
2717 def test_sub_object_sub_method(self):
2718 object_ = GIMarshallingTests.SubObject()
2719 object_.sub_method()
2720
2721 def test_sub_object_overwritten_method(self):
2722 object_ = GIMarshallingTests.SubObject()
2723 object_.overwritten_method()
2724
2725 self.assertRaises(
2726 TypeError,
2727 GIMarshallingTests.SubObject.overwritten_method,
2728 GIMarshallingTests.Object(),
2729 )
2730
2731 def test_sub_object_int(self):
2732 object_ = GIMarshallingTests.SubObject()
2733 self.assertEqual(object_.int_, 0)
2734
2735 # FIXME: Don't work yet.
2736 # object_.int_ = 42
2737 # self.assertEqual(object_.int_, 42)
2738
2739 def test_object_none_return(self):
2740 object_ = GIMarshallingTests.Object.none_return()
2741 self.assertTrue(isinstance(object_, GIMarshallingTests.Object))
2742 self.assertEqual(object_.__grefcount__, 2)
2743
2744 def test_object_full_return(self):
2745 object_ = GIMarshallingTests.Object.full_return()
2746 self.assertTrue(isinstance(object_, GIMarshallingTests.Object))
2747 self.assertEqual(object_.__grefcount__, 1)
2748
2749 def test_object_none_in(self):
2750 object_ = GIMarshallingTests.Object(int=42)
2751 GIMarshallingTests.Object.none_in(object_)
2752 self.assertEqual(object_.__grefcount__, 1)
2753
2754 object_ = GIMarshallingTests.SubObject(int=42)
2755 GIMarshallingTests.Object.none_in(object_)
2756
2757 object_ = GObject.GObject()
2758 self.assertRaises(TypeError, GIMarshallingTests.Object.none_in, object_)
2759
2760 self.assertRaises(TypeError, GIMarshallingTests.Object.none_in, None)
2761
2762 def test_object_none_out(self):
2763 object_ = GIMarshallingTests.Object.none_out()
2764 self.assertTrue(isinstance(object_, GIMarshallingTests.Object))
2765 self.assertEqual(object_.__grefcount__, 2)
2766
2767 new_object = GIMarshallingTests.Object.none_out()
2768 self.assertTrue(new_object is object_)
2769
2770 def test_object_full_out(self):
2771 object_ = GIMarshallingTests.Object.full_out()
2772 self.assertTrue(isinstance(object_, GIMarshallingTests.Object))
2773 self.assertEqual(object_.__grefcount__, 1)
2774
2775 def test_object_none_inout(self):
2776 object_ = GIMarshallingTests.Object(int=42)
2777 new_object = GIMarshallingTests.Object.none_inout(object_)
2778
2779 self.assertTrue(isinstance(new_object, GIMarshallingTests.Object))
2780
2781 self.assertFalse(object_ is new_object)
2782
2783 self.assertEqual(object_.__grefcount__, 1)
2784 self.assertEqual(new_object.__grefcount__, 2)
2785
2786 new_new_object = GIMarshallingTests.Object.none_inout(object_)
2787 self.assertTrue(new_new_object is new_object)
2788
2789 GIMarshallingTests.Object.none_inout(GIMarshallingTests.SubObject(int=42))
2790
2791 def test_object_full_inout(self):
2792 # Using gimarshallingtests.c from GI versions > 1.38.0 will show this
2793 # test as an "unexpected success" due to reference leak fixes in that file.
2794 # TODO: remove the expectedFailure once PyGI relies on GI > 1.38.0.
2795 object_ = GIMarshallingTests.Object(int=42)
2796 new_object = GIMarshallingTests.Object.full_inout(object_)
2797
2798 self.assertTrue(isinstance(new_object, GIMarshallingTests.Object))
2799
2800 self.assertFalse(object_ is new_object)
2801
2802 self.assertEqual(object_.__grefcount__, 1)
2803 self.assertEqual(new_object.__grefcount__, 1)
2804
2805 def test_repr(self):
2806 self.assertRegex(
2807 repr(GIMarshallingTests.Object(int=42)),
2808 r"<GIMarshallingTests.Object object at 0x[^\s]+ "
2809 r"\(GIMarshallingTestsObject at 0x[^\s]+\)>",
2810 )
2811
2812 def test_nongir_repr(self):
2813 self.assertRegex(
2814 repr(Gio.File.new_for_path("/")),
2815 r"<__gi__.GLocalFile object at 0x[^\s]+ " r"\(GLocalFile at 0x[^\s]+\)>",
2816 )
2817
2818 def test_constructor_bad_cls_arg(self):
2819 # Get the unbound version of a constructor
2820 newv = GObject.GObject.newv.__func__
2821
2822 class Foo:
2823 pass
2824
2825 with self.assertRaisesRegex(AttributeError, r"has no attribute '__name__'"):
2826 foo = Foo()
2827 newv(foo)
2828
2829 with self.assertRaisesRegex(TypeError, r"attribute is not a string"):
2830 foo = Foo()
2831 foo.__name__ = 42
2832 newv(foo)
2833
2834
2835 # FIXME: Doesn't actually return the same object.
2836 # def test_object_inout_same(self):
2837 # object_ = GIMarshallingTests.Object()
2838 # new_object = GIMarshallingTests.object_full_inout(object_)
2839 # self.assertTrue(object_ is new_object)
2840 # self.assertEqual(object_.__grefcount__, 1)
2841
2842
2843 class TestPythonGObject(unittest.TestCase):
2844 class Object(GIMarshallingTests.Object):
2845 return_for_caller_allocated_out_parameter = "test caller alloc return"
2846
2847 def __init__(self, int):
2848 GIMarshallingTests.Object.__init__(self)
2849 self.val = None
2850
2851 def method(self):
2852 # Don't call super, which asserts that self.int == 42.
2853 pass
2854
2855 def do_method_int8_in(self, int8):
2856 self.val = int8
2857
2858 def do_method_int8_out(self):
2859 return 42
2860
2861 def do_method_int8_arg_and_out_caller(self, arg):
2862 return arg + 1
2863
2864 def do_method_int8_arg_and_out_callee(self, arg):
2865 return arg + 1
2866
2867 def do_method_str_arg_out_ret(self, arg):
2868 return (arg.upper(), len(arg))
2869
2870 def do_method_with_default_implementation(self, int8):
2871 GIMarshallingTests.Object.do_method_with_default_implementation(self, int8)
2872 self.props.int += int8
2873
2874 def do_vfunc_return_value_only(self):
2875 return 4242
2876
2877 def do_vfunc_one_out_parameter(self):
2878 return 42.42
2879
2880 def do_vfunc_multiple_out_parameters(self):
2881 return (42.42, 3.14)
2882
2883 def do_vfunc_return_value_and_one_out_parameter(self):
2884 return (5, 42)
2885
2886 def do_vfunc_return_value_and_multiple_out_parameters(self):
2887 return (5, 42, 99)
2888
2889 def do_vfunc_caller_allocated_out_parameter(self):
2890 return self.return_for_caller_allocated_out_parameter
2891
2892 class SubObject(GIMarshallingTests.SubObject):
2893 def __init__(self, int):
2894 GIMarshallingTests.SubObject.__init__(self)
2895 self.val = None
2896
2897 def do_method_with_default_implementation(self, int8):
2898 self.val = int8
2899
2900 def do_vfunc_return_value_only(self):
2901 return 2121
2902
2903 class Interface3Impl(GObject.Object, GIMarshallingTests.Interface3):
2904 def __init__(self):
2905 GObject.Object.__init__(self)
2906 self.variants = None
2907 self.n_variants = None
2908
2909 def do_test_variant_array_in(self, variants, n_variants):
2910 self.variants = variants
2911 self.n_variants = n_variants
2912
2913 class ErrorObject(GIMarshallingTests.Object):
2914 def do_vfunc_return_value_only(self):
2915 raise ValueError("Return value should be 0")
2916
2917 def test_object(self):
2918 self.assertTrue(issubclass(self.Object, GIMarshallingTests.Object))
2919
2920 object_ = self.Object(int=42)
2921 self.assertTrue(isinstance(object_, self.Object))
2922
2923 def test_object_fail(self):
2924 with self.assertRaises(GLib.Error):
2925 GIMarshallingTests.Object.new_fail(int_=42)
2926
2927 def test_object_method(self):
2928 self.Object(int=0).method()
2929
2930 def test_object_vfuncs(self):
2931 object_ = self.Object(int=42)
2932 object_.method_int8_in(84)
2933 self.assertEqual(object_.val, 84)
2934 self.assertEqual(object_.method_int8_out(), 42)
2935
2936 # can be dropped when bumping g-i dependencies to >= 1.35.2
2937 if hasattr(object_, "method_int8_arg_and_out_caller"):
2938 self.assertEqual(object_.method_int8_arg_and_out_caller(42), 43)
2939 self.assertEqual(object_.method_int8_arg_and_out_callee(42), 43)
2940 self.assertEqual(object_.method_str_arg_out_ret("hello"), ("HELLO", 5))
2941
2942 object_.method_with_default_implementation(42)
2943 self.assertEqual(object_.props.int, 84)
2944
2945 self.assertEqual(object_.vfunc_return_value_only(), 4242)
2946 self.assertAlmostEqual(object_.vfunc_one_out_parameter(), 42.42, places=5)
2947
2948 (a, b) = object_.vfunc_multiple_out_parameters()
2949 self.assertAlmostEqual(a, 42.42, places=5)
2950 self.assertAlmostEqual(b, 3.14, places=5)
2951
2952 self.assertEqual(object_.vfunc_return_value_and_one_out_parameter(), (5, 42))
2953 self.assertEqual(
2954 object_.vfunc_return_value_and_multiple_out_parameters(), (5, 42, 99)
2955 )
2956
2957 self.assertEqual(
2958 object_.vfunc_caller_allocated_out_parameter(),
2959 object_.return_for_caller_allocated_out_parameter,
2960 )
2961
2962 class ObjectWithoutVFunc(GIMarshallingTests.Object):
2963 def __init__(self, int):
2964 GIMarshallingTests.Object.__init__(self)
2965
2966 object_ = ObjectWithoutVFunc(int=42)
2967 object_.method_with_default_implementation(84)
2968 self.assertEqual(object_.props.int, 84)
2969
2970 @unittest.skipUnless(hasattr(sys, "getrefcount"), "no sys.getrefcount")
2971 def test_vfunc_return_ref_count(self):
2972 obj = self.Object(int=42)
2973 ref_count = sys.getrefcount(obj.return_for_caller_allocated_out_parameter)
2974 ret = obj.vfunc_caller_allocated_out_parameter()
2975 gc.collect()
2976
2977 # Make sure the return and what the vfunc returned
2978 # are equal but not the same object.
2979 self.assertEqual(ret, obj.return_for_caller_allocated_out_parameter)
2980 self.assertFalse(ret is obj.return_for_caller_allocated_out_parameter)
2981 self.assertEqual(
2982 sys.getrefcount(obj.return_for_caller_allocated_out_parameter), ref_count
2983 )
2984
2985 def test_vfunc_return_no_ref_count(self):
2986 obj = self.Object(int=42)
2987 ret = obj.vfunc_caller_allocated_out_parameter()
2988 self.assertEqual(ret, obj.return_for_caller_allocated_out_parameter)
2989 self.assertFalse(ret is obj.return_for_caller_allocated_out_parameter)
2990
2991 def test_subobject_parent_vfunc(self):
2992 object_ = self.SubObject(int=81)
2993 object_.method_with_default_implementation(87)
2994 self.assertEqual(object_.val, 87)
2995
2996 def test_subobject_child_vfunc(self):
2997 object_ = self.SubObject(int=1)
2998 self.assertEqual(object_.vfunc_return_value_only(), 2121)
2999
3000 def test_subobject_non_vfunc_do_method(self):
3001 class PythonObjectWithNonVFuncDoMethod:
3002 def do_not_a_vfunc(self):
3003 return 5
3004
3005 class ObjectOverrideNonVFuncDoMethod(
3006 GIMarshallingTests.Object, PythonObjectWithNonVFuncDoMethod
3007 ):
3008 def do_not_a_vfunc(self):
3009 value = super().do_not_a_vfunc()
3010 return 13 + value
3011
3012 object_ = ObjectOverrideNonVFuncDoMethod()
3013 self.assertEqual(18, object_.do_not_a_vfunc())
3014
3015 def test_native_function_not_set_in_subclass_dict(self):
3016 # Previously, GI was setting virtual functions on the class as well
3017 # as any *native* class that subclasses it. Here we check that it is only
3018 # set on the class that the method is originally from.
3019 self.assertTrue(
3020 "do_method_with_default_implementation"
3021 in GIMarshallingTests.Object.__dict__
3022 )
3023 self.assertTrue(
3024 "do_method_with_default_implementation"
3025 not in GIMarshallingTests.SubObject.__dict__
3026 )
3027
3028 def test_subobject_with_interface_and_non_vfunc_do_method(self):
3029 # There was a bug for searching for vfuncs in interfaces. It was
3030 # triggered by having a do_* method that wasn't overriding
3031 # a native vfunc, as well as inheriting from an interface.
3032 class GObjectSubclassWithInterface(
3033 GObject.GObject, GIMarshallingTests.Interface
3034 ):
3035 def do_method_not_a_vfunc(self):
3036 pass
3037
3038 def test_subsubobject(self):
3039 class SubSubSubObject(GIMarshallingTests.SubSubObject):
3040 def do_method_deep_hierarchy(self, num):
3041 self.props.int = num * 2
3042
3043 sub_sub_sub_object = SubSubSubObject()
3044 GIMarshallingTests.SubSubObject.do_method_deep_hierarchy(sub_sub_sub_object, 5)
3045 self.assertEqual(sub_sub_sub_object.props.int, 5)
3046
3047 def test_interface3impl(self):
3048 iface3 = self.Interface3Impl()
3049 variants = [GLib.Variant("i", 27), GLib.Variant("s", "Hello")]
3050 iface3.test_variant_array_in(variants)
3051 self.assertEqual(iface3.n_variants, 2)
3052 self.assertEqual(iface3.variants[0].unpack(), 27)
3053 self.assertEqual(iface3.variants[1].unpack(), "Hello")
3054
3055 def test_python_subsubobject_vfunc(self):
3056 class PySubObject(GIMarshallingTests.Object):
3057 def __init__(self):
3058 GIMarshallingTests.Object.__init__(self)
3059 self.sub_method_int8_called = 0
3060
3061 def do_method_int8_in(self, int8):
3062 self.sub_method_int8_called += 1
3063
3064 class PySubSubObject(PySubObject):
3065 def __init__(self):
3066 PySubObject.__init__(self)
3067 self.subsub_method_int8_called = 0
3068
3069 def do_method_int8_in(self, int8):
3070 self.subsub_method_int8_called += 1
3071
3072 so = PySubObject()
3073 so.method_int8_in(1)
3074 self.assertEqual(so.sub_method_int8_called, 1)
3075
3076 # it should call the method on the SubSub object only
3077 sso = PySubSubObject()
3078 sso.method_int8_in(1)
3079 self.assertEqual(sso.subsub_method_int8_called, 1)
3080 self.assertEqual(sso.sub_method_int8_called, 0)
3081
3082 def test_callback_in_vfunc(self):
3083 class SubObject(GIMarshallingTests.Object):
3084 def __init__(self):
3085 GObject.GObject.__init__(self)
3086 self.worked = False
3087
3088 def do_vfunc_with_callback(self, callback):
3089 self.worked = callback(42) == 42
3090
3091 object_ = SubObject()
3092 object_.call_vfunc_with_callback()
3093 self.assertTrue(object_.worked)
3094 object_.worked = False
3095 object_.call_vfunc_with_callback()
3096 self.assertTrue(object_.worked)
3097
3098 def test_exception_in_vfunc_return_value(self):
3099 obj = self.ErrorObject()
3100 with capture_exceptions() as exc:
3101 self.assertEqual(obj.vfunc_return_value_only(), 0)
3102 self.assertEqual(len(exc), 1)
3103 self.assertEqual(exc[0].type, ValueError)
3104
3105 def test_callback_owned_box(self):
3106 def callback(box, data):
3107 self.box = box
3108
3109 def nop_callback(box, data):
3110 pass
3111
3112 GIMarshallingTests.callback_owned_boxed(callback, None)
3113 GIMarshallingTests.callback_owned_boxed(nop_callback, None)
3114 self.assertEqual(self.box.long_, 1)
3115
3116 def test_callback_user_data_after_callback(self):
3117 def callback(*args):
3118 self.callback_args = args
3119
3120 GIMarshallingTests.callback_user_data_after_callback(1, 2, callback)
3121 self.assertEqual(self.callback_args, (1, 2))
3122
3123 GIMarshallingTests.callback_user_data_after_callback(3, 4, callback, "testdata")
3124 self.assertEqual(self.callback_args, (3, 4, "testdata"))
3125
3126 GIMarshallingTests.callback_user_data_after_callback(
3127 5, 6, callback, "more testdata", "even more testdata"
3128 )
3129 self.assertEqual(
3130 self.callback_args, (5, 6, "more testdata", "even more testdata")
3131 )
3132
3133 def test_callback_user_data_before_callback(self):
3134 def callback(*args):
3135 self.callback_args = args
3136
3137 GIMarshallingTests.callback_user_data_before_callback(1, 2, None, callback)
3138 self.assertEqual(self.callback_args, (1, 2, None))
3139
3140 GIMarshallingTests.callback_user_data_before_callback(
3141 3, 4, "testdata", callback
3142 )
3143 self.assertEqual(self.callback_args, (3, 4, "testdata"))
3144
3145 GIMarshallingTests.callback_user_data_before_callback(
3146 5, 6, ("more testdata", "even more testdata"), callback
3147 )
3148 self.assertEqual(
3149 self.callback_args, (5, 6, ("more testdata", "even more testdata"))
3150 )
3151
3152
3153 class TestMultiOutputArgs(unittest.TestCase):
3154 def test_int_out_out(self):
3155 self.assertEqual((6, 7), GIMarshallingTests.int_out_out())
3156
3157 def test_int_return_out(self):
3158 self.assertEqual((6, 7), GIMarshallingTests.int_return_out())
3159
3160
3161 # Interface
3162
3163
3164 class TestInterfaces(unittest.TestCase):
3165 class TestInterfaceImpl(GObject.GObject, GIMarshallingTests.Interface):
3166 def __init__(self):
3167 GObject.GObject.__init__(self)
3168 self.val = None
3169
3170 def do_test_int8_in(self, int8):
3171 self.val = int8
3172
3173 def setUp(self):
3174 self.instance = self.TestInterfaceImpl()
3175
3176 def test_iface_impl(self):
3177 instance = GIMarshallingTests.InterfaceImpl()
3178 assert instance.get_as_interface() is instance
3179 instance.test_int8_in(42)
3180
3181 def test_wrapper(self):
3182 self.assertTrue(issubclass(GIMarshallingTests.Interface, GObject.GInterface))
3183 self.assertEqual(
3184 GIMarshallingTests.Interface.__gtype__.name, "GIMarshallingTestsInterface"
3185 )
3186 self.assertRaises(NotImplementedError, GIMarshallingTests.Interface)
3187
3188 def test_implementation(self):
3189 self.assertTrue(
3190 issubclass(self.TestInterfaceImpl, GIMarshallingTests.Interface)
3191 )
3192 self.assertTrue(isinstance(self.instance, GIMarshallingTests.Interface))
3193
3194 def test_int8_int(self):
3195 GIMarshallingTests.test_interface_test_int8_in(self.instance, 42)
3196 self.assertEqual(self.instance.val, 42)
3197
3198 def test_subclass(self):
3199 class TestInterfaceImplA(self.TestInterfaceImpl):
3200 pass
3201
3202 class TestInterfaceImplB(TestInterfaceImplA):
3203 pass
3204
3205 instance = TestInterfaceImplA()
3206 GIMarshallingTests.test_interface_test_int8_in(instance, 42)
3207 self.assertEqual(instance.val, 42)
3208
3209 def test_subclass_override(self):
3210 class TestInterfaceImplD(TestInterfaces.TestInterfaceImpl):
3211 val2 = None
3212
3213 def do_test_int8_in(self, int8):
3214 self.val2 = int8
3215
3216 instance = TestInterfaceImplD()
3217 self.assertEqual(instance.val, None)
3218 self.assertEqual(instance.val2, None)
3219
3220 GIMarshallingTests.test_interface_test_int8_in(instance, 42)
3221 self.assertEqual(instance.val, None)
3222 self.assertEqual(instance.val2, 42)
3223
3224 def test_type_mismatch(self):
3225 obj = GIMarshallingTests.Object()
3226
3227 # wrong type for first argument: interface
3228 enum = Gio.File.new_for_path(".").enumerate_children(
3229 "", Gio.FileQueryInfoFlags.NONE, None
3230 )
3231 try:
3232 enum.next_file(obj)
3233 self.fail("call with wrong type argument unexpectedly succeeded")
3234 except TypeError as e:
3235 # should have argument name
3236 self.assertTrue("cancellable" in str(e), e)
3237 # should have expected type
3238 self.assertTrue("xpected Gio.Cancellable" in str(e), e)
3239 # should have actual type
3240 self.assertTrue("GIMarshallingTests.Object" in str(e), e)
3241
3242 # wrong type for self argument: interface
3243 try:
3244 Gio.FileEnumerator.next_file(obj, None)
3245 self.fail("call with wrong type argument unexpectedly succeeded")
3246 except TypeError as e:
3247 # should have argument name
3248 self.assertTrue("self" in str(e), e)
3249 # should have expected type
3250 self.assertTrue("xpected Gio.FileEnumerator" in str(e), e)
3251 # should have actual type
3252 self.assertTrue("GIMarshallingTests.Object" in str(e), e)
3253
3254 # wrong type for first argument: GObject
3255 var = GLib.Variant("s", "mystring")
3256 action = Gio.SimpleAction.new("foo", var.get_type())
3257 try:
3258 action.activate(obj)
3259 self.fail("call with wrong type argument unexpectedly succeeded")
3260 except TypeError as e:
3261 # should have argument name
3262 self.assertTrue("parameter" in str(e), e)
3263 # should have expected type
3264 self.assertTrue("xpected GLib.Variant" in str(e), e)
3265 # should have actual type
3266 self.assertTrue("GIMarshallingTests.Object" in str(e), e)
3267
3268 # wrong type for self argument: GObject
3269 try:
3270 Gio.SimpleAction.activate(obj, obj)
3271 self.fail("call with wrong type argument unexpectedly succeeded")
3272 except TypeError as e:
3273 # should have argument name
3274 self.assertTrue("self" in str(e), e)
3275 # should have expected type
3276 self.assertTrue("xpected Gio.Action" in str(e), e)
3277 # should have actual type
3278 self.assertTrue("GIMarshallingTests.Object" in str(e), e)
3279
3280
3281 class TestMRO(unittest.TestCase):
3282 def test_mro(self):
3283 # check that our own MRO calculation matches what we would expect
3284 # from Python's own C3 calculations
3285 class A:
3286 pass
3287
3288 class B(A):
3289 pass
3290
3291 class C(A):
3292 pass
3293
3294 class D(B, C):
3295 pass
3296
3297 class E(D, GIMarshallingTests.Object):
3298 pass
3299
3300 expected = (
3301 E,
3302 D,
3303 B,
3304 C,
3305 A,
3306 GIMarshallingTests.Object,
3307 GObject.Object,
3308 GObject.Object.__base__,
3309 gi._gi.GObject,
3310 object,
3311 )
3312 self.assertEqual(expected, E.__mro__)
3313
3314 @unittest.skipIf(
3315 sys.implementation.name == "pypy", "PyPy 3.11 causes cycle among base classes"
3316 )
3317 def test_interface_collision(self):
3318 # there was a problem with Python bailing out because of
3319 # http://en.wikipedia.org/wiki/Diamond_problem with interfaces,
3320 # which shouldn't really be a problem.
3321
3322 class TestInterfaceImpl(GObject.GObject, GIMarshallingTests.Interface):
3323 pass
3324
3325 class TestInterfaceImpl2(GIMarshallingTests.Interface, TestInterfaceImpl):
3326 pass
3327
3328 class TestInterfaceImpl3(TestInterfaceImpl, GIMarshallingTests.Interface2):
3329 pass
3330
3331 def test_old_style_mixin(self):
3332 # Note: Old style classes don't exist in Python 3
3333 class Mixin:
3334 pass
3335
3336 with warnings.catch_warnings(record=True) as warn:
3337 warnings.simplefilter("always")
3338
3339 # Dynamically create a new gi based class with an old
3340 # style mixin.
3341 type("GIWithOldStyleMixin", (GIMarshallingTests.Object, Mixin), {})
3342
3343 self.assertEqual(len(warn), 0)
3344
3345
3346 class TestInterfaceClash(unittest.TestCase):
3347 def test_clash(self):
3348 def create_clash():
3349 class TestClash(
3350 GObject.GObject,
3351 GIMarshallingTests.Interface,
3352 GIMarshallingTests.Interface2,
3353 ):
3354 def do_test_int8_in(self, int8):
3355 pass
3356
3357 TestClash()
3358
3359 self.assertRaises(TypeError, create_clash)
3360
3361
3362 class TestOverrides(unittest.TestCase):
3363 def test_constant(self):
3364 self.assertEqual(GIMarshallingTests.OVERRIDES_CONSTANT, 7)
3365
3366 def test_struct(self):
3367 # Test that the constructor has been overridden.
3368 struct = GIMarshallingTests.OverridesStruct(42)
3369
3370 self.assertTrue(isinstance(struct, GIMarshallingTests.OverridesStruct))
3371
3372 # Test that the method has been overridden.
3373 self.assertEqual(6, struct.method())
3374
3375 del struct
3376
3377 # Test that the overrides wrapper has been registered.
3378 struct = GIMarshallingTests.overrides_struct_returnv()
3379
3380 self.assertTrue(isinstance(struct, GIMarshallingTests.OverridesStruct))
3381
3382 del struct
3383
3384 def test_object(self):
3385 # Test that the constructor has been overridden.
3386 object_ = GIMarshallingTests.OverridesObject(42)
3387
3388 self.assertTrue(isinstance(object_, GIMarshallingTests.OverridesObject))
3389
3390 # Test that the alternate constructor has been overridden.
3391 object_ = GIMarshallingTests.OverridesObject.new(42)
3392
3393 self.assertTrue(isinstance(object_, GIMarshallingTests.OverridesObject))
3394
3395 # Test that the method has been overridden.
3396 self.assertEqual(6, object_.method())
3397
3398 # Test that the overrides wrapper has been registered.
3399 object_ = GIMarshallingTests.OverridesObject.returnv()
3400
3401 self.assertTrue(isinstance(object_, GIMarshallingTests.OverridesObject))
3402
3403 def test_module_name(self):
3404 # overridden types
3405 self.assertEqual(
3406 GIMarshallingTests.OverridesStruct.__module__,
3407 "gi.overrides.GIMarshallingTests",
3408 )
3409 self.assertEqual(
3410 GIMarshallingTests.OverridesObject.__module__,
3411 "gi.overrides.GIMarshallingTests",
3412 )
3413 self.assertEqual(GObject.Object.__module__, "gi.overrides.GObject")
3414
3415 # not overridden
3416 self.assertEqual(
3417 GIMarshallingTests.SubObject.__module__, "gi.repository.GIMarshallingTests"
3418 )
3419 self.assertEqual(GObject.InitiallyUnowned.__module__, "gi.repository.GObject")
3420
3421
3422 class TestDir(unittest.TestCase):
3423 def test_members_list(self):
3424 list = dir(GIMarshallingTests)
3425 self.assertTrue("OverridesStruct" in list)
3426 self.assertTrue("BoxedStruct" in list)
3427 self.assertTrue("OVERRIDES_CONSTANT" in list)
3428 self.assertTrue("GEnum" in list)
3429 self.assertTrue("int32_return_max" in list)
3430
3431 def test_modules_list(self):
3432 import gi.repository
3433
3434 list = dir(gi.repository)
3435 self.assertTrue("GIMarshallingTests" in list)
3436
3437 # FIXME: test to see if a module which was not imported is in the list
3438 # we should be listing every typelib we find, not just the ones
3439 # which are imported
3440 #
3441 # to test this I recommend we compile a fake module which
3442 # our tests would never import and check to see if it is
3443 # in the list:
3444 #
3445 # self.assertTrue('DoNotImportDummyTests' in list)
3446
3447
3448 class TestParamSpec(unittest.TestCase):
3449 def test_param_spec_in_bool(self):
3450 ps = GObject.param_spec_boolean(
3451 "mybool", "test-bool", "boolblurb", True, GObject.ParamFlags.READABLE
3452 )
3453 GIMarshallingTests.param_spec_in_bool(ps)
3454
3455 def test_param_spec_return(self):
3456 obj = GIMarshallingTests.param_spec_return()
3457 self.assertEqual(obj.name, "test-param")
3458 self.assertEqual(obj.nick, "test")
3459 self.assertEqual(obj.value_type, GObject.TYPE_STRING)
3460
3461 def test_param_spec_out(self):
3462 obj = GIMarshallingTests.param_spec_out()
3463 self.assertEqual(obj.name, "test-param")
3464 self.assertEqual(obj.nick, "test")
3465 self.assertEqual(obj.value_type, GObject.TYPE_STRING)
3466
3467
3468 class TestKeywordArgs(unittest.TestCase):
3469 def test_calling(self):
3470 kw_func = GIMarshallingTests.int_three_in_three_out
3471
3472 self.assertEqual(kw_func(1, 2, 3), (1, 2, 3))
3473 self.assertEqual(kw_func(**{"a": 4, "b": 5, "c": 6}), (4, 5, 6))
3474 self.assertEqual(kw_func(1, **{"b": 7, "c": 8}), (1, 7, 8))
3475 self.assertEqual(kw_func(1, 7, **{"c": 8}), (1, 7, 8))
3476 self.assertEqual(kw_func(1, c=8, **{"b": 7}), (1, 7, 8))
3477 self.assertEqual(kw_func(2, c=4, b=3), (2, 3, 4))
3478 self.assertEqual(kw_func(a=2, c=4, b=3), (2, 3, 4))
3479
3480 def assertRaisesMessage(self, exception, message, func, *args, **kwargs):
3481 try:
3482 func(*args, **kwargs)
3483 except exception:
3484 (_e_type, e) = sys.exc_info()[:2]
3485 if message is not None:
3486 self.assertEqual(str(e), message)
3487 except:
3488 raise
3489 else:
3490 msg = f"{func.__name__}() did not raise {exception.__name__}"
3491 raise AssertionError(msg)
3492
3493 def test_type_errors(self):
3494 # test too few args
3495 self.assertRaisesMessage(
3496 TypeError,
3497 "GIMarshallingTests.int_three_in_three_out() takes exactly 3 arguments (0 given)",
3498 GIMarshallingTests.int_three_in_three_out,
3499 )
3500 self.assertRaisesMessage(
3501 TypeError,
3502 "GIMarshallingTests.int_three_in_three_out() takes exactly 3 arguments (1 given)",
3503 GIMarshallingTests.int_three_in_three_out,
3504 1,
3505 )
3506 self.assertRaisesMessage(
3507 TypeError,
3508 "GIMarshallingTests.int_three_in_three_out() takes exactly 3 arguments (0 given)",
3509 GIMarshallingTests.int_three_in_three_out,
3510 *(),
3511 )
3512 self.assertRaisesMessage(
3513 TypeError,
3514 "GIMarshallingTests.int_three_in_three_out() takes exactly 3 arguments (0 given)",
3515 GIMarshallingTests.int_three_in_three_out,
3516 *(),
3517 **{},
3518 )
3519 self.assertRaisesMessage(
3520 TypeError,
3521 "GIMarshallingTests.int_three_in_three_out() takes exactly 3 non-keyword arguments (0 given)",
3522 GIMarshallingTests.int_three_in_three_out,
3523 *(),
3524 **{"c": 4},
3525 )
3526
3527 # test too many args
3528 self.assertRaisesMessage(
3529 TypeError,
3530 "GIMarshallingTests.int_three_in_three_out() takes exactly 3 arguments (4 given)",
3531 GIMarshallingTests.int_three_in_three_out,
3532 *(1, 2, 3, 4),
3533 )
3534 self.assertRaisesMessage(
3535 TypeError,
3536 "GIMarshallingTests.int_three_in_three_out() takes exactly 3 non-keyword arguments (4 given)",
3537 GIMarshallingTests.int_three_in_three_out,
3538 *(1, 2, 3, 4),
3539 c=6,
3540 )
3541
3542 # test too many keyword args
3543 self.assertRaisesMessage(
3544 TypeError,
3545 "GIMarshallingTests.int_three_in_three_out() got multiple values for keyword argument 'a'",
3546 GIMarshallingTests.int_three_in_three_out,
3547 1,
3548 2,
3549 3,
3550 **{"a": 4, "b": 5},
3551 )
3552 self.assertRaisesMessage(
3553 TypeError,
3554 "GIMarshallingTests.int_three_in_three_out() got an unexpected keyword argument 'd'",
3555 GIMarshallingTests.int_three_in_three_out,
3556 d=4,
3557 )
3558 self.assertRaisesMessage(
3559 TypeError,
3560 "GIMarshallingTests.int_three_in_three_out() got an unexpected keyword argument 'e'",
3561 GIMarshallingTests.int_three_in_three_out,
3562 **{"e": 2},
3563 )
3564
3565 def test_kwargs_are_not_modified(self):
3566 d = {"b": 2}
3567 d2 = d.copy()
3568 GIMarshallingTests.int_three_in_three_out(1, c=4, **d)
3569 self.assertEqual(d, d2)
3570
3571 def test_allow_none_as_default(self):
3572 GIMarshallingTests.int_two_in_utf8_two_in_with_allow_none(1, 2, "3", "4")
3573 GIMarshallingTests.int_two_in_utf8_two_in_with_allow_none(1, 2, "3")
3574 GIMarshallingTests.int_two_in_utf8_two_in_with_allow_none(1, 2)
3575 GIMarshallingTests.int_two_in_utf8_two_in_with_allow_none(1, 2, d="4")
3576
3577 GIMarshallingTests.array_in_utf8_two_in_out_of_order("1", [-1, 0, 1, 2])
3578 GIMarshallingTests.array_in_utf8_two_in_out_of_order("1", [-1, 0, 1, 2], "2")
3579 self.assertRaises(
3580 TypeError,
3581 GIMarshallingTests.array_in_utf8_two_in_out_of_order,
3582 [-1, 0, 1, 2],
3583 a="1",
3584 )
3585 self.assertRaises(
3586 TypeError,
3587 GIMarshallingTests.array_in_utf8_two_in_out_of_order,
3588 [-1, 0, 1, 2],
3589 )
3590
3591 GIMarshallingTests.array_in_utf8_two_in([-1, 0, 1, 2], "1", "2")
3592 GIMarshallingTests.array_in_utf8_two_in([-1, 0, 1, 2], "1")
3593 GIMarshallingTests.array_in_utf8_two_in([-1, 0, 1, 2])
3594 GIMarshallingTests.array_in_utf8_two_in([-1, 0, 1, 2], b="2")
3595
3596 GIMarshallingTests.int_one_in_utf8_two_in_one_allows_none(1, "2", "3")
3597 GIMarshallingTests.int_one_in_utf8_two_in_one_allows_none(1, c="3")
3598
3599 self.assertRaises(
3600 TypeError, GIMarshallingTests.int_one_in_utf8_two_in_one_allows_none, 1, "3"
3601 )
3602
3603
3604 class TestKeywords(unittest.TestCase):
3605 def test_method(self):
3606 # g_variant_print()
3607 v = GLib.Variant("i", 1)
3608 self.assertEqual(v.print_(False), "1")
3609
3610 def test_function(self):
3611 # g_thread_yield()
3612 self.assertEqual(GLib.Thread.yield_(), None)
3613
3614 def test_struct_method(self):
3615 # g_timer_continue()
3616 # we cannot currently instantiate GLib.Timer objects, so just ensure
3617 # the method exists
3618 self.assertTrue(callable(GLib.Timer.continue_))
3619
3620 def test_uppercase(self):
3621 self.assertEqual(GLib.IOCondition.IN.value_nicks, ["in"])
3622
3623
3624 class TestModule(unittest.TestCase):
3625 def test_type(self):
3626 self.assertIsInstance(GIMarshallingTests, types.ModuleType)
3627
3628 def test_path(self):
3629 path = GIMarshallingTests.__path__
3630 assert isinstance(path, list)
3631 assert len(path) == 1
3632 assert path[0].endswith("GIMarshallingTests-1.0.typelib")
3633
3634 def test_str(self):
3635 self.assertTrue(
3636 "'GIMarshallingTests' from '" in str(GIMarshallingTests),
3637 str(GIMarshallingTests),
3638 )
3639
3640 def test_dir(self):
3641 dir_ = dir(GIMarshallingTests)
3642 self.assertGreater(len(dir_), 10)
3643
3644 self.assertTrue("SimpleStruct" in dir_)
3645 self.assertTrue("Interface2" in dir_)
3646 self.assertTrue("CONSTANT_GERROR_CODE" in dir_)
3647 self.assertTrue("array_zero_terminated_inout" in dir_)
3648
3649 # assert that dir() does not contain garbage
3650 for item_name in dir_:
3651 item = getattr(GIMarshallingTests, item_name)
3652 self.assertTrue(hasattr(item, "__class__"))
3653
3654 def test_help(self):
3655 with capture_output() as (stdout, _stderr):
3656 help(GIMarshallingTests)
3657 output = stdout.getvalue()
3658
3659 self.assertTrue("SimpleStruct" in output, output)
3660 self.assertTrue("Interface2" in output, output)
3661 self.assertTrue("method_array_inout" in output, output)
3662
3663
3664 class TestProjectVersion(unittest.TestCase):
3665 def test_version_str(self):
3666 self.assertGreater(gi.__version__, "3.")
3667
3668 def test_version_info(self):
3669 self.assertEqual(len(gi.version_info), 3)
3670 self.assertGreaterEqual(gi.version_info, (3, 3, 5))
3671
3672 def test_check_version(self):
3673 self.assertRaises(ValueError, gi.check_version, (99, 0, 0))
3674 self.assertRaises(ValueError, gi.check_version, "99.0.0")
3675 gi.check_version((3, 3, 5))
3676 gi.check_version("3.3.5")
3677
3678
3679 class TestGIWarning(unittest.TestCase):
3680 def test_warning(self):
3681 ignored_by_default = (
3682 DeprecationWarning,
3683 PendingDeprecationWarning,
3684 ImportWarning,
3685 )
3686
3687 with warnings.catch_warnings(record=True) as warn:
3688 warnings.simplefilter("always")
3689 warnings.warn("test", PyGIWarning)
3690 self.assertTrue(issubclass(warn[0].category, Warning))
3691 # We don't want PyGIWarning get ignored by default
3692 self.assertFalse(issubclass(warn[0].category, ignored_by_default))
3693
3694
3695 class TestDeprecation(unittest.TestCase):
3696 def test_method(self):
3697 d = GLib.Date.new()
3698 with self.assertWarns(DeprecationWarning) as w:
3699 d.set_time(1)
3700 self.assertEqual(str(w.warning), "GLib.Date.set_time is deprecated")
3701 self.assertIn("test_gi.py", w.filename)
3702
3703 def test_function(self):
3704 with self.assertWarns(DeprecationWarning) as w:
3705 GLib.strcasecmp("foo", "bar")
3706 self.assertEqual(str(w.warning), "GLib.strcasecmp is deprecated")
3707 self.assertIn("test_gi.py", w.filename)
3708
3709 def test_deprecated_attribute_compat(self):
3710 # test that deprecatied attributes behave like instance attributes
3711
3712 # save the deprecation
3713 deprecation = GLib._deprecations["IO_STATUS_ERROR"]
3714
3715 with self.assertWarns(PyGIDeprecationWarning) as w:
3716 self.assertTrue(hasattr(GLib, "IO_STATUS_ERROR"))
3717 self.assertEqual(
3718 str(w.warning),
3719 "GLib.IO_STATUS_ERROR is deprecated; use GLib.IOStatus.ERROR instead",
3720 )
3721 self.assertIn("test_gi.py", w.filename)
3722
3723 # deprecated attributes appear in dir()
3724 self.assertIn("IO_STATUS_ERROR", dir(GLib))
3725
3726 try:
3727 # check if replacing works
3728 GLib.IO_STATUS_ERROR = "foo"
3729 self.assertEqual(GLib.IO_STATUS_ERROR, "foo")
3730 finally:
3731 # restore deprecation
3732 with contextlib.suppress(AttributeError):
3733 del GLib.IO_STATUS_ERROR
3734 GLib._deprecations["IO_STATUS_ERROR"] = deprecation
3735
3736 try:
3737 # check if deleting works
3738 del GLib.IO_STATUS_ERROR
3739 self.assertFalse(hasattr(GLib, "IO_STATUS_ERROR"))
3740 finally:
3741 # restore deprecation
3742 with contextlib.suppress(AttributeError):
3743 del GLib.IO_STATUS_ERROR
3744 GLib._deprecations["IO_STATUS_ERROR"] = deprecation
3745
3746 def test_deprecated_attribute_warning(self):
3747 with warnings.catch_warnings(record=True) as warn:
3748 warnings.simplefilter("always")
3749 self.assertEqual(GLib.IO_STATUS_ERROR, GLib.IOStatus.ERROR)
3750 GLib.IO_STATUS_ERROR
3751 GLib.IO_STATUS_ERROR
3752 self.assertEqual(len(warn), 3)
3753 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
3754 self.assertRegex(
3755 str(warn[0].message), ".*GLib.IO_STATUS_ERROR.*GLib.IOStatus.ERROR.*"
3756 )
3757
3758 def test_deprecated_attribute_warning_coverage(self):
3759 with warnings.catch_warnings(record=True) as warn:
3760 warnings.simplefilter("always")
3761 GObject.markup_escape_text
3762 GObject.PRIORITY_DEFAULT
3763 GObject.GError
3764 GObject.PARAM_CONSTRUCT
3765 GObject.SIGNAL_ACTION
3766 GObject.property
3767 GObject.IO_STATUS_ERROR
3768 GObject.G_MAXUINT64
3769 GLib.IO_STATUS_ERROR
3770 GLib.SPAWN_SEARCH_PATH
3771 GLib.OPTION_FLAG_HIDDEN
3772 GLib.IO_FLAG_IS_WRITEABLE
3773 GLib.IO_FLAG_NONBLOCK
3774 GLib.USER_DIRECTORY_DESKTOP
3775 GLib.OPTION_ERROR_BAD_VALUE
3776 GLib.glib_version
3777 GLib.pyglib_version
3778 self.assertEqual(len(warn), 17)
3779
3780 def test_deprecated_init_no_keywords(self):
3781 def init(self, **kwargs):
3782 self.assertDictEqual(kwargs, {"a": 1, "b": 2, "c": 3})
3783
3784 fn = gi.overrides.deprecated_init(init, arg_names=("a", "b", "c"))
3785 with self.assertWarns(PyGIDeprecationWarning) as w:
3786 fn(self, 1, 2, 3)
3787 self.assertRegex(str(w.warning), ".*keyword.*a, b, c.*")
3788 self.assertIn("test_gi.py", w.filename)
3789
3790 def test_deprecated_init_no_keywords_out_of_order(self):
3791 def init(self, **kwargs):
3792 self.assertDictEqual(kwargs, {"a": 1, "b": 2, "c": 3})
3793
3794 fn = gi.overrides.deprecated_init(init, arg_names=("b", "a", "c"))
3795 with self.assertWarns(PyGIDeprecationWarning) as w:
3796 fn(self, 2, 1, 3)
3797 self.assertRegex(str(w.warning), ".*keyword.*b, a, c.*")
3798 self.assertIn("test_gi.py", w.filename)
3799
3800 def test_deprecated_init_ignored_keyword(self):
3801 def init(self, **kwargs):
3802 self.assertDictEqual(kwargs, {"a": 1, "c": 3})
3803
3804 fn = gi.overrides.deprecated_init(
3805 init, arg_names=("a", "b", "c"), ignore=("b",)
3806 )
3807 with self.assertWarns(PyGIDeprecationWarning) as w:
3808 fn(self, 1, 2, 3)
3809 self.assertRegex(str(w.warning), ".*keyword.*a, b, c.*")
3810 self.assertIn("test_gi.py", w.filename)
3811
3812 def test_deprecated_init_with_aliases(self):
3813 def init(self, **kwargs):
3814 self.assertDictEqual(kwargs, {"a": 1, "b": 2, "c": 3})
3815
3816 fn = gi.overrides.deprecated_init(
3817 init, arg_names=("a", "b", "c"), deprecated_aliases={"b": "bb", "c": "cc"}
3818 )
3819 with self.assertWarns(PyGIDeprecationWarning) as w:
3820 fn(self, a=1, bb=2, cc=3)
3821 self.assertRegex(
3822 str(w.warning), '.*keyword.*"bb, cc".*deprecated.*"b, c" respectively'
3823 )
3824 self.assertIn("test_gi.py", w.filename)
3825
3826 def test_deprecated_init_with_defaults(self):
3827 def init(self, **kwargs):
3828 self.assertDictEqual(kwargs, {"a": 1, "b": 2, "c": 3})
3829
3830 fn = gi.overrides.deprecated_init(
3831 init, arg_names=("a", "b", "c"), deprecated_defaults={"b": 2, "c": 3}
3832 )
3833 with self.assertWarns(PyGIDeprecationWarning) as w:
3834 fn(self, a=1)
3835 self.assertRegex(
3836 str(w.warning),
3837 ".*relying on deprecated non-standard defaults.*explicitly use: b=2, c=3",
3838 )
3839 self.assertIn("test_gi.py", w.filename)