1 # -*- Mode: Python; py-indent-offset: 4 -*-
3 # vim: tabstop=4 shiftwidth=4 expandtab
11 from gi.repository import Regress as Everything
12 from gi.repository import GObject
13 from gi.repository import GLib
14 from gi.repository import Gio
17 from gi.repository import Gtk
22 from helper import capture_exceptions
25 if sys.version_info < (3, 0):
26 UNICHAR = "\xe2\x99\xa5"
27 PY2_UNICODE_UNICHAR = unicode(UNICHAR, 'UTF-8')
32 const_str = b'const \xe2\x99\xa5 utf8'
33 if sys.version_info >= (3, 0):
34 const_str = const_str.decode('UTF-8')
35 noconst_str = 'non' + const_str
38 class RawGList(ctypes.Structure):
39 _fields_ = [('data', ctypes.c_void_p),
40 ('next', ctypes.c_void_p),
41 ('prev', ctypes.c_void_p)]
44 def from_wrapped(cls, obj):
45 offset = sys.getsizeof(object()) # size of PyObject_HEAD
46 return ctypes.POINTER(cls).from_address(id(obj) + offset)
49 class TestInstanceTransfer(unittest.TestCase):
52 obj = Everything.TestObj()
54 obj.instance_method_full()
57 class TestEverything(unittest.TestCase):
60 self.assertEqual(Everything.test_boolean(False), False)
61 self.assertEqual(Everything.test_boolean(True), True)
62 self.assertEqual(Everything.test_boolean('hello'), True)
63 self.assertEqual(Everything.test_boolean(''), False)
65 self.assertEqual(Everything.test_boolean_true(True), True)
66 self.assertEqual(Everything.test_boolean_false(False), False)
69 self.assertEqual(Everything.test_int8(GLib.MAXINT8),
71 self.assertEqual(Everything.test_int8(GLib.MININT8),
73 self.assertRaises(OverflowError, Everything.test_int8, GLib.MAXINT8 + 1)
75 self.assertEqual(Everything.test_uint8(GLib.MAXUINT8),
77 self.assertEqual(Everything.test_uint8(0), 0)
78 self.assertRaises(OverflowError, Everything.test_uint8, -1)
79 self.assertRaises(OverflowError, Everything.test_uint8, GLib.MAXUINT8 + 1)
82 self.assertEqual(Everything.test_int16(GLib.MAXINT16),
84 self.assertEqual(Everything.test_int16(GLib.MININT16),
86 self.assertRaises(OverflowError, Everything.test_int16, GLib.MAXINT16 + 1)
88 self.assertEqual(Everything.test_uint16(GLib.MAXUINT16),
90 self.assertEqual(Everything.test_uint16(0), 0)
91 self.assertRaises(OverflowError, Everything.test_uint16, -1)
92 self.assertRaises(OverflowError, Everything.test_uint16, GLib.MAXUINT16 + 1)
95 self.assertEqual(Everything.test_int32(GLib.MAXINT32),
97 self.assertEqual(Everything.test_int32(GLib.MININT32),
99 self.assertRaises(OverflowError, Everything.test_int32, GLib.MAXINT32 + 1)
101 self.assertEqual(Everything.test_uint32(GLib.MAXUINT32),
103 self.assertEqual(Everything.test_uint32(0), 0)
104 self.assertRaises(OverflowError, Everything.test_uint32, -1)
105 self.assertRaises(OverflowError, Everything.test_uint32, GLib.MAXUINT32 + 1)
107 def test_int64(self):
108 self.assertEqual(Everything.test_int64(GLib.MAXINT64),
110 self.assertEqual(Everything.test_int64(GLib.MININT64),
112 self.assertRaises(OverflowError, Everything.test_int64, GLib.MAXINT64 + 1)
114 self.assertEqual(Everything.test_uint64(GLib.MAXUINT64),
116 self.assertEqual(Everything.test_uint64(0), 0)
117 self.assertRaises(OverflowError, Everything.test_uint64, -1)
118 self.assertRaises(OverflowError, Everything.test_uint64, GLib.MAXUINT64 + 1)
121 self.assertEqual(Everything.test_int(GLib.MAXINT),
123 self.assertEqual(Everything.test_int(GLib.MININT),
125 self.assertRaises(OverflowError, Everything.test_int, GLib.MAXINT + 1)
127 self.assertEqual(Everything.test_uint(GLib.MAXUINT),
129 self.assertEqual(Everything.test_uint(0), 0)
130 self.assertRaises(OverflowError, Everything.test_uint, -1)
131 self.assertRaises(OverflowError, Everything.test_uint, GLib.MAXUINT + 1)
133 def test_short(self):
134 self.assertEqual(Everything.test_short(GLib.MAXSHORT),
136 self.assertEqual(Everything.test_short(GLib.MINSHORT),
138 self.assertRaises(OverflowError, Everything.test_short, GLib.MAXSHORT + 1)
140 self.assertEqual(Everything.test_ushort(GLib.MAXUSHORT),
142 self.assertEqual(Everything.test_ushort(0), 0)
143 self.assertRaises(OverflowError, Everything.test_ushort, -1)
144 self.assertRaises(OverflowError, Everything.test_ushort, GLib.MAXUSHORT + 1)
147 self.assertEqual(Everything.test_long(GLib.MAXLONG),
149 self.assertEqual(Everything.test_long(GLib.MINLONG),
151 self.assertRaises(OverflowError, Everything.test_long, GLib.MAXLONG + 1)
153 self.assertEqual(Everything.test_ulong(GLib.MAXULONG),
155 self.assertEqual(Everything.test_ulong(0), 0)
156 self.assertRaises(OverflowError, Everything.test_ulong, -1)
157 self.assertRaises(OverflowError, Everything.test_ulong, GLib.MAXULONG + 1)
160 self.assertEqual(Everything.test_ssize(GLib.MAXSSIZE),
162 self.assertEqual(Everything.test_ssize(GLib.MINSSIZE),
164 self.assertRaises(OverflowError, Everything.test_ssize, GLib.MAXSSIZE + 1)
166 self.assertEqual(Everything.test_size(GLib.MAXSIZE),
168 self.assertEqual(Everything.test_size(0), 0)
169 self.assertRaises(OverflowError, Everything.test_size, -1)
170 self.assertRaises(OverflowError, Everything.test_size, GLib.MAXSIZE + 1)
172 def test_timet(self):
173 self.assertEqual(Everything.test_timet(42), 42)
174 self.assertRaises(OverflowError, Everything.test_timet, GLib.MAXUINT64 + 1)
176 def test_unichar(self):
177 self.assertEqual("c", Everything.test_unichar("c"))
179 if sys.version_info < (3, 0):
180 self.assertEqual(UNICHAR, Everything.test_unichar(PY2_UNICODE_UNICHAR))
181 self.assertEqual(UNICHAR, Everything.test_unichar(UNICHAR))
182 self.assertRaises(TypeError, Everything.test_unichar, "")
183 self.assertRaises(TypeError, Everything.test_unichar, "morethanonechar")
185 def test_float(self):
186 self.assertEqual(Everything.test_float(GLib.MAXFLOAT),
188 self.assertEqual(Everything.test_float(GLib.MINFLOAT),
190 self.assertRaises(OverflowError, Everything.test_float, GLib.MAXFLOAT * 2)
192 def test_double(self):
193 self.assertEqual(Everything.test_double(GLib.MAXDOUBLE),
195 self.assertEqual(Everything.test_double(GLib.MINDOUBLE),
198 (two, three) = Everything.test_multi_double_args(2.5)
199 self.assertAlmostEqual(two, 5.0)
200 self.assertAlmostEqual(three, 7.5)
202 def test_value(self):
203 self.assertEqual(Everything.test_int_value_arg(GLib.MAXINT), GLib.MAXINT)
204 self.assertEqual(Everything.test_value_return(GLib.MAXINT), GLib.MAXINT)
206 def test_variant(self):
207 v = Everything.test_gvariant_i()
208 self.assertEqual(v.get_type_string(), 'i')
209 self.assertEqual(v.get_int32(), 1)
211 v = Everything.test_gvariant_s()
212 self.assertEqual(v.get_type_string(), 's')
213 self.assertEqual(v.get_string(), 'one')
215 v = Everything.test_gvariant_v()
216 self.assertEqual(v.get_type_string(), 'v')
218 self.assertEqual(vi.get_type_string(), 's')
219 self.assertEqual(vi.get_string(), 'contents')
221 v = Everything.test_gvariant_as()
222 self.assertEqual(v.get_type_string(), 'as')
223 self.assertEqual(v.get_strv(), ['one', 'two', 'three'])
225 v = Everything.test_gvariant_asv()
226 self.assertEqual(v.get_type_string(), 'a{sv}')
227 self.assertEqual(v.lookup_value('nosuchkey', None), None)
228 name = v.lookup_value('name', None)
229 self.assertEqual(name.get_string(), 'foo')
230 timeout = v.lookup_value('timeout', None)
231 self.assertEqual(timeout.get_int32(), 10)
233 def test_utf8_const_return(self):
234 self.assertEqual(Everything.test_utf8_const_return(), const_str)
236 def test_utf8_nonconst_return(self):
237 self.assertEqual(Everything.test_utf8_nonconst_return(), noconst_str)
239 def test_utf8_out(self):
240 self.assertEqual(Everything.test_utf8_out(), noconst_str)
242 def test_utf8_const_in(self):
243 Everything.test_utf8_const_in(const_str)
245 def test_utf8_inout(self):
246 self.assertEqual(Everything.test_utf8_inout(const_str), noconst_str)
248 def test_filename_return(self):
249 self.assertEqual(Everything.test_filename_return(), ['åäö', '/etc/fstab'])
251 def test_int_out_utf8(self):
252 # returns g_utf8_strlen() in out argument
253 self.assertEqual(Everything.test_int_out_utf8(''), 0)
254 self.assertEqual(Everything.test_int_out_utf8('hello world'), 11)
255 self.assertEqual(Everything.test_int_out_utf8('åäö'), 3)
257 def test_utf8_out_out(self):
258 self.assertEqual(Everything.test_utf8_out_out(), ('first', 'second'))
260 def test_utf8_out_nonconst_return(self):
261 self.assertEqual(Everything.test_utf8_out_nonconst_return(), ('first', 'second'))
264 self.assertEqual(Everything.test_enum_param(Everything.TestEnum.VALUE1), 'value1')
265 self.assertEqual(Everything.test_enum_param(Everything.TestEnum.VALUE3), 'value3')
266 self.assertRaises(TypeError, Everything.test_enum_param, 'hello')
268 # FIXME: ValueError: invalid enum value: 2147483648
269 @unittest.expectedFailure
270 def test_enum_unsigned(self):
271 self.assertEqual(Everything.test_unsigned_enum_param(Everything.TestEnumUnsigned.VALUE1), 'value1')
272 self.assertEqual(Everything.test_unsigned_enum_param(Everything.TestEnumUnsigned.VALUE3), 'value3')
273 self.assertRaises(TypeError, Everything.test_unsigned_enum_param, 'hello')
275 def test_flags(self):
276 result = Everything.global_get_flags_out()
277 # assert that it's not an int
278 self.assertEqual(type(result), Everything.TestFlags)
279 self.assertEqual(result, Everything.TestFlags.FLAG1 | Everything.TestFlags.FLAG3)
281 def test_floating(self):
282 e = Everything.TestFloating()
283 self.assertEqual(e.__grefcount__, 1)
285 e = GObject.new(Everything.TestFloating)
286 self.assertEqual(e.__grefcount__, 1)
288 e = Everything.TestFloating.new()
289 self.assertEqual(e.__grefcount__, 1)
291 def test_caller_allocates(self):
292 struct_a = Everything.TestStructA()
293 struct_a.some_int = 10
294 struct_a.some_int8 = 21
295 struct_a.some_double = 3.14
296 struct_a.some_enum = Everything.TestEnum.VALUE3
298 struct_a_clone = struct_a.clone()
299 self.assertTrue(struct_a != struct_a_clone)
300 self.assertEqual(struct_a.some_int, struct_a_clone.some_int)
301 self.assertEqual(struct_a.some_int8, struct_a_clone.some_int8)
302 self.assertEqual(struct_a.some_double, struct_a_clone.some_double)
303 self.assertEqual(struct_a.some_enum, struct_a_clone.some_enum)
305 struct_b = Everything.TestStructB()
306 struct_b.some_int8 = 8
307 struct_b.nested_a.some_int = 20
308 struct_b.nested_a.some_int8 = 12
309 struct_b.nested_a.some_double = 333.3333
310 struct_b.nested_a.some_enum = Everything.TestEnum.VALUE2
312 struct_b_clone = struct_b.clone()
313 self.assertTrue(struct_b != struct_b_clone)
314 self.assertEqual(struct_b.some_int8, struct_b_clone.some_int8)
315 self.assertEqual(struct_b.nested_a.some_int, struct_b_clone.nested_a.some_int)
316 self.assertEqual(struct_b.nested_a.some_int8, struct_b_clone.nested_a.some_int8)
317 self.assertEqual(struct_b.nested_a.some_double, struct_b_clone.nested_a.some_double)
318 self.assertEqual(struct_b.nested_a.some_enum, struct_b_clone.nested_a.some_enum)
320 struct_a = Everything.test_struct_a_parse('ignored')
321 self.assertEqual(struct_a.some_int, 23)
323 def test_wrong_type_of_arguments(self):
325 Everything.test_int8()
327 (e_type, e) = sys.exc_info()[:2]
328 self.assertEqual(e.args, ("Regress.test_int8() takes exactly 1 argument (0 given)",))
330 def test_gtypes(self):
331 gchararray_gtype = GObject.type_from_name('gchararray')
332 gtype = Everything.test_gtype(str)
333 self.assertEqual(gchararray_gtype, gtype)
334 gtype = Everything.test_gtype('gchararray')
335 self.assertEqual(gchararray_gtype, gtype)
336 gobject_gtype = GObject.GObject.__gtype__
337 gtype = Everything.test_gtype(GObject.GObject)
338 self.assertEqual(gobject_gtype, gtype)
339 gtype = Everything.test_gtype('GObject')
340 self.assertEqual(gobject_gtype, gtype)
341 self.assertRaises(TypeError, Everything.test_gtype, 'invalidgtype')
343 class NotARegisteredClass(object):
346 self.assertRaises(TypeError, Everything.test_gtype, NotARegisteredClass)
348 class ARegisteredClass(GObject.GObject):
349 __gtype_name__ = 'EverythingTestsARegisteredClass'
351 gtype = Everything.test_gtype('EverythingTestsARegisteredClass')
352 self.assertEqual(ARegisteredClass.__gtype__, gtype)
353 gtype = Everything.test_gtype(ARegisteredClass)
354 self.assertEqual(ARegisteredClass.__gtype__, gtype)
355 self.assertRaises(TypeError, Everything.test_gtype, 'ARegisteredClass')
358 attr_list = dir(Everything)
360 # test that typelib attributes are listed
361 self.assertTrue('TestStructA' in attr_list)
363 # test that class attributes and methods are listed
364 self.assertTrue('__class__' in attr_list)
365 self.assertTrue('__dir__' in attr_list)
366 self.assertTrue('__repr__' in attr_list)
368 # test that instance members are listed
369 self.assertTrue('_namespace' in attr_list)
370 self.assertTrue('_version' in attr_list)
372 # test that there are no duplicates returned
373 self.assertEqual(len(attr_list), len(set(attr_list)))
375 def test_array_int_in_empty(self):
376 self.assertEqual(Everything.test_array_int_in([]), 0)
378 def test_array_int_in(self):
379 self.assertEqual(Everything.test_array_int_in([1, 5, -2]), 4)
381 def test_array_int_out(self):
382 self.assertEqual(Everything.test_array_int_out(), [0, 1, 2, 3, 4])
384 def test_array_int_full_out(self):
385 self.assertEqual(Everything.test_array_int_full_out(), [0, 1, 2, 3, 4])
387 def test_array_int_none_out(self):
388 self.assertEqual(Everything.test_array_int_none_out(), [1, 2, 3, 4, 5])
390 def test_array_int_inout(self):
391 self.assertEqual(Everything.test_array_int_inout([1, 5, 42, -8]), [6, 43, -7])
393 def test_array_int_inout_empty(self):
394 self.assertEqual(Everything.test_array_int_inout([]), [])
396 def test_array_gint8_in(self):
397 if sys.version_info >= (3, 0):
398 self.assertEqual(Everything.test_array_gint8_in(b'\x01\x03\x05'), 9)
399 self.assertEqual(Everything.test_array_gint8_in([1, 3, 5, -50]), -41)
401 def test_array_gint16_in(self):
402 self.assertEqual(Everything.test_array_gint16_in([256, 257, -1000, 10000]), 9513)
404 def test_array_gint32_in(self):
405 self.assertEqual(Everything.test_array_gint32_in([30000, 1, -2]), 29999)
407 def test_array_gint64_in(self):
408 self.assertEqual(Everything.test_array_gint64_in([2 ** 33, 2 ** 34]), 2 ** 33 + 2 ** 34)
410 def test_array_gtype_in(self):
411 self.assertEqual(Everything.test_array_gtype_in(
412 [GObject.TYPE_STRING, GObject.TYPE_UINT64, GObject.TYPE_VARIANT]),
413 '[gchararray,guint64,GVariant,]')
415 def test_array_fixed_size_int_in(self):
417 self.assertEqual(Everything.test_array_fixed_size_int_in([1, 2, -10, 5, 3]), 1)
419 def test_array_fixed_size_int_in_error(self):
420 self.assertRaises(ValueError, Everything.test_array_fixed_size_int_in, [1, 2, 3, 4])
421 self.assertRaises(ValueError, Everything.test_array_fixed_size_int_in, [1, 2, 3, 4, 5, 6])
423 def test_array_fixed_size_int_out(self):
424 self.assertEqual(Everything.test_array_fixed_size_int_out(), [0, 1, 2, 3, 4])
426 def test_array_fixed_size_int_return(self):
427 self.assertEqual(Everything.test_array_fixed_size_int_return(), [0, 1, 2, 3, 4])
429 def test_garray_container_return(self):
430 # GPtrArray transfer container
431 result = Everything.test_garray_container_return()
432 self.assertEqual(result, ['regress'])
435 def test_garray_full_return(self):
436 # GPtrArray transfer full
437 result = Everything.test_garray_full_return()
438 self.assertEqual(result, ['regress'])
441 def test_strv_out(self):
442 self.assertEqual(Everything.test_strv_out(), ['thanks', 'for', 'all', 'the', 'fish'])
444 def test_strv_out_c(self):
445 self.assertEqual(Everything.test_strv_out_c(), ['thanks', 'for', 'all', 'the', 'fish'])
447 def test_strv_out_container(self):
448 self.assertEqual(Everything.test_strv_out_container(), ['1', '2', '3'])
450 def test_strv_outarg(self):
451 self.assertEqual(Everything.test_strv_outarg(), ['1', '2', '3'])
453 def test_strv_in_gvalue(self):
454 self.assertEqual(Everything.test_strv_in_gvalue(), ['one', 'two', 'three'])
456 def test_strv_in(self):
457 Everything.test_strv_in(['1', '2', '3'])
459 def test_glist(self):
460 self.assertEqual(Everything.test_glist_nothing_return(), ['1', '2', '3'])
461 self.assertEqual(Everything.test_glist_nothing_return2(), ['1', '2', '3'])
462 self.assertEqual(Everything.test_glist_container_return(), ['1', '2', '3'])
463 self.assertEqual(Everything.test_glist_everything_return(), ['1', '2', '3'])
465 Everything.test_glist_nothing_in(['1', '2', '3'])
466 Everything.test_glist_nothing_in2(['1', '2', '3'])
468 @unittest.skipUnless(hasattr(Everything, 'test_glist_gtype_container_in'),
469 'Requires newer version of GI')
470 def test_glist_gtype(self):
471 Everything.test_glist_gtype_container_in(
472 [Everything.TestObj, Everything.TestSubObj])
474 def test_gslist(self):
475 self.assertEqual(Everything.test_gslist_nothing_return(), ['1', '2', '3'])
476 self.assertEqual(Everything.test_gslist_nothing_return2(), ['1', '2', '3'])
477 self.assertEqual(Everything.test_gslist_container_return(), ['1', '2', '3'])
478 self.assertEqual(Everything.test_gslist_everything_return(), ['1', '2', '3'])
480 Everything.test_gslist_nothing_in(['1', '2', '3'])
481 Everything.test_gslist_nothing_in2(['1', '2', '3'])
483 def test_hash_return(self):
484 expected = {'foo': 'bar', 'baz': 'bat', 'qux': 'quux'}
486 self.assertEqual(Everything.test_ghash_null_return(), None)
487 self.assertEqual(Everything.test_ghash_nothing_return(), expected)
488 self.assertEqual(Everything.test_ghash_nothing_return(), expected)
489 self.assertEqual(Everything.test_ghash_container_return(), expected)
490 self.assertEqual(Everything.test_ghash_everything_return(), expected)
492 result = Everything.test_ghash_gvalue_return()
493 self.assertEqual(result['integer'], 12)
494 self.assertEqual(result['boolean'], True)
495 self.assertEqual(result['string'], 'some text')
496 self.assertEqual(result['strings'], ['first', 'second', 'third'])
497 self.assertEqual(result['flags'], Everything.TestFlags.FLAG1 | Everything.TestFlags.FLAG3)
498 self.assertEqual(result['enum'], Everything.TestEnum.VALUE2)
501 # FIXME: CRITICAL **: Unsupported type ghash
502 def disabled_test_hash_return_nested(self):
503 self.assertEqual(Everything.test_ghash_nested_everything_return(), {})
504 self.assertEqual(Everything.test_ghash_nested_everything_return2(), {})
506 def test_hash_in(self):
507 expected = {'foo': 'bar', 'baz': 'bat', 'qux': 'quux'}
509 Everything.test_ghash_nothing_in(expected)
510 Everything.test_ghash_nothing_in2(expected)
512 def test_hash_in_with_typed_strv(self):
514 __gtype__ = GObject.TYPE_STRV
516 data = {'integer': 12,
518 'string': 'some text',
519 'strings': GStrv(['first', 'second', 'third']),
520 'flags': Everything.TestFlags.FLAG1 | Everything.TestFlags.FLAG3,
521 'enum': Everything.TestEnum.VALUE2,
523 Everything.test_ghash_gvalue_in(data)
526 def test_hash_in_with_gvalue_strv(self):
527 data = {'integer': 12,
529 'string': 'some text',
530 'strings': GObject.Value(GObject.TYPE_STRV, ['first', 'second', 'third']),
531 'flags': Everything.TestFlags.FLAG1 | Everything.TestFlags.FLAG3,
532 'enum': Everything.TestEnum.VALUE2,
534 Everything.test_ghash_gvalue_in(data)
537 def test_struct_gpointer(self):
539 raw = RawGList.from_wrapped(glist)
541 # Note that pointer fields use 0 for NULL in PyGObject and None in ctypes
542 self.assertEqual(glist.data, 0)
543 self.assertEqual(raw.contents.data, None)
546 self.assertEqual(glist.data, 123)
547 self.assertEqual(raw.contents.data, 123)
550 self.assertEqual(glist.data, 0)
551 self.assertEqual(raw.contents.data, None)
553 # Setting to anything other than an int should raise
554 self.assertRaises(TypeError, setattr, glist.data, 'nan')
555 self.assertRaises(TypeError, setattr, glist.data, object())
556 self.assertRaises(TypeError, setattr, glist.data, 123.321)
558 def test_struct_opaque(self):
559 # we should get a sensible error message
561 Everything.TestBoxedPrivate()
562 self.fail('allocating disguised struct without default constructor unexpectedly succeeded')
564 (e_type, e_value, e_tb) = sys.exc_info()
565 self.assertEqual(e_type, TypeError)
566 self.assertTrue('TestBoxedPrivate' in str(e_value), str(e_value))
567 self.assertTrue('constructor' in str(e_value), str(e_value))
568 tb = ''.join(traceback.format_exception(e_type, e_value, e_tb))
569 self.assertTrue('test_everything.py", line' in tb, tb)
572 class TestNullableArgs(unittest.TestCase):
573 def test_in_nullable_hash(self):
574 Everything.test_ghash_null_in(None)
576 def test_in_nullable_list(self):
577 Everything.test_gslist_null_in(None)
578 Everything.test_glist_null_in(None)
579 Everything.test_gslist_null_in([])
580 Everything.test_glist_null_in([])
582 def test_in_nullable_array(self):
583 Everything.test_array_int_null_in(None)
584 Everything.test_array_int_null_in([])
586 def test_in_nullable_string(self):
587 Everything.test_utf8_null_in(None)
589 def test_in_nullable_object(self):
590 Everything.func_obj_null_in(None)
592 def test_out_nullable_hash(self):
593 self.assertEqual(None, Everything.test_ghash_null_out())
595 def test_out_nullable_list(self):
596 self.assertEqual([], Everything.test_gslist_null_out())
597 self.assertEqual([], Everything.test_glist_null_out())
599 def test_out_nullable_array(self):
600 self.assertEqual([], Everything.test_array_int_null_out())
602 def test_out_nullable_string(self):
603 self.assertEqual(None, Everything.test_utf8_null_out())
605 def test_out_nullable_object(self):
606 self.assertEqual(None, Everything.TestObj.null_out())
609 class TestCallbacks(unittest.TestCase):
611 main_loop = GLib.MainLoop()
613 def test_callback(self):
614 TestCallbacks.called = False
617 TestCallbacks.called = True
619 Everything.test_simple_callback(callback)
620 self.assertTrue(TestCallbacks.called)
622 def test_callback_exception(self):
624 This test ensures that we get errors from callbacks correctly
625 and in particular that we do not segv when callbacks fail
629 self.fail('unexpected surviving zero divsion:' + str(x))
631 # note that we do NOT expect the ZeroDivisionError to be propagated
632 # through from the callback, as it crosses the Python<->C boundary
633 # twice. (See GNOME #616279)
634 with capture_exceptions() as exc:
635 Everything.test_simple_callback(callback)
637 self.assertEqual(exc[0].type, ZeroDivisionError)
639 def test_double_callback_exception(self):
641 This test ensures that we get errors from callbacks correctly
642 and in particular that we do not segv when callbacks fail
646 self.fail('unexpected surviving zero divsion:' + str(x))
649 Everything.test_boolean(True)
650 Everything.test_boolean(False)
651 Everything.test_simple_callback(badcallback())
653 # note that we do NOT expect the ZeroDivisionError to be propagated
654 # through from the callback, as it crosses the Python<->C boundary
655 # twice. (See GNOME #616279)
656 with capture_exceptions() as exc:
657 Everything.test_simple_callback(callback)
659 self.assertEqual(exc[0].type, ZeroDivisionError)
661 def test_return_value_callback(self):
662 TestCallbacks.called = False
665 TestCallbacks.called = True
668 self.assertEqual(Everything.test_callback(callback), 44)
669 self.assertTrue(TestCallbacks.called)
671 def test_callback_scope_async(self):
672 TestCallbacks.called = False
675 def callback(user_data):
676 self.assertEqual(user_data, ud)
677 TestCallbacks.called = True
680 ud_refcount = sys.getrefcount(ud)
681 callback_refcount = sys.getrefcount(callback)
683 self.assertEqual(Everything.test_callback_async(callback, ud), None)
684 # Callback should not have run and the ref count is increased by 1
685 self.assertEqual(TestCallbacks.called, False)
686 self.assertEqual(sys.getrefcount(callback), callback_refcount + 1)
687 self.assertEqual(sys.getrefcount(ud), ud_refcount + 1)
689 # test_callback_thaw_async will run the callback previously supplied.
690 # references should be auto decremented after this call.
691 self.assertEqual(Everything.test_callback_thaw_async(), 44)
692 self.assertTrue(TestCallbacks.called)
694 # Make sure refcounts are returned to normal
695 self.assertEqual(sys.getrefcount(callback), callback_refcount)
696 self.assertEqual(sys.getrefcount(ud), ud_refcount)
698 def test_callback_scope_call_multi(self):
699 # This tests a callback that gets called multiple times from a
700 # single scope call in python.
701 TestCallbacks.called = 0
704 TestCallbacks.called += 1
705 return TestCallbacks.called
707 refcount = sys.getrefcount(callback)
708 result = Everything.test_multi_callback(callback)
709 # first callback should give 1, second 2, and the function sums them up
710 self.assertEqual(result, 3)
711 self.assertEqual(TestCallbacks.called, 2)
712 self.assertEqual(sys.getrefcount(callback), refcount)
714 def test_callback_scope_call_array(self):
715 # This tests a callback that gets called multiple times from a
716 # single scope call in python with array arguments
717 TestCallbacks.callargs = []
719 # FIXME: would be cleaner without the explicit length args:
720 # def callback(one, two):
721 def callback(one, one_length, two, two_length):
722 TestCallbacks.callargs.append((one, two))
723 return len(TestCallbacks.callargs)
725 refcount = sys.getrefcount(callback)
726 result = Everything.test_array_callback(callback)
727 # first callback should give 1, second 2, and the function sums them up
728 self.assertEqual(result, 3)
729 self.assertEqual(TestCallbacks.callargs,
730 [([-1, 0, 1, 2], ['one', 'two', 'three'])] * 2)
731 self.assertEqual(sys.getrefcount(callback), refcount)
733 @unittest.skipUnless(hasattr(Everything, 'test_array_inout_callback'),
734 'Requires newer version of GI')
735 def test_callback_scope_call_array_inout(self):
736 # This tests a callback that gets called multiple times from a
737 # single scope call in python with inout array arguments
738 TestCallbacks.callargs = []
740 def callback(ints, ints_length):
741 TestCallbacks.callargs.append(ints)
742 return ints[1:], len(ints[1:])
744 refcount = sys.getrefcount(callback)
745 result = Everything.test_array_inout_callback(callback)
746 self.assertEqual(TestCallbacks.callargs,
747 [[-2, -1, 0, 1, 2], [-1, 0, 1, 2]])
748 # first callback should give 4, second 3
749 self.assertEqual(result, 3)
750 self.assertEqual(sys.getrefcount(callback), refcount)
752 def test_callback_userdata(self):
753 TestCallbacks.called = 0
755 def callback(userdata):
756 self.assertEqual(userdata, "Test%d" % TestCallbacks.called)
757 TestCallbacks.called += 1
758 return TestCallbacks.called
761 val = Everything.test_callback_user_data(callback, "Test%d" % i)
762 self.assertEqual(val, i + 1)
764 self.assertEqual(TestCallbacks.called, 100)
766 def test_callback_userdata_no_user_data(self):
767 TestCallbacks.called = 0
770 TestCallbacks.called += 1
771 return TestCallbacks.called
774 val = Everything.test_callback_user_data(callback)
775 self.assertEqual(val, i + 1)
777 self.assertEqual(TestCallbacks.called, 100)
779 def test_callback_userdata_varargs(self):
780 TestCallbacks.called = 0
781 collected_user_data = []
784 collected_user_data.extend([a, b])
785 TestCallbacks.called += 1
786 return TestCallbacks.called
789 val = Everything.test_callback_user_data(callback, 1, 2)
790 self.assertEqual(val, i + 1)
792 self.assertEqual(TestCallbacks.called, 10)
793 self.assertSequenceEqual(collected_user_data, [1, 2] * 10)
795 def test_callback_userdata_as_kwarg_tuple(self):
796 TestCallbacks.called = 0
797 collected_user_data = []
799 def callback(user_data):
800 collected_user_data.extend(user_data)
801 TestCallbacks.called += 1
802 return TestCallbacks.called
805 val = Everything.test_callback_user_data(callback, user_data=(1, 2))
806 self.assertEqual(val, i + 1)
808 self.assertEqual(TestCallbacks.called, 10)
809 self.assertSequenceEqual(collected_user_data, [1, 2] * 10)
811 def test_callback_user_data_middle_none(self):
814 def callback(userdata):
815 cb_info['called'] = True
816 cb_info['userdata'] = userdata
819 (y, z, q) = Everything.test_torture_signature_2(
820 42, callback, None, 'some string', 3)
821 self.assertEqual(y, 42)
822 self.assertEqual(z, 84)
823 self.assertEqual(q, 14)
824 self.assertTrue(cb_info['called'])
825 self.assertEqual(cb_info['userdata'], None)
827 def test_callback_user_data_middle_single(self):
830 def callback(userdata):
831 cb_info['called'] = True
832 cb_info['userdata'] = userdata
835 (y, z, q) = Everything.test_torture_signature_2(
836 42, callback, 'User Data', 'some string', 3)
837 self.assertEqual(y, 42)
838 self.assertEqual(z, 84)
839 self.assertEqual(q, 14)
840 self.assertTrue(cb_info['called'])
841 self.assertEqual(cb_info['userdata'], 'User Data')
843 def test_callback_user_data_middle_tuple(self):
846 def callback(userdata):
847 cb_info['called'] = True
848 cb_info['userdata'] = userdata
851 (y, z, q) = Everything.test_torture_signature_2(
852 42, callback, (-5, 'User Data'), 'some string', 3)
853 self.assertEqual(y, 42)
854 self.assertEqual(z, 84)
855 self.assertEqual(q, 14)
856 self.assertTrue(cb_info['called'])
857 self.assertEqual(cb_info['userdata'], (-5, 'User Data'))
859 def test_async_ready_callback(self):
860 TestCallbacks.called = False
861 TestCallbacks.main_loop = GLib.MainLoop()
863 def callback(obj, result, user_data):
864 TestCallbacks.main_loop.quit()
865 TestCallbacks.called = True
867 Everything.test_async_ready_callback(callback)
869 TestCallbacks.main_loop.run()
871 self.assertTrue(TestCallbacks.called)
873 def test_callback_scope_notified_with_destroy(self):
874 TestCallbacks.called = 0
875 ud = 'Test scope notified data 33'
877 def callback(user_data):
878 self.assertEqual(user_data, ud)
879 TestCallbacks.called += 1
882 value_refcount = sys.getrefcount(ud)
883 callback_refcount = sys.getrefcount(callback)
885 # Callback is immediately called.
887 res = Everything.test_callback_destroy_notify(callback, ud)
888 self.assertEqual(res, 33)
890 self.assertEqual(TestCallbacks.called, 100)
891 self.assertEqual(sys.getrefcount(callback), callback_refcount + 100)
892 self.assertEqual(sys.getrefcount(ud), value_refcount + 100)
894 # thaw will call the callback again, this time resources should be freed
895 self.assertEqual(Everything.test_callback_thaw_notifications(), 33 * 100)
896 self.assertEqual(TestCallbacks.called, 200)
897 self.assertEqual(sys.getrefcount(callback), callback_refcount)
898 self.assertEqual(sys.getrefcount(ud), value_refcount)
900 def test_callback_scope_notified_with_destroy_no_user_data(self):
901 TestCallbacks.called = 0
903 def callback(user_data):
904 self.assertEqual(user_data, None)
905 TestCallbacks.called += 1
908 callback_refcount = sys.getrefcount(callback)
910 # Run with warning as exception
911 with warnings.catch_warnings(record=True) as w:
912 warnings.simplefilter("error")
913 self.assertRaises(RuntimeWarning,
914 Everything.test_callback_destroy_notify_no_user_data,
917 self.assertEqual(TestCallbacks.called, 0)
918 self.assertEqual(sys.getrefcount(callback), callback_refcount)
920 # Run with warning as warning
921 with warnings.catch_warnings(record=True) as w:
922 # Cause all warnings to always be triggered.
923 warnings.simplefilter("default")
925 res = Everything.test_callback_destroy_notify_no_user_data(callback)
927 self.assertEqual(len(w), 1)
928 self.assertTrue(issubclass(w[-1].category, RuntimeWarning))
929 self.assertTrue('Callables passed to' in str(w[-1].message))
931 self.assertEqual(res, 34)
932 self.assertEqual(TestCallbacks.called, 1)
933 self.assertEqual(sys.getrefcount(callback), callback_refcount + 1)
935 # thaw will call the callback again,
936 # refcount will not go down without user_data parameter
937 self.assertEqual(Everything.test_callback_thaw_notifications(), 34)
938 self.assertEqual(TestCallbacks.called, 2)
939 self.assertEqual(sys.getrefcount(callback), callback_refcount + 1)
941 def test_callback_in_methods(self):
942 object_ = Everything.TestObj()
945 TestCallbacks.called = True
948 TestCallbacks.called = False
949 object_.instance_method_callback(callback)
950 self.assertTrue(TestCallbacks.called)
952 TestCallbacks.called = False
953 Everything.TestObj.static_method_callback(callback)
954 self.assertTrue(TestCallbacks.called)
956 def callbackWithUserData(user_data):
957 TestCallbacks.called += 1
960 TestCallbacks.called = 0
961 Everything.TestObj.new_callback(callbackWithUserData, None)
962 self.assertEqual(TestCallbacks.called, 1)
963 # Note: using "new_callback" adds the notification to the same global
964 # list as Everything.test_callback_destroy_notify, so thaw the list
965 # so we don't get confusion between tests.
966 self.assertEqual(Everything.test_callback_thaw_notifications(), 42)
967 self.assertEqual(TestCallbacks.called, 2)
969 def test_callback_none(self):
970 # make sure this doesn't assert or crash
971 Everything.test_simple_callback(None)
973 def test_callback_gerror(self):
975 self.assertEqual(error.message, 'regression test error')
976 self.assertTrue('g-io' in error.domain)
977 self.assertEqual(error.code, Gio.IOErrorEnum.NOT_SUPPORTED)
978 TestCallbacks.called = True
980 TestCallbacks.called = False
981 Everything.test_gerror_callback(callback)
982 self.assertTrue(TestCallbacks.called)
984 def test_callback_null_gerror(self):
986 self.assertEqual(error, None)
987 TestCallbacks.called = True
989 TestCallbacks.called = False
990 Everything.test_null_gerror_callback(callback)
991 self.assertTrue(TestCallbacks.called)
993 def test_callback_owned_gerror(self):
995 self.assertEqual(error.message, 'regression test owned error')
996 self.assertTrue('g-io' in error.domain)
997 self.assertEqual(error.code, Gio.IOErrorEnum.PERMISSION_DENIED)
998 TestCallbacks.called = True
1000 TestCallbacks.called = False
1001 Everything.test_owned_gerror_callback(callback)
1002 self.assertTrue(TestCallbacks.called)
1004 def test_callback_hashtable(self):
1006 self.assertEqual(data, mydict)
1008 TestCallbacks.called = True
1010 mydict = {'foo': 1, 'bar': 2}
1011 TestCallbacks.called = False
1012 Everything.test_hash_table_callback(mydict, callback)
1013 self.assertTrue(TestCallbacks.called)
1014 self.assertEqual(mydict, {'foo': 1, 'bar': 2, 'new': 42})
1017 class TestClosures(unittest.TestCase):
1018 def test_no_arg(self):
1024 result = Everything.test_closure(callback)
1025 self.assertTrue(self.called)
1026 self.assertEqual(result, 42)
1028 def test_int_arg(self):
1034 result = Everything.test_closure_one_arg(callback, 42)
1035 self.assertTrue(self.called)
1036 self.assertEqual(result, 43)
1038 def test_variant(self):
1039 def callback(variant):
1043 self.assertEqual(variant.get_type_string(), 'i')
1044 return GLib.Variant('i', variant.get_int32() + 1)
1047 result = Everything.test_closure_variant(callback, GLib.Variant('i', 42))
1048 self.assertTrue(self.called)
1049 self.assertEqual(result.get_type_string(), 'i')
1050 self.assertEqual(result.get_int32(), 43)
1053 result = Everything.test_closure_variant(callback, None)
1054 self.assertTrue(self.called)
1055 self.assertEqual(result, None)
1058 self.assertRaises(TypeError, Everything.test_closure_variant, callback, 'foo')
1059 self.assertFalse(self.called)
1061 def test_variant_wrong_return_type(self):
1062 def callback(variant):
1065 with capture_exceptions() as exc:
1066 # this does not directly raise an exception (see
1067 # https://bugzilla.gnome.org/show_bug.cgi?id=616279)
1068 result = Everything.test_closure_variant(callback, GLib.Variant('i', 42))
1069 # ... but the result shouldn't be a string
1070 self.assertEqual(result, None)
1071 # and the error should be shown
1072 self.assertEqual(len(exc), 1)
1073 self.assertEqual(exc[0].type, TypeError)
1074 self.assertTrue('return value' in str(exc[0].value), exc[0].value)
1077 class TestBoxed(unittest.TestCase):
1078 def test_boxed(self):
1079 object_ = Everything.TestObj()
1080 self.assertEqual(object_.props.boxed, None)
1082 boxed = Everything.TestBoxed()
1083 boxed.some_int8 = 42
1084 object_.props.boxed = boxed
1086 self.assertTrue(isinstance(object_.props.boxed, Everything.TestBoxed))
1087 self.assertEqual(object_.props.boxed.some_int8, 42)
1089 def test_boxed_alternative_constructor(self):
1090 boxed = Everything.TestBoxed.new_alternative_constructor1(5)
1091 self.assertEqual(boxed.some_int8, 5)
1093 boxed = Everything.TestBoxed.new_alternative_constructor2(5, 3)
1094 self.assertEqual(boxed.some_int8, 8)
1096 boxed = Everything.TestBoxed.new_alternative_constructor3("-3")
1097 self.assertEqual(boxed.some_int8, -3)
1099 def test_boxed_equality(self):
1100 boxed42 = Everything.TestBoxed.new_alternative_constructor1(42)
1101 boxed5 = Everything.TestBoxed.new_alternative_constructor1(5)
1102 boxed42_2 = Everything.TestBoxed.new_alternative_constructor2(41, 1)
1104 self.assertFalse(boxed42.equals(boxed5))
1105 self.assertTrue(boxed42.equals(boxed42_2))
1106 self.assertTrue(boxed42_2.equals(boxed42))
1107 self.assertTrue(boxed42.equals(boxed42))
1109 def test_boxed_b_constructor(self):
1110 with warnings.catch_warnings(record=True) as warn:
1111 warnings.simplefilter('always')
1112 boxed = Everything.TestBoxedB(42, 47)
1113 self.assertTrue(issubclass(warn[0].category, TypeError))
1115 self.assertEqual(boxed.some_int8, 0)
1116 self.assertEqual(boxed.some_long, 0)
1118 def test_boxed_c_equality(self):
1119 boxed = Everything.TestBoxedC()
1120 # TestBoxedC uses refcounting, so we know that
1121 # the pointer is the same when copied
1123 self.assertEqual(boxed, copy)
1124 self.assertNotEqual(id(boxed), id(copy))
1127 class TestTortureProfile(unittest.TestCase):
1128 def test_torture_profile(self):
1132 object_ = Everything.TestObj()
1133 sys.stdout.write("\ttorture test 1 (10000 iterations): ")
1135 start_time = time.clock()
1136 for i in range(10000):
1137 (y, z, q) = object_.torture_signature_0(5000,
1141 end_time = time.clock()
1142 delta_time = end_time - start_time
1143 total_time += delta_time
1144 print("%f secs" % delta_time)
1146 sys.stdout.write("\ttorture test 2 (10000 iterations): ")
1148 start_time = time.clock()
1149 for i in range(10000):
1150 (y, z, q) = Everything.TestObj().torture_signature_0(
1151 5000, "Torture Test 2", 12345)
1153 end_time = time.clock()
1154 delta_time = end_time - start_time
1155 total_time += delta_time
1156 print("%f secs" % delta_time)
1158 sys.stdout.write("\ttorture test 3 (10000 iterations): ")
1159 start_time = time.clock()
1160 for i in range(10000):
1162 (y, z, q) = object_.torture_signature_1(
1163 5000, "Torture Test 3", 12345)
1166 end_time = time.clock()
1167 delta_time = end_time - start_time
1168 total_time += delta_time
1169 print("%f secs" % delta_time)
1171 sys.stdout.write("\ttorture test 4 (10000 iterations): ")
1173 def callback(userdata):
1176 userdata = [1, 2, 3, 4]
1177 start_time = time.clock()
1178 for i in range(10000):
1179 (y, z, q) = Everything.test_torture_signature_2(
1180 5000, callback, userdata, "Torture Test 4", 12345)
1181 end_time = time.clock()
1182 delta_time = end_time - start_time
1183 total_time += delta_time
1184 print("%f secs" % delta_time)
1186 print("\tTotal: %f sec" % total_time)
1189 class TestAdvancedInterfaces(unittest.TestCase):
1190 def test_array_objs(self):
1191 obj1, obj2 = Everything.test_array_fixed_out_objects()
1192 self.assertTrue(isinstance(obj1, Everything.TestObj))
1193 self.assertTrue(isinstance(obj2, Everything.TestObj))
1194 self.assertNotEqual(obj1, obj2)
1196 def test_obj_skip_return_val(self):
1197 obj = Everything.TestObj()
1198 ret = obj.skip_return_val(50, 42.0, 60, 2, 3)
1199 self.assertEqual(len(ret), 3)
1200 self.assertEqual(ret[0], 51)
1201 self.assertEqual(ret[1], 61)
1202 self.assertEqual(ret[2], 32)
1204 def test_obj_skip_return_val_no_out(self):
1205 obj = Everything.TestObj()
1206 # raises an error for 0, succeeds for any other value
1207 self.assertRaises(GLib.GError, obj.skip_return_val_no_out, 0)
1209 ret = obj.skip_return_val_no_out(1)
1210 self.assertEqual(ret, None)