Debian Codegraph @

tests/test_everything.py

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