test_everything.py 46.8 KB
Newer Older
Tomeu Vizoso's avatar
Tomeu Vizoso committed
1
# -*- Mode: Python; py-indent-offset: 4 -*-
2
# coding=utf-8
Tomeu Vizoso's avatar
Tomeu Vizoso committed
3
4
5
# vim: tabstop=4 shiftwidth=4 expandtab

import unittest
6
import traceback
7
import ctypes
8
import warnings
Tomeu Vizoso's avatar
Tomeu Vizoso committed
9
10
import sys

11
12
13
try:
    import cairo
    has_cairo = True
14
    from gi.repository import Regress as Everything
15
16
except ImportError:
    has_cairo = False
Tomeu Vizoso's avatar
Tomeu Vizoso committed
17

18
#import gi
19
from gi.repository import GObject
20
from gi.repository import GLib
21
from gi.repository import Gio
Tomeu Vizoso's avatar
Tomeu Vizoso committed
22

23
24
25
26
27
28
try:
    from gi.repository import Gtk
    Gtk  # pyflakes
except:
    Gtk = None

29
30
31
32
33
34
35
if sys.version_info < (3, 0):
    UNICHAR = "\xe2\x99\xa5"
    PY2_UNICODE_UNICHAR = unicode(UNICHAR, 'UTF-8')
else:
    UNICHAR = "鈾"


36
37
38
39
40
41
42
43
44
45
46
class RawGList(ctypes.Structure):
    _fields_ = [('data', ctypes.c_void_p),
                ('next', ctypes.c_void_p),
                ('prev', ctypes.c_void_p)]

    @classmethod
    def from_wrapped(cls, obj):
        offset = sys.getsizeof(object())  # size of PyObject_HEAD
        return ctypes.POINTER(cls).from_address(id(obj) + offset)


47
@unittest.skipUnless(has_cairo, 'built without cairo support')
Tomeu Vizoso's avatar
Tomeu Vizoso committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class TestEverything(unittest.TestCase):

    def test_cairo_context(self):
        context = Everything.test_cairo_context_full_return()
        self.assertTrue(isinstance(context, cairo.Context))

        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 10, 10)
        context = cairo.Context(surface)
        Everything.test_cairo_context_none_in(context)

    def test_cairo_surface(self):
        surface = Everything.test_cairo_surface_none_return()
        self.assertTrue(isinstance(surface, cairo.ImageSurface))
        self.assertTrue(isinstance(surface, cairo.Surface))
62
63
64
        self.assertEqual(surface.get_format(), cairo.FORMAT_ARGB32)
        self.assertEqual(surface.get_width(), 10)
        self.assertEqual(surface.get_height(), 10)
Tomeu Vizoso's avatar
Tomeu Vizoso committed
65
66
67
68

        surface = Everything.test_cairo_surface_full_return()
        self.assertTrue(isinstance(surface, cairo.ImageSurface))
        self.assertTrue(isinstance(surface, cairo.Surface))
69
70
71
        self.assertEqual(surface.get_format(), cairo.FORMAT_ARGB32)
        self.assertEqual(surface.get_width(), 10)
        self.assertEqual(surface.get_height(), 10)
Tomeu Vizoso's avatar
Tomeu Vizoso committed
72
73
74
75
76
77
78

        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 10, 10)
        Everything.test_cairo_surface_none_in(surface)

        surface = Everything.test_cairo_surface_full_out()
        self.assertTrue(isinstance(surface, cairo.ImageSurface))
        self.assertTrue(isinstance(surface, cairo.Surface))
79
80
81
        self.assertEqual(surface.get_format(), cairo.FORMAT_ARGB32)
        self.assertEqual(surface.get_width(), 10)
        self.assertEqual(surface.get_height(), 10)
Tomeu Vizoso's avatar
Tomeu Vizoso committed
82

83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
    def test_bool(self):
        self.assertEqual(Everything.test_boolean(False), False)
        self.assertEqual(Everything.test_boolean(True), True)
        self.assertEqual(Everything.test_boolean('hello'), True)
        self.assertEqual(Everything.test_boolean(''), False)

        self.assertEqual(Everything.test_boolean_true(True), True)
        self.assertEqual(Everything.test_boolean_false(False), False)

    def test_int8(self):
        self.assertEqual(Everything.test_int8(GObject.G_MAXINT8),
                         GObject.G_MAXINT8)
        self.assertEqual(Everything.test_int8(GObject.G_MININT8),
                         GObject.G_MININT8)
        self.assertRaises(ValueError, Everything.test_int8, GObject.G_MAXINT8 + 1)

        self.assertEqual(Everything.test_uint8(GObject.G_MAXUINT8),
                         GObject.G_MAXUINT8)
        self.assertEqual(Everything.test_uint8(0), 0)
        self.assertRaises(ValueError, Everything.test_uint8, -1)
        self.assertRaises(ValueError, Everything.test_uint8, GObject.G_MAXUINT8 + 1)

    def test_int16(self):
        self.assertEqual(Everything.test_int16(GObject.G_MAXINT16),
                         GObject.G_MAXINT16)
        self.assertEqual(Everything.test_int16(GObject.G_MININT16),
                         GObject.G_MININT16)
        self.assertRaises(ValueError, Everything.test_int16, GObject.G_MAXINT16 + 1)

        self.assertEqual(Everything.test_uint16(GObject.G_MAXUINT16),
                         GObject.G_MAXUINT16)
        self.assertEqual(Everything.test_uint16(0), 0)
        self.assertRaises(ValueError, Everything.test_uint16, -1)
        self.assertRaises(ValueError, Everything.test_uint16, GObject.G_MAXUINT16 + 1)

    def test_int32(self):
        self.assertEqual(Everything.test_int32(GObject.G_MAXINT32),
                         GObject.G_MAXINT32)
        self.assertEqual(Everything.test_int32(GObject.G_MININT32),
                         GObject.G_MININT32)
        self.assertRaises(ValueError, Everything.test_int32, GObject.G_MAXINT32 + 1)

        self.assertEqual(Everything.test_uint32(GObject.G_MAXUINT32),
                         GObject.G_MAXUINT32)
        self.assertEqual(Everything.test_uint32(0), 0)
        self.assertRaises(ValueError, Everything.test_uint32, -1)
        self.assertRaises(ValueError, Everything.test_uint32, GObject.G_MAXUINT32 + 1)

    def test_int64(self):
        self.assertEqual(Everything.test_int64(GObject.G_MAXINT64),
                         GObject.G_MAXINT64)
        self.assertEqual(Everything.test_int64(GObject.G_MININT64),
                         GObject.G_MININT64)
        self.assertRaises(ValueError, Everything.test_int64, GObject.G_MAXINT64 + 1)

        self.assertEqual(Everything.test_uint64(GObject.G_MAXUINT64),
                         GObject.G_MAXUINT64)
        self.assertEqual(Everything.test_uint64(0), 0)
        self.assertRaises(ValueError, Everything.test_uint64, -1)
        self.assertRaises(ValueError, Everything.test_uint64, GObject.G_MAXUINT64 + 1)

    def test_int(self):
        self.assertEqual(Everything.test_int(GObject.G_MAXINT),
                         GObject.G_MAXINT)
        self.assertEqual(Everything.test_int(GObject.G_MININT),
                         GObject.G_MININT)
        self.assertRaises(ValueError, Everything.test_int, GObject.G_MAXINT + 1)

        self.assertEqual(Everything.test_uint(GObject.G_MAXUINT),
                         GObject.G_MAXUINT)
        self.assertEqual(Everything.test_uint(0), 0)
        self.assertRaises(ValueError, Everything.test_uint, -1)
        self.assertRaises(ValueError, Everything.test_uint, GObject.G_MAXUINT + 1)

    def test_short(self):
        self.assertEqual(Everything.test_short(GObject.G_MAXSHORT),
                         GObject.G_MAXSHORT)
        self.assertEqual(Everything.test_short(GObject.G_MINSHORT),
                         GObject.G_MINSHORT)
        self.assertRaises(ValueError, Everything.test_short, GObject.G_MAXSHORT + 1)

        self.assertEqual(Everything.test_ushort(GObject.G_MAXUSHORT),
                         GObject.G_MAXUSHORT)
        self.assertEqual(Everything.test_ushort(0), 0)
        self.assertRaises(ValueError, Everything.test_ushort, -1)
        self.assertRaises(ValueError, Everything.test_ushort, GObject.G_MAXUSHORT + 1)

    def test_long(self):
        self.assertEqual(Everything.test_long(GObject.G_MAXLONG),
                         GObject.G_MAXLONG)
        self.assertEqual(Everything.test_long(GObject.G_MINLONG),
                         GObject.G_MINLONG)
        self.assertRaises(ValueError, Everything.test_long, GObject.G_MAXLONG + 1)

        self.assertEqual(Everything.test_ulong(GObject.G_MAXULONG),
                         GObject.G_MAXULONG)
        self.assertEqual(Everything.test_ulong(0), 0)
        self.assertRaises(ValueError, Everything.test_ulong, -1)
        self.assertRaises(ValueError, Everything.test_ulong, GObject.G_MAXULONG + 1)

    def test_size(self):
        self.assertEqual(Everything.test_ssize(GObject.G_MAXSSIZE),
                         GObject.G_MAXSSIZE)
        self.assertEqual(Everything.test_ssize(GObject.G_MINSSIZE),
                         GObject.G_MINSSIZE)
        self.assertRaises(ValueError, Everything.test_ssize, GObject.G_MAXSSIZE + 1)

        self.assertEqual(Everything.test_size(GObject.G_MAXSIZE),
                         GObject.G_MAXSIZE)
        self.assertEqual(Everything.test_size(0), 0)
        self.assertRaises(ValueError, Everything.test_size, -1)
        self.assertRaises(ValueError, Everything.test_size, GObject.G_MAXSIZE + 1)

    def test_timet(self):
        self.assertEqual(Everything.test_timet(42), 42)
        self.assertRaises(ValueError, Everything.test_timet, GObject.G_MAXUINT64 + 1)

Paolo Borelli's avatar
Paolo Borelli committed
200
    def test_unichar(self):
201
        self.assertEqual("c", Everything.test_unichar("c"))
202
203

        if sys.version_info < (3, 0):
204
205
            self.assertEqual(UNICHAR, Everything.test_unichar(PY2_UNICODE_UNICHAR))
        self.assertEqual(UNICHAR, Everything.test_unichar(UNICHAR))
206
207
        self.assertRaises(TypeError, Everything.test_unichar, "")
        self.assertRaises(TypeError, Everything.test_unichar, "morethanonechar")
208

209
210
211
212
213
214
215
216
217
218
219
220
221
222
    def test_float(self):
        self.assertEqual(Everything.test_float(GObject.G_MAXFLOAT),
                         GObject.G_MAXFLOAT)
        self.assertEqual(Everything.test_float(GObject.G_MINFLOAT),
                         GObject.G_MINFLOAT)
        self.assertRaises(ValueError, Everything.test_float, GObject.G_MAXFLOAT * 2)

    def test_double(self):
        self.assertEqual(Everything.test_double(GObject.G_MAXDOUBLE),
                         GObject.G_MAXDOUBLE)
        self.assertEqual(Everything.test_double(GObject.G_MINDOUBLE),
                         GObject.G_MINDOUBLE)
        self.assertRaises(ValueError, Everything.test_double, GObject.G_MAXDOUBLE * 2)

223
224
225
226
        (two, three) = Everything.test_multi_double_args(2.5)
        self.assertAlmostEqual(two, 5.0)
        self.assertAlmostEqual(three, 7.5)

227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
    def test_value(self):
        self.assertEqual(Everything.test_int_value_arg(GObject.G_MAXINT), GObject.G_MAXINT)
        self.assertEqual(Everything.test_value_return(GObject.G_MAXINT), GObject.G_MAXINT)

    def test_variant(self):
        v = Everything.test_gvariant_i()
        self.assertEqual(v.get_type_string(), 'i')
        self.assertEqual(v.get_int32(), 1)

        v = Everything.test_gvariant_s()
        self.assertEqual(v.get_type_string(), 's')
        self.assertEqual(v.get_string(), 'one')

        v = Everything.test_gvariant_v()
        self.assertEqual(v.get_type_string(), 'v')
        vi = v.get_variant()
        self.assertEqual(vi.get_type_string(), 's')
        self.assertEqual(vi.get_string(), 'contents')

        v = Everything.test_gvariant_as()
        self.assertEqual(v.get_type_string(), 'as')
        self.assertEqual(v.get_strv(), ['one', 'two', 'three'])

        v = Everything.test_gvariant_asv()
        self.assertEqual(v.get_type_string(), 'a{sv}')
        self.assertEqual(v.lookup_value('nosuchkey', None), None)
        name = v.lookup_value('name', None)
        self.assertEqual(name.get_string(), 'foo')
        timeout = v.lookup_value('timeout', None)
        self.assertEqual(timeout.get_int32(), 10)

    def test_string(self):
Martin Pitt's avatar
Martin Pitt committed
259
260
261
        const_str = b'const \xe2\x99\xa5 utf8'
        if sys.version_info >= (3, 0):
            const_str = const_str.decode('UTF-8')
262
263
264
265
266
267
268
269
270
        noconst_str = 'non' + const_str

        self.assertEqual(Everything.test_utf8_const_return(), const_str)
        self.assertEqual(Everything.test_utf8_nonconst_return(), noconst_str)
        self.assertEqual(Everything.test_utf8_out(), noconst_str)

        Everything.test_utf8_const_in(const_str)
        self.assertEqual(Everything.test_utf8_inout(const_str), noconst_str)

271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
        self.assertEqual(Everything.test_filename_return(), ['氓盲枚', '/etc/fstab'])

        # returns g_utf8_strlen() in out argument
        self.assertEqual(Everything.test_int_out_utf8(''), 0)
        self.assertEqual(Everything.test_int_out_utf8('hello world'), 11)
        self.assertEqual(Everything.test_int_out_utf8('氓盲枚'), 3)

        self.assertEqual(Everything.test_utf8_out_out(), ('first', 'second'))
        self.assertEqual(Everything.test_utf8_out_nonconst_return(), ('first', 'second'))

    def test_enum(self):
        self.assertEqual(Everything.test_enum_param(Everything.TestEnum.VALUE1), 'value1')
        self.assertEqual(Everything.test_enum_param(Everything.TestEnum.VALUE3), 'value3')
        self.assertRaises(TypeError, Everything.test_enum_param, 'hello')

    # FIXME: ValueError: invalid enum value: 2147483648
    @unittest.expectedFailure
    def test_enum_unsigned(self):
        self.assertEqual(Everything.test_unsigned_enum_param(Everything.TestEnumUnsigned.VALUE1), 'value1')
        self.assertEqual(Everything.test_unsigned_enum_param(Everything.TestEnumUnsigned.VALUE3), 'value3')
        self.assertRaises(TypeError, Everything.test_unsigned_enum_param, 'hello')

    def test_flags(self):
        result = Everything.global_get_flags_out()
        # assert that it's not an int
        self.assertEqual(type(result), Everything.TestFlags)
        self.assertEqual(result, Everything.TestFlags.FLAG1 | Everything.TestFlags.FLAG3)

299
    def test_floating(self):
300
        e = Everything.TestFloating()
301
        self.assertEqual(e.__grefcount__, 1)
302
303

        e = GObject.new(Everything.TestFloating)
304
        self.assertEqual(e.__grefcount__, 1)
305
306

        e = Everything.TestFloating.new()
307
        self.assertEqual(e.__grefcount__, 1)
308

309
310
311
312
313
314
315
316
317
    def test_caller_allocates(self):
        struct_a = Everything.TestStructA()
        struct_a.some_int = 10
        struct_a.some_int8 = 21
        struct_a.some_double = 3.14
        struct_a.some_enum = Everything.TestEnum.VALUE3

        struct_a_clone = struct_a.clone()
        self.assertTrue(struct_a != struct_a_clone)
318
319
320
321
        self.assertEqual(struct_a.some_int, struct_a_clone.some_int)
        self.assertEqual(struct_a.some_int8, struct_a_clone.some_int8)
        self.assertEqual(struct_a.some_double, struct_a_clone.some_double)
        self.assertEqual(struct_a.some_enum, struct_a_clone.some_enum)
322
323
324
325
326
327
328
329
330
331

        struct_b = Everything.TestStructB()
        struct_b.some_int8 = 8
        struct_b.nested_a.some_int = 20
        struct_b.nested_a.some_int8 = 12
        struct_b.nested_a.some_double = 333.3333
        struct_b.nested_a.some_enum = Everything.TestEnum.VALUE2

        struct_b_clone = struct_b.clone()
        self.assertTrue(struct_b != struct_b_clone)
332
333
334
335
336
        self.assertEqual(struct_b.some_int8, struct_b_clone.some_int8)
        self.assertEqual(struct_b.nested_a.some_int, struct_b_clone.nested_a.some_int)
        self.assertEqual(struct_b.nested_a.some_int8, struct_b_clone.nested_a.some_int8)
        self.assertEqual(struct_b.nested_a.some_double, struct_b_clone.nested_a.some_double)
        self.assertEqual(struct_b.nested_a.some_enum, struct_b_clone.nested_a.some_enum)
337

338
339
340
        struct_a = Everything.test_struct_a_parse('ignored')
        self.assertEqual(struct_a.some_int, 23)

341
342
343
    def test_wrong_type_of_arguments(self):
        try:
            Everything.test_int8()
344
345
        except TypeError:
            (e_type, e) = sys.exc_info()[:2]
346
            self.assertEqual(e.args, ("test_int8() takes exactly 1 argument (0 given)",))
347

348
349
350
    def test_gtypes(self):
        gchararray_gtype = GObject.type_from_name('gchararray')
        gtype = Everything.test_gtype(str)
351
        self.assertEqual(gchararray_gtype, gtype)
352
        gtype = Everything.test_gtype('gchararray')
353
        self.assertEqual(gchararray_gtype, gtype)
354
355
        gobject_gtype = GObject.GObject.__gtype__
        gtype = Everything.test_gtype(GObject.GObject)
356
        self.assertEqual(gobject_gtype, gtype)
357
        gtype = Everything.test_gtype('GObject')
358
        self.assertEqual(gobject_gtype, gtype)
359
360
361
362
363
364
365
366
367
368
369
        self.assertRaises(TypeError, Everything.test_gtype, 'invalidgtype')

        class NotARegisteredClass(object):
            pass

        self.assertRaises(TypeError, Everything.test_gtype, NotARegisteredClass)

        class ARegisteredClass(GObject.GObject):
            __gtype_name__ = 'EverythingTestsARegisteredClass'

        gtype = Everything.test_gtype('EverythingTestsARegisteredClass')
370
        self.assertEqual(ARegisteredClass.__gtype__, gtype)
371
        gtype = Everything.test_gtype(ARegisteredClass)
372
        self.assertEqual(ARegisteredClass.__gtype__, gtype)
373
        self.assertRaises(TypeError, Everything.test_gtype, 'ARegisteredClass')
374

375
376
    def test_dir(self):
        attr_list = dir(Everything)
377

378
379
        # test that typelib attributes are listed
        self.assertTrue('TestStructA' in attr_list)
380

381
382
383
384
        # test that class attributes and methods are listed
        self.assertTrue('__class__' in attr_list)
        self.assertTrue('__dir__' in attr_list)
        self.assertTrue('__repr__' in attr_list)
385

386
387
        # test that instance members are listed
        self.assertTrue('_namespace' in attr_list)
388
        self.assertTrue('_version' in attr_list)
389

390
391
        # test that there are no duplicates returned
        self.assertEqual(len(attr_list), len(set(attr_list)))
392

393
394
395
396
397
398
399
400
    def test_array(self):
        self.assertEqual(Everything.test_array_int_in([]), 0)
        self.assertEqual(Everything.test_array_int_in([1, 5, -2]), 4)
        self.assertEqual(Everything.test_array_int_out(), [0, 1, 2, 3, 4])
        self.assertEqual(Everything.test_array_int_full_out(), [0, 1, 2, 3, 4])
        self.assertEqual(Everything.test_array_int_none_out(), [1, 2, 3, 4, 5])
        self.assertEqual(Everything.test_array_int_inout([1, 5, 42, -8]), [6, 43, -7])

Martin Pitt's avatar
Martin Pitt committed
401
402
        if sys.version_info >= (3, 0):
            self.assertEqual(Everything.test_array_gint8_in(b'\x01\x03\x05'), 9)
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
        self.assertEqual(Everything.test_array_gint8_in([1, 3, 5, -50]), -41)
        self.assertEqual(Everything.test_array_gint16_in([256, 257, -1000, 10000]), 9513)
        self.assertEqual(Everything.test_array_gint32_in([30000, 1, -2]), 29999)
        self.assertEqual(Everything.test_array_gint64_in([2 ** 33, 2 ** 34]), 2 ** 33 + 2 ** 34)

        self.assertEqual(Everything.test_array_gtype_in(
            [GObject.TYPE_STRING, GObject.TYPE_UINT64, GObject.TYPE_VARIANT]),
            '[gchararray,guint64,GVariant,]')

    def test_array_fixed_size(self):
        # fixed length of 5
        self.assertEqual(Everything.test_array_fixed_size_int_in([1, 2, -10, 5, 3]), 1)
        self.assertRaises(ValueError, Everything.test_array_fixed_size_int_in, [1, 2, 3, 4])
        self.assertRaises(ValueError, Everything.test_array_fixed_size_int_in, [1, 2, 3, 4, 5, 6])

        self.assertEqual(Everything.test_array_fixed_size_int_out(), [0, 1, 2, 3, 4])
        self.assertEqual(Everything.test_array_fixed_size_int_return(), [0, 1, 2, 3, 4])

Xavier Claessens's avatar
Xavier Claessens committed
421
    def test_ptrarray(self):
422
423
        # transfer container
        result = Everything.test_garray_container_return()
424
        self.assertEqual(result, ['regress'])
425
426
427
428
        result = None

        # transfer full
        result = Everything.test_garray_full_return()
429
        self.assertEqual(result, ['regress'])
430
        result = None
Xavier Claessens's avatar
Xavier Claessens committed
431

432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
    def test_strv(self):
        self.assertEqual(Everything.test_strv_out(), ['thanks', 'for', 'all', 'the', 'fish'])
        self.assertEqual(Everything.test_strv_out_c(), ['thanks', 'for', 'all', 'the', 'fish'])
        self.assertEqual(Everything.test_strv_out_container(), ['1', '2', '3'])
        self.assertEqual(Everything.test_strv_outarg(), ['1', '2', '3'])

        self.assertEqual(Everything.test_strv_in_gvalue(), ['one', 'two', 'three'])

        Everything.test_strv_in(['1', '2', '3'])

    def test_glist(self):
        self.assertEqual(Everything.test_glist_nothing_return(), ['1', '2', '3'])
        self.assertEqual(Everything.test_glist_nothing_return2(), ['1', '2', '3'])
        self.assertEqual(Everything.test_glist_container_return(), ['1', '2', '3'])
        self.assertEqual(Everything.test_glist_everything_return(), ['1', '2', '3'])

        Everything.test_glist_nothing_in(['1', '2', '3'])
        Everything.test_glist_nothing_in2(['1', '2', '3'])

    def test_gslist(self):
        self.assertEqual(Everything.test_gslist_nothing_return(), ['1', '2', '3'])
        self.assertEqual(Everything.test_gslist_nothing_return2(), ['1', '2', '3'])
        self.assertEqual(Everything.test_gslist_container_return(), ['1', '2', '3'])
        self.assertEqual(Everything.test_gslist_everything_return(), ['1', '2', '3'])

        Everything.test_gslist_nothing_in(['1', '2', '3'])
        Everything.test_gslist_nothing_in2(['1', '2', '3'])

460
    def test_hash_return(self):
461
462
463
464
465
466
467
468
        expected = {'foo': 'bar', 'baz': 'bat', 'qux': 'quux'}

        self.assertEqual(Everything.test_ghash_null_return(), None)
        self.assertEqual(Everything.test_ghash_nothing_return(), expected)
        self.assertEqual(Everything.test_ghash_nothing_return(), expected)
        self.assertEqual(Everything.test_ghash_container_return(), expected)
        self.assertEqual(Everything.test_ghash_everything_return(), expected)

469
        result = Everything.test_ghash_gvalue_return()
470
471
472
        self.assertEqual(result['integer'], 12)
        self.assertEqual(result['boolean'], True)
        self.assertEqual(result['string'], 'some text')
473
        self.assertEqual(result['strings'], ['first', 'second', 'third'])
474
475
        self.assertEqual(result['flags'], Everything.TestFlags.FLAG1 | Everything.TestFlags.FLAG3)
        self.assertEqual(result['enum'], Everything.TestEnum.VALUE2)
476
477
        result = None

478
479
480
481
482
    # FIXME: CRITICAL **: Unsupported type ghash
    def disabled_test_hash_return_nested(self):
        self.assertEqual(Everything.test_ghash_nested_everything_return(), {})
        self.assertEqual(Everything.test_ghash_nested_everything_return2(), {})

483
    def test_hash_in(self):
484
485
486
        # specifying a simple string array for "strings" does not work due to
        # https://bugzilla.gnome.org/show_bug.cgi?id=666636
        # workaround by explicitly building a GStrv object
487
        class GStrv(list):
Martin Pitt's avatar
Martin Pitt committed
488
            __gtype__ = GObject.TYPE_STRV
489

490
491
492
493
494
        expected = {'foo': 'bar', 'baz': 'bat', 'qux': 'quux'}

        Everything.test_ghash_nothing_in(expected)
        Everything.test_ghash_nothing_in2(expected)

495
496
497
498
499
500
501
        data = {'integer': 12,
                'boolean': True,
                'string': 'some text',
                'strings': GStrv(['first', 'second', 'third']),
                'flags': Everything.TestFlags.FLAG1 | Everything.TestFlags.FLAG3,
                'enum': Everything.TestEnum.VALUE2,
               }
502
503
        Everything.test_ghash_gvalue_in(data)
        data = None
504

505
    def test_struct_gpointer(self):
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
        glist = GLib.List()
        raw = RawGList.from_wrapped(glist)

        self.assertEqual(glist.data, None)
        self.assertEqual(raw.contents.data, None)

        glist.data = 123
        self.assertEqual(glist.data, 123)
        self.assertEqual(raw.contents.data, 123)

        glist.data = None
        self.assertEqual(glist.data, None)
        self.assertEqual(raw.contents.data, None)

        # Setting to anything other than an int should raise
        self.assertRaises(TypeError, setattr, glist.data, 'nan')
        self.assertRaises(TypeError, setattr, glist.data, object())
        self.assertRaises(TypeError, setattr, glist.data, 123.321)
524

525
526
527
528
529
    def test_struct_opaque(self):
        # we should get a sensible error message
        try:
            Everything.TestBoxedPrivate()
            self.fail('allocating disguised struct without default constructor unexpectedly succeeded')
530
531
532
533
534
535
536
        except TypeError:
            (e_type, e_value, e_tb) = sys.exc_info()
            self.assertEqual(e_type, TypeError)
            self.assertTrue('TestBoxedPrivate' in str(e_value), str(e_value))
            self.assertTrue('override' in str(e_value), str(e_value))
            self.assertTrue('constructor' in str(e_value), str(e_value))
            tb = ''.join(traceback.format_exception(e_type, e_value, e_tb))
537
538
            self.assertTrue('tests/test_everything.py", line' in tb, tb)

539

540
@unittest.skipUnless(has_cairo, 'built without cairo support')
541
542
543
544
545
546
547
class TestNullableArgs(unittest.TestCase):
    def test_in_nullable_hash(self):
        Everything.test_ghash_null_in(None)

    def test_in_nullable_list(self):
        Everything.test_gslist_null_in(None)
        Everything.test_glist_null_in(None)
548
549
        Everything.test_gslist_null_in([])
        Everything.test_glist_null_in([])
550
551

    def test_in_nullable_array(self):
552
        Everything.test_array_int_null_in(None)
553
        Everything.test_array_int_null_in([])
554
555
556
557

    def test_in_nullable_string(self):
        Everything.test_utf8_null_in(None)

558
    def test_in_nullable_object(self):
559
        Everything.func_obj_null_in(None)
560

561
562
563
564
    def test_out_nullable_hash(self):
        self.assertEqual(None, Everything.test_ghash_null_out())

    def test_out_nullable_list(self):
565
566
        self.assertEqual([], Everything.test_gslist_null_out())
        self.assertEqual([], Everything.test_glist_null_out())
567
568

    def test_out_nullable_array(self):
569
        self.assertEqual([], Everything.test_array_int_null_out())
570
571
572
573

    def test_out_nullable_string(self):
        self.assertEqual(None, Everything.test_utf8_null_out())

574
    def test_out_nullable_object(self):
575
        self.assertEqual(None, Everything.TestObj.null_out())
576

577

578
@unittest.skipUnless(has_cairo, 'built without cairo support')
579
580
class TestCallbacks(unittest.TestCase):
    called = False
581
    main_loop = GLib.MainLoop()
Tomeu Vizoso's avatar
Tomeu Vizoso committed
582

583
    def test_callback(self):
584
        TestCallbacks.called = False
585

586
587
        def callback():
            TestCallbacks.called = True
588

589
590
591
        Everything.test_simple_callback(callback)
        self.assertTrue(TestCallbacks.called)

592
    def test_callback_exception(self):
593
594
595
596
597
598
        """
        This test ensures that we get errors from callbacks correctly
        and in particular that we do not segv when callbacks fail
        """
        def callback():
            x = 1 / 0
599
            self.fail('unexpected surviving zero divsion:' + str(x))
600

601
602
603
604
        # note that we do NOT expect the ZeroDivisionError to be propagated
        # through from the callback, as it crosses the Python<->C boundary
        # twice. (See GNOME #616279)
        Everything.test_simple_callback(callback)
605

606
    def test_double_callback_exception(self):
607
608
609
610
611
612
        """
        This test ensures that we get errors from callbacks correctly
        and in particular that we do not segv when callbacks fail
        """
        def badcallback():
            x = 1 / 0
613
            self.fail('unexpected surviving zero divsion:' + str(x))
614
615
616
617
618
619

        def callback():
            Everything.test_boolean(True)
            Everything.test_boolean(False)
            Everything.test_simple_callback(badcallback())

620
621
622
623
        # note that we do NOT expect the ZeroDivisionError to be propagated
        # through from the callback, as it crosses the Python<->C boundary
        # twice. (See GNOME #616279)
        Everything.test_simple_callback(callback)
624

625
    def test_return_value_callback(self):
626
        TestCallbacks.called = False
627

628
629
630
631
        def callback():
            TestCallbacks.called = True
            return 44

632
        self.assertEqual(Everything.test_callback(callback), 44)
633
        self.assertTrue(TestCallbacks.called)
634

635
    def test_callback_scope_async(self):
636
        TestCallbacks.called = False
637
        ud = 'Test Value 44'
638

639
640
        def callback(user_data):
            self.assertEqual(user_data, ud)
641
            TestCallbacks.called = True
642
643
644
645
            return 44

        ud_refcount = sys.getrefcount(ud)
        callback_refcount = sys.getrefcount(callback)
646

647
648
649
650
651
652
653
654
655
        self.assertEqual(Everything.test_callback_async(callback, ud), None)
        # Callback should not have run and the ref count is increased by 1
        self.assertEqual(TestCallbacks.called, False)
        self.assertEqual(sys.getrefcount(callback), callback_refcount + 1)
        self.assertEqual(sys.getrefcount(ud), ud_refcount + 1)

        # test_callback_thaw_async will run the callback previously supplied.
        # references should be auto decremented after this call.
        self.assertEqual(Everything.test_callback_thaw_async(), 44)
656
        self.assertTrue(TestCallbacks.called)
657

658
659
660
661
662
663
664
        # Make sure refcounts are returned to normal
        self.assertEqual(sys.getrefcount(callback), callback_refcount)
        self.assertEqual(sys.getrefcount(ud), ud_refcount)

    def test_callback_scope_call_multi(self):
        # This tests a callback that gets called multiple times from a
        # single scope call in python.
665
        TestCallbacks.called = 0
666

667
668
        def callback():
            TestCallbacks.called += 1
669
            return TestCallbacks.called
670

671
        refcount = sys.getrefcount(callback)
672
673
674
        result = Everything.test_multi_callback(callback)
        # first callback should give 1, second 2, and the function sums them up
        self.assertEqual(result, 3)
675
        self.assertEqual(TestCallbacks.called, 2)
676
        self.assertEqual(sys.getrefcount(callback), refcount)
677

678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
    # FIXME: TypeError: callback() takes 2 positional arguments but 4 were given
    # does not remove the array length arguments
    @unittest.expectedFailure
    def test_callback_scope_call_array(self):
        # This tests a callback that gets called multiple times from a
        # single scope call in python with array arguments
        TestCallbacks.callargs = []

        # works with:
        #def callback(one, one_length, two, two_length):
        def callback(one, two):
            TestCallbacks.callargs.append((one, two))
            return len(TestCallbacks.callargs)

        refcount = sys.getrefcount(callback)
        result = Everything.test_array_callback(callback)
        # first callback should give 1, second 2, and the function sums them up
        self.assertEqual(result, 3)
        self.assertEqual(TestCallbacks.callargs,
                         [([-1, 0, 1, 2], ['one', 'two', 'three'])] * 2)
        self.assertEqual(sys.getrefcount(callback), refcount)

700
    def test_callback_userdata(self):
701
        TestCallbacks.called = 0
702

703
        def callback(userdata):
704
            self.assertEqual(userdata, "Test%d" % TestCallbacks.called)
705
706
            TestCallbacks.called += 1
            return TestCallbacks.called
707

708
709
        for i in range(100):
            val = Everything.test_callback_user_data(callback, "Test%d" % i)
710
            self.assertEqual(val, i + 1)
711

712
        self.assertEqual(TestCallbacks.called, 100)
Tomeu Vizoso's avatar
Tomeu Vizoso committed
713

714
    def test_async_ready_callback(self):
Tomeu Vizoso's avatar
Tomeu Vizoso committed
715
        TestCallbacks.called = False
716
        TestCallbacks.main_loop = GLib.MainLoop()
Tomeu Vizoso's avatar
Tomeu Vizoso committed
717
718
719
720
721
722
723
724
725
726

        def callback(obj, result, user_data):
            TestCallbacks.main_loop.quit()
            TestCallbacks.called = True

        Everything.test_async_ready_callback(callback)

        TestCallbacks.main_loop.run()

        self.assertTrue(TestCallbacks.called)
Tomeu Vizoso's avatar
Tomeu Vizoso committed
727

728
729
730
731
    def test_callback_scope_notified_with_destroy(self):
        TestCallbacks.called = 0
        ud = 'Test scope notified data 33'

Tomeu Vizoso's avatar
Tomeu Vizoso committed
732
        def callback(user_data):
733
734
735
            self.assertEqual(user_data, ud)
            TestCallbacks.called += 1
            return 33
Tomeu Vizoso's avatar
Tomeu Vizoso committed
736

737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
        value_refcount = sys.getrefcount(ud)
        callback_refcount = sys.getrefcount(callback)

        # Callback is immediately called.
        for i in range(100):
            res = Everything.test_callback_destroy_notify(callback, ud)
            self.assertEqual(res, 33)

        self.assertEqual(TestCallbacks.called, 100)
        self.assertEqual(sys.getrefcount(callback), callback_refcount + 100)
        self.assertEqual(sys.getrefcount(ud), value_refcount + 100)

        # thaw will call the callback again, this time resources should be freed
        self.assertEqual(Everything.test_callback_thaw_notifications(), 33 * 100)
        self.assertEqual(TestCallbacks.called, 200)
        self.assertEqual(sys.getrefcount(callback), callback_refcount)
        self.assertEqual(sys.getrefcount(ud), value_refcount)

    def test_callback_scope_notified_with_destroy_no_user_data(self):
        TestCallbacks.called = 0

        def callback(user_data):
            self.assertEqual(user_data, None)
            TestCallbacks.called += 1
            return 34

        callback_refcount = sys.getrefcount(callback)

        # Run with warning as exception
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("error")
            self.assertRaises(RuntimeWarning,
                              Everything.test_callback_destroy_notify_no_user_data,
                              callback)

        self.assertEqual(TestCallbacks.called, 0)
        self.assertEqual(sys.getrefcount(callback), callback_refcount)

        # Run with warning as warning
        with warnings.catch_warnings(record=True) as w:
            # Cause all warnings to always be triggered.
            warnings.simplefilter("default")
            # Trigger a warning.
            res = Everything.test_callback_destroy_notify_no_user_data(callback)
            # Verify some things
            self.assertEqual(len(w), 1)
            self.assertTrue(issubclass(w[-1].category, RuntimeWarning))
            self.assertTrue('Callables passed to' in str(w[-1].message))

        self.assertEqual(res, 34)
        self.assertEqual(TestCallbacks.called, 1)
        self.assertEqual(sys.getrefcount(callback), callback_refcount + 1)

        # thaw will call the callback again,
        # refcount will not go down without user_data parameter
        self.assertEqual(Everything.test_callback_thaw_notifications(), 34)
        self.assertEqual(TestCallbacks.called, 2)
        self.assertEqual(sys.getrefcount(callback), callback_refcount + 1)
795

796
    def test_callback_in_methods(self):
797
798
799
800
        object_ = Everything.TestObj()

        def callback():
            TestCallbacks.called = True
801
            return 42
802
803
804
805
806
807
808
809
810
811

        TestCallbacks.called = False
        object_.instance_method_callback(callback)
        self.assertTrue(TestCallbacks.called)

        TestCallbacks.called = False
        Everything.TestObj.static_method_callback(callback)
        self.assertTrue(TestCallbacks.called)

        def callbackWithUserData(user_data):
812
            TestCallbacks.called += 1
813
            return 42
814

815
        TestCallbacks.called = 0
816
        Everything.TestObj.new_callback(callbackWithUserData, None)
817
818
819
820
821
822
        self.assertEqual(TestCallbacks.called, 1)
        # Note: using "new_callback" adds the notification to the same global
        # list as Everything.test_callback_destroy_notify, so thaw the list
        # so we don't get confusion between tests.
        self.assertEqual(Everything.test_callback_thaw_notifications(), 42)
        self.assertEqual(TestCallbacks.called, 2)
823

824
    def test_callback_none(self):
825
        # make sure this doesn't assert or crash
826
        Everything.test_simple_callback(None)
827

828
    def test_callback_gerror(self):
829
830
831
832
833
834
835
836
837
838
        def callback(error):
            self.assertEqual(error.message, 'regression test error')
            self.assertTrue('g-io' in error.domain)
            self.assertEqual(error.code, Gio.IOErrorEnum.NOT_SUPPORTED)
            TestCallbacks.called = True

        TestCallbacks.called = False
        Everything.test_gerror_callback(callback)
        self.assertTrue(TestCallbacks.called)

839
840
841
842
843
844
845
846
847
    def test_callback_null_gerror(self):
        def callback(error):
            self.assertEqual(error, None)
            TestCallbacks.called = True

        TestCallbacks.called = False
        Everything.test_null_gerror_callback(callback)
        self.assertTrue(TestCallbacks.called)

848
    def test_callback_owned_gerror(self):
849
850
851
852
853
854
855
856
857
858
        def callback(error):
            self.assertEqual(error.message, 'regression test owned error')
            self.assertTrue('g-io' in error.domain)
            self.assertEqual(error.code, Gio.IOErrorEnum.PERMISSION_DENIED)
            TestCallbacks.called = True

        TestCallbacks.called = False
        Everything.test_owned_gerror_callback(callback)
        self.assertTrue(TestCallbacks.called)

859
    def test_callback_hashtable(self):
860
861
862
863
864
        def callback(data):
            self.assertEqual(data, mydict)
            mydict['new'] = 42
            TestCallbacks.called = True

865
        mydict = {'foo': 1, 'bar': 2}
866
867
868
        TestCallbacks.called = False
        Everything.test_hash_table_callback(mydict, callback)
        self.assertTrue(TestCallbacks.called)
869
870
        self.assertEqual(mydict, {'foo': 1, 'bar': 2, 'new': 42})

871

872
@unittest.skipUnless(has_cairo, 'built without cairo support')
Martin Pitt's avatar
Martin Pitt committed
873
class TestClosures(unittest.TestCase):
874
875
876
877
878
879
880
881
882
883
    def test_no_arg(self):
        def callback():
            self.called = True
            return 42

        self.called = False
        result = Everything.test_closure(callback)
        self.assertTrue(self.called)
        self.assertEqual(result, 42)

Martin Pitt's avatar
Martin Pitt committed
884
885
886
    def test_int_arg(self):
        def callback(num):
            self.called = True
887
            return num + 1
Martin Pitt's avatar
Martin Pitt committed
888
889
890
891
892
893
894
895
896

        self.called = False
        result = Everything.test_closure_one_arg(callback, 42)
        self.assertTrue(self.called)
        self.assertEqual(result, 43)

    def test_variant(self):
        def callback(variant):
            self.called = True
897
898
899
            if variant is None:
                return None
            self.assertEqual(variant.get_type_string(), 'i')
Martin Pitt's avatar
Martin Pitt committed
900
901
902
903
904
905
906
            return GLib.Variant('i', variant.get_int32() + 1)

        self.called = False
        result = Everything.test_closure_variant(callback, GLib.Variant('i', 42))
        self.assertTrue(self.called)
        self.assertEqual(result.get_type_string(), 'i')
        self.assertEqual(result.get_int32(), 43)
907

908
909
910
911
912
913
914
915
916
        self.called = False
        result = Everything.test_closure_variant(callback, None)
        self.assertTrue(self.called)
        self.assertEqual(result, None)

        self.called = False
        self.assertRaises(TypeError, Everything.test_closure_variant, callback, 'foo')
        self.assertFalse(self.called)

917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
    def test_variant_wrong_return_type(self):
        def callback(variant):
            return 'no_variant'

        # reset last error
        sys.last_type = None

        # this does not directly raise an exception (see
        # https://bugzilla.gnome.org/show_bug.cgi?id=616279)
        result = Everything.test_closure_variant(callback, GLib.Variant('i', 42))
        # ... but the result shouldn't be a string
        self.assertEqual(result, None)
        # and the error should be shown
        self.assertEqual(sys.last_type, TypeError)
        self.assertTrue('return value' in str(sys.last_value), sys.last_value)

933

934
@unittest.skipUnless(has_cairo, 'built without cairo support')
935
936
class TestProperties(unittest.TestCase):

937
938
939
    def test_basic(self):
        object_ = Everything.TestObj()

940
        self.assertEqual(object_.props.int, 0)
941
942
        object_.props.int = 42
        self.assertTrue(isinstance(object_.props.int, int))
943
        self.assertEqual(object_.props.int, 42)
944

945
        self.assertEqual(object_.props.float, 0.0)
946
947
        object_.props.float = 42.42
        self.assertTrue(isinstance(object_.props.float, float))
Martin Pitt's avatar
Martin Pitt committed
948
        self.assertAlmostEqual(object_.props.float, 42.42, places=5)
949

950
        self.assertEqual(object_.props.double, 0.0)
951
952
        object_.props.double = 42.42
        self.assertTrue(isinstance(object_.props.double, float))
Martin Pitt's avatar
Martin Pitt committed
953
        self.assertAlmostEqual(object_.props.double, 42.42, places=5)
954

955
        self.assertEqual(object_.props.string, None)
956
957
        object_.props.string = 'mec'
        self.assertTrue(isinstance(object_.props.string, str))
958
        self.assertEqual(object_.props.string, 'mec')
959

960
        self.assertEqual(object_.props.gtype, GObject.TYPE_INVALID)
961
        object_.props.gtype = int
962
        self.assertEqual(object_.props.gtype, GObject.TYPE_INT)
963

964
965
    def test_hash_table(self):
        object_ = Everything.TestObj()
966
        self.assertEqual(object_.props.hash_table, None)
967
968
969

        object_.props.hash_table = {'mec': 56}
        self.assertTrue(isinstance(object_.props.hash_table, dict))
970
        self.assertEqual(list(object_.props.hash_table.items())[0], ('mec', 56))
971
972
973

    def test_list(self):
        object_ = Everything.TestObj()
974
        self.assertEqual(object_.props.list, [])
975
976
977

        object_.props.list = ['1', '2', '3']
        self.assertTrue(isinstance(object_.props.list, list))
978
        self.assertEqual(object_.props.list, ['1', '2', '3'])
979
980
981

    def test_boxed(self):
        object_ = Everything.TestObj()
982
        self.assertEqual(object_.props.boxed, None)
983
984
985
986
987
988

        boxed = Everything.TestBoxed()
        boxed.some_int8 = 42
        object_.props.boxed = boxed

        self.assertTrue(isinstance(object_.props.boxed, Everything.TestBoxed))
989
        self.assertEqual(object_.props.boxed.some_int8, 42)
990

991
992
993
994
995
996
997
998
999
1000
    def test_boxed_alternative_constructor(self):
        boxed = Everything.TestBoxed.new_alternative_constructor1(5)
        self.assertEqual(boxed.some_int8, 5)

        boxed = Everything.TestBoxed.new_alternative_constructor2(5, 3)
        self.assertEqual(boxed.some_int8, 8)

        boxed = Everything.TestBoxed.new_alternative_constructor3("-3")
        self.assertEqual(boxed.some_int8, -3)

Jasper St. Pierre's avatar
Jasper St. Pierre committed
1001
    def test_boxed_equality(self):
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
        boxed42 = Everything.TestBoxed.new_alternative_constructor1(42)
        boxed5 = Everything.TestBoxed.new_alternative_constructor1(5)
        boxed42_2 = Everything.TestBoxed.new_alternative_constructor2(41, 1)

        self.assertFalse(boxed42.equals(boxed5))
        self.assertTrue(boxed42.equals(boxed42_2))
        self.assertTrue(boxed42_2.equals(boxed42))
        self.assertTrue(boxed42.equals(boxed42))

    def test_boxed_c_equality(self):
Jasper St. Pierre's avatar
Jasper St. Pierre committed
1012
1013
1014
1015
1016
1017
1018
        boxed = Everything.TestBoxedC()
        # TestBoxedC uses refcounting, so we know that
        # the pointer is the same when copied
        copy = boxed.copy()
        self.assertEqual(boxed, copy)
        self.assertNotEqual(id(boxed), id(copy))

1019
1020
    def test_gtype(self):
        object_ = Everything.TestObj()
1021
        self.assertEqual(object_.props.gtype, GObject.TYPE_INVALID)
1022
        object_.props.gtype = int
1023
        self.assertEqual(object_.props.gtype, GObject.TYPE_INT)
1024

Martin Pitt's avatar
Martin Pitt committed
1025
        object_ = Everything.TestObj(gtype=int)
1026
        self.assertEqual(object_.props.gtype, GObject.TYPE_INT)
1027
        object_.props.gtype = str
1028
        self.assertEqual(object_.props.gtype, GObject.TYPE_STRING)
1029

1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
    def test_parent_class(self):
        class A(Everything.TestObj):
            prop1 = GObject.Property(type=int)

        a = A()
        a.props.int = 20
        self.assertEqual(a.props.int, 20)

        # test parent property which needs introspection
        a.props.list = ("str1", "str2")
        self.assertEqual(a.props.list, ["str1", "str2"])

1042

1043
@unittest.skipUnless(has_cairo, 'built without cairo support')
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
class TestTortureProfile(unittest.TestCase):
    def test_torture_profile(self):
        import time
        total_time = 0
        print("")
        object_ = Everything.TestObj()
        sys.stdout.write("\ttorture test 1 (10000 iterations): ")

        start_time = time.clock()
        for i in range(10000):
1054
1055
1056
            (y, z, q) = object_.torture_signature_0(5000,
                                                    "Torture Test 1",
                                                    12345)
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066

        end_time = time.clock()
        delta_time = end_time - start_time
        total_time += delta_time
        print("%f secs" % delta_time)

        sys.stdout.write("\ttorture test 2 (10000 iterations): ")

        start_time = time.clock()
        for i in range(10000):
1067
1068
            (y, z, q) = Everything.TestObj().torture_signature_0(
                5000, "Torture Test 2", 12345)
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078

        end_time = time.clock()
        delta_time = end_time - start_time
        total_time += delta_time
        print("%f secs" % delta_time)

        sys.stdout.write("\ttorture test 3 (10000 iterations): ")
        start_time = time.clock()
        for i in range(10000):
            try:
1079
1080
                (y, z, q) = object_.torture_signature_1(
                    5000, "Torture Test 3", 12345)
1081
1082
1083
1084
1085
1086
1087
1088
            except:
                pass
        end_time = time.clock()
        delta_time = end_time - start_time
        total_time += delta_time
        print("%f secs" % delta_time)

        sys.stdout.write("\ttorture test 4 (10000 iterations): ")
1089

1090
1091
1092
        def callback(userdata):
            pass

1093
        userdata = [1, 2, 3, 4]
1094
1095
        start_time = time.clock()
        for i in range(10000):
1096
1097
            (y, z, q) = Everything.test_torture_signature_2(
                5000, callback, userdata, "Torture Test 4", 12345)
1098
1099
1100
1101
1102
1103
1104
        end_time = time.clock()
        delta_time = end_time - start_time
        total_time += delta_time
        print("%f secs" % delta_time)
        print("\t====")
        print("\tTotal: %f sec" % total_time)

1105

1106
@unittest.skipUnless(has_cairo, 'built without cairo support')
1107
1108
1109
1110
1111
1112
class TestAdvancedInterfaces(unittest.TestCase):
    def test_array_objs(self):
        obj1, obj2 = Everything.test_array_fixed_out_objects()
        self.assertTrue(isinstance(obj1, Everything.TestObj))
        self.assertTrue(isinstance(obj2, Everything.TestObj))
        self.assertNotEqual(obj1, obj2)
1113
1114

    def test_obj_skip_return_val(self):
Johan Dahlin's avatar
Johan Dahlin committed
1115
1116
        obj = Everything.TestObj()
        ret = obj.skip_return_val(50, 42.0, 60, 2, 3)
1117
1118
1119
1120
        self.assertEqual(len(ret), 3)
        self.assertEqual(ret[0], 51)
        self.assertEqual(ret[1], 61)
        self.assertEqual(ret[2], 32)
1121

1122
    def test_obj_skip_return_val_no_out(self):
Johan Dahlin's avatar
Johan Dahlin committed
1123
        obj = Everything.TestObj()
1124
1125
1126
1127
        # raises an error for 0, succeeds for any other value
        self.assertRaises(GLib.GError, obj.skip_return_val_no_out, 0)

        ret = obj.skip_return_val_no_out(1)
1128
        self.assertEqual(ret, None)
1129

1130

1131
@unittest.skipUnless(has_cairo, 'built without cairo support')
1132
1133
class TestSignals(unittest.TestCase):
    def test_object_param_signal(self):
Johan Dahlin's avatar
Johan Dahlin committed
1134
        obj = Everything.TestObj()
1135

1136
        def callback(obj, obj_param):
1137
            self.assertEqual(obj_param.props.int, 3)
1138
            self.assertGreater(obj_param.__grefcount__, 1)
1139
            obj.called = True
1140

1141
        obj.called = False
1142
1143
        obj.connect('sig-with-obj', callback)
        obj.emit_sig_with_obj()
1144
        self.assertTrue(obj.called)
1145

1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
    def test_int64_param_from_py(self):
        obj = Everything.TestObj()

        def callback(obj, i):
            obj.callback_i = i
            return i

        obj.callback_i = None
        obj.connect('sig-with-int64-prop', callback)
        rv = obj.emit('sig-with-int64-prop', GObject.G_MAXINT64)
        self.assertEqual(rv, GObject.G_MAXINT64)
        self.assertEqual(obj.callback_i, GObject.G_MAXINT64)

    def test_uint64_param_from_py(self):
        obj = Everything.TestObj()

        def callback(obj, i):
            obj.callback_i = i
            return i

        obj.callback_i = None
        obj.connect('sig-with-uint64-prop', callback)
        rv = obj.emit('sig-with-uint64-prop', GObject.G_MAXUINT64)
        self.assertEqual(rv, GObject.G_MAXUINT64)
        self.assertEqual(obj.callback_i, GObject.G_MAXUINT64)

    def test_int64_param_from_c(self):
        obj = Everything.TestObj()

        def callback(obj, i):
            obj.callback_i = i
            return i

        obj.callback_i = None

        obj.connect('sig-with-int64-prop', callback)
        obj.emit_sig_with_int64()
        self.assertEqual(obj.callback_i, GObject.G_MAXINT64)

    def test_uint64_param_from_c(self):
        obj = Everything.TestObj()

        def callback(obj, i):
            obj.callback_i = i
            return i

        obj.callback_i = None

        obj.connect('sig-with-uint64-prop', callback)
        obj.emit_sig_with_uint64()
        self.assertEqual(obj.callback_i, GObject.G_MAXUINT64)

1198

1199
1200
@unittest.skipUnless(has_cairo, 'built without cairo support')
@unittest.skipUnless(Gtk, 'Gtk not available')
1201
1202
1203
1204
1205
class TestPango(unittest.TestCase):
    def test_cairo_font_options(self):
        screen = Gtk.Window().get_screen()
        font_opts = screen.get_font_options()
        self.assertEqual(type(font_opts.get_subpixel_order()), int)