cc79dc32b97d1c55e6b1f07fec1984171875244d
[platform/upstream/pygobject2.git] / tests / test_everything.py
1 # -*- Mode: Python; py-indent-offset: 4 -*-
2 # coding=utf-8
3 # vim: tabstop=4 shiftwidth=4 expandtab
4
5 import unittest
6 import traceback
7 import ctypes
8 import warnings
9 import sys
10
11 try:
12     import cairo
13     has_cairo = True
14     from gi.repository import Regress as Everything
15 except ImportError:
16     has_cairo = False
17
18 from gi.repository import GObject
19 from gi.repository import GLib
20 from gi.repository import Gio
21
22 try:
23     from gi.repository import Gtk
24     Gtk  # pyflakes
25 except:
26     Gtk = None
27
28 if sys.version_info < (3, 0):
29     UNICHAR = "\xe2\x99\xa5"
30     PY2_UNICODE_UNICHAR = unicode(UNICHAR, 'UTF-8')
31 else:
32     UNICHAR = "♥"
33
34
35 class RawGList(ctypes.Structure):
36     _fields_ = [('data', ctypes.c_void_p),
37                 ('next', ctypes.c_void_p),
38                 ('prev', ctypes.c_void_p)]
39
40     @classmethod
41     def from_wrapped(cls, obj):
42         offset = sys.getsizeof(object())  # size of PyObject_HEAD
43         return ctypes.POINTER(cls).from_address(id(obj) + offset)
44
45
46 @unittest.skipUnless(has_cairo, 'built without cairo support')
47 class TestEverything(unittest.TestCase):
48
49     def test_cairo_context(self):
50         context = Everything.test_cairo_context_full_return()
51         self.assertTrue(isinstance(context, cairo.Context))
52
53         surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 10, 10)
54         context = cairo.Context(surface)
55         Everything.test_cairo_context_none_in(context)
56
57     def test_cairo_surface(self):
58         surface = Everything.test_cairo_surface_none_return()
59         self.assertTrue(isinstance(surface, cairo.ImageSurface))
60         self.assertTrue(isinstance(surface, cairo.Surface))
61         self.assertEqual(surface.get_format(), cairo.FORMAT_ARGB32)
62         self.assertEqual(surface.get_width(), 10)
63         self.assertEqual(surface.get_height(), 10)
64
65         surface = Everything.test_cairo_surface_full_return()
66         self.assertTrue(isinstance(surface, cairo.ImageSurface))
67         self.assertTrue(isinstance(surface, cairo.Surface))
68         self.assertEqual(surface.get_format(), cairo.FORMAT_ARGB32)
69         self.assertEqual(surface.get_width(), 10)
70         self.assertEqual(surface.get_height(), 10)
71
72         surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 10, 10)
73         Everything.test_cairo_surface_none_in(surface)
74
75         surface = Everything.test_cairo_surface_full_out()
76         self.assertTrue(isinstance(surface, cairo.ImageSurface))
77         self.assertTrue(isinstance(surface, cairo.Surface))
78         self.assertEqual(surface.get_format(), cairo.FORMAT_ARGB32)
79         self.assertEqual(surface.get_width(), 10)
80         self.assertEqual(surface.get_height(), 10)
81
82     def test_bool(self):
83         self.assertEqual(Everything.test_boolean(False), False)
84         self.assertEqual(Everything.test_boolean(True), True)
85         self.assertEqual(Everything.test_boolean('hello'), True)
86         self.assertEqual(Everything.test_boolean(''), False)
87
88         self.assertEqual(Everything.test_boolean_true(True), True)
89         self.assertEqual(Everything.test_boolean_false(False), False)
90
91     def test_int8(self):
92         self.assertEqual(Everything.test_int8(GObject.G_MAXINT8),
93                          GObject.G_MAXINT8)
94         self.assertEqual(Everything.test_int8(GObject.G_MININT8),
95                          GObject.G_MININT8)
96         self.assertRaises(OverflowError, Everything.test_int8, GObject.G_MAXINT8 + 1)
97
98         self.assertEqual(Everything.test_uint8(GObject.G_MAXUINT8),
99                          GObject.G_MAXUINT8)
100         self.assertEqual(Everything.test_uint8(0), 0)
101         self.assertRaises(OverflowError, Everything.test_uint8, -1)
102         self.assertRaises(OverflowError, Everything.test_uint8, GObject.G_MAXUINT8 + 1)
103
104     def test_int16(self):
105         self.assertEqual(Everything.test_int16(GObject.G_MAXINT16),
106                          GObject.G_MAXINT16)
107         self.assertEqual(Everything.test_int16(GObject.G_MININT16),
108                          GObject.G_MININT16)
109         self.assertRaises(OverflowError, Everything.test_int16, GObject.G_MAXINT16 + 1)
110
111         self.assertEqual(Everything.test_uint16(GObject.G_MAXUINT16),
112                          GObject.G_MAXUINT16)
113         self.assertEqual(Everything.test_uint16(0), 0)
114         self.assertRaises(OverflowError, Everything.test_uint16, -1)
115         self.assertRaises(OverflowError, Everything.test_uint16, GObject.G_MAXUINT16 + 1)
116
117     def test_int32(self):
118         self.assertEqual(Everything.test_int32(GObject.G_MAXINT32),
119                          GObject.G_MAXINT32)
120         self.assertEqual(Everything.test_int32(GObject.G_MININT32),
121                          GObject.G_MININT32)
122         self.assertRaises(OverflowError, Everything.test_int32, GObject.G_MAXINT32 + 1)
123
124         self.assertEqual(Everything.test_uint32(GObject.G_MAXUINT32),
125                          GObject.G_MAXUINT32)
126         self.assertEqual(Everything.test_uint32(0), 0)
127         self.assertRaises(OverflowError, Everything.test_uint32, -1)
128         self.assertRaises(OverflowError, Everything.test_uint32, GObject.G_MAXUINT32 + 1)
129
130     def test_int64(self):
131         self.assertEqual(Everything.test_int64(GObject.G_MAXINT64),
132                          GObject.G_MAXINT64)
133         self.assertEqual(Everything.test_int64(GObject.G_MININT64),
134                          GObject.G_MININT64)
135         self.assertRaises(OverflowError, Everything.test_int64, GObject.G_MAXINT64 + 1)
136
137         self.assertEqual(Everything.test_uint64(GObject.G_MAXUINT64),
138                          GObject.G_MAXUINT64)
139         self.assertEqual(Everything.test_uint64(0), 0)
140         self.assertRaises(OverflowError, Everything.test_uint64, -1)
141         self.assertRaises(OverflowError, Everything.test_uint64, GObject.G_MAXUINT64 + 1)
142
143     def test_int(self):
144         self.assertEqual(Everything.test_int(GObject.G_MAXINT),
145                          GObject.G_MAXINT)
146         self.assertEqual(Everything.test_int(GObject.G_MININT),
147                          GObject.G_MININT)
148         self.assertRaises(OverflowError, Everything.test_int, GObject.G_MAXINT + 1)
149
150         self.assertEqual(Everything.test_uint(GObject.G_MAXUINT),
151                          GObject.G_MAXUINT)
152         self.assertEqual(Everything.test_uint(0), 0)
153         self.assertRaises(OverflowError, Everything.test_uint, -1)
154         self.assertRaises(OverflowError, Everything.test_uint, GObject.G_MAXUINT + 1)
155
156     def test_short(self):
157         self.assertEqual(Everything.test_short(GObject.G_MAXSHORT),
158                          GObject.G_MAXSHORT)
159         self.assertEqual(Everything.test_short(GObject.G_MINSHORT),
160                          GObject.G_MINSHORT)
161         self.assertRaises(OverflowError, Everything.test_short, GObject.G_MAXSHORT + 1)
162
163         self.assertEqual(Everything.test_ushort(GObject.G_MAXUSHORT),
164                          GObject.G_MAXUSHORT)
165         self.assertEqual(Everything.test_ushort(0), 0)
166         self.assertRaises(OverflowError, Everything.test_ushort, -1)
167         self.assertRaises(OverflowError, Everything.test_ushort, GObject.G_MAXUSHORT + 1)
168
169     def test_long(self):
170         self.assertEqual(Everything.test_long(GObject.G_MAXLONG),
171                          GObject.G_MAXLONG)
172         self.assertEqual(Everything.test_long(GObject.G_MINLONG),
173                          GObject.G_MINLONG)
174         self.assertRaises(OverflowError, Everything.test_long, GObject.G_MAXLONG + 1)
175
176         self.assertEqual(Everything.test_ulong(GObject.G_MAXULONG),
177                          GObject.G_MAXULONG)
178         self.assertEqual(Everything.test_ulong(0), 0)
179         self.assertRaises(OverflowError, Everything.test_ulong, -1)
180         self.assertRaises(OverflowError, Everything.test_ulong, GObject.G_MAXULONG + 1)
181
182     def test_size(self):
183         self.assertEqual(Everything.test_ssize(GObject.G_MAXSSIZE),
184                          GObject.G_MAXSSIZE)
185         self.assertEqual(Everything.test_ssize(GObject.G_MINSSIZE),
186                          GObject.G_MINSSIZE)
187         self.assertRaises(OverflowError, Everything.test_ssize, GObject.G_MAXSSIZE + 1)
188
189         self.assertEqual(Everything.test_size(GObject.G_MAXSIZE),
190                          GObject.G_MAXSIZE)
191         self.assertEqual(Everything.test_size(0), 0)
192         self.assertRaises(OverflowError, Everything.test_size, -1)
193         self.assertRaises(OverflowError, Everything.test_size, GObject.G_MAXSIZE + 1)
194
195     def test_timet(self):
196         self.assertEqual(Everything.test_timet(42), 42)
197         self.assertRaises(OverflowError, Everything.test_timet, GObject.G_MAXUINT64 + 1)
198
199     def test_unichar(self):
200         self.assertEqual("c", Everything.test_unichar("c"))
201
202         if sys.version_info < (3, 0):
203             self.assertEqual(UNICHAR, Everything.test_unichar(PY2_UNICODE_UNICHAR))
204         self.assertEqual(UNICHAR, Everything.test_unichar(UNICHAR))
205         self.assertRaises(TypeError, Everything.test_unichar, "")
206         self.assertRaises(TypeError, Everything.test_unichar, "morethanonechar")
207
208     def test_float(self):
209         self.assertEqual(Everything.test_float(GObject.G_MAXFLOAT),
210                          GObject.G_MAXFLOAT)
211         self.assertEqual(Everything.test_float(GObject.G_MINFLOAT),
212                          GObject.G_MINFLOAT)
213         self.assertRaises(OverflowError, Everything.test_float, GObject.G_MAXFLOAT * 2)
214
215     def test_double(self):
216         self.assertEqual(Everything.test_double(GObject.G_MAXDOUBLE),
217                          GObject.G_MAXDOUBLE)
218         self.assertEqual(Everything.test_double(GObject.G_MINDOUBLE),
219                          GObject.G_MINDOUBLE)
220
221         (two, three) = Everything.test_multi_double_args(2.5)
222         self.assertAlmostEqual(two, 5.0)
223         self.assertAlmostEqual(three, 7.5)
224
225     def test_value(self):
226         self.assertEqual(Everything.test_int_value_arg(GObject.G_MAXINT), GObject.G_MAXINT)
227         self.assertEqual(Everything.test_value_return(GObject.G_MAXINT), GObject.G_MAXINT)
228
229     def test_variant(self):
230         v = Everything.test_gvariant_i()
231         self.assertEqual(v.get_type_string(), 'i')
232         self.assertEqual(v.get_int32(), 1)
233
234         v = Everything.test_gvariant_s()
235         self.assertEqual(v.get_type_string(), 's')
236         self.assertEqual(v.get_string(), 'one')
237
238         v = Everything.test_gvariant_v()
239         self.assertEqual(v.get_type_string(), 'v')
240         vi = v.get_variant()
241         self.assertEqual(vi.get_type_string(), 's')
242         self.assertEqual(vi.get_string(), 'contents')
243
244         v = Everything.test_gvariant_as()
245         self.assertEqual(v.get_type_string(), 'as')
246         self.assertEqual(v.get_strv(), ['one', 'two', 'three'])
247
248         v = Everything.test_gvariant_asv()
249         self.assertEqual(v.get_type_string(), 'a{sv}')
250         self.assertEqual(v.lookup_value('nosuchkey', None), None)
251         name = v.lookup_value('name', None)
252         self.assertEqual(name.get_string(), 'foo')
253         timeout = v.lookup_value('timeout', None)
254         self.assertEqual(timeout.get_int32(), 10)
255
256     def test_string(self):
257         const_str = b'const \xe2\x99\xa5 utf8'
258         if sys.version_info >= (3, 0):
259             const_str = const_str.decode('UTF-8')
260         noconst_str = 'non' + const_str
261
262         self.assertEqual(Everything.test_utf8_const_return(), const_str)
263         self.assertEqual(Everything.test_utf8_nonconst_return(), noconst_str)
264         self.assertEqual(Everything.test_utf8_out(), noconst_str)
265
266         Everything.test_utf8_const_in(const_str)
267         self.assertEqual(Everything.test_utf8_inout(const_str), noconst_str)
268
269         self.assertEqual(Everything.test_filename_return(), ['åäö', '/etc/fstab'])
270
271         # returns g_utf8_strlen() in out argument
272         self.assertEqual(Everything.test_int_out_utf8(''), 0)
273         self.assertEqual(Everything.test_int_out_utf8('hello world'), 11)
274         self.assertEqual(Everything.test_int_out_utf8('åäö'), 3)
275
276         self.assertEqual(Everything.test_utf8_out_out(), ('first', 'second'))
277         self.assertEqual(Everything.test_utf8_out_nonconst_return(), ('first', 'second'))
278
279     def test_enum(self):
280         self.assertEqual(Everything.test_enum_param(Everything.TestEnum.VALUE1), 'value1')
281         self.assertEqual(Everything.test_enum_param(Everything.TestEnum.VALUE3), 'value3')
282         self.assertRaises(TypeError, Everything.test_enum_param, 'hello')
283
284     # FIXME: ValueError: invalid enum value: 2147483648
285     @unittest.expectedFailure
286     def test_enum_unsigned(self):
287         self.assertEqual(Everything.test_unsigned_enum_param(Everything.TestEnumUnsigned.VALUE1), 'value1')
288         self.assertEqual(Everything.test_unsigned_enum_param(Everything.TestEnumUnsigned.VALUE3), 'value3')
289         self.assertRaises(TypeError, Everything.test_unsigned_enum_param, 'hello')
290
291     def test_flags(self):
292         result = Everything.global_get_flags_out()
293         # assert that it's not an int
294         self.assertEqual(type(result), Everything.TestFlags)
295         self.assertEqual(result, Everything.TestFlags.FLAG1 | Everything.TestFlags.FLAG3)
296
297     def test_floating(self):
298         e = Everything.TestFloating()
299         self.assertEqual(e.__grefcount__, 1)
300
301         e = GObject.new(Everything.TestFloating)
302         self.assertEqual(e.__grefcount__, 1)
303
304         e = Everything.TestFloating.new()
305         self.assertEqual(e.__grefcount__, 1)
306
307     def test_caller_allocates(self):
308         struct_a = Everything.TestStructA()
309         struct_a.some_int = 10
310         struct_a.some_int8 = 21
311         struct_a.some_double = 3.14
312         struct_a.some_enum = Everything.TestEnum.VALUE3
313
314         struct_a_clone = struct_a.clone()
315         self.assertTrue(struct_a != struct_a_clone)
316         self.assertEqual(struct_a.some_int, struct_a_clone.some_int)
317         self.assertEqual(struct_a.some_int8, struct_a_clone.some_int8)
318         self.assertEqual(struct_a.some_double, struct_a_clone.some_double)
319         self.assertEqual(struct_a.some_enum, struct_a_clone.some_enum)
320
321         struct_b = Everything.TestStructB()
322         struct_b.some_int8 = 8
323         struct_b.nested_a.some_int = 20
324         struct_b.nested_a.some_int8 = 12
325         struct_b.nested_a.some_double = 333.3333
326         struct_b.nested_a.some_enum = Everything.TestEnum.VALUE2
327
328         struct_b_clone = struct_b.clone()
329         self.assertTrue(struct_b != struct_b_clone)
330         self.assertEqual(struct_b.some_int8, struct_b_clone.some_int8)
331         self.assertEqual(struct_b.nested_a.some_int, struct_b_clone.nested_a.some_int)
332         self.assertEqual(struct_b.nested_a.some_int8, struct_b_clone.nested_a.some_int8)
333         self.assertEqual(struct_b.nested_a.some_double, struct_b_clone.nested_a.some_double)
334         self.assertEqual(struct_b.nested_a.some_enum, struct_b_clone.nested_a.some_enum)
335
336         struct_a = Everything.test_struct_a_parse('ignored')
337         self.assertEqual(struct_a.some_int, 23)
338
339     def test_wrong_type_of_arguments(self):
340         try:
341             Everything.test_int8()
342         except TypeError:
343             (e_type, e) = sys.exc_info()[:2]
344             self.assertEqual(e.args, ("test_int8() takes exactly 1 argument (0 given)",))
345
346     def test_gtypes(self):
347         gchararray_gtype = GObject.type_from_name('gchararray')
348         gtype = Everything.test_gtype(str)
349         self.assertEqual(gchararray_gtype, gtype)
350         gtype = Everything.test_gtype('gchararray')
351         self.assertEqual(gchararray_gtype, gtype)
352         gobject_gtype = GObject.GObject.__gtype__
353         gtype = Everything.test_gtype(GObject.GObject)
354         self.assertEqual(gobject_gtype, gtype)
355         gtype = Everything.test_gtype('GObject')
356         self.assertEqual(gobject_gtype, gtype)
357         self.assertRaises(TypeError, Everything.test_gtype, 'invalidgtype')
358
359         class NotARegisteredClass(object):
360             pass
361
362         self.assertRaises(TypeError, Everything.test_gtype, NotARegisteredClass)
363
364         class ARegisteredClass(GObject.GObject):
365             __gtype_name__ = 'EverythingTestsARegisteredClass'
366
367         gtype = Everything.test_gtype('EverythingTestsARegisteredClass')
368         self.assertEqual(ARegisteredClass.__gtype__, gtype)
369         gtype = Everything.test_gtype(ARegisteredClass)
370         self.assertEqual(ARegisteredClass.__gtype__, gtype)
371         self.assertRaises(TypeError, Everything.test_gtype, 'ARegisteredClass')
372
373     def test_dir(self):
374         attr_list = dir(Everything)
375
376         # test that typelib attributes are listed
377         self.assertTrue('TestStructA' in attr_list)
378
379         # test that class attributes and methods are listed
380         self.assertTrue('__class__' in attr_list)
381         self.assertTrue('__dir__' in attr_list)
382         self.assertTrue('__repr__' in attr_list)
383
384         # test that instance members are listed
385         self.assertTrue('_namespace' in attr_list)
386         self.assertTrue('_version' in attr_list)
387
388         # test that there are no duplicates returned
389         self.assertEqual(len(attr_list), len(set(attr_list)))
390
391     def test_array(self):
392         self.assertEqual(Everything.test_array_int_in([]), 0)
393         self.assertEqual(Everything.test_array_int_in([1, 5, -2]), 4)
394         self.assertEqual(Everything.test_array_int_out(), [0, 1, 2, 3, 4])
395         self.assertEqual(Everything.test_array_int_full_out(), [0, 1, 2, 3, 4])
396         self.assertEqual(Everything.test_array_int_none_out(), [1, 2, 3, 4, 5])
397         self.assertEqual(Everything.test_array_int_inout([1, 5, 42, -8]), [6, 43, -7])
398
399         if sys.version_info >= (3, 0):
400             self.assertEqual(Everything.test_array_gint8_in(b'\x01\x03\x05'), 9)
401         self.assertEqual(Everything.test_array_gint8_in([1, 3, 5, -50]), -41)
402         self.assertEqual(Everything.test_array_gint16_in([256, 257, -1000, 10000]), 9513)
403         self.assertEqual(Everything.test_array_gint32_in([30000, 1, -2]), 29999)
404         self.assertEqual(Everything.test_array_gint64_in([2 ** 33, 2 ** 34]), 2 ** 33 + 2 ** 34)
405
406         self.assertEqual(Everything.test_array_gtype_in(
407             [GObject.TYPE_STRING, GObject.TYPE_UINT64, GObject.TYPE_VARIANT]),
408             '[gchararray,guint64,GVariant,]')
409
410     def test_array_fixed_size(self):
411         # fixed length of 5
412         self.assertEqual(Everything.test_array_fixed_size_int_in([1, 2, -10, 5, 3]), 1)
413         self.assertRaises(ValueError, Everything.test_array_fixed_size_int_in, [1, 2, 3, 4])
414         self.assertRaises(ValueError, Everything.test_array_fixed_size_int_in, [1, 2, 3, 4, 5, 6])
415
416         self.assertEqual(Everything.test_array_fixed_size_int_out(), [0, 1, 2, 3, 4])
417         self.assertEqual(Everything.test_array_fixed_size_int_return(), [0, 1, 2, 3, 4])
418
419     def test_ptrarray(self):
420         # transfer container
421         result = Everything.test_garray_container_return()
422         self.assertEqual(result, ['regress'])
423         result = None
424
425         # transfer full
426         result = Everything.test_garray_full_return()
427         self.assertEqual(result, ['regress'])
428         result = None
429
430     def test_strv(self):
431         self.assertEqual(Everything.test_strv_out(), ['thanks', 'for', 'all', 'the', 'fish'])
432         self.assertEqual(Everything.test_strv_out_c(), ['thanks', 'for', 'all', 'the', 'fish'])
433         self.assertEqual(Everything.test_strv_out_container(), ['1', '2', '3'])
434         self.assertEqual(Everything.test_strv_outarg(), ['1', '2', '3'])
435
436         self.assertEqual(Everything.test_strv_in_gvalue(), ['one', 'two', 'three'])
437
438         Everything.test_strv_in(['1', '2', '3'])
439
440     def test_glist(self):
441         self.assertEqual(Everything.test_glist_nothing_return(), ['1', '2', '3'])
442         self.assertEqual(Everything.test_glist_nothing_return2(), ['1', '2', '3'])
443         self.assertEqual(Everything.test_glist_container_return(), ['1', '2', '3'])
444         self.assertEqual(Everything.test_glist_everything_return(), ['1', '2', '3'])
445
446         Everything.test_glist_nothing_in(['1', '2', '3'])
447         Everything.test_glist_nothing_in2(['1', '2', '3'])
448
449     def test_gslist(self):
450         self.assertEqual(Everything.test_gslist_nothing_return(), ['1', '2', '3'])
451         self.assertEqual(Everything.test_gslist_nothing_return2(), ['1', '2', '3'])
452         self.assertEqual(Everything.test_gslist_container_return(), ['1', '2', '3'])
453         self.assertEqual(Everything.test_gslist_everything_return(), ['1', '2', '3'])
454
455         Everything.test_gslist_nothing_in(['1', '2', '3'])
456         Everything.test_gslist_nothing_in2(['1', '2', '3'])
457
458     def test_hash_return(self):
459         expected = {'foo': 'bar', 'baz': 'bat', 'qux': 'quux'}
460
461         self.assertEqual(Everything.test_ghash_null_return(), None)
462         self.assertEqual(Everything.test_ghash_nothing_return(), expected)
463         self.assertEqual(Everything.test_ghash_nothing_return(), expected)
464         self.assertEqual(Everything.test_ghash_container_return(), expected)
465         self.assertEqual(Everything.test_ghash_everything_return(), expected)
466
467         result = Everything.test_ghash_gvalue_return()
468         self.assertEqual(result['integer'], 12)
469         self.assertEqual(result['boolean'], True)
470         self.assertEqual(result['string'], 'some text')
471         self.assertEqual(result['strings'], ['first', 'second', 'third'])
472         self.assertEqual(result['flags'], Everything.TestFlags.FLAG1 | Everything.TestFlags.FLAG3)
473         self.assertEqual(result['enum'], Everything.TestEnum.VALUE2)
474         result = None
475
476     # FIXME: CRITICAL **: Unsupported type ghash
477     def disabled_test_hash_return_nested(self):
478         self.assertEqual(Everything.test_ghash_nested_everything_return(), {})
479         self.assertEqual(Everything.test_ghash_nested_everything_return2(), {})
480
481     def test_hash_in(self):
482         expected = {'foo': 'bar', 'baz': 'bat', 'qux': 'quux'}
483
484         Everything.test_ghash_nothing_in(expected)
485         Everything.test_ghash_nothing_in2(expected)
486
487     def test_hash_in_with_typed_strv(self):
488         class GStrv(list):
489             __gtype__ = GObject.TYPE_STRV
490
491         data = {'integer': 12,
492                 'boolean': True,
493                 'string': 'some text',
494                 'strings': GStrv(['first', 'second', 'third']),
495                 'flags': Everything.TestFlags.FLAG1 | Everything.TestFlags.FLAG3,
496                 'enum': Everything.TestEnum.VALUE2,
497                }
498         Everything.test_ghash_gvalue_in(data)
499         data = None
500
501     def test_hash_in_with_gvalue_strv(self):
502         data = {'integer': 12,
503                 'boolean': True,
504                 'string': 'some text',
505                 'strings': GObject.Value(GObject.TYPE_STRV, ['first', 'second', 'third']),
506                 'flags': Everything.TestFlags.FLAG1 | Everything.TestFlags.FLAG3,
507                 'enum': Everything.TestEnum.VALUE2,
508                }
509         Everything.test_ghash_gvalue_in(data)
510         data = None
511
512     def test_struct_gpointer(self):
513         glist = GLib.List()
514         raw = RawGList.from_wrapped(glist)
515
516         # Note that pointer fields use 0 for NULL in PyGObject and None in ctypes
517         self.assertEqual(glist.data, 0)
518         self.assertEqual(raw.contents.data, None)
519
520         glist.data = 123
521         self.assertEqual(glist.data, 123)
522         self.assertEqual(raw.contents.data, 123)
523
524         glist.data = None
525         self.assertEqual(glist.data, 0)
526         self.assertEqual(raw.contents.data, None)
527
528         # Setting to anything other than an int should raise
529         self.assertRaises(TypeError, setattr, glist.data, 'nan')
530         self.assertRaises(TypeError, setattr, glist.data, object())
531         self.assertRaises(TypeError, setattr, glist.data, 123.321)
532
533     def test_struct_opaque(self):
534         # we should get a sensible error message
535         try:
536             Everything.TestBoxedPrivate()
537             self.fail('allocating disguised struct without default constructor unexpectedly succeeded')
538         except TypeError:
539             (e_type, e_value, e_tb) = sys.exc_info()
540             self.assertEqual(e_type, TypeError)
541             self.assertTrue('TestBoxedPrivate' in str(e_value), str(e_value))
542             self.assertTrue('constructor' in str(e_value), str(e_value))
543             tb = ''.join(traceback.format_exception(e_type, e_value, e_tb))
544             self.assertTrue('tests/test_everything.py", line' in tb, tb)
545
546
547 @unittest.skipUnless(has_cairo, 'built without cairo support')
548 class TestNullableArgs(unittest.TestCase):
549     def test_in_nullable_hash(self):
550         Everything.test_ghash_null_in(None)
551
552     def test_in_nullable_list(self):
553         Everything.test_gslist_null_in(None)
554         Everything.test_glist_null_in(None)
555         Everything.test_gslist_null_in([])
556         Everything.test_glist_null_in([])
557
558     def test_in_nullable_array(self):
559         Everything.test_array_int_null_in(None)
560         Everything.test_array_int_null_in([])
561
562     def test_in_nullable_string(self):
563         Everything.test_utf8_null_in(None)
564
565     def test_in_nullable_object(self):
566         Everything.func_obj_null_in(None)
567
568     def test_out_nullable_hash(self):
569         self.assertEqual(None, Everything.test_ghash_null_out())
570
571     def test_out_nullable_list(self):
572         self.assertEqual([], Everything.test_gslist_null_out())
573         self.assertEqual([], Everything.test_glist_null_out())
574
575     def test_out_nullable_array(self):
576         self.assertEqual([], Everything.test_array_int_null_out())
577
578     def test_out_nullable_string(self):
579         self.assertEqual(None, Everything.test_utf8_null_out())
580
581     def test_out_nullable_object(self):
582         self.assertEqual(None, Everything.TestObj.null_out())
583
584
585 @unittest.skipUnless(has_cairo, 'built without cairo support')
586 class TestCallbacks(unittest.TestCase):
587     called = False
588     main_loop = GLib.MainLoop()
589
590     def test_callback(self):
591         TestCallbacks.called = False
592
593         def callback():
594             TestCallbacks.called = True
595
596         Everything.test_simple_callback(callback)
597         self.assertTrue(TestCallbacks.called)
598
599     def test_callback_exception(self):
600         """
601         This test ensures that we get errors from callbacks correctly
602         and in particular that we do not segv when callbacks fail
603         """
604         def callback():
605             x = 1 / 0
606             self.fail('unexpected surviving zero divsion:' + str(x))
607
608         # note that we do NOT expect the ZeroDivisionError to be propagated
609         # through from the callback, as it crosses the Python<->C boundary
610         # twice. (See GNOME #616279)
611         Everything.test_simple_callback(callback)
612
613     def test_double_callback_exception(self):
614         """
615         This test ensures that we get errors from callbacks correctly
616         and in particular that we do not segv when callbacks fail
617         """
618         def badcallback():
619             x = 1 / 0
620             self.fail('unexpected surviving zero divsion:' + str(x))
621
622         def callback():
623             Everything.test_boolean(True)
624             Everything.test_boolean(False)
625             Everything.test_simple_callback(badcallback())
626
627         # note that we do NOT expect the ZeroDivisionError to be propagated
628         # through from the callback, as it crosses the Python<->C boundary
629         # twice. (See GNOME #616279)
630         Everything.test_simple_callback(callback)
631
632     def test_return_value_callback(self):
633         TestCallbacks.called = False
634
635         def callback():
636             TestCallbacks.called = True
637             return 44
638
639         self.assertEqual(Everything.test_callback(callback), 44)
640         self.assertTrue(TestCallbacks.called)
641
642     def test_callback_scope_async(self):
643         TestCallbacks.called = False
644         ud = 'Test Value 44'
645
646         def callback(user_data):
647             self.assertEqual(user_data, ud)
648             TestCallbacks.called = True
649             return 44
650
651         ud_refcount = sys.getrefcount(ud)
652         callback_refcount = sys.getrefcount(callback)
653
654         self.assertEqual(Everything.test_callback_async(callback, ud), None)
655         # Callback should not have run and the ref count is increased by 1
656         self.assertEqual(TestCallbacks.called, False)
657         self.assertEqual(sys.getrefcount(callback), callback_refcount + 1)
658         self.assertEqual(sys.getrefcount(ud), ud_refcount + 1)
659
660         # test_callback_thaw_async will run the callback previously supplied.
661         # references should be auto decremented after this call.
662         self.assertEqual(Everything.test_callback_thaw_async(), 44)
663         self.assertTrue(TestCallbacks.called)
664
665         # Make sure refcounts are returned to normal
666         self.assertEqual(sys.getrefcount(callback), callback_refcount)
667         self.assertEqual(sys.getrefcount(ud), ud_refcount)
668
669     def test_callback_scope_call_multi(self):
670         # This tests a callback that gets called multiple times from a
671         # single scope call in python.
672         TestCallbacks.called = 0
673
674         def callback():
675             TestCallbacks.called += 1
676             return TestCallbacks.called
677
678         refcount = sys.getrefcount(callback)
679         result = Everything.test_multi_callback(callback)
680         # first callback should give 1, second 2, and the function sums them up
681         self.assertEqual(result, 3)
682         self.assertEqual(TestCallbacks.called, 2)
683         self.assertEqual(sys.getrefcount(callback), refcount)
684
685     def test_callback_scope_call_array(self):
686         # This tests a callback that gets called multiple times from a
687         # single scope call in python with array arguments
688         TestCallbacks.callargs = []
689
690         # FIXME: would be cleaner without the explicit length args:
691         # def callback(one, two):
692         def callback(one, one_length, two, two_length):
693             TestCallbacks.callargs.append((one, two))
694             return len(TestCallbacks.callargs)
695
696         refcount = sys.getrefcount(callback)
697         result = Everything.test_array_callback(callback)
698         # first callback should give 1, second 2, and the function sums them up
699         self.assertEqual(result, 3)
700         self.assertEqual(TestCallbacks.callargs,
701                          [([-1, 0, 1, 2], ['one', 'two', 'three'])] * 2)
702         self.assertEqual(sys.getrefcount(callback), refcount)
703
704     def test_callback_userdata(self):
705         TestCallbacks.called = 0
706
707         def callback(userdata):
708             self.assertEqual(userdata, "Test%d" % TestCallbacks.called)
709             TestCallbacks.called += 1
710             return TestCallbacks.called
711
712         for i in range(100):
713             val = Everything.test_callback_user_data(callback, "Test%d" % i)
714             self.assertEqual(val, i + 1)
715
716         self.assertEqual(TestCallbacks.called, 100)
717
718     def test_callback_userdata_no_user_data(self):
719         TestCallbacks.called = 0
720
721         def callback():
722             TestCallbacks.called += 1
723             return TestCallbacks.called
724
725         for i in range(100):
726             val = Everything.test_callback_user_data(callback)
727             self.assertEqual(val, i + 1)
728
729         self.assertEqual(TestCallbacks.called, 100)
730
731     def test_callback_userdata_varargs(self):
732         TestCallbacks.called = 0
733         collected_user_data = []
734
735         def callback(a, b):
736             collected_user_data.extend([a, b])
737             TestCallbacks.called += 1
738             return TestCallbacks.called
739
740         for i in range(10):
741             val = Everything.test_callback_user_data(callback, 1, 2)
742             self.assertEqual(val, i + 1)
743
744         self.assertEqual(TestCallbacks.called, 10)
745         self.assertSequenceEqual(collected_user_data, [1, 2] * 10)
746
747     def test_callback_userdata_as_kwarg_tuple(self):
748         TestCallbacks.called = 0
749         collected_user_data = []
750
751         def callback(user_data):
752             collected_user_data.extend(user_data)
753             TestCallbacks.called += 1
754             return TestCallbacks.called
755
756         for i in range(10):
757             val = Everything.test_callback_user_data(callback, user_data=(1, 2))
758             self.assertEqual(val, i + 1)
759
760         self.assertEqual(TestCallbacks.called, 10)
761         self.assertSequenceEqual(collected_user_data, [1, 2] * 10)
762
763     def test_callback_user_data_middle_none(self):
764         cb_info = {}
765
766         def callback(userdata):
767             cb_info['called'] = True
768             cb_info['userdata'] = userdata
769             return 1
770
771         (y, z, q) = Everything.test_torture_signature_2(
772             42, callback, None, 'some string', 3)
773         self.assertEqual(y, 42)
774         self.assertEqual(z, 84)
775         self.assertEqual(q, 14)
776         self.assertTrue(cb_info['called'])
777         self.assertEqual(cb_info['userdata'], None)
778
779     def test_callback_user_data_middle_single(self):
780         cb_info = {}
781
782         def callback(userdata):
783             cb_info['called'] = True
784             cb_info['userdata'] = userdata
785             return 1
786
787         (y, z, q) = Everything.test_torture_signature_2(
788             42, callback, 'User Data', 'some string', 3)
789         self.assertEqual(y, 42)
790         self.assertEqual(z, 84)
791         self.assertEqual(q, 14)
792         self.assertTrue(cb_info['called'])
793         self.assertEqual(cb_info['userdata'], 'User Data')
794
795     def test_callback_user_data_middle_tuple(self):
796         cb_info = {}
797
798         def callback(userdata):
799             cb_info['called'] = True
800             cb_info['userdata'] = userdata
801             return 1
802
803         (y, z, q) = Everything.test_torture_signature_2(
804             42, callback, (-5, 'User Data'), 'some string', 3)
805         self.assertEqual(y, 42)
806         self.assertEqual(z, 84)
807         self.assertEqual(q, 14)
808         self.assertTrue(cb_info['called'])
809         self.assertEqual(cb_info['userdata'], (-5, 'User Data'))
810
811     def test_async_ready_callback(self):
812         TestCallbacks.called = False
813         TestCallbacks.main_loop = GLib.MainLoop()
814
815         def callback(obj, result, user_data):
816             TestCallbacks.main_loop.quit()
817             TestCallbacks.called = True
818
819         Everything.test_async_ready_callback(callback)
820
821         TestCallbacks.main_loop.run()
822
823         self.assertTrue(TestCallbacks.called)
824
825     def test_callback_scope_notified_with_destroy(self):
826         TestCallbacks.called = 0
827         ud = 'Test scope notified data 33'
828
829         def callback(user_data):
830             self.assertEqual(user_data, ud)
831             TestCallbacks.called += 1
832             return 33
833
834         value_refcount = sys.getrefcount(ud)
835         callback_refcount = sys.getrefcount(callback)
836
837         # Callback is immediately called.
838         for i in range(100):
839             res = Everything.test_callback_destroy_notify(callback, ud)
840             self.assertEqual(res, 33)
841
842         self.assertEqual(TestCallbacks.called, 100)
843         self.assertEqual(sys.getrefcount(callback), callback_refcount + 100)
844         self.assertEqual(sys.getrefcount(ud), value_refcount + 100)
845
846         # thaw will call the callback again, this time resources should be freed
847         self.assertEqual(Everything.test_callback_thaw_notifications(), 33 * 100)
848         self.assertEqual(TestCallbacks.called, 200)
849         self.assertEqual(sys.getrefcount(callback), callback_refcount)
850         self.assertEqual(sys.getrefcount(ud), value_refcount)
851
852     def test_callback_scope_notified_with_destroy_no_user_data(self):
853         TestCallbacks.called = 0
854
855         def callback(user_data):
856             self.assertEqual(user_data, None)
857             TestCallbacks.called += 1
858             return 34
859
860         callback_refcount = sys.getrefcount(callback)
861
862         # Run with warning as exception
863         with warnings.catch_warnings(record=True) as w:
864             warnings.simplefilter("error")
865             self.assertRaises(RuntimeWarning,
866                               Everything.test_callback_destroy_notify_no_user_data,
867                               callback)
868
869         self.assertEqual(TestCallbacks.called, 0)
870         self.assertEqual(sys.getrefcount(callback), callback_refcount)
871
872         # Run with warning as warning
873         with warnings.catch_warnings(record=True) as w:
874             # Cause all warnings to always be triggered.
875             warnings.simplefilter("default")
876             # Trigger a warning.
877             res = Everything.test_callback_destroy_notify_no_user_data(callback)
878             # Verify some things
879             self.assertEqual(len(w), 1)
880             self.assertTrue(issubclass(w[-1].category, RuntimeWarning))
881             self.assertTrue('Callables passed to' in str(w[-1].message))
882
883         self.assertEqual(res, 34)
884         self.assertEqual(TestCallbacks.called, 1)
885         self.assertEqual(sys.getrefcount(callback), callback_refcount + 1)
886
887         # thaw will call the callback again,
888         # refcount will not go down without user_data parameter
889         self.assertEqual(Everything.test_callback_thaw_notifications(), 34)
890         self.assertEqual(TestCallbacks.called, 2)
891         self.assertEqual(sys.getrefcount(callback), callback_refcount + 1)
892
893     def test_callback_in_methods(self):
894         object_ = Everything.TestObj()
895
896         def callback():
897             TestCallbacks.called = True
898             return 42
899
900         TestCallbacks.called = False
901         object_.instance_method_callback(callback)
902         self.assertTrue(TestCallbacks.called)
903
904         TestCallbacks.called = False
905         Everything.TestObj.static_method_callback(callback)
906         self.assertTrue(TestCallbacks.called)
907
908         def callbackWithUserData(user_data):
909             TestCallbacks.called += 1
910             return 42
911
912         TestCallbacks.called = 0
913         Everything.TestObj.new_callback(callbackWithUserData, None)
914         self.assertEqual(TestCallbacks.called, 1)
915         # Note: using "new_callback" adds the notification to the same global
916         # list as Everything.test_callback_destroy_notify, so thaw the list
917         # so we don't get confusion between tests.
918         self.assertEqual(Everything.test_callback_thaw_notifications(), 42)
919         self.assertEqual(TestCallbacks.called, 2)
920
921     def test_callback_none(self):
922         # make sure this doesn't assert or crash
923         Everything.test_simple_callback(None)
924
925     def test_callback_gerror(self):
926         def callback(error):
927             self.assertEqual(error.message, 'regression test error')
928             self.assertTrue('g-io' in error.domain)
929             self.assertEqual(error.code, Gio.IOErrorEnum.NOT_SUPPORTED)
930             TestCallbacks.called = True
931
932         TestCallbacks.called = False
933         Everything.test_gerror_callback(callback)
934         self.assertTrue(TestCallbacks.called)
935
936     def test_callback_null_gerror(self):
937         def callback(error):
938             self.assertEqual(error, None)
939             TestCallbacks.called = True
940
941         TestCallbacks.called = False
942         Everything.test_null_gerror_callback(callback)
943         self.assertTrue(TestCallbacks.called)
944
945     def test_callback_owned_gerror(self):
946         def callback(error):
947             self.assertEqual(error.message, 'regression test owned error')
948             self.assertTrue('g-io' in error.domain)
949             self.assertEqual(error.code, Gio.IOErrorEnum.PERMISSION_DENIED)
950             TestCallbacks.called = True
951
952         TestCallbacks.called = False
953         Everything.test_owned_gerror_callback(callback)
954         self.assertTrue(TestCallbacks.called)
955
956     def test_callback_hashtable(self):
957         def callback(data):
958             self.assertEqual(data, mydict)
959             mydict['new'] = 42
960             TestCallbacks.called = True
961
962         mydict = {'foo': 1, 'bar': 2}
963         TestCallbacks.called = False
964         Everything.test_hash_table_callback(mydict, callback)
965         self.assertTrue(TestCallbacks.called)
966         self.assertEqual(mydict, {'foo': 1, 'bar': 2, 'new': 42})
967
968
969 @unittest.skipUnless(has_cairo, 'built without cairo support')
970 class TestClosures(unittest.TestCase):
971     def test_no_arg(self):
972         def callback():
973             self.called = True
974             return 42
975
976         self.called = False
977         result = Everything.test_closure(callback)
978         self.assertTrue(self.called)
979         self.assertEqual(result, 42)
980
981     def test_int_arg(self):
982         def callback(num):
983             self.called = True
984             return num + 1
985
986         self.called = False
987         result = Everything.test_closure_one_arg(callback, 42)
988         self.assertTrue(self.called)
989         self.assertEqual(result, 43)
990
991     def test_variant(self):
992         def callback(variant):
993             self.called = True
994             if variant is None:
995                 return None
996             self.assertEqual(variant.get_type_string(), 'i')
997             return GLib.Variant('i', variant.get_int32() + 1)
998
999         self.called = False
1000         result = Everything.test_closure_variant(callback, GLib.Variant('i', 42))
1001         self.assertTrue(self.called)
1002         self.assertEqual(result.get_type_string(), 'i')
1003         self.assertEqual(result.get_int32(), 43)
1004
1005         self.called = False
1006         result = Everything.test_closure_variant(callback, None)
1007         self.assertTrue(self.called)
1008         self.assertEqual(result, None)
1009
1010         self.called = False
1011         self.assertRaises(TypeError, Everything.test_closure_variant, callback, 'foo')
1012         self.assertFalse(self.called)
1013
1014     def test_variant_wrong_return_type(self):
1015         def callback(variant):
1016             return 'no_variant'
1017
1018         # reset last error
1019         sys.last_type = None
1020
1021         # this does not directly raise an exception (see
1022         # https://bugzilla.gnome.org/show_bug.cgi?id=616279)
1023         result = Everything.test_closure_variant(callback, GLib.Variant('i', 42))
1024         # ... but the result shouldn't be a string
1025         self.assertEqual(result, None)
1026         # and the error should be shown
1027         self.assertEqual(sys.last_type, TypeError)
1028         self.assertTrue('return value' in str(sys.last_value), sys.last_value)
1029
1030
1031 @unittest.skipUnless(has_cairo, 'built without cairo support')
1032 class TestProperties(unittest.TestCase):
1033
1034     def test_basic(self):
1035         object_ = Everything.TestObj()
1036
1037         self.assertEqual(object_.props.int, 0)
1038         object_.props.int = 42
1039         self.assertTrue(isinstance(object_.props.int, int))
1040         self.assertEqual(object_.props.int, 42)
1041
1042         self.assertEqual(object_.props.float, 0.0)
1043         object_.props.float = 42.42
1044         self.assertTrue(isinstance(object_.props.float, float))
1045         self.assertAlmostEqual(object_.props.float, 42.42, places=5)
1046
1047         self.assertEqual(object_.props.double, 0.0)
1048         object_.props.double = 42.42
1049         self.assertTrue(isinstance(object_.props.double, float))
1050         self.assertAlmostEqual(object_.props.double, 42.42, places=5)
1051
1052         self.assertEqual(object_.props.string, None)
1053         object_.props.string = 'mec'
1054         self.assertTrue(isinstance(object_.props.string, str))
1055         self.assertEqual(object_.props.string, 'mec')
1056
1057         self.assertEqual(object_.props.gtype, GObject.TYPE_INVALID)
1058         object_.props.gtype = int
1059         self.assertEqual(object_.props.gtype, GObject.TYPE_INT)
1060
1061     def test_hash_table(self):
1062         object_ = Everything.TestObj()
1063         self.assertEqual(object_.props.hash_table, None)
1064
1065         object_.props.hash_table = {'mec': 56}
1066         self.assertTrue(isinstance(object_.props.hash_table, dict))
1067         self.assertEqual(list(object_.props.hash_table.items())[0], ('mec', 56))
1068
1069     def test_list(self):
1070         object_ = Everything.TestObj()
1071         self.assertEqual(object_.props.list, [])
1072
1073         object_.props.list = ['1', '2', '3']
1074         self.assertTrue(isinstance(object_.props.list, list))
1075         self.assertEqual(object_.props.list, ['1', '2', '3'])
1076
1077     def test_boxed(self):
1078         object_ = Everything.TestObj()
1079         self.assertEqual(object_.props.boxed, None)
1080
1081         boxed = Everything.TestBoxed()
1082         boxed.some_int8 = 42
1083         object_.props.boxed = boxed
1084
1085         self.assertTrue(isinstance(object_.props.boxed, Everything.TestBoxed))
1086         self.assertEqual(object_.props.boxed.some_int8, 42)
1087
1088     def test_boxed_alternative_constructor(self):
1089         boxed = Everything.TestBoxed.new_alternative_constructor1(5)
1090         self.assertEqual(boxed.some_int8, 5)
1091
1092         boxed = Everything.TestBoxed.new_alternative_constructor2(5, 3)
1093         self.assertEqual(boxed.some_int8, 8)
1094
1095         boxed = Everything.TestBoxed.new_alternative_constructor3("-3")
1096         self.assertEqual(boxed.some_int8, -3)
1097
1098     def test_boxed_equality(self):
1099         boxed42 = Everything.TestBoxed.new_alternative_constructor1(42)
1100         boxed5 = Everything.TestBoxed.new_alternative_constructor1(5)
1101         boxed42_2 = Everything.TestBoxed.new_alternative_constructor2(41, 1)
1102
1103         self.assertFalse(boxed42.equals(boxed5))
1104         self.assertTrue(boxed42.equals(boxed42_2))
1105         self.assertTrue(boxed42_2.equals(boxed42))
1106         self.assertTrue(boxed42.equals(boxed42))
1107
1108     def test_boxed_c_equality(self):
1109         boxed = Everything.TestBoxedC()
1110         # TestBoxedC uses refcounting, so we know that
1111         # the pointer is the same when copied
1112         copy = boxed.copy()
1113         self.assertEqual(boxed, copy)
1114         self.assertNotEqual(id(boxed), id(copy))
1115
1116     def test_gtype(self):
1117         object_ = Everything.TestObj()
1118         self.assertEqual(object_.props.gtype, GObject.TYPE_INVALID)
1119         object_.props.gtype = int
1120         self.assertEqual(object_.props.gtype, GObject.TYPE_INT)
1121
1122         object_ = Everything.TestObj(gtype=int)
1123         self.assertEqual(object_.props.gtype, GObject.TYPE_INT)
1124         object_.props.gtype = str
1125         self.assertEqual(object_.props.gtype, GObject.TYPE_STRING)
1126
1127     def test_parent_class(self):
1128         class A(Everything.TestObj):
1129             prop1 = GObject.Property(type=int)
1130
1131         a = A()
1132         a.props.int = 20
1133         self.assertEqual(a.props.int, 20)
1134
1135         # test parent property which needs introspection
1136         a.props.list = ("str1", "str2")
1137         self.assertEqual(a.props.list, ["str1", "str2"])
1138
1139
1140 @unittest.skipUnless(has_cairo, 'built without cairo support')
1141 class TestTortureProfile(unittest.TestCase):
1142     def test_torture_profile(self):
1143         import time
1144         total_time = 0
1145         print("")
1146         object_ = Everything.TestObj()
1147         sys.stdout.write("\ttorture test 1 (10000 iterations): ")
1148
1149         start_time = time.clock()
1150         for i in range(10000):
1151             (y, z, q) = object_.torture_signature_0(5000,
1152                                                     "Torture Test 1",
1153                                                     12345)
1154
1155         end_time = time.clock()
1156         delta_time = end_time - start_time
1157         total_time += delta_time
1158         print("%f secs" % delta_time)
1159
1160         sys.stdout.write("\ttorture test 2 (10000 iterations): ")
1161
1162         start_time = time.clock()
1163         for i in range(10000):
1164             (y, z, q) = Everything.TestObj().torture_signature_0(
1165                 5000, "Torture Test 2", 12345)
1166
1167         end_time = time.clock()
1168         delta_time = end_time - start_time
1169         total_time += delta_time
1170         print("%f secs" % delta_time)
1171
1172         sys.stdout.write("\ttorture test 3 (10000 iterations): ")
1173         start_time = time.clock()
1174         for i in range(10000):
1175             try:
1176                 (y, z, q) = object_.torture_signature_1(
1177                     5000, "Torture Test 3", 12345)
1178             except:
1179                 pass
1180         end_time = time.clock()
1181         delta_time = end_time - start_time
1182         total_time += delta_time
1183         print("%f secs" % delta_time)
1184
1185         sys.stdout.write("\ttorture test 4 (10000 iterations): ")
1186
1187         def callback(userdata):
1188             return 0
1189
1190         userdata = [1, 2, 3, 4]
1191         start_time = time.clock()
1192         for i in range(10000):
1193             (y, z, q) = Everything.test_torture_signature_2(
1194                 5000, callback, userdata, "Torture Test 4", 12345)
1195         end_time = time.clock()
1196         delta_time = end_time - start_time
1197         total_time += delta_time
1198         print("%f secs" % delta_time)
1199         print("\t====")
1200         print("\tTotal: %f sec" % total_time)
1201
1202
1203 @unittest.skipUnless(has_cairo, 'built without cairo support')
1204 class TestAdvancedInterfaces(unittest.TestCase):
1205     def test_array_objs(self):
1206         obj1, obj2 = Everything.test_array_fixed_out_objects()
1207         self.assertTrue(isinstance(obj1, Everything.TestObj))
1208         self.assertTrue(isinstance(obj2, Everything.TestObj))
1209         self.assertNotEqual(obj1, obj2)
1210
1211     def test_obj_skip_return_val(self):
1212         obj = Everything.TestObj()
1213         ret = obj.skip_return_val(50, 42.0, 60, 2, 3)
1214         self.assertEqual(len(ret), 3)
1215         self.assertEqual(ret[0], 51)
1216         self.assertEqual(ret[1], 61)
1217         self.assertEqual(ret[2], 32)
1218
1219     def test_obj_skip_return_val_no_out(self):
1220         obj = Everything.TestObj()
1221         # raises an error for 0, succeeds for any other value
1222         self.assertRaises(GLib.GError, obj.skip_return_val_no_out, 0)
1223
1224         ret = obj.skip_return_val_no_out(1)
1225         self.assertEqual(ret, None)
1226
1227
1228 @unittest.skipUnless(has_cairo, 'built without cairo support')
1229 class TestSignals(unittest.TestCase):
1230     def test_object_param_signal(self):
1231         obj = Everything.TestObj()
1232
1233         def callback(obj, obj_param):
1234             self.assertEqual(obj_param.props.int, 3)
1235             self.assertGreater(obj_param.__grefcount__, 1)
1236             obj.called = True
1237
1238         obj.called = False
1239         obj.connect('sig-with-obj', callback)
1240         obj.emit_sig_with_obj()
1241         self.assertTrue(obj.called)
1242
1243     def test_connect_after(self):
1244         obj = Everything.TestObj()
1245
1246         def callback(obj, obj_param):
1247             obj.called = True
1248
1249         obj.called = False
1250         obj.connect_after('sig-with-obj', callback)
1251         obj.emit_sig_with_obj()
1252         self.assertTrue(obj.called)
1253
1254     def test_connect_object(self):
1255         obj = Everything.TestObj()
1256
1257         def callback(obj, obj_param):
1258             obj.called = True
1259
1260         obj.called = False
1261         obj.connect_object('sig-with-obj', callback, obj)
1262         obj.emit_sig_with_obj()
1263         self.assertTrue(obj.called)
1264
1265     def test_connect_object_after(self):
1266         obj = Everything.TestObj()
1267
1268         def callback(obj, obj_param):
1269             obj.called = True
1270
1271         obj.called = False
1272         obj.connect_object_after('sig-with-obj', callback, obj)
1273         obj.emit_sig_with_obj()
1274         self.assertTrue(obj.called)
1275
1276     def test_int64_param_from_py(self):
1277         obj = Everything.TestObj()
1278
1279         def callback(obj, i):
1280             obj.callback_i = i
1281             return i
1282
1283         obj.callback_i = None
1284         obj.connect('sig-with-int64-prop', callback)
1285         rv = obj.emit('sig-with-int64-prop', GObject.G_MAXINT64)
1286         self.assertEqual(rv, GObject.G_MAXINT64)
1287         self.assertEqual(obj.callback_i, GObject.G_MAXINT64)
1288
1289     def test_uint64_param_from_py(self):
1290         obj = Everything.TestObj()
1291
1292         def callback(obj, i):
1293             obj.callback_i = i
1294             return i
1295
1296         obj.callback_i = None
1297         obj.connect('sig-with-uint64-prop', callback)
1298         rv = obj.emit('sig-with-uint64-prop', GObject.G_MAXUINT64)
1299         self.assertEqual(rv, GObject.G_MAXUINT64)
1300         self.assertEqual(obj.callback_i, GObject.G_MAXUINT64)
1301
1302     def test_int64_param_from_c(self):
1303         obj = Everything.TestObj()
1304
1305         def callback(obj, i):
1306             obj.callback_i = i
1307             return i
1308
1309         obj.callback_i = None
1310
1311         obj.connect('sig-with-int64-prop', callback)
1312         obj.emit_sig_with_int64()
1313         self.assertEqual(obj.callback_i, GObject.G_MAXINT64)
1314
1315     def test_uint64_param_from_c(self):
1316         obj = Everything.TestObj()
1317
1318         def callback(obj, i):
1319             obj.callback_i = i
1320             return i
1321
1322         obj.callback_i = None
1323
1324         obj.connect('sig-with-uint64-prop', callback)
1325         obj.emit_sig_with_uint64()
1326         self.assertEqual(obj.callback_i, GObject.G_MAXUINT64)
1327
1328     def test_intarray_ret(self):
1329         obj = Everything.TestObj()
1330
1331         def callback(obj, i):
1332             obj.callback_i = i
1333             return [i, i + 1]
1334
1335         obj.callback_i = None
1336
1337         try:
1338             obj.connect('sig-with-intarray-ret', callback)
1339         except TypeError as e:
1340             # compat with g-i 1.34.x
1341             if 'unknown signal' in str(e):
1342                 return
1343             raise
1344
1345         rv = obj.emit('sig-with-intarray-ret', 42)
1346         self.assertEqual(obj.callback_i, 42)
1347         self.assertEqual(type(rv), GLib.Array)
1348         self.assertEqual(rv.len, 2)
1349
1350
1351 @unittest.skipUnless(has_cairo, 'built without cairo support')
1352 @unittest.skipUnless(Gtk, 'Gtk not available')
1353 class TestPango(unittest.TestCase):
1354     def test_cairo_font_options(self):
1355         screen = Gtk.Window().get_screen()
1356         font_opts = screen.get_font_options()
1357         self.assertEqual(type(font_opts.get_subpixel_order()), int)