functions: revert the function init order to make pylint happy again. See #217
[pygobject.git] / tests / test_gi.py
blob2b6f3c0afcf0450f3e52e42ac005a58928743f4d
1 # -*- Mode: Python; py-indent-offset: 4 -*-
2 # coding=utf-8
3 # vim: tabstop=4 shiftwidth=4 expandtab
5 from __future__ import absolute_import
7 import sys
9 import unittest
10 import tempfile
11 import shutil
12 import os
13 import gc
14 import weakref
15 import warnings
16 import pickle
17 import platform
19 import gi
20 import gi.overrides
21 from gi import PyGIWarning
22 from gi import PyGIDeprecationWarning
23 from gi.repository import GObject, GLib, Gio
24 from gi.repository import GIMarshallingTests
25 from gi._compat import PY2, PY3
26 import pytest
28 from .helper import capture_exceptions, capture_output
31 CONSTANT_UTF8 = "const ♥ utf8"
32 CONSTANT_UCS4 = u"const ♥ utf8"
35 class Number(object):
37 def __init__(self, value):
38 self.value = value
40 def __int__(self):
41 return int(self.value)
43 def __float__(self):
44 return float(self.value)
47 class Sequence(object):
49 def __init__(self, sequence):
50 self.sequence = sequence
52 def __len__(self):
53 return len(self.sequence)
55 def __getitem__(self, key):
56 return self.sequence[key]
59 class TestConstant(unittest.TestCase):
61 def test_constant_utf8(self):
62 self.assertEqual(CONSTANT_UTF8, GIMarshallingTests.CONSTANT_UTF8)
64 def test_constant_number(self):
65 self.assertEqual(42, GIMarshallingTests.CONSTANT_NUMBER)
67 def test_min_max_int(self):
68 self.assertEqual(GLib.MAXINT32, 2 ** 31 - 1)
69 self.assertEqual(GLib.MININT32, -2 ** 31)
70 self.assertEqual(GLib.MAXUINT32, 2 ** 32 - 1)
72 self.assertEqual(GLib.MAXINT64, 2 ** 63 - 1)
73 self.assertEqual(GLib.MININT64, -2 ** 63)
74 self.assertEqual(GLib.MAXUINT64, 2 ** 64 - 1)
77 class TestBoolean(unittest.TestCase):
79 def test_boolean_return(self):
80 self.assertEqual(True, GIMarshallingTests.boolean_return_true())
81 self.assertEqual(False, GIMarshallingTests.boolean_return_false())
83 def test_boolean_in(self):
84 GIMarshallingTests.boolean_in_true(True)
85 GIMarshallingTests.boolean_in_false(False)
87 GIMarshallingTests.boolean_in_true(1)
88 GIMarshallingTests.boolean_in_false(0)
90 def test_boolean_out(self):
91 self.assertEqual(True, GIMarshallingTests.boolean_out_true())
92 self.assertEqual(False, GIMarshallingTests.boolean_out_false())
94 def test_boolean_inout(self):
95 self.assertEqual(False, GIMarshallingTests.boolean_inout_true_false(True))
96 self.assertEqual(True, GIMarshallingTests.boolean_inout_false_true(False))
99 class TestInt8(unittest.TestCase):
101 MAX = GLib.MAXINT8
102 MIN = GLib.MININT8
104 def test_int8_return(self):
105 self.assertEqual(self.MAX, GIMarshallingTests.int8_return_max())
106 self.assertEqual(self.MIN, GIMarshallingTests.int8_return_min())
108 def test_int8_in(self):
109 max = Number(self.MAX)
110 min = Number(self.MIN)
112 GIMarshallingTests.int8_in_max(max)
113 GIMarshallingTests.int8_in_min(min)
115 max.value += 1
116 min.value -= 1
118 self.assertRaises(OverflowError, GIMarshallingTests.int8_in_max, max)
119 self.assertRaises(OverflowError, GIMarshallingTests.int8_in_min, min)
121 self.assertRaises(TypeError, GIMarshallingTests.int8_in_max, "self.MAX")
123 def test_int8_out(self):
124 self.assertEqual(self.MAX, GIMarshallingTests.int8_out_max())
125 self.assertEqual(self.MIN, GIMarshallingTests.int8_out_min())
127 def test_int8_inout(self):
128 self.assertEqual(self.MIN, GIMarshallingTests.int8_inout_max_min(Number(self.MAX)))
129 self.assertEqual(self.MAX, GIMarshallingTests.int8_inout_min_max(Number(self.MIN)))
132 class TestUInt8(unittest.TestCase):
134 MAX = GLib.MAXUINT8
136 def test_uint8_return(self):
137 self.assertEqual(self.MAX, GIMarshallingTests.uint8_return())
139 def test_uint8_in(self):
140 number = Number(self.MAX)
142 GIMarshallingTests.uint8_in(number)
143 GIMarshallingTests.uint8_in(b'\xff')
145 number.value += 1
146 self.assertRaises(OverflowError, GIMarshallingTests.uint8_in, number)
147 self.assertRaises(OverflowError, GIMarshallingTests.uint8_in, Number(-1))
149 self.assertRaises(TypeError, GIMarshallingTests.uint8_in, "self.MAX")
151 def test_uint8_out(self):
152 self.assertEqual(self.MAX, GIMarshallingTests.uint8_out())
154 def test_uint8_inout(self):
155 self.assertEqual(0, GIMarshallingTests.uint8_inout(Number(self.MAX)))
158 class TestInt16(unittest.TestCase):
160 MAX = GLib.MAXINT16
161 MIN = GLib.MININT16
163 def test_int16_return(self):
164 self.assertEqual(self.MAX, GIMarshallingTests.int16_return_max())
165 self.assertEqual(self.MIN, GIMarshallingTests.int16_return_min())
167 def test_int16_in(self):
168 max = Number(self.MAX)
169 min = Number(self.MIN)
171 GIMarshallingTests.int16_in_max(max)
172 GIMarshallingTests.int16_in_min(min)
174 max.value += 1
175 min.value -= 1
177 self.assertRaises(OverflowError, GIMarshallingTests.int16_in_max, max)
178 self.assertRaises(OverflowError, GIMarshallingTests.int16_in_min, min)
180 self.assertRaises(TypeError, GIMarshallingTests.int16_in_max, "self.MAX")
182 def test_int16_out(self):
183 self.assertEqual(self.MAX, GIMarshallingTests.int16_out_max())
184 self.assertEqual(self.MIN, GIMarshallingTests.int16_out_min())
186 def test_int16_inout(self):
187 self.assertEqual(self.MIN, GIMarshallingTests.int16_inout_max_min(Number(self.MAX)))
188 self.assertEqual(self.MAX, GIMarshallingTests.int16_inout_min_max(Number(self.MIN)))
191 class TestUInt16(unittest.TestCase):
193 MAX = GLib.MAXUINT16
195 def test_uint16_return(self):
196 self.assertEqual(self.MAX, GIMarshallingTests.uint16_return())
198 def test_uint16_in(self):
199 number = Number(self.MAX)
201 GIMarshallingTests.uint16_in(number)
203 number.value += 1
205 self.assertRaises(OverflowError, GIMarshallingTests.uint16_in, number)
206 self.assertRaises(OverflowError, GIMarshallingTests.uint16_in, Number(-1))
208 self.assertRaises(TypeError, GIMarshallingTests.uint16_in, "self.MAX")
210 def test_uint16_out(self):
211 self.assertEqual(self.MAX, GIMarshallingTests.uint16_out())
213 def test_uint16_inout(self):
214 self.assertEqual(0, GIMarshallingTests.uint16_inout(Number(self.MAX)))
217 class TestInt32(unittest.TestCase):
219 MAX = GLib.MAXINT32
220 MIN = GLib.MININT32
222 def test_int32_return(self):
223 self.assertEqual(self.MAX, GIMarshallingTests.int32_return_max())
224 self.assertEqual(self.MIN, GIMarshallingTests.int32_return_min())
226 def test_int32_in(self):
227 max = Number(self.MAX)
228 min = Number(self.MIN)
230 GIMarshallingTests.int32_in_max(max)
231 GIMarshallingTests.int32_in_min(min)
233 max.value += 1
234 min.value -= 1
236 self.assertRaises(OverflowError, GIMarshallingTests.int32_in_max, max)
237 self.assertRaises(OverflowError, GIMarshallingTests.int32_in_min, min)
239 self.assertRaises(TypeError, GIMarshallingTests.int32_in_max, "self.MAX")
241 def test_int32_out(self):
242 self.assertEqual(self.MAX, GIMarshallingTests.int32_out_max())
243 self.assertEqual(self.MIN, GIMarshallingTests.int32_out_min())
245 def test_int32_inout(self):
246 self.assertEqual(self.MIN, GIMarshallingTests.int32_inout_max_min(Number(self.MAX)))
247 self.assertEqual(self.MAX, GIMarshallingTests.int32_inout_min_max(Number(self.MIN)))
250 class TestUInt32(unittest.TestCase):
252 MAX = GLib.MAXUINT32
254 def test_uint32_return(self):
255 self.assertEqual(self.MAX, GIMarshallingTests.uint32_return())
257 def test_uint32_in(self):
258 number = Number(self.MAX)
260 GIMarshallingTests.uint32_in(number)
262 number.value += 1
264 self.assertRaises(OverflowError, GIMarshallingTests.uint32_in, number)
265 self.assertRaises(OverflowError, GIMarshallingTests.uint32_in, Number(-1))
267 self.assertRaises(TypeError, GIMarshallingTests.uint32_in, "self.MAX")
269 def test_uint32_out(self):
270 self.assertEqual(self.MAX, GIMarshallingTests.uint32_out())
272 def test_uint32_inout(self):
273 self.assertEqual(0, GIMarshallingTests.uint32_inout(Number(self.MAX)))
276 class TestInt64(unittest.TestCase):
278 MAX = 2 ** 63 - 1
279 MIN = - (2 ** 63)
281 def test_int64_return(self):
282 self.assertEqual(self.MAX, GIMarshallingTests.int64_return_max())
283 self.assertEqual(self.MIN, GIMarshallingTests.int64_return_min())
285 def test_int64_in(self):
286 max = Number(self.MAX)
287 min = Number(self.MIN)
289 GIMarshallingTests.int64_in_max(max)
290 GIMarshallingTests.int64_in_min(min)
292 max.value += 1
293 min.value -= 1
295 self.assertRaises(OverflowError, GIMarshallingTests.int64_in_max, max)
296 self.assertRaises(OverflowError, GIMarshallingTests.int64_in_min, min)
298 self.assertRaises(TypeError, GIMarshallingTests.int64_in_max, "self.MAX")
300 def test_int64_out(self):
301 self.assertEqual(self.MAX, GIMarshallingTests.int64_out_max())
302 self.assertEqual(self.MIN, GIMarshallingTests.int64_out_min())
304 def test_int64_inout(self):
305 self.assertEqual(self.MIN, GIMarshallingTests.int64_inout_max_min(Number(self.MAX)))
306 self.assertEqual(self.MAX, GIMarshallingTests.int64_inout_min_max(Number(self.MIN)))
309 class TestUInt64(unittest.TestCase):
311 MAX = 2 ** 64 - 1
313 def test_uint64_return(self):
314 self.assertEqual(self.MAX, GIMarshallingTests.uint64_return())
316 def test_uint64_in(self):
317 number = Number(self.MAX)
319 GIMarshallingTests.uint64_in(number)
321 number.value += 1
323 self.assertRaises(OverflowError, GIMarshallingTests.uint64_in, number)
324 self.assertRaises(OverflowError, GIMarshallingTests.uint64_in, Number(-1))
326 self.assertRaises(TypeError, GIMarshallingTests.uint64_in, "self.MAX")
328 def test_uint64_out(self):
329 self.assertEqual(self.MAX, GIMarshallingTests.uint64_out())
331 def test_uint64_inout(self):
332 self.assertEqual(0, GIMarshallingTests.uint64_inout(Number(self.MAX)))
335 class TestShort(unittest.TestCase):
337 MAX = GLib.MAXSHORT
338 MIN = GLib.MINSHORT
340 def test_short_return(self):
341 self.assertEqual(self.MAX, GIMarshallingTests.short_return_max())
342 self.assertEqual(self.MIN, GIMarshallingTests.short_return_min())
344 def test_short_in(self):
345 max = Number(self.MAX)
346 min = Number(self.MIN)
348 GIMarshallingTests.short_in_max(max)
349 GIMarshallingTests.short_in_min(min)
351 max.value += 1
352 min.value -= 1
354 self.assertRaises(OverflowError, GIMarshallingTests.short_in_max, max)
355 self.assertRaises(OverflowError, GIMarshallingTests.short_in_min, min)
357 self.assertRaises(TypeError, GIMarshallingTests.short_in_max, "self.MAX")
359 def test_short_out(self):
360 self.assertEqual(self.MAX, GIMarshallingTests.short_out_max())
361 self.assertEqual(self.MIN, GIMarshallingTests.short_out_min())
363 def test_short_inout(self):
364 self.assertEqual(self.MIN, GIMarshallingTests.short_inout_max_min(Number(self.MAX)))
365 self.assertEqual(self.MAX, GIMarshallingTests.short_inout_min_max(Number(self.MIN)))
368 class TestUShort(unittest.TestCase):
370 MAX = GLib.MAXUSHORT
372 def test_ushort_return(self):
373 self.assertEqual(self.MAX, GIMarshallingTests.ushort_return())
375 def test_ushort_in(self):
376 number = Number(self.MAX)
378 GIMarshallingTests.ushort_in(number)
380 number.value += 1
382 self.assertRaises(OverflowError, GIMarshallingTests.ushort_in, number)
383 self.assertRaises(OverflowError, GIMarshallingTests.ushort_in, Number(-1))
385 self.assertRaises(TypeError, GIMarshallingTests.ushort_in, "self.MAX")
387 def test_ushort_out(self):
388 self.assertEqual(self.MAX, GIMarshallingTests.ushort_out())
390 def test_ushort_inout(self):
391 self.assertEqual(0, GIMarshallingTests.ushort_inout(Number(self.MAX)))
394 class TestInt(unittest.TestCase):
396 MAX = GLib.MAXINT
397 MIN = GLib.MININT
399 def test_int_return(self):
400 self.assertEqual(self.MAX, GIMarshallingTests.int_return_max())
401 self.assertEqual(self.MIN, GIMarshallingTests.int_return_min())
403 def test_int_in(self):
404 max = Number(self.MAX)
405 min = Number(self.MIN)
407 GIMarshallingTests.int_in_max(max)
408 GIMarshallingTests.int_in_min(min)
410 max.value += 1
411 min.value -= 1
413 self.assertRaises(OverflowError, GIMarshallingTests.int_in_max, max)
414 self.assertRaises(OverflowError, GIMarshallingTests.int_in_min, min)
416 self.assertRaises(TypeError, GIMarshallingTests.int_in_max, "self.MAX")
418 def test_int_out(self):
419 self.assertEqual(self.MAX, GIMarshallingTests.int_out_max())
420 self.assertEqual(self.MIN, GIMarshallingTests.int_out_min())
422 def test_int_inout(self):
423 self.assertEqual(self.MIN, GIMarshallingTests.int_inout_max_min(Number(self.MAX)))
424 self.assertEqual(self.MAX, GIMarshallingTests.int_inout_min_max(Number(self.MIN)))
425 self.assertRaises(TypeError, GIMarshallingTests.int_inout_min_max, Number(self.MIN), 42)
428 class TestUInt(unittest.TestCase):
430 MAX = GLib.MAXUINT
432 def test_uint_return(self):
433 self.assertEqual(self.MAX, GIMarshallingTests.uint_return())
435 def test_uint_in(self):
436 number = Number(self.MAX)
438 GIMarshallingTests.uint_in(number)
440 number.value += 1
442 self.assertRaises(OverflowError, GIMarshallingTests.uint_in, number)
443 self.assertRaises(OverflowError, GIMarshallingTests.uint_in, Number(-1))
445 self.assertRaises(TypeError, GIMarshallingTests.uint_in, "self.MAX")
447 def test_uint_out(self):
448 self.assertEqual(self.MAX, GIMarshallingTests.uint_out())
450 def test_uint_inout(self):
451 self.assertEqual(0, GIMarshallingTests.uint_inout(Number(self.MAX)))
454 class TestLong(unittest.TestCase):
456 MAX = GLib.MAXLONG
457 MIN = GLib.MINLONG
459 def test_long_return(self):
460 self.assertEqual(self.MAX, GIMarshallingTests.long_return_max())
461 self.assertEqual(self.MIN, GIMarshallingTests.long_return_min())
463 def test_long_in(self):
464 max = Number(self.MAX)
465 min = Number(self.MIN)
467 GIMarshallingTests.long_in_max(max)
468 GIMarshallingTests.long_in_min(min)
470 max.value += 1
471 min.value -= 1
473 self.assertRaises(OverflowError, GIMarshallingTests.long_in_max, max)
474 self.assertRaises(OverflowError, GIMarshallingTests.long_in_min, min)
476 self.assertRaises(TypeError, GIMarshallingTests.long_in_max, "self.MAX")
478 def test_long_out(self):
479 self.assertEqual(self.MAX, GIMarshallingTests.long_out_max())
480 self.assertEqual(self.MIN, GIMarshallingTests.long_out_min())
482 def test_long_inout(self):
483 self.assertEqual(self.MIN, GIMarshallingTests.long_inout_max_min(Number(self.MAX)))
484 self.assertEqual(self.MAX, GIMarshallingTests.long_inout_min_max(Number(self.MIN)))
487 class TestULong(unittest.TestCase):
489 MAX = GLib.MAXULONG
491 def test_ulong_return(self):
492 self.assertEqual(self.MAX, GIMarshallingTests.ulong_return())
494 def test_ulong_in(self):
495 number = Number(self.MAX)
497 GIMarshallingTests.ulong_in(number)
499 number.value += 1
501 self.assertRaises(OverflowError, GIMarshallingTests.ulong_in, number)
502 self.assertRaises(OverflowError, GIMarshallingTests.ulong_in, Number(-1))
504 self.assertRaises(TypeError, GIMarshallingTests.ulong_in, "self.MAX")
506 def test_ulong_out(self):
507 self.assertEqual(self.MAX, GIMarshallingTests.ulong_out())
509 def test_ulong_inout(self):
510 self.assertEqual(0, GIMarshallingTests.ulong_inout(Number(self.MAX)))
513 class TestSSize(unittest.TestCase):
515 MAX = GLib.MAXSSIZE
516 MIN = GLib.MINSSIZE
518 def test_ssize_return(self):
519 self.assertEqual(self.MAX, GIMarshallingTests.ssize_return_max())
520 self.assertEqual(self.MIN, GIMarshallingTests.ssize_return_min())
522 def test_ssize_in(self):
523 max = Number(self.MAX)
524 min = Number(self.MIN)
526 GIMarshallingTests.ssize_in_max(max)
527 GIMarshallingTests.ssize_in_min(min)
529 max.value += 1
530 min.value -= 1
532 self.assertRaises(OverflowError, GIMarshallingTests.ssize_in_max, max)
533 self.assertRaises(OverflowError, GIMarshallingTests.ssize_in_min, min)
535 self.assertRaises(TypeError, GIMarshallingTests.ssize_in_max, "self.MAX")
537 def test_ssize_out(self):
538 self.assertEqual(self.MAX, GIMarshallingTests.ssize_out_max())
539 self.assertEqual(self.MIN, GIMarshallingTests.ssize_out_min())
541 def test_ssize_inout(self):
542 self.assertEqual(self.MIN, GIMarshallingTests.ssize_inout_max_min(Number(self.MAX)))
543 self.assertEqual(self.MAX, GIMarshallingTests.ssize_inout_min_max(Number(self.MIN)))
546 class TestSize(unittest.TestCase):
548 MAX = GLib.MAXSIZE
550 def test_size_return(self):
551 self.assertEqual(self.MAX, GIMarshallingTests.size_return())
553 def test_size_in(self):
554 number = Number(self.MAX)
556 GIMarshallingTests.size_in(number)
558 number.value += 1
560 self.assertRaises(OverflowError, GIMarshallingTests.size_in, number)
561 self.assertRaises(OverflowError, GIMarshallingTests.size_in, Number(-1))
563 self.assertRaises(TypeError, GIMarshallingTests.size_in, "self.MAX")
565 def test_size_out(self):
566 self.assertEqual(self.MAX, GIMarshallingTests.size_out())
568 def test_size_inout(self):
569 self.assertEqual(0, GIMarshallingTests.size_inout(Number(self.MAX)))
572 class TestTimet(unittest.TestCase):
574 def test_time_t_return(self):
575 self.assertEqual(1234567890, GIMarshallingTests.time_t_return())
577 def test_time_t_in(self):
578 GIMarshallingTests.time_t_in(1234567890)
579 self.assertRaises(TypeError, GIMarshallingTests.time_t_in, "hello")
581 def test_time_t_out(self):
582 self.assertEqual(1234567890, GIMarshallingTests.time_t_out())
584 def test_time_t_inout(self):
585 self.assertEqual(0, GIMarshallingTests.time_t_inout(1234567890))
588 class TestFloat(unittest.TestCase):
590 MAX = GLib.MAXFLOAT
591 MIN = GLib.MINFLOAT
593 def test_float_return(self):
594 self.assertAlmostEqual(self.MAX, GIMarshallingTests.float_return())
596 def test_float_in(self):
597 GIMarshallingTests.float_in(Number(self.MAX))
599 self.assertRaises(TypeError, GIMarshallingTests.float_in, "self.MAX")
601 def test_float_out(self):
602 self.assertAlmostEqual(self.MAX, GIMarshallingTests.float_out())
604 def test_float_inout(self):
605 self.assertAlmostEqual(self.MIN, GIMarshallingTests.float_inout(Number(self.MAX)))
608 class TestDouble(unittest.TestCase):
610 MAX = GLib.MAXDOUBLE
611 MIN = GLib.MINDOUBLE
613 def test_double_return(self):
614 self.assertAlmostEqual(self.MAX, GIMarshallingTests.double_return())
616 def test_double_in(self):
617 GIMarshallingTests.double_in(Number(self.MAX))
619 self.assertRaises(TypeError, GIMarshallingTests.double_in, "self.MAX")
621 def test_double_out(self):
622 self.assertAlmostEqual(self.MAX, GIMarshallingTests.double_out())
624 def test_double_inout(self):
625 self.assertAlmostEqual(self.MIN, GIMarshallingTests.double_inout(Number(self.MAX)))
628 class TestGType(unittest.TestCase):
630 def test_gtype_name(self):
631 self.assertEqual("void", GObject.TYPE_NONE.name)
632 self.assertEqual("gchararray", GObject.TYPE_STRING.name)
634 def check_readonly(gtype):
635 gtype.name = "foo"
637 errors = (AttributeError,)
638 if platform.python_implementation() == "PyPy":
639 # https://bitbucket.org/pypy/pypy/issues/2788
640 errors = (AttributeError, TypeError)
642 self.assertRaises(errors, check_readonly, GObject.TYPE_NONE)
643 self.assertRaises(errors, check_readonly, GObject.TYPE_STRING)
645 def test_gtype_return(self):
646 self.assertEqual(GObject.TYPE_NONE, GIMarshallingTests.gtype_return())
647 self.assertEqual(GObject.TYPE_STRING, GIMarshallingTests.gtype_string_return())
649 def test_gtype_in(self):
650 GIMarshallingTests.gtype_in(GObject.TYPE_NONE)
651 GIMarshallingTests.gtype_string_in(GObject.TYPE_STRING)
652 self.assertRaises(TypeError, GIMarshallingTests.gtype_in, "foo")
653 self.assertRaises(TypeError, GIMarshallingTests.gtype_string_in, "foo")
655 def test_gtype_out(self):
656 self.assertEqual(GObject.TYPE_NONE, GIMarshallingTests.gtype_out())
657 self.assertEqual(GObject.TYPE_STRING, GIMarshallingTests.gtype_string_out())
659 def test_gtype_inout(self):
660 self.assertEqual(GObject.TYPE_INT, GIMarshallingTests.gtype_inout(GObject.TYPE_NONE))
663 class TestUtf8(unittest.TestCase):
665 def test_utf8_as_uint8array_in(self):
666 data = CONSTANT_UTF8
667 if not isinstance(data, bytes):
668 data = data.encode("utf-8")
669 GIMarshallingTests.utf8_as_uint8array_in(data)
671 def test_utf8_none_return(self):
672 self.assertEqual(CONSTANT_UTF8, GIMarshallingTests.utf8_none_return())
674 def test_utf8_full_return(self):
675 self.assertEqual(CONSTANT_UTF8, GIMarshallingTests.utf8_full_return())
677 def test_extra_utf8_full_return_invalid(self):
678 with pytest.raises(UnicodeDecodeError):
679 value = GIMarshallingTests.extra_utf8_full_return_invalid()
680 if PY2:
681 value.decode("utf-8")
683 def test_extra_utf8_full_out_invalid(self):
684 with pytest.raises(UnicodeDecodeError):
685 value = GIMarshallingTests.extra_utf8_full_out_invalid()
686 if PY2:
687 value.decode("utf-8")
689 def test_utf8_none_in(self):
690 GIMarshallingTests.utf8_none_in(CONSTANT_UTF8)
691 if PY2:
692 GIMarshallingTests.utf8_none_in(CONSTANT_UTF8.decode("utf-8"))
694 self.assertRaises(TypeError, GIMarshallingTests.utf8_none_in, 42)
695 self.assertRaises(TypeError, GIMarshallingTests.utf8_none_in, None)
697 def test_utf8_none_out(self):
698 self.assertEqual(CONSTANT_UTF8, GIMarshallingTests.utf8_none_out())
700 def test_utf8_full_out(self):
701 self.assertEqual(CONSTANT_UTF8, GIMarshallingTests.utf8_full_out())
703 def test_utf8_dangling_out(self):
704 GIMarshallingTests.utf8_dangling_out()
706 def test_utf8_none_inout(self):
707 self.assertEqual("", GIMarshallingTests.utf8_none_inout(CONSTANT_UTF8))
709 def test_utf8_full_inout(self):
710 self.assertEqual("", GIMarshallingTests.utf8_full_inout(CONSTANT_UTF8))
713 class TestFilename(unittest.TestCase):
714 def setUp(self):
715 self.workdir = tempfile.mkdtemp()
717 def tearDown(self):
718 shutil.rmtree(self.workdir)
720 def tests_filename_list_return(self):
721 assert GIMarshallingTests.filename_list_return() == []
723 @unittest.skipIf(os.name == "nt", "fixme")
724 def test_filename_in(self):
725 fname = os.path.join(self.workdir, u'testäø.txt')
727 try:
728 os.path.exists(fname)
729 except ValueError:
730 # non-unicode fs encoding
731 return
733 self.assertRaises(GLib.GError, GLib.file_get_contents, fname)
735 with open(fname.encode('UTF-8'), 'wb') as f:
736 f.write(b'hello world!\n\x01\x02')
738 (result, contents) = GLib.file_get_contents(fname)
739 self.assertEqual(result, True)
740 self.assertEqual(contents, b'hello world!\n\x01\x02')
742 def test_filename_in_nullable(self):
743 self.assertTrue(GIMarshallingTests.filename_copy(None) is None)
744 self.assertRaises(TypeError, GIMarshallingTests.filename_exists, None)
746 @unittest.skipIf(os.name == "nt", "fixme")
747 def test_filename_out(self):
748 self.assertRaises(GLib.GError, GLib.Dir.make_tmp, 'test')
749 name = 'testäø.XXXXXX'
751 try:
752 os.path.exists(name)
753 except ValueError:
754 # non-unicode fs encoding
755 return
757 dirname = GLib.Dir.make_tmp(name)
758 self.assertTrue(os.path.sep + 'testäø.' in dirname, dirname)
759 self.assertTrue(os.path.isdir(dirname))
760 os.rmdir(dirname)
762 def test_wrong_types(self):
763 self.assertRaises(TypeError, GIMarshallingTests.filename_copy, 23)
764 self.assertRaises(TypeError, GIMarshallingTests.filename_copy, [])
766 def test_null(self):
767 self.assertTrue(GIMarshallingTests.filename_copy(None) is None)
768 self.assertRaises(TypeError, GIMarshallingTests.filename_exists, None)
770 def test_round_trip(self):
771 self.assertEqual(GIMarshallingTests.filename_copy(u"foo"), "foo")
772 self.assertEqual(GIMarshallingTests.filename_copy(b"foo"), "foo")
774 def test_contains_null(self):
775 self.assertRaises(
776 (ValueError, TypeError),
777 GIMarshallingTests.filename_copy, b"foo\x00")
778 self.assertRaises(
779 (ValueError, TypeError),
780 GIMarshallingTests.filename_copy, u"foo\x00")
782 def test_as_is_py2(self):
783 if not PY2:
784 return
786 values = [
787 b"foo",
788 b"\xff\xff",
789 b"\xc3\xb6\xc3\xa4\xc3\xbc",
790 b"\xed\xa0\xbd",
791 b"\xf0\x90\x80\x81",
794 for v in values:
795 self.assertEqual(GIMarshallingTests.filename_copy(v), v)
796 self.assertEqual(GIMarshallingTests.filename_to_glib_repr(v), v)
798 def test_win32_surrogates(self):
799 if os.name != "nt":
800 return
802 copy = GIMarshallingTests.filename_copy
803 glib_repr = GIMarshallingTests.filename_to_glib_repr
805 if PY3:
806 self.assertEqual(copy(u"\ud83d"), u"\ud83d")
807 self.assertEqual(copy(u"\x61\uDC00"), u"\x61\uDC00")
808 self.assertEqual(copy(u"\uD800\uDC01"), u"\U00010001")
809 self.assertEqual(copy(u"\uD83D\x20\uDCA9"), u"\uD83D\x20\uDCA9")
810 else:
811 self.assertEqual(copy(u"\ud83d"), u"\ud83d".encode("utf-8"))
812 self.assertEqual(copy(u"\uD800\uDC01").decode("utf-8"),
813 u"\U00010001")
815 self.assertEqual(glib_repr(u"\ud83d"), b"\xed\xa0\xbd")
816 self.assertEqual(glib_repr(u"\uD800\uDC01"), b"\xf0\x90\x80\x81")
818 self.assertEqual(
819 glib_repr(u"\uD800\uDBFF"), b"\xED\xA0\x80\xED\xAF\xBF")
820 self.assertEqual(
821 glib_repr(u"\uD800\uE000"), b"\xED\xA0\x80\xEE\x80\x80")
822 self.assertEqual(
823 glib_repr(u"\uD7FF\uDC00"), b"\xED\x9F\xBF\xED\xB0\x80")
824 self.assertEqual(glib_repr(u"\x61\uDC00"), b"\x61\xED\xB0\x80")
825 self.assertEqual(glib_repr(u"\uDC00"), b"\xED\xB0\x80")
827 def test_win32_bytes_py3(self):
828 if not (os.name == "nt" and PY3):
829 return
831 values = [
832 b"foo",
833 b"\xff\xff",
834 b"\xc3\xb6\xc3\xa4\xc3\xbc",
835 b"\xed\xa0\xbd",
836 b"\xf0\x90\x80\x81",
839 for v in values:
840 try:
841 uni = v.decode(sys.getfilesystemencoding(), "surrogatepass")
842 except UnicodeDecodeError:
843 continue
844 self.assertEqual(GIMarshallingTests.filename_copy(v), uni)
846 def test_unix_various(self):
847 if os.name == "nt":
848 return
850 copy = GIMarshallingTests.filename_copy
851 glib_repr = GIMarshallingTests.filename_to_glib_repr
853 if PY3:
854 try:
855 os.fsdecode(b"\xff\xfe")
856 except UnicodeDecodeError:
857 self.assertRaises(UnicodeDecodeError, copy, b"\xff\xfe")
858 else:
859 str_path = copy(b"\xff\xfe")
860 self.assertTrue(isinstance(str_path, str))
861 self.assertEqual(str_path, os.fsdecode(b"\xff\xfe"))
862 self.assertEqual(copy(str_path), str_path)
863 self.assertEqual(glib_repr(b"\xff\xfe"), b"\xff\xfe")
864 self.assertEqual(glib_repr(str_path), b"\xff\xfe")
866 # if getfilesystemencoding is ASCII, then we should fail like
867 # os.fsencode
868 try:
869 byte_path = os.fsencode(u"ä")
870 except UnicodeEncodeError:
871 self.assertRaises(UnicodeEncodeError, copy, u"ä")
872 else:
873 self.assertEqual(copy(u"ä"), u"ä")
874 self.assertEqual(glib_repr(u"ä"), byte_path)
875 else:
876 self.assertTrue(isinstance(copy(b"\xff\xfe"), bytes))
877 self.assertEqual(copy(u"foo"), b"foo")
878 self.assertTrue(isinstance(copy(u"foo"), bytes))
879 try:
880 byte_path = u"ä".encode(sys.getfilesystemencoding())
881 except UnicodeEncodeError:
882 self.assertRaises(UnicodeEncodeError, copy, u"ä")
883 else:
884 self.assertEqual(copy(u"ä"), byte_path)
885 self.assertEqual(glib_repr(u"ä"), byte_path)
887 @unittest.skip("glib can't handle non-unicode paths")
888 def test_win32_surrogates_exists(self):
889 if os.name != "nt":
890 return
892 path = os.path.join(self.workdir, u"\ud83d")
893 with open(path, "wb"):
894 self.assertTrue(os.path.exists(path))
895 self.assertTrue(GIMarshallingTests.filename_exists(path))
896 os.unlink(path)
898 def test_path_exists_various_types(self):
899 wd = self.workdir
900 wdb = os.fsencode(wd) if PY3 else wd
902 paths = [(wdb, b"foo-1"), (wd, u"foo-2"), (wd, u"öäü-3")]
903 if PY3:
904 try:
905 paths.append((wd, os.fsdecode(b"\xff\xfe-4")))
906 except UnicodeDecodeError:
907 # depends on the code page
908 pass
910 if os.name != "nt":
911 paths.append((wdb, b"\xff\xfe-5"))
913 def valid_path(p):
914 try:
915 os.path.exists(p)
916 except ValueError:
917 return False
918 return True
920 for (d, path) in paths:
921 if not valid_path(path):
922 continue
923 path = os.path.join(d, path)
924 with open(path, "wb"):
925 self.assertTrue(GIMarshallingTests.filename_exists(path))
928 class TestArray(unittest.TestCase):
930 @unittest.skipUnless(
931 hasattr(GIMarshallingTests, "array_bool_in"), "too old gi")
932 def test_array_bool_in(self):
933 GIMarshallingTests.array_bool_in([True, False, True, True])
935 @unittest.skipUnless(
936 hasattr(GIMarshallingTests, "array_bool_out"), "too old gi")
937 def test_array_bool_out(self):
938 assert GIMarshallingTests.array_bool_out() == [True, False, True, True]
940 @unittest.skipUnless(
941 hasattr(GIMarshallingTests, "array_int64_in"), "too old gi")
942 def test_array_int64_in(self):
943 GIMarshallingTests.array_int64_in([-1, 0, 1, 2])
945 @unittest.skipUnless(
946 hasattr(GIMarshallingTests, "array_uint64_in"), "too old gi")
947 def test_array_uint64_in(self):
948 GIMarshallingTests.array_uint64_in([GLib.MAXUINT64, 0, 1, 2])
950 @unittest.skipUnless(
951 hasattr(GIMarshallingTests, "array_unichar_in"), "too old gi")
952 def test_array_unichar_in(self):
953 GIMarshallingTests.array_unichar_in(list(CONSTANT_UCS4))
954 GIMarshallingTests.array_unichar_in(CONSTANT_UCS4)
956 @unittest.skipUnless(
957 hasattr(GIMarshallingTests, "array_unichar_out"), "too old gi")
958 def test_array_unichar_out(self):
959 if PY2:
960 result = [c.encode("utf-8") for c in list(CONSTANT_UCS4)]
961 else:
962 result = list(CONSTANT_UCS4)
963 assert GIMarshallingTests.array_unichar_out() == result
965 @unittest.skip("broken")
966 def test_array_zero_terminated_return_unichar(self):
967 assert GIMarshallingTests.array_zero_terminated_return_unichar() == \
968 list(CONSTANT_UCS4)
970 def test_array_fixed_int_return(self):
971 self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.array_fixed_int_return())
973 def test_array_fixed_short_return(self):
974 self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.array_fixed_short_return())
976 def test_array_fixed_int_in(self):
977 GIMarshallingTests.array_fixed_int_in(Sequence([-1, 0, 1, 2]))
979 self.assertRaises(TypeError, GIMarshallingTests.array_fixed_int_in, Sequence([-1, '0', 1, 2]))
981 self.assertRaises(TypeError, GIMarshallingTests.array_fixed_int_in, 42)
982 self.assertRaises(TypeError, GIMarshallingTests.array_fixed_int_in, None)
984 def test_array_fixed_short_in(self):
985 GIMarshallingTests.array_fixed_short_in(Sequence([-1, 0, 1, 2]))
987 def test_array_fixed_out(self):
988 self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.array_fixed_out())
990 def test_array_fixed_inout(self):
991 self.assertEqual([2, 1, 0, -1], GIMarshallingTests.array_fixed_inout([-1, 0, 1, 2]))
993 def test_array_return(self):
994 self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.array_return())
996 def test_array_return_etc(self):
997 self.assertEqual(([5, 0, 1, 9], 14), GIMarshallingTests.array_return_etc(5, 9))
999 def test_array_in(self):
1000 GIMarshallingTests.array_in(Sequence([-1, 0, 1, 2]))
1001 GIMarshallingTests.array_in_guint64_len(Sequence([-1, 0, 1, 2]))
1002 GIMarshallingTests.array_in_guint8_len(Sequence([-1, 0, 1, 2]))
1004 def test_array_in_len_before(self):
1005 GIMarshallingTests.array_in_len_before(Sequence([-1, 0, 1, 2]))
1007 def test_array_in_len_zero_terminated(self):
1008 GIMarshallingTests.array_in_len_zero_terminated(Sequence([-1, 0, 1, 2]))
1010 def test_array_uint8_in(self):
1011 GIMarshallingTests.array_uint8_in(Sequence([97, 98, 99, 100]))
1012 GIMarshallingTests.array_uint8_in(b"abcd")
1014 def test_array_string_in(self):
1015 GIMarshallingTests.array_string_in(['foo', 'bar'])
1017 def test_array_out(self):
1018 self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.array_out())
1020 def test_array_out_etc(self):
1021 self.assertEqual(([-5, 0, 1, 9], 4), GIMarshallingTests.array_out_etc(-5, 9))
1023 def test_array_inout(self):
1024 self.assertEqual([-2, -1, 0, 1, 2], GIMarshallingTests.array_inout(Sequence([-1, 0, 1, 2])))
1026 def test_array_inout_etc(self):
1027 self.assertEqual(([-5, -1, 0, 1, 9], 4),
1028 GIMarshallingTests.array_inout_etc(-5, Sequence([-1, 0, 1, 2]), 9))
1030 def test_method_array_in(self):
1031 object_ = GIMarshallingTests.Object()
1032 object_.method_array_in(Sequence([-1, 0, 1, 2]))
1034 def test_method_array_out(self):
1035 object_ = GIMarshallingTests.Object()
1036 self.assertEqual([-1, 0, 1, 2], object_.method_array_out())
1038 def test_method_array_inout(self):
1039 object_ = GIMarshallingTests.Object()
1040 self.assertEqual([-2, -1, 0, 1, 2], object_.method_array_inout(Sequence([-1, 0, 1, 2])))
1042 def test_method_array_return(self):
1043 object_ = GIMarshallingTests.Object()
1044 self.assertEqual([-1, 0, 1, 2], object_.method_array_return())
1046 def test_array_enum_in(self):
1047 GIMarshallingTests.array_enum_in([GIMarshallingTests.Enum.VALUE1,
1048 GIMarshallingTests.Enum.VALUE2,
1049 GIMarshallingTests.Enum.VALUE3])
1051 def test_array_boxed_struct_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
1059 GIMarshallingTests.array_struct_in([struct1, struct2, struct3])
1061 def test_array_boxed_struct_in_item_marshal_failure(self):
1062 struct1 = GIMarshallingTests.BoxedStruct()
1063 struct1.long_ = 1
1064 struct2 = GIMarshallingTests.BoxedStruct()
1065 struct2.long_ = 2
1067 self.assertRaises(TypeError, GIMarshallingTests.array_struct_in,
1068 [struct1, struct2, 'not_a_struct'])
1070 def test_array_boxed_struct_value_in(self):
1071 struct1 = GIMarshallingTests.BoxedStruct()
1072 struct1.long_ = 1
1073 struct2 = GIMarshallingTests.BoxedStruct()
1074 struct2.long_ = 2
1075 struct3 = GIMarshallingTests.BoxedStruct()
1076 struct3.long_ = 3
1078 GIMarshallingTests.array_struct_value_in([struct1, struct2, struct3])
1080 def test_array_boxed_struct_value_in_item_marshal_failure(self):
1081 struct1 = GIMarshallingTests.BoxedStruct()
1082 struct1.long_ = 1
1083 struct2 = GIMarshallingTests.BoxedStruct()
1084 struct2.long_ = 2
1086 self.assertRaises(TypeError, GIMarshallingTests.array_struct_value_in,
1087 [struct1, struct2, 'not_a_struct'])
1089 def test_array_boxed_struct_take_in(self):
1090 struct1 = GIMarshallingTests.BoxedStruct()
1091 struct1.long_ = 1
1092 struct2 = GIMarshallingTests.BoxedStruct()
1093 struct2.long_ = 2
1094 struct3 = GIMarshallingTests.BoxedStruct()
1095 struct3.long_ = 3
1097 GIMarshallingTests.array_struct_take_in([struct1, struct2, struct3])
1099 self.assertEqual(1, struct1.long_)
1101 def test_array_boxed_struct_return(self):
1102 (struct1, struct2, struct3) = GIMarshallingTests.array_zero_terminated_return_struct()
1103 self.assertEqual(GIMarshallingTests.BoxedStruct, type(struct1))
1104 self.assertEqual(GIMarshallingTests.BoxedStruct, type(struct2))
1105 self.assertEqual(GIMarshallingTests.BoxedStruct, type(struct3))
1106 self.assertEqual(42, struct1.long_)
1107 self.assertEqual(43, struct2.long_)
1108 self.assertEqual(44, struct3.long_)
1110 def test_array_simple_struct_in(self):
1111 struct1 = GIMarshallingTests.SimpleStruct()
1112 struct1.long_ = 1
1113 struct2 = GIMarshallingTests.SimpleStruct()
1114 struct2.long_ = 2
1115 struct3 = GIMarshallingTests.SimpleStruct()
1116 struct3.long_ = 3
1118 GIMarshallingTests.array_simple_struct_in([struct1, struct2, struct3])
1120 def test_array_simple_struct_in_item_marshal_failure(self):
1121 struct1 = GIMarshallingTests.SimpleStruct()
1122 struct1.long_ = 1
1123 struct2 = GIMarshallingTests.SimpleStruct()
1124 struct2.long_ = 2
1126 self.assertRaises(TypeError, GIMarshallingTests.array_simple_struct_in,
1127 [struct1, struct2, 'not_a_struct'])
1129 def test_array_multi_array_key_value_in(self):
1130 GIMarshallingTests.multi_array_key_value_in(["one", "two", "three"],
1131 [1, 2, 3])
1133 def test_array_in_nonzero_nonlen(self):
1134 GIMarshallingTests.array_in_nonzero_nonlen(1, b'abcd')
1136 def test_array_fixed_out_struct(self):
1137 struct1, struct2 = GIMarshallingTests.array_fixed_out_struct()
1139 self.assertEqual(7, struct1.long_)
1140 self.assertEqual(6, struct1.int8)
1141 self.assertEqual(6, struct2.long_)
1142 self.assertEqual(7, struct2.int8)
1144 def test_array_zero_terminated_return(self):
1145 self.assertEqual(['0', '1', '2'], GIMarshallingTests.array_zero_terminated_return())
1147 def test_array_zero_terminated_return_null(self):
1148 self.assertEqual([], GIMarshallingTests.array_zero_terminated_return_null())
1150 def test_array_zero_terminated_in(self):
1151 GIMarshallingTests.array_zero_terminated_in(Sequence(['0', '1', '2']))
1153 def test_array_zero_terminated_out(self):
1154 self.assertEqual(['0', '1', '2'], GIMarshallingTests.array_zero_terminated_out())
1156 def test_array_zero_terminated_inout(self):
1157 self.assertEqual(['-1', '0', '1', '2'], GIMarshallingTests.array_zero_terminated_inout(['0', '1', '2']))
1159 def test_init_function(self):
1160 self.assertEqual((True, []), GIMarshallingTests.init_function([]))
1161 self.assertEqual((True, []), GIMarshallingTests.init_function(['hello']))
1162 self.assertEqual((True, ['hello']),
1163 GIMarshallingTests.init_function(['hello', 'world']))
1165 def test_enum_array_return_type(self):
1166 self.assertEqual(GIMarshallingTests.enum_array_return_type(),
1167 [GIMarshallingTests.ExtraEnum.VALUE1,
1168 GIMarshallingTests.ExtraEnum.VALUE2,
1169 GIMarshallingTests.ExtraEnum.VALUE3])
1172 class TestGStrv(unittest.TestCase):
1174 def test_gstrv_return(self):
1175 self.assertEqual(['0', '1', '2'], GIMarshallingTests.gstrv_return())
1177 def test_gstrv_in(self):
1178 GIMarshallingTests.gstrv_in(Sequence(['0', '1', '2']))
1180 def test_gstrv_out(self):
1181 self.assertEqual(['0', '1', '2'], GIMarshallingTests.gstrv_out())
1183 def test_gstrv_inout(self):
1184 self.assertEqual(['-1', '0', '1', '2'], GIMarshallingTests.gstrv_inout(['0', '1', '2']))
1187 class TestArrayGVariant(unittest.TestCase):
1189 def test_array_gvariant_none_in(self):
1190 v = [GLib.Variant("i", 27), GLib.Variant("s", "Hello")]
1191 returned = [GLib.Variant.unpack(r) for r in GIMarshallingTests.array_gvariant_none_in(v)]
1192 self.assertEqual([27, "Hello"], returned)
1194 def test_array_gvariant_container_in(self):
1195 v = [GLib.Variant("i", 27), GLib.Variant("s", "Hello")]
1196 returned = [GLib.Variant.unpack(r) for r in GIMarshallingTests.array_gvariant_container_in(v)]
1197 self.assertEqual([27, "Hello"], returned)
1199 def test_array_gvariant_full_in(self):
1200 v = [GLib.Variant("i", 27), GLib.Variant("s", "Hello")]
1201 returned = [GLib.Variant.unpack(r) for r in GIMarshallingTests.array_gvariant_full_in(v)]
1202 self.assertEqual([27, "Hello"], returned)
1204 def test_bytearray_gvariant(self):
1205 v = GLib.Variant.new_bytestring(b"foo")
1206 self.assertEqual(v.get_bytestring(), b"foo")
1209 class TestGArray(unittest.TestCase):
1211 @unittest.skipUnless(
1212 hasattr(GIMarshallingTests, "garray_bool_none_in"), "too old gi")
1213 def test_garray_bool_none_in(self):
1214 GIMarshallingTests.garray_bool_none_in([True, False, True, True])
1216 @unittest.skipUnless(
1217 hasattr(GIMarshallingTests, "garray_unichar_none_in"), "too old gi")
1218 def test_garray_unichar_none_in(self):
1219 GIMarshallingTests.garray_unichar_none_in(CONSTANT_UCS4)
1220 GIMarshallingTests.garray_unichar_none_in(list(CONSTANT_UCS4))
1222 def test_garray_int_none_return(self):
1223 self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.garray_int_none_return())
1225 def test_garray_uint64_none_return(self):
1226 self.assertEqual([0, GLib.MAXUINT64], GIMarshallingTests.garray_uint64_none_return())
1228 def test_garray_utf8_none_return(self):
1229 self.assertEqual(['0', '1', '2'], GIMarshallingTests.garray_utf8_none_return())
1231 def test_garray_utf8_container_return(self):
1232 self.assertEqual(['0', '1', '2'], GIMarshallingTests.garray_utf8_container_return())
1234 def test_garray_utf8_full_return(self):
1235 self.assertEqual(['0', '1', '2'], GIMarshallingTests.garray_utf8_full_return())
1237 def test_garray_int_none_in(self):
1238 GIMarshallingTests.garray_int_none_in(Sequence([-1, 0, 1, 2]))
1240 self.assertRaises(TypeError, GIMarshallingTests.garray_int_none_in, Sequence([-1, '0', 1, 2]))
1242 self.assertRaises(TypeError, GIMarshallingTests.garray_int_none_in, 42)
1243 self.assertRaises(TypeError, GIMarshallingTests.garray_int_none_in, None)
1245 def test_garray_uint64_none_in(self):
1246 GIMarshallingTests.garray_uint64_none_in(Sequence([0, GLib.MAXUINT64]))
1248 def test_garray_utf8_none_in(self):
1249 GIMarshallingTests.garray_utf8_none_in(Sequence(['0', '1', '2']))
1251 def test_garray_utf8_none_out(self):
1252 self.assertEqual(['0', '1', '2'], GIMarshallingTests.garray_utf8_none_out())
1254 def test_garray_utf8_container_out(self):
1255 self.assertEqual(['0', '1', '2'], GIMarshallingTests.garray_utf8_container_out())
1257 def test_garray_utf8_full_out(self):
1258 self.assertEqual(['0', '1', '2'], GIMarshallingTests.garray_utf8_full_out())
1260 def test_garray_utf8_full_out_caller_allocated(self):
1261 self.assertEqual(['0', '1', '2'], GIMarshallingTests.garray_utf8_full_out_caller_allocated())
1263 def test_garray_utf8_none_inout(self):
1264 self.assertEqual(['-2', '-1', '0', '1'], GIMarshallingTests.garray_utf8_none_inout(Sequence(('0', '1', '2'))))
1266 def test_garray_utf8_container_inout(self):
1267 self.assertEqual(['-2', '-1', '0', '1'], GIMarshallingTests.garray_utf8_container_inout(['0', '1', '2']))
1269 def test_garray_utf8_full_inout(self):
1270 self.assertEqual(['-2', '-1', '0', '1'], GIMarshallingTests.garray_utf8_full_inout(['0', '1', '2']))
1273 class TestGPtrArray(unittest.TestCase):
1275 def test_gptrarray_utf8_none_return(self):
1276 self.assertEqual(['0', '1', '2'], GIMarshallingTests.gptrarray_utf8_none_return())
1278 def test_gptrarray_utf8_container_return(self):
1279 self.assertEqual(['0', '1', '2'], GIMarshallingTests.gptrarray_utf8_container_return())
1281 def test_gptrarray_utf8_full_return(self):
1282 self.assertEqual(['0', '1', '2'], GIMarshallingTests.gptrarray_utf8_full_return())
1284 def test_gptrarray_utf8_none_in(self):
1285 GIMarshallingTests.gptrarray_utf8_none_in(Sequence(['0', '1', '2']))
1287 def test_gptrarray_utf8_none_out(self):
1288 self.assertEqual(['0', '1', '2'], GIMarshallingTests.gptrarray_utf8_none_out())
1290 def test_gptrarray_utf8_container_out(self):
1291 self.assertEqual(['0', '1', '2'], GIMarshallingTests.gptrarray_utf8_container_out())
1293 def test_gptrarray_utf8_full_out(self):
1294 self.assertEqual(['0', '1', '2'], GIMarshallingTests.gptrarray_utf8_full_out())
1296 def test_gptrarray_utf8_none_inout(self):
1297 self.assertEqual(['-2', '-1', '0', '1'], GIMarshallingTests.gptrarray_utf8_none_inout(Sequence(('0', '1', '2'))))
1299 def test_gptrarray_utf8_container_inout(self):
1300 self.assertEqual(['-2', '-1', '0', '1'], GIMarshallingTests.gptrarray_utf8_container_inout(['0', '1', '2']))
1302 def test_gptrarray_utf8_full_inout(self):
1303 self.assertEqual(['-2', '-1', '0', '1'], GIMarshallingTests.gptrarray_utf8_full_inout(['0', '1', '2']))
1306 class TestGBytes(unittest.TestCase):
1307 def test_gbytes_create(self):
1308 b = GLib.Bytes.new(b'\x00\x01\xFF')
1309 self.assertEqual(3, b.get_size())
1310 self.assertEqual(b'\x00\x01\xFF', b.get_data())
1312 def test_gbytes_create_take(self):
1313 b = GLib.Bytes.new_take(b'\x00\x01\xFF')
1314 self.assertEqual(3, b.get_size())
1315 self.assertEqual(b'\x00\x01\xFF', b.get_data())
1317 def test_gbytes_full_return(self):
1318 b = GIMarshallingTests.gbytes_full_return()
1319 self.assertEqual(4, b.get_size())
1320 self.assertEqual(b'\x00\x31\xFF\x33', b.get_data())
1322 def test_gbytes_none_in(self):
1323 b = GIMarshallingTests.gbytes_full_return()
1324 GIMarshallingTests.gbytes_none_in(b)
1326 def test_compare(self):
1327 a1 = GLib.Bytes.new(b'\x00\x01\xFF')
1328 a2 = GLib.Bytes.new(b'\x00\x01\xFF')
1329 b = GLib.Bytes.new(b'\x00\x01\xFE')
1331 self.assertTrue(a1.equal(a2))
1332 self.assertTrue(a2.equal(a1))
1333 self.assertFalse(a1.equal(b))
1334 self.assertFalse(b.equal(a2))
1336 self.assertEqual(0, a1.compare(a2))
1337 self.assertLess(0, a1.compare(b))
1338 self.assertGreater(0, b.compare(a1))
1341 class TestGByteArray(unittest.TestCase):
1342 def test_new(self):
1343 ba = GLib.ByteArray.new()
1344 self.assertEqual(b'', ba)
1346 ba = GLib.ByteArray.new_take(b'\x01\x02\xFF')
1347 self.assertEqual(b'\x01\x02\xFF', ba)
1349 def test_bytearray_full_return(self):
1350 self.assertEqual(b'\x001\xFF3', GIMarshallingTests.bytearray_full_return())
1352 def test_bytearray_none_in(self):
1353 b = b'\x00\x31\xFF\x33'
1354 ba = GLib.ByteArray.new_take(b)
1356 # b should always have the same value even
1357 # though the generated GByteArray is being modified
1358 GIMarshallingTests.bytearray_none_in(b)
1359 GIMarshallingTests.bytearray_none_in(b)
1361 # The GByteArray is just a bytes
1362 # thus it will not reflect any changes
1363 GIMarshallingTests.bytearray_none_in(ba)
1364 GIMarshallingTests.bytearray_none_in(ba)
1367 class TestGList(unittest.TestCase):
1369 def test_glist_int_none_return(self):
1370 self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.glist_int_none_return())
1372 def test_glist_uint32_none_return(self):
1373 self.assertEqual([0, GLib.MAXUINT32], GIMarshallingTests.glist_uint32_none_return())
1375 def test_glist_utf8_none_return(self):
1376 self.assertEqual(['0', '1', '2'], GIMarshallingTests.glist_utf8_none_return())
1378 def test_glist_utf8_container_return(self):
1379 self.assertEqual(['0', '1', '2'], GIMarshallingTests.glist_utf8_container_return())
1381 def test_glist_utf8_full_return(self):
1382 self.assertEqual(['0', '1', '2'], GIMarshallingTests.glist_utf8_full_return())
1384 def test_glist_int_none_in(self):
1385 GIMarshallingTests.glist_int_none_in(Sequence((-1, 0, 1, 2)))
1387 self.assertRaises(TypeError, GIMarshallingTests.glist_int_none_in, Sequence((-1, '0', 1, 2)))
1389 self.assertRaises(TypeError, GIMarshallingTests.glist_int_none_in, 42)
1390 self.assertRaises(TypeError, GIMarshallingTests.glist_int_none_in, None)
1392 def test_glist_int_none_in_error_getitem(self):
1394 class FailingSequence(Sequence):
1395 def __getitem__(self, key):
1396 raise Exception
1398 self.assertRaises(Exception, GIMarshallingTests.glist_int_none_in, FailingSequence((-1, 0, 1, 2)))
1400 def test_glist_uint32_none_in(self):
1401 GIMarshallingTests.glist_uint32_none_in(Sequence((0, GLib.MAXUINT32)))
1403 def test_glist_utf8_none_in(self):
1404 GIMarshallingTests.glist_utf8_none_in(Sequence(('0', '1', '2')))
1406 def test_glist_utf8_none_out(self):
1407 self.assertEqual(['0', '1', '2'], GIMarshallingTests.glist_utf8_none_out())
1409 def test_glist_utf8_container_out(self):
1410 self.assertEqual(['0', '1', '2'], GIMarshallingTests.glist_utf8_container_out())
1412 def test_glist_utf8_full_out(self):
1413 self.assertEqual(['0', '1', '2'], GIMarshallingTests.glist_utf8_full_out())
1415 def test_glist_utf8_none_inout(self):
1416 self.assertEqual(['-2', '-1', '0', '1'], GIMarshallingTests.glist_utf8_none_inout(Sequence(('0', '1', '2'))))
1418 def test_glist_utf8_container_inout(self):
1419 self.assertEqual(['-2', '-1', '0', '1'], GIMarshallingTests.glist_utf8_container_inout(('0', '1', '2')))
1421 def test_glist_utf8_full_inout(self):
1422 self.assertEqual(['-2', '-1', '0', '1'], GIMarshallingTests.glist_utf8_full_inout(('0', '1', '2')))
1425 class TestGSList(unittest.TestCase):
1427 def test_gslist_int_none_return(self):
1428 self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.gslist_int_none_return())
1430 def test_gslist_utf8_none_return(self):
1431 self.assertEqual(['0', '1', '2'], GIMarshallingTests.gslist_utf8_none_return())
1433 def test_gslist_utf8_container_return(self):
1434 self.assertEqual(['0', '1', '2'], GIMarshallingTests.gslist_utf8_container_return())
1436 def test_gslist_utf8_full_return(self):
1437 self.assertEqual(['0', '1', '2'], GIMarshallingTests.gslist_utf8_full_return())
1439 def test_gslist_int_none_in(self):
1440 GIMarshallingTests.gslist_int_none_in(Sequence((-1, 0, 1, 2)))
1442 self.assertRaises(TypeError, GIMarshallingTests.gslist_int_none_in, Sequence((-1, '0', 1, 2)))
1444 self.assertRaises(TypeError, GIMarshallingTests.gslist_int_none_in, 42)
1445 self.assertRaises(TypeError, GIMarshallingTests.gslist_int_none_in, None)
1447 def test_gslist_int_none_in_error_getitem(self):
1449 class FailingSequence(Sequence):
1450 def __getitem__(self, key):
1451 raise Exception
1453 self.assertRaises(Exception, GIMarshallingTests.gslist_int_none_in, FailingSequence((-1, 0, 1, 2)))
1455 def test_gslist_utf8_none_in(self):
1456 GIMarshallingTests.gslist_utf8_none_in(Sequence(('0', '1', '2')))
1458 def test_gslist_utf8_none_out(self):
1459 self.assertEqual(['0', '1', '2'], GIMarshallingTests.gslist_utf8_none_out())
1461 def test_gslist_utf8_container_out(self):
1462 self.assertEqual(['0', '1', '2'], GIMarshallingTests.gslist_utf8_container_out())
1464 def test_gslist_utf8_full_out(self):
1465 self.assertEqual(['0', '1', '2'], GIMarshallingTests.gslist_utf8_full_out())
1467 def test_gslist_utf8_none_inout(self):
1468 self.assertEqual(['-2', '-1', '0', '1'], GIMarshallingTests.gslist_utf8_none_inout(Sequence(('0', '1', '2'))))
1470 def test_gslist_utf8_container_inout(self):
1471 self.assertEqual(['-2', '-1', '0', '1'], GIMarshallingTests.gslist_utf8_container_inout(('0', '1', '2')))
1473 def test_gslist_utf8_full_inout(self):
1474 self.assertEqual(['-2', '-1', '0', '1'], GIMarshallingTests.gslist_utf8_full_inout(('0', '1', '2')))
1477 class TestGHashTable(unittest.TestCase):
1479 @unittest.skip("broken")
1480 def test_ghashtable_double_in(self):
1481 GIMarshallingTests.ghashtable_double_in(
1482 {"-1": -0.1, "0": 0.0, "1": 0.1, "2": 0.2})
1484 @unittest.skip("broken")
1485 def test_ghashtable_float_in(self):
1486 GIMarshallingTests.ghashtable_float_in(
1487 {"-1": -0.1, "0": 0.0, "1": 0.1, "2": 0.2})
1489 @unittest.skip("broken")
1490 def test_ghashtable_int64_in(self):
1491 GIMarshallingTests.ghashtable_int64_in(
1492 {"-1": GLib.MAXUINT32 + 1, "0": 0, "1": 1, "2": 2})
1494 @unittest.skip("broken")
1495 def test_ghashtable_uint64_in(self):
1496 GIMarshallingTests.ghashtable_uint64_in(
1497 {"-1": GLib.MAXUINT32 + 1, "0": 0, "1": 1, "2": 2})
1499 def test_ghashtable_int_none_return(self):
1500 self.assertEqual({-1: 1, 0: 0, 1: -1, 2: -2}, GIMarshallingTests.ghashtable_int_none_return())
1502 def test_ghashtable_int_none_return2(self):
1503 self.assertEqual({'-1': '1', '0': '0', '1': '-1', '2': '-2'}, GIMarshallingTests.ghashtable_utf8_none_return())
1505 def test_ghashtable_int_container_return(self):
1506 self.assertEqual({'-1': '1', '0': '0', '1': '-1', '2': '-2'}, GIMarshallingTests.ghashtable_utf8_container_return())
1508 def test_ghashtable_int_full_return(self):
1509 self.assertEqual({'-1': '1', '0': '0', '1': '-1', '2': '-2'}, GIMarshallingTests.ghashtable_utf8_full_return())
1511 def test_ghashtable_int_none_in(self):
1512 GIMarshallingTests.ghashtable_int_none_in({-1: 1, 0: 0, 1: -1, 2: -2})
1514 self.assertRaises(TypeError, GIMarshallingTests.ghashtable_int_none_in, {-1: 1, '0': 0, 1: -1, 2: -2})
1515 self.assertRaises(TypeError, GIMarshallingTests.ghashtable_int_none_in, {-1: 1, 0: '0', 1: -1, 2: -2})
1517 self.assertRaises(TypeError, GIMarshallingTests.ghashtable_int_none_in, '{-1: 1, 0: 0, 1: -1, 2: -2}')
1518 self.assertRaises(TypeError, GIMarshallingTests.ghashtable_int_none_in, None)
1520 def test_ghashtable_utf8_none_in(self):
1521 GIMarshallingTests.ghashtable_utf8_none_in({'-1': '1', '0': '0', '1': '-1', '2': '-2'})
1523 def test_ghashtable_utf8_none_out(self):
1524 self.assertEqual({'-1': '1', '0': '0', '1': '-1', '2': '-2'}, GIMarshallingTests.ghashtable_utf8_none_out())
1526 def test_ghashtable_utf8_container_out(self):
1527 self.assertEqual({'-1': '1', '0': '0', '1': '-1', '2': '-2'}, GIMarshallingTests.ghashtable_utf8_container_out())
1529 def test_ghashtable_utf8_full_out(self):
1530 self.assertEqual({'-1': '1', '0': '0', '1': '-1', '2': '-2'}, GIMarshallingTests.ghashtable_utf8_full_out())
1532 def test_ghashtable_utf8_none_inout(self):
1533 i = {'-1': '1', '0': '0', '1': '-1', '2': '-2'}
1534 self.assertEqual({'-1': '1', '0': '0', '1': '1'},
1535 GIMarshallingTests.ghashtable_utf8_none_inout(i))
1537 def test_ghashtable_utf8_container_inout(self):
1538 i = {'-1': '1', '0': '0', '1': '-1', '2': '-2'}
1539 self.assertEqual({'-1': '1', '0': '0', '1': '1'},
1540 GIMarshallingTests.ghashtable_utf8_container_inout(i))
1542 def test_ghashtable_utf8_full_inout(self):
1543 i = {'-1': '1', '0': '0', '1': '-1', '2': '-2'}
1544 self.assertEqual({'-1': '1', '0': '0', '1': '1'},
1545 GIMarshallingTests.ghashtable_utf8_full_inout(i))
1547 def test_ghashtable_enum_none_in(self):
1548 GIMarshallingTests.ghashtable_enum_none_in({1: GIMarshallingTests.ExtraEnum.VALUE1,
1549 2: GIMarshallingTests.ExtraEnum.VALUE2,
1550 3: GIMarshallingTests.ExtraEnum.VALUE3})
1552 def test_ghashtable_enum_none_return(self):
1553 self.assertEqual({1: GIMarshallingTests.ExtraEnum.VALUE1,
1554 2: GIMarshallingTests.ExtraEnum.VALUE2,
1555 3: GIMarshallingTests.ExtraEnum.VALUE3},
1556 GIMarshallingTests.ghashtable_enum_none_return())
1559 class TestGValue(unittest.TestCase):
1561 def test_gvalue_return(self):
1562 self.assertEqual(42, GIMarshallingTests.gvalue_return())
1564 def test_gvalue_in(self):
1565 GIMarshallingTests.gvalue_in(42)
1566 value = GObject.Value(GObject.TYPE_INT, 42)
1567 GIMarshallingTests.gvalue_in(value)
1569 def test_gvalue_in_with_modification(self):
1570 value = GObject.Value(GObject.TYPE_INT, 42)
1571 GIMarshallingTests.gvalue_in_with_modification(value)
1572 self.assertEqual(value.get_int(), 24)
1574 def test_gvalue_int64_in(self):
1575 value = GObject.Value(GObject.TYPE_INT64, GLib.MAXINT64)
1576 GIMarshallingTests.gvalue_int64_in(value)
1578 def test_gvalue_in_with_type(self):
1579 value = GObject.Value(GObject.TYPE_STRING, 'foo')
1580 GIMarshallingTests.gvalue_in_with_type(value, GObject.TYPE_STRING)
1582 value = GObject.Value(GIMarshallingTests.Flags.__gtype__,
1583 GIMarshallingTests.Flags.VALUE1)
1584 GIMarshallingTests.gvalue_in_with_type(value, GObject.TYPE_FLAGS)
1586 def test_gvalue_in_enum(self):
1587 value = GObject.Value(GIMarshallingTests.Enum.__gtype__,
1588 GIMarshallingTests.Enum.VALUE3)
1589 GIMarshallingTests.gvalue_in_enum(value)
1591 def test_gvalue_out(self):
1592 self.assertEqual(42, GIMarshallingTests.gvalue_out())
1594 def test_gvalue_int64_out(self):
1595 self.assertEqual(GLib.MAXINT64, GIMarshallingTests.gvalue_int64_out())
1597 def test_gvalue_out_caller_allocates(self):
1598 self.assertEqual(42, GIMarshallingTests.gvalue_out_caller_allocates())
1600 def test_gvalue_inout(self):
1601 self.assertEqual('42', GIMarshallingTests.gvalue_inout(42))
1602 value = GObject.Value(int, 42)
1603 self.assertEqual('42', GIMarshallingTests.gvalue_inout(value))
1605 def test_gvalue_flat_array_in(self):
1606 # the function already asserts the correct values
1607 GIMarshallingTests.gvalue_flat_array([42, "42", True])
1609 def test_gvalue_flat_array_in_item_marshal_failure(self):
1610 # Tests the failure to marshal 2^256 to a GValue mid-way through the array marshaling.
1611 self.assertRaises(OverflowError, GIMarshallingTests.gvalue_flat_array,
1612 [42, 2 ** 256, True])
1614 self.assertRaises(OverflowError, GIMarshallingTests.gvalue_flat_array,
1615 [GLib.MAXINT + 1, "42", True])
1616 self.assertRaises(OverflowError, GIMarshallingTests.gvalue_flat_array,
1617 [GLib.MININT - 1, "42", True])
1619 with pytest.raises(
1620 OverflowError,
1621 match='Item 0: %d not in range %d to %d' % (
1622 GLib.MAXINT + 1, GLib.MININT, GLib.MAXINT)):
1623 GIMarshallingTests.gvalue_flat_array([GLib.MAXINT + 1, "42", True])
1625 if PY2:
1626 min_, max_ = GLib.MINLONG, GLib.MAXLONG
1627 else:
1628 min_, max_ = GLib.MININT, GLib.MAXINT
1630 with pytest.raises(
1631 OverflowError,
1632 match='Item 0: %d not in range %d to %d' % (
1633 GLib.MAXUINT64 * 2, min_, max_)):
1634 GIMarshallingTests.gvalue_flat_array([GLib.MAXUINT64 * 2, "42", True])
1636 def test_gvalue_flat_array_out(self):
1637 values = GIMarshallingTests.return_gvalue_flat_array()
1638 self.assertEqual(values, [42, '42', True])
1640 def test_gvalue_gobject_ref_counts_simple(self):
1641 obj = GObject.Object()
1642 grefcount = obj.__grefcount__
1643 value = GObject.Value(GObject.TYPE_OBJECT, obj)
1644 del value
1645 gc.collect()
1646 gc.collect()
1647 assert obj.__grefcount__ == grefcount
1649 @unittest.skipIf(platform.python_implementation() == "PyPy" and PY3, "fixme")
1650 def test_gvalue_gobject_ref_counts(self):
1651 # Tests a GObject held by a GValue
1652 obj = GObject.Object()
1653 ref = weakref.ref(obj)
1654 grefcount = obj.__grefcount__
1656 value = GObject.Value()
1657 value.init(GObject.TYPE_OBJECT)
1659 # TYPE_OBJECT will inc ref count as it should
1660 value.set_object(obj)
1661 self.assertEqual(obj.__grefcount__, grefcount + 1)
1663 # multiple set_object should not inc ref count
1664 value.set_object(obj)
1665 self.assertEqual(obj.__grefcount__, grefcount + 1)
1667 # get_object will re-use the same wrapper as obj
1668 res = value.get_object()
1669 self.assertEqual(obj, res)
1670 self.assertEqual(obj.__grefcount__, grefcount + 1)
1672 # multiple get_object should not inc ref count
1673 res = value.get_object()
1674 self.assertEqual(obj.__grefcount__, grefcount + 1)
1676 # deletion of the result and value holder should bring the
1677 # refcount back to where we started
1678 del res
1679 del value
1680 gc.collect()
1681 gc.collect()
1682 self.assertEqual(obj.__grefcount__, grefcount)
1684 del obj
1685 gc.collect()
1686 self.assertEqual(ref(), None)
1688 @unittest.skipUnless(hasattr(sys, "getrefcount"), "no sys.getrefcount")
1689 def test_gvalue_boxed_ref_counts(self):
1690 # Tests a boxed type wrapping a python object pointer (TYPE_PYOBJECT)
1691 # held by a GValue
1692 class Obj(object):
1693 pass
1695 obj = Obj()
1696 ref = weakref.ref(obj)
1697 refcount = sys.getrefcount(obj)
1699 value = GObject.Value()
1700 value.init(GObject.TYPE_PYOBJECT)
1702 # boxed TYPE_PYOBJECT will inc ref count as it should
1703 value.set_boxed(obj)
1704 self.assertEqual(sys.getrefcount(obj), refcount + 1)
1706 # multiple set_boxed should not inc ref count
1707 value.set_boxed(obj)
1708 self.assertEqual(sys.getrefcount(obj), refcount + 1)
1710 res = value.get_boxed()
1711 self.assertEqual(obj, res)
1712 self.assertEqual(sys.getrefcount(obj), refcount + 2)
1714 # multiple get_boxed should not inc ref count
1715 res = value.get_boxed()
1716 self.assertEqual(sys.getrefcount(obj), refcount + 2)
1718 # deletion of the result and value holder should bring the
1719 # refcount back to where we started
1720 del res
1721 del value
1722 gc.collect()
1723 self.assertEqual(sys.getrefcount(obj), refcount)
1725 del obj
1726 gc.collect()
1727 self.assertEqual(ref(), None)
1729 @unittest.skip("broken")
1730 def test_gvalue_flat_array_round_trip(self):
1731 self.assertEqual([42, '42', True],
1732 GIMarshallingTests.gvalue_flat_array_round_trip(42, '42', True))
1735 class TestGClosure(unittest.TestCase):
1737 def test_in(self):
1738 GIMarshallingTests.gclosure_in(lambda: 42)
1740 def test_pass(self):
1741 # test passing a closure between two C calls
1742 closure = GIMarshallingTests.gclosure_return()
1743 GIMarshallingTests.gclosure_in(closure)
1745 def test_type_error(self):
1746 self.assertRaises(TypeError, GIMarshallingTests.gclosure_in, 42)
1747 self.assertRaises(TypeError, GIMarshallingTests.gclosure_in, None)
1750 class TestCallbacks(unittest.TestCase):
1751 def test_return_value_only(self):
1752 def cb():
1753 return 5
1754 self.assertEqual(GIMarshallingTests.callback_return_value_only(cb), 5)
1756 def test_one_out_arg(self):
1757 def cb():
1758 return 5.5
1759 self.assertAlmostEqual(GIMarshallingTests.callback_one_out_parameter(cb), 5.5)
1761 def test_multiple_out_args(self):
1762 def cb():
1763 return (5.5, 42.0)
1764 res = GIMarshallingTests.callback_multiple_out_parameters(cb)
1765 self.assertAlmostEqual(res[0], 5.5)
1766 self.assertAlmostEqual(res[1], 42.0)
1768 def test_return_and_one_out_arg(self):
1769 def cb():
1770 return (5, 42.0)
1771 res = GIMarshallingTests.callback_return_value_and_one_out_parameter(cb)
1772 self.assertEqual(res[0], 5)
1773 self.assertAlmostEqual(res[1], 42.0)
1775 def test_return_and_multiple_out_arg(self):
1776 def cb():
1777 return (5, 42, -1000)
1778 self.assertEqual(GIMarshallingTests.callback_return_value_and_multiple_out_parameters(cb),
1779 (5, 42, -1000))
1782 class TestPointer(unittest.TestCase):
1783 def test_pointer_in_return(self):
1784 self.assertEqual(GIMarshallingTests.pointer_in_return(42), 42)
1787 class TestEnum(unittest.TestCase):
1789 def test_enum(self):
1790 self.assertTrue(issubclass(GIMarshallingTests.Enum, int))
1791 self.assertTrue(isinstance(GIMarshallingTests.Enum.VALUE1, GIMarshallingTests.Enum))
1792 self.assertTrue(isinstance(GIMarshallingTests.Enum.VALUE2, GIMarshallingTests.Enum))
1793 self.assertTrue(isinstance(GIMarshallingTests.Enum.VALUE3, GIMarshallingTests.Enum))
1794 self.assertEqual(42, GIMarshallingTests.Enum.VALUE3)
1796 def test_value_nick_and_name(self):
1797 self.assertEqual(GIMarshallingTests.Enum.VALUE1.value_nick, 'value1')
1798 self.assertEqual(GIMarshallingTests.Enum.VALUE2.value_nick, 'value2')
1799 self.assertEqual(GIMarshallingTests.Enum.VALUE3.value_nick, 'value3')
1801 self.assertEqual(GIMarshallingTests.Enum.VALUE1.value_name, 'GI_MARSHALLING_TESTS_ENUM_VALUE1')
1802 self.assertEqual(GIMarshallingTests.Enum.VALUE2.value_name, 'GI_MARSHALLING_TESTS_ENUM_VALUE2')
1803 self.assertEqual(GIMarshallingTests.Enum.VALUE3.value_name, 'GI_MARSHALLING_TESTS_ENUM_VALUE3')
1805 def test_enum_in(self):
1806 GIMarshallingTests.enum_in(GIMarshallingTests.Enum.VALUE3)
1807 GIMarshallingTests.enum_in(42)
1809 self.assertRaises(TypeError, GIMarshallingTests.enum_in, 43)
1810 self.assertRaises(TypeError, GIMarshallingTests.enum_in, 'GIMarshallingTests.Enum.VALUE3')
1812 def test_enum_return(self):
1813 enum = GIMarshallingTests.enum_returnv()
1814 self.assertTrue(isinstance(enum, GIMarshallingTests.Enum))
1815 self.assertEqual(enum, GIMarshallingTests.Enum.VALUE3)
1817 def test_enum_out(self):
1818 enum = GIMarshallingTests.enum_out()
1819 self.assertTrue(isinstance(enum, GIMarshallingTests.Enum))
1820 self.assertEqual(enum, GIMarshallingTests.Enum.VALUE3)
1822 def test_enum_inout(self):
1823 enum = GIMarshallingTests.enum_inout(GIMarshallingTests.Enum.VALUE3)
1824 self.assertTrue(isinstance(enum, GIMarshallingTests.Enum))
1825 self.assertEqual(enum, GIMarshallingTests.Enum.VALUE1)
1827 def test_enum_second(self):
1828 # check for the bug where different non-gtype enums share the same class
1829 self.assertNotEqual(GIMarshallingTests.Enum, GIMarshallingTests.SecondEnum)
1831 # check that values are not being shared between different enums
1832 self.assertTrue(hasattr(GIMarshallingTests.SecondEnum, "SECONDVALUE1"))
1833 self.assertRaises(AttributeError, getattr, GIMarshallingTests.Enum, "SECONDVALUE1")
1834 self.assertTrue(hasattr(GIMarshallingTests.Enum, "VALUE1"))
1835 self.assertRaises(AttributeError, getattr, GIMarshallingTests.SecondEnum, "VALUE1")
1837 def test_enum_gtype_name_is_namespaced(self):
1838 self.assertEqual(GIMarshallingTests.Enum.__gtype__.name,
1839 'PyGIMarshallingTestsEnum')
1841 def test_enum_add_type_error(self):
1842 self.assertRaises(TypeError,
1843 gi._gi.enum_add,
1844 GIMarshallingTests.NoTypeFlags.__gtype__)
1846 def test_type_module_name(self):
1847 self.assertEqual(GIMarshallingTests.Enum.__name__, "Enum")
1848 self.assertEqual(GIMarshallingTests.Enum.__module__,
1849 "gi.repository.GIMarshallingTests")
1851 def test_hash(self):
1852 assert (hash(GIMarshallingTests.Enum.VALUE1) ==
1853 hash(GIMarshallingTests.Enum(GIMarshallingTests.Enum.VALUE1)))
1855 def test_repr(self):
1856 self.assertEqual(repr(GIMarshallingTests.Enum.VALUE3),
1857 "<enum GI_MARSHALLING_TESTS_ENUM_VALUE3 of type "
1858 "GIMarshallingTests.Enum>")
1861 class TestEnumVFuncResults(unittest.TestCase):
1862 class EnumTester(GIMarshallingTests.Object):
1863 def do_vfunc_return_enum(self):
1864 return GIMarshallingTests.Enum.VALUE2
1866 def do_vfunc_out_enum(self):
1867 return GIMarshallingTests.Enum.VALUE3
1869 def test_vfunc_return_enum(self):
1870 tester = self.EnumTester()
1871 self.assertEqual(tester.vfunc_return_enum(), GIMarshallingTests.Enum.VALUE2)
1873 def test_vfunc_out_enum(self):
1874 tester = self.EnumTester()
1875 self.assertEqual(tester.vfunc_out_enum(), GIMarshallingTests.Enum.VALUE3)
1878 class TestGEnum(unittest.TestCase):
1880 def test_genum(self):
1881 self.assertTrue(issubclass(GIMarshallingTests.GEnum, GObject.GEnum))
1882 self.assertTrue(isinstance(GIMarshallingTests.GEnum.VALUE1, GIMarshallingTests.GEnum))
1883 self.assertTrue(isinstance(GIMarshallingTests.GEnum.VALUE2, GIMarshallingTests.GEnum))
1884 self.assertTrue(isinstance(GIMarshallingTests.GEnum.VALUE3, GIMarshallingTests.GEnum))
1885 self.assertEqual(42, GIMarshallingTests.GEnum.VALUE3)
1887 def test_pickle(self):
1888 v = GIMarshallingTests.GEnum.VALUE3
1889 new_v = pickle.loads(pickle.dumps(v))
1890 assert new_v == v
1891 assert isinstance(new_v, GIMarshallingTests.GEnum)
1893 def test_value_nick_and_name(self):
1894 self.assertEqual(GIMarshallingTests.GEnum.VALUE1.value_nick, 'value1')
1895 self.assertEqual(GIMarshallingTests.GEnum.VALUE2.value_nick, 'value2')
1896 self.assertEqual(GIMarshallingTests.GEnum.VALUE3.value_nick, 'value3')
1898 self.assertEqual(GIMarshallingTests.GEnum.VALUE1.value_name, 'GI_MARSHALLING_TESTS_GENUM_VALUE1')
1899 self.assertEqual(GIMarshallingTests.GEnum.VALUE2.value_name, 'GI_MARSHALLING_TESTS_GENUM_VALUE2')
1900 self.assertEqual(GIMarshallingTests.GEnum.VALUE3.value_name, 'GI_MARSHALLING_TESTS_GENUM_VALUE3')
1902 def test_genum_in(self):
1903 GIMarshallingTests.genum_in(GIMarshallingTests.GEnum.VALUE3)
1904 GIMarshallingTests.genum_in(42)
1905 GIMarshallingTests.GEnum.in_(42)
1907 self.assertRaises(TypeError, GIMarshallingTests.genum_in, 43)
1908 self.assertRaises(TypeError, GIMarshallingTests.genum_in, 'GIMarshallingTests.GEnum.VALUE3')
1910 def test_genum_return(self):
1911 genum = GIMarshallingTests.genum_returnv()
1912 self.assertTrue(isinstance(genum, GIMarshallingTests.GEnum))
1913 self.assertEqual(genum, GIMarshallingTests.GEnum.VALUE3)
1915 def test_genum_out(self):
1916 genum = GIMarshallingTests.genum_out()
1917 genum = GIMarshallingTests.GEnum.out()
1918 self.assertTrue(isinstance(genum, GIMarshallingTests.GEnum))
1919 self.assertEqual(genum, GIMarshallingTests.GEnum.VALUE3)
1921 def test_genum_inout(self):
1922 genum = GIMarshallingTests.genum_inout(GIMarshallingTests.GEnum.VALUE3)
1923 self.assertTrue(isinstance(genum, GIMarshallingTests.GEnum))
1924 self.assertEqual(genum, GIMarshallingTests.GEnum.VALUE1)
1926 def test_type_module_name(self):
1927 self.assertEqual(GIMarshallingTests.GEnum.__name__, "GEnum")
1928 self.assertEqual(GIMarshallingTests.GEnum.__module__,
1929 "gi.repository.GIMarshallingTests")
1931 def test_hash(self):
1932 assert (hash(GIMarshallingTests.GEnum.VALUE3) ==
1933 hash(GIMarshallingTests.GEnum(GIMarshallingTests.GEnum.VALUE3)))
1935 def test_repr(self):
1936 self.assertEqual(repr(GIMarshallingTests.GEnum.VALUE3),
1937 "<enum GI_MARSHALLING_TESTS_GENUM_VALUE3 of type "
1938 "GIMarshallingTests.GEnum>")
1941 class TestGFlags(unittest.TestCase):
1943 def test_flags(self):
1944 self.assertTrue(issubclass(GIMarshallingTests.Flags, GObject.GFlags))
1945 self.assertTrue(isinstance(GIMarshallingTests.Flags.VALUE1, GIMarshallingTests.Flags))
1946 self.assertTrue(isinstance(GIMarshallingTests.Flags.VALUE2, GIMarshallingTests.Flags))
1947 self.assertTrue(isinstance(GIMarshallingTests.Flags.VALUE3, GIMarshallingTests.Flags))
1948 # __or__() operation should still return an instance, not an int.
1949 self.assertTrue(isinstance(GIMarshallingTests.Flags.VALUE1 | GIMarshallingTests.Flags.VALUE2,
1950 GIMarshallingTests.Flags))
1951 self.assertEqual(1 << 1, GIMarshallingTests.Flags.VALUE2)
1953 def test_value_nick_and_name(self):
1954 self.assertEqual(GIMarshallingTests.Flags.VALUE1.first_value_nick, 'value1')
1955 self.assertEqual(GIMarshallingTests.Flags.VALUE2.first_value_nick, 'value2')
1956 self.assertEqual(GIMarshallingTests.Flags.VALUE3.first_value_nick, 'value3')
1958 self.assertEqual(GIMarshallingTests.Flags.VALUE1.first_value_name, 'GI_MARSHALLING_TESTS_FLAGS_VALUE1')
1959 self.assertEqual(GIMarshallingTests.Flags.VALUE2.first_value_name, 'GI_MARSHALLING_TESTS_FLAGS_VALUE2')
1960 self.assertEqual(GIMarshallingTests.Flags.VALUE3.first_value_name, 'GI_MARSHALLING_TESTS_FLAGS_VALUE3')
1962 def test_flags_in(self):
1963 GIMarshallingTests.flags_in(GIMarshallingTests.Flags.VALUE2)
1964 GIMarshallingTests.Flags.in_(GIMarshallingTests.Flags.VALUE2)
1965 # result of __or__() operation should still be valid instance, not an int.
1966 GIMarshallingTests.flags_in(GIMarshallingTests.Flags.VALUE2 | GIMarshallingTests.Flags.VALUE2)
1967 GIMarshallingTests.flags_in_zero(Number(0))
1968 GIMarshallingTests.Flags.in_zero(Number(0))
1970 self.assertRaises(TypeError, GIMarshallingTests.flags_in, 1 << 1)
1971 self.assertRaises(TypeError, GIMarshallingTests.flags_in, 'GIMarshallingTests.Flags.VALUE2')
1973 def test_flags_return(self):
1974 flags = GIMarshallingTests.flags_returnv()
1975 self.assertTrue(isinstance(flags, GIMarshallingTests.Flags))
1976 self.assertEqual(flags, GIMarshallingTests.Flags.VALUE2)
1978 def test_flags_return_method(self):
1979 flags = GIMarshallingTests.Flags.returnv()
1980 self.assertTrue(isinstance(flags, GIMarshallingTests.Flags))
1981 self.assertEqual(flags, GIMarshallingTests.Flags.VALUE2)
1983 def test_flags_out(self):
1984 flags = GIMarshallingTests.flags_out()
1985 self.assertTrue(isinstance(flags, GIMarshallingTests.Flags))
1986 self.assertEqual(flags, GIMarshallingTests.Flags.VALUE2)
1988 def test_flags_inout(self):
1989 flags = GIMarshallingTests.flags_inout(GIMarshallingTests.Flags.VALUE2)
1990 self.assertTrue(isinstance(flags, GIMarshallingTests.Flags))
1991 self.assertEqual(flags, GIMarshallingTests.Flags.VALUE1)
1993 def test_type_module_name(self):
1994 self.assertEqual(GIMarshallingTests.Flags.__name__, "Flags")
1995 self.assertEqual(GIMarshallingTests.Flags.__module__,
1996 "gi.repository.GIMarshallingTests")
1998 def test_repr(self):
1999 self.assertEqual(repr(GIMarshallingTests.Flags.VALUE2),
2000 "<flags GI_MARSHALLING_TESTS_FLAGS_VALUE2 of type "
2001 "GIMarshallingTests.Flags>")
2003 def test_hash(self):
2004 assert (hash(GIMarshallingTests.Flags.VALUE2) ==
2005 hash(GIMarshallingTests.Flags(GIMarshallingTests.Flags.VALUE2)))
2007 def test_flags_large_in(self):
2008 GIMarshallingTests.extra_flags_large_in(
2009 GIMarshallingTests.ExtraFlags.VALUE2)
2012 class TestNoTypeFlags(unittest.TestCase):
2014 def test_flags(self):
2015 self.assertTrue(issubclass(GIMarshallingTests.NoTypeFlags, GObject.GFlags))
2016 self.assertTrue(isinstance(GIMarshallingTests.NoTypeFlags.VALUE1, GIMarshallingTests.NoTypeFlags))
2017 self.assertTrue(isinstance(GIMarshallingTests.NoTypeFlags.VALUE2, GIMarshallingTests.NoTypeFlags))
2018 self.assertTrue(isinstance(GIMarshallingTests.NoTypeFlags.VALUE3, GIMarshallingTests.NoTypeFlags))
2019 # __or__() operation should still return an instance, not an int.
2020 self.assertTrue(isinstance(GIMarshallingTests.NoTypeFlags.VALUE1 | GIMarshallingTests.NoTypeFlags.VALUE2,
2021 GIMarshallingTests.NoTypeFlags))
2022 self.assertEqual(1 << 1, GIMarshallingTests.NoTypeFlags.VALUE2)
2024 def test_value_nick_and_name(self):
2025 self.assertEqual(GIMarshallingTests.NoTypeFlags.VALUE1.first_value_nick, 'value1')
2026 self.assertEqual(GIMarshallingTests.NoTypeFlags.VALUE2.first_value_nick, 'value2')
2027 self.assertEqual(GIMarshallingTests.NoTypeFlags.VALUE3.first_value_nick, 'value3')
2029 self.assertEqual(GIMarshallingTests.NoTypeFlags.VALUE1.first_value_name, 'GI_MARSHALLING_TESTS_NO_TYPE_FLAGS_VALUE1')
2030 self.assertEqual(GIMarshallingTests.NoTypeFlags.VALUE2.first_value_name, 'GI_MARSHALLING_TESTS_NO_TYPE_FLAGS_VALUE2')
2031 self.assertEqual(GIMarshallingTests.NoTypeFlags.VALUE3.first_value_name, 'GI_MARSHALLING_TESTS_NO_TYPE_FLAGS_VALUE3')
2033 def test_flags_in(self):
2034 GIMarshallingTests.no_type_flags_in(GIMarshallingTests.NoTypeFlags.VALUE2)
2035 GIMarshallingTests.no_type_flags_in(GIMarshallingTests.NoTypeFlags.VALUE2 | GIMarshallingTests.NoTypeFlags.VALUE2)
2036 GIMarshallingTests.no_type_flags_in_zero(Number(0))
2038 self.assertRaises(TypeError, GIMarshallingTests.no_type_flags_in, 1 << 1)
2039 self.assertRaises(TypeError, GIMarshallingTests.no_type_flags_in, 'GIMarshallingTests.NoTypeFlags.VALUE2')
2041 def test_flags_return(self):
2042 flags = GIMarshallingTests.no_type_flags_returnv()
2043 self.assertTrue(isinstance(flags, GIMarshallingTests.NoTypeFlags))
2044 self.assertEqual(flags, GIMarshallingTests.NoTypeFlags.VALUE2)
2046 def test_flags_out(self):
2047 flags = GIMarshallingTests.no_type_flags_out()
2048 self.assertTrue(isinstance(flags, GIMarshallingTests.NoTypeFlags))
2049 self.assertEqual(flags, GIMarshallingTests.NoTypeFlags.VALUE2)
2051 def test_flags_inout(self):
2052 flags = GIMarshallingTests.no_type_flags_inout(GIMarshallingTests.NoTypeFlags.VALUE2)
2053 self.assertTrue(isinstance(flags, GIMarshallingTests.NoTypeFlags))
2054 self.assertEqual(flags, GIMarshallingTests.NoTypeFlags.VALUE1)
2056 def test_flags_gtype_name_is_namespaced(self):
2057 self.assertEqual(GIMarshallingTests.NoTypeFlags.__gtype__.name,
2058 'PyGIMarshallingTestsNoTypeFlags')
2060 def test_type_module_name(self):
2061 self.assertEqual(GIMarshallingTests.NoTypeFlags.__name__,
2062 "NoTypeFlags")
2063 self.assertEqual(GIMarshallingTests.NoTypeFlags.__module__,
2064 "gi.repository.GIMarshallingTests")
2066 def test_repr(self):
2067 self.assertEqual(repr(GIMarshallingTests.NoTypeFlags.VALUE2),
2068 "<flags GI_MARSHALLING_TESTS_NO_TYPE_FLAGS_VALUE2 of "
2069 "type GIMarshallingTests.NoTypeFlags>")
2072 class TestStructure(unittest.TestCase):
2074 def test_simple_struct(self):
2075 self.assertTrue(issubclass(GIMarshallingTests.SimpleStruct, GObject.GPointer))
2077 struct = GIMarshallingTests.SimpleStruct()
2078 self.assertTrue(isinstance(struct, GIMarshallingTests.SimpleStruct))
2080 self.assertEqual(0, struct.long_)
2081 self.assertEqual(0, struct.int8)
2083 struct.long_ = 6
2084 struct.int8 = 7
2086 self.assertEqual(6, struct.long_)
2087 self.assertEqual(7, struct.int8)
2089 del struct
2091 def test_nested_struct(self):
2092 struct = GIMarshallingTests.NestedStruct()
2094 self.assertTrue(isinstance(struct.simple_struct, GIMarshallingTests.SimpleStruct))
2096 struct.simple_struct.long_ = 42
2097 self.assertEqual(42, struct.simple_struct.long_)
2099 del struct
2101 def test_not_simple_struct(self):
2102 struct = GIMarshallingTests.NotSimpleStruct()
2103 self.assertEqual(None, struct.pointer)
2105 def test_simple_struct_return(self):
2106 struct = GIMarshallingTests.simple_struct_returnv()
2108 self.assertTrue(isinstance(struct, GIMarshallingTests.SimpleStruct))
2109 self.assertEqual(6, struct.long_)
2110 self.assertEqual(7, struct.int8)
2112 del struct
2114 def test_simple_struct_in(self):
2115 struct = GIMarshallingTests.SimpleStruct()
2116 struct.long_ = 6
2117 struct.int8 = 7
2119 GIMarshallingTests.SimpleStruct.inv(struct)
2121 del struct
2123 struct = GIMarshallingTests.NestedStruct()
2125 self.assertRaises(TypeError, GIMarshallingTests.SimpleStruct.inv, struct)
2127 del struct
2129 self.assertRaises(TypeError, GIMarshallingTests.SimpleStruct.inv, None)
2131 def test_simple_struct_method(self):
2132 struct = GIMarshallingTests.SimpleStruct()
2133 struct.long_ = 6
2134 struct.int8 = 7
2136 struct.method()
2138 del struct
2140 self.assertRaises(TypeError, GIMarshallingTests.SimpleStruct.method)
2142 def test_pointer_struct(self):
2143 self.assertTrue(issubclass(GIMarshallingTests.PointerStruct, GObject.GPointer))
2145 struct = GIMarshallingTests.PointerStruct()
2146 self.assertTrue(isinstance(struct, GIMarshallingTests.PointerStruct))
2148 del struct
2150 def test_pointer_struct_return(self):
2151 struct = GIMarshallingTests.pointer_struct_returnv()
2153 self.assertTrue(isinstance(struct, GIMarshallingTests.PointerStruct))
2154 self.assertEqual(42, struct.long_)
2156 del struct
2158 def test_pointer_struct_in(self):
2159 struct = GIMarshallingTests.PointerStruct()
2160 struct.long_ = 42
2162 struct.inv()
2164 del struct
2166 def test_boxed_struct(self):
2167 self.assertTrue(issubclass(GIMarshallingTests.BoxedStruct, GObject.GBoxed))
2169 struct = GIMarshallingTests.BoxedStruct()
2170 self.assertTrue(isinstance(struct, GIMarshallingTests.BoxedStruct))
2172 self.assertEqual(0, struct.long_)
2173 self.assertEqual(None, struct.string_)
2174 self.assertEqual([], struct.g_strv)
2176 del struct
2178 def test_boxed_struct_new(self):
2179 struct = GIMarshallingTests.BoxedStruct.new()
2180 self.assertTrue(isinstance(struct, GIMarshallingTests.BoxedStruct))
2181 self.assertEqual(struct.long_, 0)
2182 self.assertEqual(struct.string_, None)
2184 del struct
2186 def test_boxed_struct_copy(self):
2187 struct = GIMarshallingTests.BoxedStruct()
2188 struct.long_ = 42
2189 struct.string_ = 'hello'
2191 new_struct = struct.copy()
2192 self.assertTrue(isinstance(new_struct, GIMarshallingTests.BoxedStruct))
2193 self.assertEqual(new_struct.long_, 42)
2194 self.assertEqual(new_struct.string_, 'hello')
2196 del new_struct
2197 del struct
2199 def test_boxed_struct_return(self):
2200 struct = GIMarshallingTests.boxed_struct_returnv()
2202 self.assertTrue(isinstance(struct, GIMarshallingTests.BoxedStruct))
2203 self.assertEqual(42, struct.long_)
2204 self.assertEqual('hello', struct.string_)
2205 self.assertEqual(['0', '1', '2'], struct.g_strv)
2207 del struct
2209 def test_boxed_struct_in(self):
2210 struct = GIMarshallingTests.BoxedStruct()
2211 struct.long_ = 42
2213 struct.inv()
2215 del struct
2217 def test_boxed_struct_out(self):
2218 struct = GIMarshallingTests.boxed_struct_out()
2220 self.assertTrue(isinstance(struct, GIMarshallingTests.BoxedStruct))
2221 self.assertEqual(42, struct.long_)
2223 del struct
2225 def test_boxed_struct_inout(self):
2226 in_struct = GIMarshallingTests.BoxedStruct()
2227 in_struct.long_ = 42
2229 out_struct = GIMarshallingTests.boxed_struct_inout(in_struct)
2231 self.assertTrue(isinstance(out_struct, GIMarshallingTests.BoxedStruct))
2232 self.assertEqual(0, out_struct.long_)
2234 del in_struct
2235 del out_struct
2237 def test_struct_field_assignment(self):
2238 struct = GIMarshallingTests.BoxedStruct()
2240 struct.long_ = 42
2241 struct.string_ = 'hello'
2242 self.assertEqual(struct.long_, 42)
2243 self.assertEqual(struct.string_, 'hello')
2245 def test_union_init(self):
2246 with warnings.catch_warnings(record=True) as warn:
2247 warnings.simplefilter('always')
2248 GIMarshallingTests.Union(42)
2250 self.assertTrue(issubclass(warn[0].category, DeprecationWarning))
2252 with warnings.catch_warnings(record=True) as warn:
2253 warnings.simplefilter('always')
2254 GIMarshallingTests.Union(f=42)
2256 self.assertTrue(issubclass(warn[0].category, DeprecationWarning))
2258 def test_union(self):
2259 union = GIMarshallingTests.Union()
2261 self.assertTrue(isinstance(union, GIMarshallingTests.Union))
2263 new_union = union.copy()
2264 self.assertTrue(isinstance(new_union, GIMarshallingTests.Union))
2266 del union
2267 del new_union
2269 def test_union_return(self):
2270 union = GIMarshallingTests.union_returnv()
2272 self.assertTrue(isinstance(union, GIMarshallingTests.Union))
2273 self.assertEqual(42, union.long_)
2275 del union
2277 def test_union_in(self):
2278 union = GIMarshallingTests.Union()
2279 union.long_ = 42
2281 union.inv()
2283 del union
2285 def test_union_method(self):
2286 union = GIMarshallingTests.Union()
2287 union.long_ = 42
2289 union.method()
2291 del union
2293 self.assertRaises(TypeError, GIMarshallingTests.Union.method)
2295 def test_repr(self):
2296 self.assertRegexpMatches(
2297 repr(GIMarshallingTests.PointerStruct()),
2298 r"<GIMarshallingTests.PointerStruct object at 0x[^\s]+ "
2299 r"\(void at 0x[^\s]+\)>")
2301 self.assertRegexpMatches(
2302 repr(GIMarshallingTests.SimpleStruct()),
2303 r"<GIMarshallingTests.SimpleStruct object at 0x[^\s]+ "
2304 r"\(void at 0x[^\s]+\)>")
2306 self.assertRegexpMatches(
2307 repr(GIMarshallingTests.Union()),
2308 r"<GIMarshallingTests.Union object at 0x[^\s]+ "
2309 r"\(GIMarshallingTestsUnion at 0x[^\s]+\)>")
2311 self.assertRegexpMatches(
2312 repr(GIMarshallingTests.BoxedStruct()),
2313 r"<GIMarshallingTests.BoxedStruct object at 0x[^\s]+ "
2314 r"\(GIMarshallingTestsBoxedStruct at 0x[^\s]+\)>")
2317 class TestGObject(unittest.TestCase):
2319 def test_object(self):
2320 self.assertTrue(issubclass(GIMarshallingTests.Object, GObject.GObject))
2322 object_ = GIMarshallingTests.Object()
2323 self.assertTrue(isinstance(object_, GIMarshallingTests.Object))
2324 self.assertEqual(object_.__grefcount__, 1)
2326 def test_object_new(self):
2327 object_ = GIMarshallingTests.Object.new(42)
2328 self.assertTrue(isinstance(object_, GIMarshallingTests.Object))
2329 self.assertEqual(object_.__grefcount__, 1)
2331 def test_object_int(self):
2332 object_ = GIMarshallingTests.Object(int=42)
2333 self.assertEqual(object_.int_, 42)
2334 # FIXME: Don't work yet.
2335 # object_.int_ = 0
2336 # self.assertEqual(object_.int_, 0)
2338 def test_object_static_method(self):
2339 GIMarshallingTests.Object.static_method()
2341 def test_object_method(self):
2342 GIMarshallingTests.Object(int=42).method()
2343 self.assertRaises(TypeError, GIMarshallingTests.Object.method, GObject.GObject())
2344 self.assertRaises(TypeError, GIMarshallingTests.Object.method)
2346 def test_sub_object(self):
2347 self.assertTrue(issubclass(GIMarshallingTests.SubObject, GIMarshallingTests.Object))
2349 object_ = GIMarshallingTests.SubObject()
2350 self.assertTrue(isinstance(object_, GIMarshallingTests.SubObject))
2352 def test_sub_object_new(self):
2353 self.assertRaises(TypeError, GIMarshallingTests.SubObject.new, 42)
2355 def test_sub_object_static_method(self):
2356 object_ = GIMarshallingTests.SubObject()
2357 object_.static_method()
2359 def test_sub_object_method(self):
2360 object_ = GIMarshallingTests.SubObject(int=42)
2361 object_.method()
2363 def test_sub_object_sub_method(self):
2364 object_ = GIMarshallingTests.SubObject()
2365 object_.sub_method()
2367 def test_sub_object_overwritten_method(self):
2368 object_ = GIMarshallingTests.SubObject()
2369 object_.overwritten_method()
2371 self.assertRaises(TypeError, GIMarshallingTests.SubObject.overwritten_method, GIMarshallingTests.Object())
2373 def test_sub_object_int(self):
2374 object_ = GIMarshallingTests.SubObject()
2375 self.assertEqual(object_.int_, 0)
2376 # FIXME: Don't work yet.
2377 # object_.int_ = 42
2378 # self.assertEqual(object_.int_, 42)
2380 def test_object_none_return(self):
2381 object_ = GIMarshallingTests.Object.none_return()
2382 self.assertTrue(isinstance(object_, GIMarshallingTests.Object))
2383 self.assertEqual(object_.__grefcount__, 2)
2385 def test_object_full_return(self):
2386 object_ = GIMarshallingTests.Object.full_return()
2387 self.assertTrue(isinstance(object_, GIMarshallingTests.Object))
2388 self.assertEqual(object_.__grefcount__, 1)
2390 def test_object_none_in(self):
2391 object_ = GIMarshallingTests.Object(int=42)
2392 GIMarshallingTests.Object.none_in(object_)
2393 self.assertEqual(object_.__grefcount__, 1)
2395 object_ = GIMarshallingTests.SubObject(int=42)
2396 GIMarshallingTests.Object.none_in(object_)
2398 object_ = GObject.GObject()
2399 self.assertRaises(TypeError, GIMarshallingTests.Object.none_in, object_)
2401 self.assertRaises(TypeError, GIMarshallingTests.Object.none_in, None)
2403 def test_object_none_out(self):
2404 object_ = GIMarshallingTests.Object.none_out()
2405 self.assertTrue(isinstance(object_, GIMarshallingTests.Object))
2406 self.assertEqual(object_.__grefcount__, 2)
2408 new_object = GIMarshallingTests.Object.none_out()
2409 self.assertTrue(new_object is object_)
2411 def test_object_full_out(self):
2412 object_ = GIMarshallingTests.Object.full_out()
2413 self.assertTrue(isinstance(object_, GIMarshallingTests.Object))
2414 self.assertEqual(object_.__grefcount__, 1)
2416 def test_object_none_inout(self):
2417 object_ = GIMarshallingTests.Object(int=42)
2418 new_object = GIMarshallingTests.Object.none_inout(object_)
2420 self.assertTrue(isinstance(new_object, GIMarshallingTests.Object))
2422 self.assertFalse(object_ is new_object)
2424 self.assertEqual(object_.__grefcount__, 1)
2425 self.assertEqual(new_object.__grefcount__, 2)
2427 new_new_object = GIMarshallingTests.Object.none_inout(object_)
2428 self.assertTrue(new_new_object is new_object)
2430 GIMarshallingTests.Object.none_inout(GIMarshallingTests.SubObject(int=42))
2432 def test_object_full_inout(self):
2433 # Using gimarshallingtests.c from GI versions > 1.38.0 will show this
2434 # test as an "unexpected success" due to reference leak fixes in that file.
2435 # TODO: remove the expectedFailure once PyGI relies on GI > 1.38.0.
2436 object_ = GIMarshallingTests.Object(int=42)
2437 new_object = GIMarshallingTests.Object.full_inout(object_)
2439 self.assertTrue(isinstance(new_object, GIMarshallingTests.Object))
2441 self.assertFalse(object_ is new_object)
2443 self.assertEqual(object_.__grefcount__, 1)
2444 self.assertEqual(new_object.__grefcount__, 1)
2446 def test_repr(self):
2447 self.assertRegexpMatches(
2448 repr(GIMarshallingTests.Object(int=42)),
2449 r"<GIMarshallingTests.Object object at 0x[^\s]+ "
2450 r"\(GIMarshallingTestsObject at 0x[^\s]+\)>")
2452 def test_nongir_repr(self):
2453 self.assertRegexpMatches(
2454 repr(Gio.File.new_for_path("")),
2455 r"<__gi__.GLocalFile object at 0x[^\s]+ "
2456 r"\(GLocalFile at 0x[^\s]+\)>")
2458 # FIXME: Doesn't actually return the same object.
2459 # def test_object_inout_same(self):
2460 # object_ = GIMarshallingTests.Object()
2461 # new_object = GIMarshallingTests.object_full_inout(object_)
2462 # self.assertTrue(object_ is new_object)
2463 # self.assertEqual(object_.__grefcount__, 1)
2466 class TestPythonGObject(unittest.TestCase):
2468 class Object(GIMarshallingTests.Object):
2469 return_for_caller_allocated_out_parameter = 'test caller alloc return'
2471 def __init__(self, int):
2472 GIMarshallingTests.Object.__init__(self)
2473 self.val = None
2475 def method(self):
2476 # Don't call super, which asserts that self.int == 42.
2477 pass
2479 def do_method_int8_in(self, int8):
2480 self.val = int8
2482 def do_method_int8_out(self):
2483 return 42
2485 def do_method_int8_arg_and_out_caller(self, arg):
2486 return arg + 1
2488 def do_method_int8_arg_and_out_callee(self, arg):
2489 return arg + 1
2491 def do_method_str_arg_out_ret(self, arg):
2492 return (arg.upper(), len(arg))
2494 def do_method_with_default_implementation(self, int8):
2495 GIMarshallingTests.Object.do_method_with_default_implementation(self, int8)
2496 self.props.int += int8
2498 def do_vfunc_return_value_only(self):
2499 return 4242
2501 def do_vfunc_one_out_parameter(self):
2502 return 42.42
2504 def do_vfunc_multiple_out_parameters(self):
2505 return (42.42, 3.14)
2507 def do_vfunc_return_value_and_one_out_parameter(self):
2508 return (5, 42)
2510 def do_vfunc_return_value_and_multiple_out_parameters(self):
2511 return (5, 42, 99)
2513 def do_vfunc_caller_allocated_out_parameter(self):
2514 return self.return_for_caller_allocated_out_parameter
2516 class SubObject(GIMarshallingTests.SubObject):
2517 def __init__(self, int):
2518 GIMarshallingTests.SubObject.__init__(self)
2519 self.val = None
2521 def do_method_with_default_implementation(self, int8):
2522 self.val = int8
2524 def do_vfunc_return_value_only(self):
2525 return 2121
2527 class Interface3Impl(GObject.Object, GIMarshallingTests.Interface3):
2528 def __init__(self):
2529 GObject.Object.__init__(self)
2530 self.variants = None
2531 self.n_variants = None
2533 def do_test_variant_array_in(self, variants, n_variants):
2534 self.variants = variants
2535 self.n_variants = n_variants
2537 class ErrorObject(GIMarshallingTests.Object):
2538 def do_vfunc_return_value_only(self):
2539 raise ValueError('Return value should be 0')
2541 def test_object(self):
2542 self.assertTrue(issubclass(self.Object, GIMarshallingTests.Object))
2544 object_ = self.Object(int=42)
2545 self.assertTrue(isinstance(object_, self.Object))
2547 @unittest.skipUnless(hasattr(GIMarshallingTests.Object, 'new_fail'),
2548 'Requires newer version of GI')
2549 def test_object_fail(self):
2550 with self.assertRaises(GLib.Error):
2551 GIMarshallingTests.Object.new_fail(int_=42)
2553 def test_object_method(self):
2554 self.Object(int=0).method()
2556 def test_object_vfuncs(self):
2557 object_ = self.Object(int=42)
2558 object_.method_int8_in(84)
2559 self.assertEqual(object_.val, 84)
2560 self.assertEqual(object_.method_int8_out(), 42)
2562 # can be dropped when bumping g-i dependencies to >= 1.35.2
2563 if hasattr(object_, 'method_int8_arg_and_out_caller'):
2564 self.assertEqual(object_.method_int8_arg_and_out_caller(42), 43)
2565 self.assertEqual(object_.method_int8_arg_and_out_callee(42), 43)
2566 self.assertEqual(object_.method_str_arg_out_ret('hello'), ('HELLO', 5))
2568 object_.method_with_default_implementation(42)
2569 self.assertEqual(object_.props.int, 84)
2571 self.assertEqual(object_.vfunc_return_value_only(), 4242)
2572 self.assertAlmostEqual(object_.vfunc_one_out_parameter(), 42.42, places=5)
2574 (a, b) = object_.vfunc_multiple_out_parameters()
2575 self.assertAlmostEqual(a, 42.42, places=5)
2576 self.assertAlmostEqual(b, 3.14, places=5)
2578 self.assertEqual(object_.vfunc_return_value_and_one_out_parameter(), (5, 42))
2579 self.assertEqual(object_.vfunc_return_value_and_multiple_out_parameters(), (5, 42, 99))
2581 self.assertEqual(object_.vfunc_caller_allocated_out_parameter(),
2582 object_.return_for_caller_allocated_out_parameter)
2584 class ObjectWithoutVFunc(GIMarshallingTests.Object):
2585 def __init__(self, int):
2586 GIMarshallingTests.Object.__init__(self)
2588 object_ = ObjectWithoutVFunc(int=42)
2589 object_.method_with_default_implementation(84)
2590 self.assertEqual(object_.props.int, 84)
2592 @unittest.skipUnless(hasattr(sys, "getrefcount"), "no sys.getrefcount")
2593 def test_vfunc_return_ref_count(self):
2594 obj = self.Object(int=42)
2595 ref_count = sys.getrefcount(obj.return_for_caller_allocated_out_parameter)
2596 ret = obj.vfunc_caller_allocated_out_parameter()
2597 gc.collect()
2599 # Make sure the return and what the vfunc returned
2600 # are equal but not the same object.
2601 self.assertEqual(ret, obj.return_for_caller_allocated_out_parameter)
2602 self.assertFalse(ret is obj.return_for_caller_allocated_out_parameter)
2603 self.assertEqual(sys.getrefcount(obj.return_for_caller_allocated_out_parameter),
2604 ref_count)
2606 def test_vfunc_return_no_ref_count(self):
2607 obj = self.Object(int=42)
2608 ret = obj.vfunc_caller_allocated_out_parameter()
2609 self.assertEqual(ret, obj.return_for_caller_allocated_out_parameter)
2610 self.assertFalse(ret is obj.return_for_caller_allocated_out_parameter)
2612 def test_subobject_parent_vfunc(self):
2613 object_ = self.SubObject(int=81)
2614 object_.method_with_default_implementation(87)
2615 self.assertEqual(object_.val, 87)
2617 def test_subobject_child_vfunc(self):
2618 object_ = self.SubObject(int=1)
2619 self.assertEqual(object_.vfunc_return_value_only(), 2121)
2621 def test_subobject_non_vfunc_do_method(self):
2622 class PythonObjectWithNonVFuncDoMethod(object):
2623 def do_not_a_vfunc(self):
2624 return 5
2626 class ObjectOverrideNonVFuncDoMethod(GIMarshallingTests.Object, PythonObjectWithNonVFuncDoMethod):
2627 def do_not_a_vfunc(self):
2628 value = super(ObjectOverrideNonVFuncDoMethod, self).do_not_a_vfunc()
2629 return 13 + value
2631 object_ = ObjectOverrideNonVFuncDoMethod()
2632 self.assertEqual(18, object_.do_not_a_vfunc())
2634 def test_native_function_not_set_in_subclass_dict(self):
2635 # Previously, GI was setting virtual functions on the class as well
2636 # as any *native* class that subclasses it. Here we check that it is only
2637 # set on the class that the method is originally from.
2638 self.assertTrue('do_method_with_default_implementation' in GIMarshallingTests.Object.__dict__)
2639 self.assertTrue('do_method_with_default_implementation' not in GIMarshallingTests.SubObject.__dict__)
2641 def test_subobject_with_interface_and_non_vfunc_do_method(self):
2642 # There was a bug for searching for vfuncs in interfaces. It was
2643 # triggered by having a do_* method that wasn't overriding
2644 # a native vfunc, as well as inheriting from an interface.
2645 class GObjectSubclassWithInterface(GObject.GObject, GIMarshallingTests.Interface):
2646 def do_method_not_a_vfunc(self):
2647 pass
2649 def test_subsubobject(self):
2650 class SubSubSubObject(GIMarshallingTests.SubSubObject):
2651 def do_method_deep_hierarchy(self, num):
2652 self.props.int = num * 2
2654 sub_sub_sub_object = SubSubSubObject()
2655 GIMarshallingTests.SubSubObject.do_method_deep_hierarchy(sub_sub_sub_object, 5)
2656 self.assertEqual(sub_sub_sub_object.props.int, 5)
2658 def test_interface3impl(self):
2659 iface3 = self.Interface3Impl()
2660 variants = [GLib.Variant('i', 27), GLib.Variant('s', 'Hello')]
2661 iface3.test_variant_array_in(variants)
2662 self.assertEqual(iface3.n_variants, 2)
2663 self.assertEqual(iface3.variants[0].unpack(), 27)
2664 self.assertEqual(iface3.variants[1].unpack(), 'Hello')
2666 def test_python_subsubobject_vfunc(self):
2667 class PySubObject(GIMarshallingTests.Object):
2668 def __init__(self):
2669 GIMarshallingTests.Object.__init__(self)
2670 self.sub_method_int8_called = 0
2672 def do_method_int8_in(self, int8):
2673 self.sub_method_int8_called += 1
2675 class PySubSubObject(PySubObject):
2676 def __init__(self):
2677 PySubObject.__init__(self)
2678 self.subsub_method_int8_called = 0
2680 def do_method_int8_in(self, int8):
2681 self.subsub_method_int8_called += 1
2683 so = PySubObject()
2684 so.method_int8_in(1)
2685 self.assertEqual(so.sub_method_int8_called, 1)
2687 # it should call the method on the SubSub object only
2688 sso = PySubSubObject()
2689 sso.method_int8_in(1)
2690 self.assertEqual(sso.subsub_method_int8_called, 1)
2691 self.assertEqual(sso.sub_method_int8_called, 0)
2693 def test_callback_in_vfunc(self):
2694 class SubObject(GIMarshallingTests.Object):
2695 def __init__(self):
2696 GObject.GObject.__init__(self)
2697 self.worked = False
2699 def do_vfunc_with_callback(self, callback):
2700 self.worked = callback(42) == 42
2702 _object = SubObject()
2703 _object.call_vfunc_with_callback()
2704 self.assertTrue(_object.worked)
2705 _object.worked = False
2706 _object.call_vfunc_with_callback()
2707 self.assertTrue(_object.worked)
2709 def test_exception_in_vfunc_return_value(self):
2710 obj = self.ErrorObject()
2711 with capture_exceptions() as exc:
2712 self.assertEqual(obj.vfunc_return_value_only(), 0)
2713 self.assertEqual(len(exc), 1)
2714 self.assertEqual(exc[0].type, ValueError)
2716 @unittest.skipUnless(hasattr(GIMarshallingTests, 'callback_owned_boxed'),
2717 'requires newer version of GI')
2718 def test_callback_owned_box(self):
2719 def callback(box, data):
2720 self.box = box
2722 def nop_callback(box, data):
2723 pass
2725 GIMarshallingTests.callback_owned_boxed(callback, None)
2726 GIMarshallingTests.callback_owned_boxed(nop_callback, None)
2727 self.assertEqual(self.box.long_, 1)
2730 class TestMultiOutputArgs(unittest.TestCase):
2732 def test_int_out_out(self):
2733 self.assertEqual((6, 7), GIMarshallingTests.int_out_out())
2735 def test_int_return_out(self):
2736 self.assertEqual((6, 7), GIMarshallingTests.int_return_out())
2739 # Interface
2741 class TestInterfaces(unittest.TestCase):
2743 class TestInterfaceImpl(GObject.GObject, GIMarshallingTests.Interface):
2744 def __init__(self):
2745 GObject.GObject.__init__(self)
2746 self.val = None
2748 def do_test_int8_in(self, int8):
2749 self.val = int8
2751 def setUp(self):
2752 self.instance = self.TestInterfaceImpl()
2754 def test_iface_impl(self):
2755 instance = GIMarshallingTests.InterfaceImpl()
2756 assert instance.get_as_interface() is instance
2757 instance.test_int8_in(42)
2759 def test_wrapper(self):
2760 self.assertTrue(issubclass(GIMarshallingTests.Interface, GObject.GInterface))
2761 self.assertEqual(GIMarshallingTests.Interface.__gtype__.name, 'GIMarshallingTestsInterface')
2762 self.assertRaises(NotImplementedError, GIMarshallingTests.Interface)
2764 def test_implementation(self):
2765 self.assertTrue(issubclass(self.TestInterfaceImpl, GIMarshallingTests.Interface))
2766 self.assertTrue(isinstance(self.instance, GIMarshallingTests.Interface))
2768 def test_int8_int(self):
2769 GIMarshallingTests.test_interface_test_int8_in(self.instance, 42)
2770 self.assertEqual(self.instance.val, 42)
2772 def test_subclass(self):
2773 class TestInterfaceImplA(self.TestInterfaceImpl):
2774 pass
2776 class TestInterfaceImplB(TestInterfaceImplA):
2777 pass
2779 instance = TestInterfaceImplA()
2780 GIMarshallingTests.test_interface_test_int8_in(instance, 42)
2781 self.assertEqual(instance.val, 42)
2783 def test_subclass_override(self):
2784 class TestInterfaceImplD(TestInterfaces.TestInterfaceImpl):
2785 val2 = None
2787 def do_test_int8_in(self, int8):
2788 self.val2 = int8
2790 instance = TestInterfaceImplD()
2791 self.assertEqual(instance.val, None)
2792 self.assertEqual(instance.val2, None)
2794 GIMarshallingTests.test_interface_test_int8_in(instance, 42)
2795 self.assertEqual(instance.val, None)
2796 self.assertEqual(instance.val2, 42)
2798 def test_type_mismatch(self):
2799 obj = GIMarshallingTests.Object()
2801 # wrong type for first argument: interface
2802 enum = Gio.File.new_for_path('.').enumerate_children(
2803 '', Gio.FileQueryInfoFlags.NONE, None)
2804 try:
2805 enum.next_file(obj)
2806 self.fail('call with wrong type argument unexpectedly succeeded')
2807 except TypeError as e:
2808 # should have argument name
2809 self.assertTrue('cancellable' in str(e), e)
2810 # should have expected type
2811 self.assertTrue('xpected Gio.Cancellable' in str(e), e)
2812 # should have actual type
2813 self.assertTrue('GIMarshallingTests.Object' in str(e), e)
2815 # wrong type for self argument: interface
2816 try:
2817 Gio.FileEnumerator.next_file(obj, None)
2818 self.fail('call with wrong type argument unexpectedly succeeded')
2819 except TypeError as e:
2820 # should have argument name
2821 self.assertTrue('self' in str(e), e)
2822 # should have expected type
2823 self.assertTrue('xpected Gio.FileEnumerator' in str(e), e)
2824 # should have actual type
2825 self.assertTrue('GIMarshallingTests.Object' in str(e), e)
2827 # wrong type for first argument: GObject
2828 var = GLib.Variant('s', 'mystring')
2829 action = Gio.SimpleAction.new('foo', var.get_type())
2830 try:
2831 action.activate(obj)
2832 self.fail('call with wrong type argument unexpectedly succeeded')
2833 except TypeError as e:
2834 # should have argument name
2835 self.assertTrue('parameter' in str(e), e)
2836 # should have expected type
2837 self.assertTrue('xpected GLib.Variant' in str(e), e)
2838 # should have actual type
2839 self.assertTrue('GIMarshallingTests.Object' in str(e), e)
2841 # wrong type for self argument: GObject
2842 try:
2843 Gio.SimpleAction.activate(obj, obj)
2844 self.fail('call with wrong type argument unexpectedly succeeded')
2845 except TypeError as e:
2846 # should have argument name
2847 self.assertTrue('self' in str(e), e)
2848 # should have expected type
2849 self.assertTrue('xpected Gio.Action' in str(e), e)
2850 # should have actual type
2851 self.assertTrue('GIMarshallingTests.Object' in str(e), e)
2854 class TestMRO(unittest.TestCase):
2855 def test_mro(self):
2856 # check that our own MRO calculation matches what we would expect
2857 # from Python's own C3 calculations
2858 class A(object):
2859 pass
2861 class B(A):
2862 pass
2864 class C(A):
2865 pass
2867 class D(B, C):
2868 pass
2870 class E(D, GIMarshallingTests.Object):
2871 pass
2873 expected = (E, D, B, C, A, GIMarshallingTests.Object,
2874 GObject.Object, GObject.Object.__base__, gi._gi.GObject,
2875 object)
2876 self.assertEqual(expected, E.__mro__)
2878 def test_interface_collision(self):
2879 # there was a problem with Python bailing out because of
2880 # http://en.wikipedia.org/wiki/Diamond_problem with interfaces,
2881 # which shouldn't really be a problem.
2883 class TestInterfaceImpl(GObject.GObject, GIMarshallingTests.Interface):
2884 pass
2886 class TestInterfaceImpl2(GIMarshallingTests.Interface,
2887 TestInterfaceImpl):
2888 pass
2890 class TestInterfaceImpl3(TestInterfaceImpl,
2891 GIMarshallingTests.Interface2):
2892 pass
2894 def test_old_style_mixin(self):
2895 # Note: Old style classes don't exist in Python 3
2896 class Mixin:
2897 pass
2899 with warnings.catch_warnings(record=True) as warn:
2900 warnings.simplefilter('always')
2902 # Dynamically create a new gi based class with an old
2903 # style mixin.
2904 type('GIWithOldStyleMixin', (GIMarshallingTests.Object, Mixin), {})
2906 if PY2:
2907 self.assertTrue(issubclass(warn[0].category, RuntimeWarning))
2908 else:
2909 self.assertEqual(len(warn), 0)
2912 class TestInterfaceClash(unittest.TestCase):
2914 def test_clash(self):
2915 def create_clash():
2916 class TestClash(GObject.GObject, GIMarshallingTests.Interface, GIMarshallingTests.Interface2):
2917 def do_test_int8_in(self, int8):
2918 pass
2919 TestClash()
2921 self.assertRaises(TypeError, create_clash)
2924 class TestOverrides(unittest.TestCase):
2926 def test_constant(self):
2927 self.assertEqual(GIMarshallingTests.OVERRIDES_CONSTANT, 7)
2929 def test_struct(self):
2930 # Test that the constructor has been overridden.
2931 struct = GIMarshallingTests.OverridesStruct(42)
2933 self.assertTrue(isinstance(struct, GIMarshallingTests.OverridesStruct))
2935 # Test that the method has been overridden.
2936 self.assertEqual(6, struct.method())
2938 del struct
2940 # Test that the overrides wrapper has been registered.
2941 struct = GIMarshallingTests.overrides_struct_returnv()
2943 self.assertTrue(isinstance(struct, GIMarshallingTests.OverridesStruct))
2945 del struct
2947 def test_object(self):
2948 # Test that the constructor has been overridden.
2949 object_ = GIMarshallingTests.OverridesObject(42)
2951 self.assertTrue(isinstance(object_, GIMarshallingTests.OverridesObject))
2953 # Test that the alternate constructor has been overridden.
2954 object_ = GIMarshallingTests.OverridesObject.new(42)
2956 self.assertTrue(isinstance(object_, GIMarshallingTests.OverridesObject))
2958 # Test that the method has been overridden.
2959 self.assertEqual(6, object_.method())
2961 # Test that the overrides wrapper has been registered.
2962 object_ = GIMarshallingTests.OverridesObject.returnv()
2964 self.assertTrue(isinstance(object_, GIMarshallingTests.OverridesObject))
2966 def test_module_name(self):
2967 # overridden types
2968 self.assertEqual(GIMarshallingTests.OverridesStruct.__module__, 'gi.overrides.GIMarshallingTests')
2969 self.assertEqual(GIMarshallingTests.OverridesObject.__module__, 'gi.overrides.GIMarshallingTests')
2970 self.assertEqual(GObject.Object.__module__, 'gi.overrides.GObject')
2972 # not overridden
2973 self.assertEqual(GIMarshallingTests.SubObject.__module__, 'gi.repository.GIMarshallingTests')
2974 self.assertEqual(GObject.InitiallyUnowned.__module__, 'gi.repository.GObject')
2977 class TestDir(unittest.TestCase):
2978 def test_members_list(self):
2979 list = dir(GIMarshallingTests)
2980 self.assertTrue('OverridesStruct' in list)
2981 self.assertTrue('BoxedStruct' in list)
2982 self.assertTrue('OVERRIDES_CONSTANT' in list)
2983 self.assertTrue('GEnum' in list)
2984 self.assertTrue('int32_return_max' in list)
2986 def test_modules_list(self):
2987 import gi.repository
2988 list = dir(gi.repository)
2989 self.assertTrue('GIMarshallingTests' in list)
2991 # FIXME: test to see if a module which was not imported is in the list
2992 # we should be listing every typelib we find, not just the ones
2993 # which are imported
2995 # to test this I recommend we compile a fake module which
2996 # our tests would never import and check to see if it is
2997 # in the list:
2999 # self.assertTrue('DoNotImportDummyTests' in list)
3002 class TestParamSpec(unittest.TestCase):
3003 # https://bugzilla.gnome.org/show_bug.cgi?id=682355
3004 @unittest.expectedFailure
3005 def test_param_spec_in_bool(self):
3006 ps = GObject.param_spec_boolean('mybool', 'test-bool', 'boolblurb',
3007 True, GObject.ParamFlags.READABLE)
3008 GIMarshallingTests.param_spec_in_bool(ps)
3010 def test_param_spec_return(self):
3011 obj = GIMarshallingTests.param_spec_return()
3012 self.assertEqual(obj.name, 'test-param')
3013 self.assertEqual(obj.nick, 'test')
3014 self.assertEqual(obj.value_type, GObject.TYPE_STRING)
3016 def test_param_spec_out(self):
3017 obj = GIMarshallingTests.param_spec_out()
3018 self.assertEqual(obj.name, 'test-param')
3019 self.assertEqual(obj.nick, 'test')
3020 self.assertEqual(obj.value_type, GObject.TYPE_STRING)
3023 class TestKeywordArgs(unittest.TestCase):
3025 def test_calling(self):
3026 kw_func = GIMarshallingTests.int_three_in_three_out
3028 self.assertEqual(kw_func(1, 2, 3), (1, 2, 3))
3029 self.assertEqual(kw_func(**{'a': 4, 'b': 5, 'c': 6}), (4, 5, 6))
3030 self.assertEqual(kw_func(1, **{'b': 7, 'c': 8}), (1, 7, 8))
3031 self.assertEqual(kw_func(1, 7, **{'c': 8}), (1, 7, 8))
3032 self.assertEqual(kw_func(1, c=8, **{'b': 7}), (1, 7, 8))
3033 self.assertEqual(kw_func(2, c=4, b=3), (2, 3, 4))
3034 self.assertEqual(kw_func(a=2, c=4, b=3), (2, 3, 4))
3036 def assertRaisesMessage(self, exception, message, func, *args, **kwargs):
3037 try:
3038 func(*args, **kwargs)
3039 except exception:
3040 (e_type, e) = sys.exc_info()[:2]
3041 if message is not None:
3042 self.assertEqual(str(e), message)
3043 except:
3044 raise
3045 else:
3046 msg = "%s() did not raise %s" % (func.__name__, exception.__name__)
3047 raise AssertionError(msg)
3049 def test_type_errors(self):
3050 # test too few args
3051 self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() takes exactly 3 arguments (0 given)",
3052 GIMarshallingTests.int_three_in_three_out)
3053 self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() takes exactly 3 arguments (1 given)",
3054 GIMarshallingTests.int_three_in_three_out, 1)
3055 self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() takes exactly 3 arguments (0 given)",
3056 GIMarshallingTests.int_three_in_three_out, *())
3057 self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() takes exactly 3 arguments (0 given)",
3058 GIMarshallingTests.int_three_in_three_out, *(), **{})
3059 self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() takes exactly 3 non-keyword arguments (0 given)",
3060 GIMarshallingTests.int_three_in_three_out, *(), **{'c': 4})
3062 # test too many args
3063 self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() takes exactly 3 arguments (4 given)",
3064 GIMarshallingTests.int_three_in_three_out, *(1, 2, 3, 4))
3065 self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() takes exactly 3 non-keyword arguments (4 given)",
3066 GIMarshallingTests.int_three_in_three_out, *(1, 2, 3, 4), c=6)
3068 # test too many keyword args
3069 self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() got multiple values for keyword argument 'a'",
3070 GIMarshallingTests.int_three_in_three_out, 1, 2, 3, **{'a': 4, 'b': 5})
3071 self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() got an unexpected keyword argument 'd'",
3072 GIMarshallingTests.int_three_in_three_out, d=4)
3073 self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() got an unexpected keyword argument 'e'",
3074 GIMarshallingTests.int_three_in_three_out, **{'e': 2})
3076 def test_kwargs_are_not_modified(self):
3077 d = {'b': 2}
3078 d2 = d.copy()
3079 GIMarshallingTests.int_three_in_three_out(1, c=4, **d)
3080 self.assertEqual(d, d2)
3082 @unittest.skipUnless(hasattr(GIMarshallingTests, 'int_one_in_utf8_two_in_one_allows_none'),
3083 'Requires newer GIMarshallingTests')
3084 def test_allow_none_as_default(self):
3085 GIMarshallingTests.int_two_in_utf8_two_in_with_allow_none(1, 2, '3', '4')
3086 GIMarshallingTests.int_two_in_utf8_two_in_with_allow_none(1, 2, '3')
3087 GIMarshallingTests.int_two_in_utf8_two_in_with_allow_none(1, 2)
3088 GIMarshallingTests.int_two_in_utf8_two_in_with_allow_none(1, 2, d='4')
3090 GIMarshallingTests.array_in_utf8_two_in_out_of_order('1', [-1, 0, 1, 2])
3091 GIMarshallingTests.array_in_utf8_two_in_out_of_order('1', [-1, 0, 1, 2], '2')
3092 self.assertRaises(TypeError,
3093 GIMarshallingTests.array_in_utf8_two_in_out_of_order,
3094 [-1, 0, 1, 2], a='1')
3095 self.assertRaises(TypeError,
3096 GIMarshallingTests.array_in_utf8_two_in_out_of_order,
3097 [-1, 0, 1, 2])
3099 GIMarshallingTests.array_in_utf8_two_in([-1, 0, 1, 2], '1', '2')
3100 GIMarshallingTests.array_in_utf8_two_in([-1, 0, 1, 2], '1')
3101 GIMarshallingTests.array_in_utf8_two_in([-1, 0, 1, 2])
3102 GIMarshallingTests.array_in_utf8_two_in([-1, 0, 1, 2], b='2')
3104 GIMarshallingTests.int_one_in_utf8_two_in_one_allows_none(1, '2', '3')
3105 self.assertRaises(TypeError,
3106 GIMarshallingTests.int_one_in_utf8_two_in_one_allows_none,
3107 1, '3')
3108 self.assertRaises(TypeError,
3109 GIMarshallingTests.int_one_in_utf8_two_in_one_allows_none,
3110 1, c='3')
3113 class TestKeywords(unittest.TestCase):
3114 def test_method(self):
3115 # g_variant_print()
3116 v = GLib.Variant('i', 1)
3117 self.assertEqual(v.print_(False), '1')
3119 def test_function(self):
3120 # g_thread_yield()
3121 self.assertEqual(GLib.Thread.yield_(), None)
3123 def test_struct_method(self):
3124 # g_timer_continue()
3125 # we cannot currently instantiate GLib.Timer objects, so just ensure
3126 # the method exists
3127 self.assertTrue(callable(GLib.Timer.continue_))
3129 def test_uppercase(self):
3130 self.assertEqual(GLib.IOCondition.IN.value_nicks, ['in'])
3133 class TestModule(unittest.TestCase):
3134 def test_path(self):
3135 path = GIMarshallingTests.__path__
3136 assert isinstance(path, list)
3137 assert len(path) == 1
3138 assert path[0].endswith('GIMarshallingTests-1.0.typelib')
3140 def test_str(self):
3141 self.assertTrue("'GIMarshallingTests' from '" in str(GIMarshallingTests),
3142 str(GIMarshallingTests))
3144 def test_dir(self):
3145 _dir = dir(GIMarshallingTests)
3146 self.assertGreater(len(_dir), 10)
3148 self.assertTrue('SimpleStruct' in _dir)
3149 self.assertTrue('Interface2' in _dir)
3150 self.assertTrue('CONSTANT_GERROR_CODE' in _dir)
3151 self.assertTrue('array_zero_terminated_inout' in _dir)
3153 # assert that dir() does not contain garbage
3154 for item_name in _dir:
3155 item = getattr(GIMarshallingTests, item_name)
3156 self.assertTrue(hasattr(item, '__class__'))
3158 def test_help(self):
3159 with capture_output() as (stdout, stderr):
3160 help(GIMarshallingTests)
3161 output = stdout.getvalue()
3163 self.assertTrue('SimpleStruct' in output, output)
3164 self.assertTrue('Interface2' in output, output)
3165 self.assertTrue('method_array_inout' in output, output)
3168 class TestProjectVersion(unittest.TestCase):
3169 def test_version_str(self):
3170 self.assertGreater(gi.__version__, "3.")
3172 def test_version_info(self):
3173 self.assertEqual(len(gi.version_info), 3)
3174 self.assertGreaterEqual(gi.version_info, (3, 3, 5))
3176 def test_check_version(self):
3177 self.assertRaises(ValueError, gi.check_version, (99, 0, 0))
3178 self.assertRaises(ValueError, gi.check_version, "99.0.0")
3179 gi.check_version((3, 3, 5))
3180 gi.check_version("3.3.5")
3183 class TestGIWarning(unittest.TestCase):
3185 def test_warning(self):
3186 ignored_by_default = (DeprecationWarning, PendingDeprecationWarning,
3187 ImportWarning)
3189 with warnings.catch_warnings(record=True) as warn:
3190 warnings.simplefilter('always')
3191 warnings.warn("test", PyGIWarning)
3192 self.assertTrue(issubclass(warn[0].category, Warning))
3193 # We don't want PyGIWarning get ignored by default
3194 self.assertFalse(issubclass(warn[0].category, ignored_by_default))
3197 class TestDeprecation(unittest.TestCase):
3198 def test_method(self):
3199 d = GLib.Date.new()
3200 with warnings.catch_warnings(record=True) as warn:
3201 warnings.simplefilter('always')
3202 d.set_time(1)
3203 self.assertTrue(issubclass(warn[0].category, DeprecationWarning))
3204 self.assertEqual(str(warn[0].message), "GLib.Date.set_time is deprecated")
3206 def test_function(self):
3207 with warnings.catch_warnings(record=True) as warn:
3208 warnings.simplefilter('always')
3209 GLib.strcasecmp("foo", "bar")
3210 self.assertTrue(issubclass(warn[0].category, DeprecationWarning))
3211 self.assertEqual(str(warn[0].message), "GLib.strcasecmp is deprecated")
3213 def test_deprecated_attribute_compat(self):
3214 # test if the deprecation descriptor behaves like an instance attribute
3216 # save the descriptor
3217 desc = type(GLib).__dict__["IO_STATUS_ERROR"]
3219 # the descriptor raises AttributeError for itself
3220 self.assertFalse(hasattr(type(GLib), "IO_STATUS_ERROR"))
3222 with warnings.catch_warnings():
3223 warnings.simplefilter('ignore', PyGIDeprecationWarning)
3224 self.assertTrue(hasattr(GLib, "IO_STATUS_ERROR"))
3226 try:
3227 # check if replacing works
3228 GLib.IO_STATUS_ERROR = "foo"
3229 self.assertEqual(GLib.IO_STATUS_ERROR, "foo")
3230 finally:
3231 # restore descriptor
3232 try:
3233 del GLib.IO_STATUS_ERROR
3234 except AttributeError:
3235 pass
3236 setattr(type(GLib), "IO_STATUS_ERROR", desc)
3238 try:
3239 # check if deleting works
3240 del GLib.IO_STATUS_ERROR
3241 self.assertFalse(hasattr(GLib, "IO_STATUS_ERROR"))
3242 finally:
3243 # restore descriptor
3244 try:
3245 del GLib.IO_STATUS_ERROR
3246 except AttributeError:
3247 pass
3248 setattr(type(GLib), "IO_STATUS_ERROR", desc)
3250 def test_deprecated_attribute_warning(self):
3251 with warnings.catch_warnings(record=True) as warn:
3252 warnings.simplefilter('always')
3253 self.assertEqual(GLib.IO_STATUS_ERROR, GLib.IOStatus.ERROR)
3254 GLib.IO_STATUS_ERROR
3255 GLib.IO_STATUS_ERROR
3256 self.assertEqual(len(warn), 3)
3257 self.assertTrue(
3258 issubclass(warn[0].category, PyGIDeprecationWarning))
3259 self.assertRegexpMatches(
3260 str(warn[0].message),
3261 ".*GLib.IO_STATUS_ERROR.*GLib.IOStatus.ERROR.*")
3263 def test_deprecated_attribute_warning_coverage(self):
3264 with warnings.catch_warnings(record=True) as warn:
3265 warnings.simplefilter('always')
3266 GObject.markup_escape_text
3267 GObject.PRIORITY_DEFAULT
3268 GObject.GError
3269 GObject.PARAM_CONSTRUCT
3270 GObject.SIGNAL_ACTION
3271 GObject.property
3272 GObject.IO_STATUS_ERROR
3273 GObject.G_MAXUINT64
3274 GLib.IO_STATUS_ERROR
3275 GLib.SPAWN_SEARCH_PATH
3276 GLib.OPTION_FLAG_HIDDEN
3277 GLib.IO_FLAG_IS_WRITEABLE
3278 GLib.IO_FLAG_NONBLOCK
3279 GLib.USER_DIRECTORY_DESKTOP
3280 GLib.OPTION_ERROR_BAD_VALUE
3281 GLib.glib_version
3282 GLib.pyglib_version
3283 self.assertEqual(len(warn), 17)
3285 def test_deprecated_init_no_keywords(self):
3286 def init(self, **kwargs):
3287 self.assertDictEqual(kwargs, {'a': 1, 'b': 2, 'c': 3})
3289 fn = gi.overrides.deprecated_init(init, arg_names=('a', 'b', 'c'))
3290 with warnings.catch_warnings(record=True) as warn:
3291 warnings.simplefilter('always')
3292 fn(self, 1, 2, 3)
3293 self.assertEqual(len(warn), 1)
3294 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
3295 self.assertRegexpMatches(str(warn[0].message),
3296 '.*keyword.*a, b, c.*')
3298 def test_deprecated_init_no_keywords_out_of_order(self):
3299 def init(self, **kwargs):
3300 self.assertDictEqual(kwargs, {'a': 1, 'b': 2, 'c': 3})
3302 fn = gi.overrides.deprecated_init(init, arg_names=('b', 'a', 'c'))
3303 with warnings.catch_warnings(record=True) as warn:
3304 warnings.simplefilter('always')
3305 fn(self, 2, 1, 3)
3306 self.assertEqual(len(warn), 1)
3307 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
3308 self.assertRegexpMatches(str(warn[0].message),
3309 '.*keyword.*b, a, c.*')
3311 def test_deprecated_init_ignored_keyword(self):
3312 def init(self, **kwargs):
3313 self.assertDictEqual(kwargs, {'a': 1, 'c': 3})
3315 fn = gi.overrides.deprecated_init(init,
3316 arg_names=('a', 'b', 'c'),
3317 ignore=('b',))
3318 with warnings.catch_warnings(record=True) as warn:
3319 warnings.simplefilter('always')
3320 fn(self, 1, 2, 3)
3321 self.assertEqual(len(warn), 1)
3322 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
3323 self.assertRegexpMatches(str(warn[0].message),
3324 '.*keyword.*a, b, c.*')
3326 def test_deprecated_init_with_aliases(self):
3327 def init(self, **kwargs):
3328 self.assertDictEqual(kwargs, {'a': 1, 'b': 2, 'c': 3})
3330 fn = gi.overrides.deprecated_init(init,
3331 arg_names=('a', 'b', 'c'),
3332 deprecated_aliases={'b': 'bb', 'c': 'cc'})
3333 with warnings.catch_warnings(record=True) as warn:
3334 warnings.simplefilter('always')
3336 fn(self, a=1, bb=2, cc=3)
3337 self.assertEqual(len(warn), 1)
3338 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
3339 self.assertRegexpMatches(str(warn[0].message),
3340 '.*keyword.*"bb, cc".*deprecated.*"b, c" respectively')
3342 def test_deprecated_init_with_defaults(self):
3343 def init(self, **kwargs):
3344 self.assertDictEqual(kwargs, {'a': 1, 'b': 2, 'c': 3})
3346 fn = gi.overrides.deprecated_init(init,
3347 arg_names=('a', 'b', 'c'),
3348 deprecated_defaults={'b': 2, 'c': 3})
3349 with warnings.catch_warnings(record=True) as warn:
3350 warnings.simplefilter('always')
3351 fn(self, a=1)
3352 self.assertEqual(len(warn), 1)
3353 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
3354 self.assertRegexpMatches(str(warn[0].message),
3355 '.*relying on deprecated non-standard defaults.*'
3356 'explicitly use: b=2, c=3')