Debian Codegraph @

tests/test_signal.py

raw
1 import gc
2 import unittest
3 import sys
4 import weakref
5 import threading
6 import time
7
8 from gi.repository import GObject, GLib, Regress, Gio
9 from gi import _signalhelper as signalhelper
10 from gi.module import repository as repo
11
12 import testhelper
13 from .helper import capture_glib_warnings, capture_gi_deprecation_warnings
14
15
16 class C(GObject.GObject):
17 __gsignals__ = {
18 "my_signal": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_INT,))
19 }
20
21 def do_my_signal(self, arg):
22 self.arg = arg
23
24
25 class D(C):
26 def do_my_signal(self, arg2):
27 self.arg2 = arg2
28 C.do_my_signal(self, arg2)
29
30
31 class TestSignalCreation(unittest.TestCase):
32 # Bug 540376.
33 def test_illegals(self):
34 self.assertRaises(
35 TypeError,
36 lambda: GObject.signal_new("test", None, 0, None, (GObject.TYPE_LONG,)),
37 )
38
39
40 class TestChaining(unittest.TestCase):
41 def setUp(self):
42 self.inst = C()
43 self.inst.connect("my_signal", self.my_signal_handler_cb, 1, 2, 3)
44
45 def my_signal_handler_cb(self, *args):
46 assert len(args) == 5
47 assert isinstance(args[0], C)
48 assert args[0] == self.inst
49
50 assert isinstance(args[1], int)
51 assert args[1] == 42
52
53 assert args[2:] == (1, 2, 3)
54
55 def test_chaining(self):
56 self.inst.emit("my_signal", 42)
57 assert self.inst.arg == 42
58
59 def test_chaining2(self):
60 inst2 = D()
61 inst2.emit("my_signal", 44)
62 assert inst2.arg == 44
63 assert inst2.arg2 == 44
64
65
66 # This is for bug 153718
67
68
69 class TestGSignalsError(unittest.TestCase):
70 def test_invalid_type(self, *args):
71 def foo():
72 class Foo(GObject.GObject):
73 __gsignals__ = None
74
75 self.assertRaises(TypeError, foo)
76 gc.collect()
77
78 def test_invalid_name(self, *args):
79 def foo():
80 class Foo(GObject.GObject):
81 __gsignals__ = {"not-exists": "override"}
82
83 with capture_glib_warnings(allow_warnings=True):
84 self.assertRaises(TypeError, foo)
85 gc.collect()
86
87
88 class TestGPropertyError(unittest.TestCase):
89 def test_invalid_type(self, *args):
90 def foo():
91 class Foo(GObject.GObject):
92 __gproperties__ = None
93
94 self.assertRaises(TypeError, foo)
95 gc.collect()
96
97 def test_invalid_name(self, *args):
98 def foo():
99 class Foo(GObject.GObject):
100 __gproperties__ = {None: None}
101
102 self.assertRaises(TypeError, foo)
103 gc.collect()
104
105
106 class TestList(unittest.TestCase):
107 def test_list_names(self):
108 self.assertEqual(GObject.signal_list_names(C), ("my-signal",))
109
110
111 def my_accumulator(ihint, return_accu, handler_return, user_data):
112 """An accumulator that stops emission when the sum of handler
113 returned values reaches 3.
114 """
115 assert user_data == "accum data"
116 if return_accu >= 3:
117 return False, return_accu
118 return True, return_accu + handler_return
119
120
121 class Foo(GObject.GObject):
122 my_acc_signal = GObject.Signal(
123 return_type=GObject.TYPE_INT,
124 flags=GObject.SignalFlags.RUN_LAST,
125 accumulator=my_accumulator,
126 accu_data="accum data",
127 )
128
129 my_other_acc_signal = GObject.Signal(
130 return_type=GObject.TYPE_BOOLEAN,
131 flags=GObject.SignalFlags.RUN_LAST,
132 accumulator=GObject.signal_accumulator_true_handled,
133 )
134
135 my_acc_first_wins = GObject.Signal(
136 return_type=GObject.TYPE_BOOLEAN,
137 flags=GObject.SignalFlags.RUN_LAST,
138 accumulator=GObject.signal_accumulator_first_wins,
139 )
140
141
142 class TestAccumulator(unittest.TestCase):
143 def test_accumulator(self):
144 inst = Foo()
145 inst.my_acc_signal.connect(lambda obj: 1)
146 inst.my_acc_signal.connect(lambda obj: 2)
147 # the value returned in the following handler will not be
148 # considered, because at this point the accumulator already
149 # reached its limit.
150 inst.my_acc_signal.connect(lambda obj: 3)
151 retval = inst.my_acc_signal.emit()
152 self.assertEqual(retval, 3)
153
154 def test_accumulator_true_handled(self):
155 inst = Foo()
156 inst.my_other_acc_signal.connect(self._true_handler1)
157 inst.my_other_acc_signal.connect(self._true_handler2)
158 # the following handler will not be called because handler2
159 # returns True, so it should stop the emission.
160 inst.my_other_acc_signal.connect(self._true_handler3)
161 self.__true_val = None
162 inst.my_other_acc_signal.emit()
163 self.assertEqual(self.__true_val, 2)
164
165 def test_accumulator_first_wins(self):
166 # First signal hit will always win
167 inst = Foo()
168 inst.my_acc_first_wins.connect(self._true_handler3)
169 inst.my_acc_first_wins.connect(self._true_handler1)
170 inst.my_acc_first_wins.connect(self._true_handler2)
171 self.__true_val = None
172 inst.my_acc_first_wins.emit()
173 self.assertEqual(self.__true_val, 3)
174
175 def _true_handler1(self, obj):
176 self.__true_val = 1
177 return False
178
179 def _true_handler2(self, obj):
180 self.__true_val = 2
181 return True
182
183 def _true_handler3(self, obj):
184 self.__true_val = 3
185 return False
186
187
188 class E(GObject.GObject):
189 __gsignals__ = {"signal": (GObject.SignalFlags.RUN_FIRST, None, ())}
190
191 # Property used to test detailed signal
192 prop = GObject.Property(type=int, default=0)
193
194 def __init__(self):
195 GObject.GObject.__init__(self)
196 self.status = 0
197
198 def do_signal(self):
199 assert self.status == 0
200 self.status = 1
201
202
203 class F(GObject.GObject):
204 __gsignals__ = {"signal": (GObject.SignalFlags.RUN_FIRST, None, ())}
205
206 def __init__(self):
207 GObject.GObject.__init__(self)
208 self.status = 0
209
210 def do_signal(self):
211 self.status += 1
212
213
214 class TestEmissionHook(unittest.TestCase):
215 def test_add(self):
216 self.hook = True
217 e = E()
218 e.connect("signal", self._callback)
219 GObject.add_emission_hook(E, "signal", self._emission_hook)
220 e.emit("signal")
221 self.assertEqual(e.status, 3)
222
223 def test_remove(self):
224 self.hook = False
225 e = E()
226 e.connect("signal", self._callback)
227 hook_id = GObject.add_emission_hook(E, "signal", self._emission_hook)
228 GObject.remove_emission_hook(E, "signal", hook_id)
229 e.emit("signal")
230 self.assertEqual(e.status, 3)
231
232 def _emission_hook(self, e):
233 self.assertEqual(e.status, 1)
234 e.status = 2
235
236 def _callback(self, e):
237 if self.hook:
238 self.assertEqual(e.status, 2)
239 else:
240 self.assertEqual(e.status, 1)
241 e.status = 3
242
243 def test_callback_return_false(self):
244 self.hook = False
245 obj = F()
246
247 def _emission_hook(obj):
248 obj.status += 1
249 return False
250
251 GObject.add_emission_hook(obj, "signal", _emission_hook)
252 obj.emit("signal")
253 obj.emit("signal")
254 self.assertEqual(obj.status, 3)
255
256 def test_callback_return_true(self):
257 self.hook = False
258 obj = F()
259
260 def _emission_hook(obj):
261 obj.status += 1
262 return True
263
264 hook_id = GObject.add_emission_hook(obj, "signal", _emission_hook)
265 obj.emit("signal")
266 obj.emit("signal")
267 GObject.remove_emission_hook(obj, "signal", hook_id)
268 self.assertEqual(obj.status, 4)
269
270 def test_callback_return_true_but_remove(self):
271 self.hook = False
272 obj = F()
273
274 def _emission_hook(obj):
275 obj.status += 1
276 return True
277
278 hook_id = GObject.add_emission_hook(obj, "signal", _emission_hook)
279 obj.emit("signal")
280 GObject.remove_emission_hook(obj, "signal", hook_id)
281 obj.emit("signal")
282 self.assertEqual(obj.status, 3)
283
284
285 class TestMatching(unittest.TestCase):
286 class Object(GObject.Object):
287 status = 0
288 prop = GObject.Property(type=int, default=0)
289
290 @GObject.Signal()
291 def my_signal(self):
292 pass
293
294 @unittest.expectedFailure # https://bugzilla.gnome.org/show_bug.cgi?id=692918
295 def test_signal_handler_block_matching(self):
296 def dummy(*args):
297 """Hack to work around:"""
298
299 def foo(obj):
300 obj.status += 1
301
302 obj = self.Object()
303 handler_id = GObject.signal_connect_closure(obj, "my-signal", foo, after=False)
304 handler_id
305
306 self.assertEqual(obj.status, 0)
307 obj.emit("my-signal")
308 self.assertEqual(obj.status, 1)
309
310 # Blocking by match criteria disables the foo callback
311 signal_id, detail = GObject.signal_parse_name("my-signal", obj, True)
312 count = GObject.signal_handlers_block_matched(
313 obj,
314 GObject.SignalMatchType.ID | GObject.SignalMatchType.CLOSURE,
315 signal_id=signal_id,
316 detail=detail,
317 closure=foo,
318 func=dummy,
319 data=dummy,
320 )
321 self.assertEqual(count, 1)
322 obj.emit("my-signal")
323 self.assertEqual(obj.status, 1)
324
325 # Unblocking by the same match criteria allows callback to work again
326 count = GObject.signal_handlers_unblock_matched(
327 obj,
328 GObject.SignalMatchType.ID | GObject.SignalMatchType.CLOSURE,
329 signal_id=signal_id,
330 detail=detail,
331 closure=foo,
332 func=dummy,
333 data=dummy,
334 )
335 self.assertEqual(count, 1)
336 obj.emit("my-signal")
337 self.assertEqual(obj.status, 2)
338
339 # Disconnecting by match criteria completely removes the handler
340 count = GObject.signal_handlers_disconnect_matched(
341 obj,
342 GObject.SignalMatchType.ID | GObject.SignalMatchType.CLOSURE,
343 signal_id=signal_id,
344 detail=detail,
345 closure=foo,
346 func=dummy,
347 data=dummy,
348 )
349 self.assertEqual(count, 1)
350 obj.emit("my-signal")
351 self.assertEqual(obj.status, 2)
352
353 def test_signal_handler_find(self):
354 def foo(obj):
355 obj.status += 1
356
357 obj = self.Object()
358 handler_id = GObject.signal_connect_closure(obj, "my-signal", foo, after=False)
359
360 signal_id, detail = GObject.signal_parse_name("my-signal", obj, True)
361 found_id = GObject.signal_handler_find(
362 obj,
363 GObject.SignalMatchType.ID,
364 signal_id=signal_id,
365 detail=detail,
366 closure=None,
367 func=0,
368 data=0,
369 )
370 self.assertEqual(handler_id, found_id)
371
372
373 class TestClosures(unittest.TestCase):
374 def setUp(self):
375 self.count = 0
376 self.emission_stopped = False
377 self.emission_error = False
378 self.handler_pending = False
379
380 def _callback_handler_pending(self, e):
381 signal_id, detail = GObject.signal_parse_name("signal", e, True)
382 self.handler_pending = GObject.signal_has_handler_pending(
383 e, signal_id, detail, may_be_blocked=False
384 )
385
386 def _callback(self, e):
387 self.count += 1
388
389 def _callback_stop_emission(self, obj, prop, stop_it):
390 if stop_it:
391 obj.stop_emission_by_name("notify::prop")
392 self.emission_stopped = True
393 else:
394 self.count += 1
395
396 def _callback_invalid_stop_emission_name(self, obj, prop):
397 with capture_glib_warnings(allow_warnings=True, allow_criticals=True) as warn:
398 obj.stop_emission_by_name("notasignal::baddetail")
399 self.emission_error = True
400 self.assertTrue(warn)
401
402 def test_disconnect_by_func(self):
403 e = E()
404 e.connect("signal", self._callback)
405 e.disconnect_by_func(self._callback)
406 e.emit("signal")
407 self.assertEqual(self.count, 0)
408
409 def test_disconnect(self):
410 e = E()
411 handler_id = e.connect("signal", self._callback)
412 self.assertTrue(e.handler_is_connected(handler_id))
413 e.disconnect(handler_id)
414 e.emit("signal")
415 self.assertEqual(self.count, 0)
416 self.assertFalse(e.handler_is_connected(handler_id))
417
418 def test_stop_emission_by_name(self):
419 e = E()
420
421 # Sandwich a callback that stops emission in between a callback that increments
422 e.connect("notify::prop", self._callback_stop_emission, False)
423 e.connect("notify::prop", self._callback_stop_emission, True)
424 e.connect("notify::prop", self._callback_stop_emission, False)
425
426 e.set_property("prop", 1234)
427 self.assertEqual(e.get_property("prop"), 1234)
428 self.assertEqual(self.count, 1)
429 self.assertTrue(self.emission_stopped)
430
431 def test_stop_emission_by_name_error(self):
432 e = E()
433
434 e.connect("notify::prop", self._callback_invalid_stop_emission_name)
435 with capture_glib_warnings():
436 e.set_property("prop", 1234)
437 self.assertTrue(self.emission_error)
438
439 def test_handler_block(self):
440 e = E()
441 e.connect("signal", self._callback)
442 e.handler_block_by_func(self._callback)
443 e.emit("signal")
444 self.assertEqual(self.count, 0)
445
446 def test_handler_unblock(self):
447 e = E()
448 handler_id = e.connect("signal", self._callback)
449 e.handler_block(handler_id)
450 e.handler_unblock_by_func(self._callback)
451 e.emit("signal")
452 self.assertEqual(self.count, 1)
453
454 def test_handler_block_method(self):
455 # Filed as #375589
456 class A:
457 def __init__(self):
458 self.a = 0
459
460 def callback(self, o):
461 self.a = 1
462 o.handler_block_by_func(self.callback)
463
464 inst = A()
465 e = E()
466 e.connect("signal", inst.callback)
467 e.emit("signal")
468 self.assertEqual(inst.a, 1)
469 gc.collect()
470
471 def test_gstring(self):
472 class C(GObject.GObject):
473 __gsignals__ = {
474 "my_signal": (
475 GObject.SignalFlags.RUN_LAST,
476 GObject.TYPE_GSTRING,
477 (GObject.TYPE_GSTRING,),
478 )
479 }
480
481 def __init__(self, test):
482 GObject.GObject.__init__(self)
483 self.test = test
484
485 def do_my_signal(self, data):
486 self.data = data
487 self.test.assertEqual(len(data), 3)
488 return "".join([data[2], data[1], data[0]])
489
490 c = C(self)
491 data = c.emit("my_signal", "\01\00\02")
492 self.assertEqual(data, "\02\00\01")
493
494 def test_handler_pending(self):
495 obj = F()
496 obj.connect("signal", self._callback_handler_pending)
497 obj.connect("signal", self._callback)
498
499 self.assertEqual(self.count, 0)
500 self.assertEqual(self.handler_pending, False)
501
502 obj.emit("signal")
503 self.assertEqual(self.count, 1)
504 self.assertEqual(self.handler_pending, True)
505
506 def test_signal_handlers_destroy(self):
507 obj = F()
508 obj.connect("signal", self._callback)
509 obj.connect("signal", self._callback)
510 obj.connect("signal", self._callback)
511
512 obj.emit("signal")
513 self.assertEqual(self.count, 3)
514
515 # count should remain at 3 after all handlers are destroyed
516 GObject.signal_handlers_destroy(obj)
517 obj.emit("signal")
518 self.assertEqual(self.count, 3)
519
520
521 class SigPropClass(GObject.GObject):
522 __gsignals__ = {
523 "my_signal": (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_INT,))
524 }
525
526 __gproperties__ = {
527 "foo": (
528 str,
529 None,
530 None,
531 "",
532 GObject.ParamFlags.WRITABLE | GObject.ParamFlags.CONSTRUCT,
533 ),
534 }
535
536 signal_emission_failed = False
537
538 def do_my_signal(self, arg):
539 self.arg = arg
540
541 def do_set_property(self, pspec, value):
542 if pspec.name == "foo":
543 self._foo = value
544 else:
545 raise AttributeError(f"unknown property {pspec.name}")
546 try:
547 self.emit("my-signal", 1)
548 except TypeError:
549 self.signal_emission_failed = True
550
551
552 class TestSigProp(unittest.TestCase):
553 def test_emit_in_property_setter(self):
554 obj = SigPropClass()
555 self.assertFalse(obj.signal_emission_failed)
556
557
558 class CM(GObject.GObject):
559 __gsignals__ = {
560 "test1": (GObject.SignalFlags.RUN_FIRST, None, ()),
561 "test2": (GObject.SignalFlags.RUN_LAST, None, (str,)),
562 "test3": (GObject.SignalFlags.RUN_LAST, int, (GObject.TYPE_DOUBLE,)),
563 "test4": (
564 GObject.SignalFlags.RUN_FIRST,
565 None,
566 (
567 bool,
568 int,
569 GObject.TYPE_FLOAT,
570 GObject.TYPE_DOUBLE,
571 int,
572 GObject.TYPE_UINT,
573 GObject.TYPE_ULONG,
574 ),
575 ),
576 "test_float": (
577 GObject.SignalFlags.RUN_LAST,
578 GObject.TYPE_FLOAT,
579 (GObject.TYPE_FLOAT,),
580 ),
581 "test_double": (
582 GObject.SignalFlags.RUN_LAST,
583 GObject.TYPE_DOUBLE,
584 (GObject.TYPE_DOUBLE,),
585 ),
586 "test_int64": (
587 GObject.SignalFlags.RUN_LAST,
588 GObject.TYPE_INT64,
589 (GObject.TYPE_INT64,),
590 ),
591 "test_string": (GObject.SignalFlags.RUN_LAST, str, (str,)),
592 "test_object": (GObject.SignalFlags.RUN_LAST, object, (object,)),
593 "test_paramspec": (GObject.SignalFlags.RUN_LAST, GObject.ParamSpec, ()),
594 "test_paramspec_in": (
595 GObject.SignalFlags.RUN_LAST,
596 GObject.ParamSpec,
597 (GObject.ParamSpec,),
598 ),
599 "test_gvalue": (GObject.SignalFlags.RUN_LAST, GObject.Value, (GObject.Value,)),
600 "test_gvalue_ret": (
601 GObject.SignalFlags.RUN_LAST,
602 GObject.Value,
603 (GObject.TYPE_GTYPE,),
604 ),
605 }
606
607 testprop = GObject.Property(type=int)
608
609
610 class _TestCMarshaller:
611 def setUp(self):
612 self.obj = CM()
613 testhelper.connectcallbacks(self.obj)
614
615 def test_test1(self):
616 self.obj.emit("test1")
617
618 def test_test2(self):
619 self.obj.emit("test2", "string")
620
621 def test_test3(self):
622 rv = self.obj.emit("test3", 42.0)
623 self.assertEqual(rv, 20)
624
625 def test_test4(self):
626 self.obj.emit("test4", True, 10, 3.14, 1.78, 20, 30, 31)
627
628 def test_float(self):
629 rv = self.obj.emit("test-float", 1.234)
630 self.assertTrue(rv >= 1.233999 and rv <= 1.2400001, rv)
631
632 def test_double(self):
633 rv = self.obj.emit("test-double", 1.234)
634 self.assertEqual(rv, 1.234)
635
636 def test_int64(self):
637 rv = self.obj.emit("test-int64", 102030405)
638 self.assertEqual(rv, 102030405)
639
640 rv = self.obj.emit("test-int64", GLib.MAXINT64)
641 self.assertEqual(rv, GLib.MAXINT64 - 1)
642
643 rv = self.obj.emit("test-int64", GLib.MININT64)
644 self.assertEqual(rv, GLib.MININT64)
645
646 def test_string(self):
647 rv = self.obj.emit("test-string", "str")
648 self.assertEqual(rv, "str")
649
650 def test_object(self):
651 rv = self.obj.emit("test-object", self)
652 self.assertEqual(rv, self)
653
654 def test_paramspec(self):
655 rv = self.obj.emit("test-paramspec")
656 self.assertEqual(rv.name, "test-param")
657 self.assertEqual(rv.nick, "test")
658
659 def test_paramspec_in(self):
660 rv = GObject.param_spec_boolean(
661 "mybool", "test-bool", "do something", True, GObject.ParamFlags.READABLE
662 )
663
664 rv2 = self.obj.emit("test-paramspec-in", rv)
665 self.assertEqual(type(rv), type(rv2))
666 self.assertEqual(rv2.name, "mybool")
667 self.assertEqual(rv2.nick, "test-bool")
668
669 def test_C_paramspec(self):
670 self.notify_called = False
671
672 def cb_notify(obj, prop):
673 self.notify_called = True
674 self.assertEqual(obj, self.obj)
675 self.assertEqual(prop.name, "testprop")
676
677 self.obj.connect("notify", cb_notify)
678 self.obj.set_property("testprop", 42)
679 self.assertTrue(self.notify_called)
680
681 def test_gvalue(self):
682 # implicit int
683 rv = self.obj.emit("test-gvalue", 42)
684 self.assertEqual(rv, 42)
685
686 # explicit float
687 v = GObject.Value(GObject.TYPE_FLOAT, 1.234)
688 rv = self.obj.emit("test-gvalue", v)
689 self.assertAlmostEqual(rv, 1.234, places=4)
690
691 # implicit float
692 rv = self.obj.emit("test-gvalue", 1.234)
693 self.assertAlmostEqual(rv, 1.234, places=4)
694
695 # explicit int64
696 v = GObject.Value(GObject.TYPE_INT64, GLib.MAXINT64)
697 rv = self.obj.emit("test-gvalue", v)
698 self.assertEqual(rv, GLib.MAXINT64)
699
700 # explicit uint64
701 v = GObject.Value(GObject.TYPE_UINT64, GLib.MAXUINT64)
702 rv = self.obj.emit("test-gvalue", v)
703 self.assertEqual(rv, GLib.MAXUINT64)
704
705 @unittest.expectedFailure # https://bugzilla.gnome.org/show_bug.cgi?id=705291
706 def test_gvalue_implicit_int64(self):
707 # implicit int64
708 rv = self.obj.emit("test-gvalue", GLib.MAXINT64)
709 self.assertEqual(rv, GLib.MAXINT64)
710
711 # implicit uint64
712 rv = self.obj.emit("test-gvalue", GLib.MAXUINT64)
713 self.assertEqual(rv, GLib.MAXUINT64)
714
715 def test_gvalue_ret(self):
716 self.assertEqual(
717 self.obj.emit("test-gvalue-ret", GObject.TYPE_INT), GLib.MAXINT
718 )
719 self.assertEqual(
720 self.obj.emit("test-gvalue-ret", GObject.TYPE_UINT), GLib.MAXUINT
721 )
722 self.assertEqual(
723 self.obj.emit("test-gvalue-ret", GObject.TYPE_INT64), GLib.MAXINT64
724 )
725 self.assertEqual(
726 self.obj.emit("test-gvalue-ret", GObject.TYPE_UINT64), GLib.MAXUINT64
727 )
728 self.assertEqual(self.obj.emit("test-gvalue-ret", GObject.TYPE_STRING), "hello")
729
730
731 class TestCMarshaller(_TestCMarshaller, unittest.TestCase):
732 pass
733
734
735 # Test for 374653
736
737
738 class TestPyGValue(unittest.TestCase):
739 def test_none_null_boxed_conversion(self):
740 class C(GObject.GObject):
741 __gsignals__ = {
742 "my_boxed_signal": (GObject.SignalFlags.RUN_LAST, GObject.TYPE_STRV, ())
743 }
744
745 obj = C()
746 obj.connect("my-boxed-signal", lambda obj: None)
747 sys.last_type = None
748 obj.emit("my-boxed-signal")
749 assert not sys.last_type
750
751
752 class TestSignalDecorator(unittest.TestCase):
753 class Decorated(GObject.GObject):
754 value = 0
755
756 @GObject.Signal
757 def pushed(self):
758 """This will push."""
759 self.value += 1
760
761 @GObject.Signal(flags=GObject.SignalFlags.RUN_LAST)
762 def pulled(self):
763 self.value -= 1
764
765 @GObject.Signal(flags=GObject.SignalFlags.DETAILED)
766 def detailed(self):
767 self.value -= 1
768
769 stomped = GObject.Signal("stomped", arg_types=(int,), doc="This will stomp.")
770 unnamed = GObject.Signal()
771
772 class DecoratedOverride(GObject.GObject):
773 overridden_closure_called = False
774 notify_called = False
775 value = GObject.Property(type=int, default=0)
776
777 @GObject.SignalOverride
778 def notify(self, *args, **kargs):
779 self.overridden_closure_called = True
780
781 def on_notify(self, obj, prop):
782 self.notify_called = True
783
784 def setUp(self):
785 self.unnamedCalled = False
786
787 def onUnnamed(self, obj):
788 self.unnamedCalled = True
789
790 def test_disconnect(self):
791 decorated = self.Decorated()
792 id_ = decorated.pushed.connect(lambda *args: None)
793 decorated.pushed.disconnect(id_)
794
795 def test_signal_repr(self):
796 decorated = self.Decorated()
797 assert repr(decorated.pushed) == 'BoundSignal("pushed")'
798
799 def test_signal_call(self):
800 decorated = self.Decorated()
801 assert decorated.value == 0
802 decorated.pushed()
803 assert decorated.value == 1
804
805 def test_connect_detailed(self):
806 decorated = self.Decorated()
807 id_ = decorated.detailed.connect_detailed(lambda *args: None, "foo")
808 decorated.pushed.disconnect(id_)
809
810 def test_get_signal_args(self):
811 self.assertEqual(
812 self.Decorated.pushed.get_signal_args(),
813 (GObject.SignalFlags.RUN_FIRST, None, (), None, None),
814 )
815 self.assertEqual(
816 self.Decorated.pulled.get_signal_args(),
817 (GObject.SignalFlags.RUN_LAST, None, (), None, None),
818 )
819 self.assertEqual(
820 self.Decorated.stomped.get_signal_args(),
821 (GObject.SignalFlags.RUN_FIRST, None, (int,), None, None),
822 )
823
824 def test_closures_called(self):
825 decorated = self.Decorated()
826 self.assertEqual(decorated.value, 0)
827 decorated.pushed.emit()
828 self.assertEqual(decorated.value, 1)
829 decorated.pulled.emit()
830 self.assertEqual(decorated.value, 0)
831
832 def test_signal_copy(self):
833 blah = self.Decorated.stomped.copy("blah")
834 self.assertEqual(str(blah), blah)
835 self.assertEqual(blah.func, self.Decorated.stomped.func)
836 self.assertEqual(blah.flags, self.Decorated.stomped.flags)
837 self.assertEqual(blah.return_type, self.Decorated.stomped.return_type)
838 self.assertEqual(blah.arg_types, self.Decorated.stomped.arg_types)
839 self.assertEqual(blah.__doc__, self.Decorated.stomped.__doc__)
840
841 def test_doc_string(self):
842 # Test the two techniques for setting doc strings on the signals
843 # class variables, through the "doc" keyword or as the getter doc string.
844 self.assertEqual(self.Decorated.stomped.__doc__, "This will stomp.")
845 self.assertEqual(self.Decorated.pushed.__doc__, "This will push.")
846
847 def test_unnamed_signal_gets_named(self):
848 self.assertEqual(str(self.Decorated.unnamed), "unnamed")
849
850 def test_unnamed_signal_gets_called(self):
851 obj = self.Decorated()
852 obj.connect("unnamed", self.onUnnamed)
853 self.assertEqual(self.unnamedCalled, False)
854 obj.emit("unnamed")
855 self.assertEqual(self.unnamedCalled, True)
856
857 def test_overridden_signal(self):
858 # Test that the pushed signal is called in with super and the override
859 # which should both increment the "value" to 3
860 obj = self.DecoratedOverride()
861 obj.connect("notify", obj.on_notify)
862 self.assertEqual(obj.value, 0)
863 obj.value = 1
864 self.assertEqual(obj.value, 1)
865 self.assertTrue(obj.overridden_closure_called)
866 self.assertTrue(obj.notify_called)
867
868
869 class TestSignalConnectors(unittest.TestCase):
870 class CustomButton(GObject.GObject):
871 on_notify_called = False
872 value = GObject.Property(type=int)
873
874 @GObject.Signal(arg_types=(int,))
875 def clicked(self, value):
876 self.value = value
877
878 def setUp(self):
879 self.obj = None
880 self.value = None
881
882 def on_clicked(self, obj, value):
883 self.obj = obj
884 self.value = value
885
886 def test_signal_notify(self):
887 def on_notify(obj, param):
888 obj.on_notify_called = True
889
890 obj = self.CustomButton()
891 obj.connect("notify", on_notify)
892 self.assertFalse(obj.on_notify_called)
893 obj.notify("value")
894 self.assertTrue(obj.on_notify_called)
895
896 def test_signal_emit(self):
897 # standard callback connection with different forms of emit.
898 obj = self.CustomButton()
899 obj.connect("clicked", self.on_clicked)
900
901 # vanilla
902 obj.emit("clicked", 1)
903 self.assertEqual(obj.value, 1)
904 self.assertEqual(obj, self.obj)
905 self.assertEqual(self.value, 1)
906
907 # using class signal as param
908 self.obj = None
909 self.value = None
910 obj.emit(self.CustomButton.clicked, 1)
911 self.assertEqual(obj, self.obj)
912 self.assertEqual(self.value, 1)
913
914 # using bound signal as param
915 self.obj = None
916 self.value = None
917 obj.emit(obj.clicked, 1)
918 self.assertEqual(obj, self.obj)
919 self.assertEqual(self.value, 1)
920
921 # using bound signal with emit
922 self.obj = None
923 self.value = None
924 obj.clicked.emit(1)
925 self.assertEqual(obj, self.obj)
926 self.assertEqual(self.value, 1)
927
928 def test_signal_class_connect(self):
929 obj = self.CustomButton()
930 obj.connect(self.CustomButton.clicked, self.on_clicked)
931 obj.emit("clicked", 2)
932 self.assertEqual(obj, self.obj)
933 self.assertEqual(self.value, 2)
934
935 def test_signal_bound_connect(self):
936 obj = self.CustomButton()
937 obj.clicked.connect(self.on_clicked)
938 obj.emit("clicked", 3)
939 self.assertEqual(obj, self.obj)
940 self.assertEqual(self.value, 3)
941
942
943 class _ConnectDataTestBase:
944 # Notes:
945 # - self.Object is overridden in sub-classes.
946 # - Numeric suffixes indicate the number of user data args passed in.
947 Object = None
948
949 def run_connect_test(self, emit_args, user_data, flags=0):
950 obj = self.Object()
951 callback_args = []
952
953 def callback(*args):
954 callback_args.append(args)
955 return 0
956
957 obj.connect_data(
958 "sig-with-int64-prop", callback, connect_flags=flags, *user_data
959 )
960 obj.emit("sig-with-int64-prop", *emit_args)
961 self.assertEqual(len(callback_args), 1)
962 return callback_args[0]
963
964 def test_0(self):
965 obj, value = self.run_connect_test([GLib.MAXINT64], user_data=[])
966 self.assertIsInstance(obj, self.Object)
967 self.assertEqual(value, GLib.MAXINT64)
968
969 def test_1(self):
970 obj, value, data = self.run_connect_test([GLib.MAXINT64], user_data=["mydata"])
971 self.assertIsInstance(obj, self.Object)
972 self.assertEqual(value, GLib.MAXINT64)
973 self.assertEqual(data, "mydata")
974
975 def test_after_0(self):
976 obj, value = self.run_connect_test(
977 [GLib.MAXINT64], user_data=[], flags=GObject.ConnectFlags.AFTER
978 )
979 self.assertIsInstance(obj, self.Object)
980 self.assertEqual(value, GLib.MAXINT64)
981
982 def test_after_1(self):
983 obj, value, data = self.run_connect_test(
984 [GLib.MAXINT64], user_data=["mydata"], flags=GObject.ConnectFlags.AFTER
985 )
986 self.assertIsInstance(obj, self.Object)
987 self.assertEqual(value, GLib.MAXINT64)
988 self.assertEqual(data, "mydata")
989
990 def test_swaped_0(self):
991 # Swapped only works with a single user data argument.
992 with self.assertRaises(ValueError):
993 self.run_connect_test(
994 [GLib.MAXINT64], user_data=[], flags=GObject.ConnectFlags.SWAPPED
995 )
996
997 def test_swaped_1(self):
998 # Notice obj and data are reversed in the return.
999 data, value, obj = self.run_connect_test(
1000 [GLib.MAXINT64], user_data=["mydata"], flags=GObject.ConnectFlags.SWAPPED
1001 )
1002 self.assertIsInstance(obj, self.Object)
1003 self.assertEqual(value, GLib.MAXINT64)
1004 self.assertEqual(data, "mydata")
1005
1006 def test_swaped_2(self):
1007 # Swapped only works with a single user data argument.
1008 with self.assertRaises(ValueError):
1009 self.run_connect_test(
1010 [GLib.MAXINT64], user_data=[1, 2], flags=GObject.ConnectFlags.SWAPPED
1011 )
1012
1013 def test_after_and_swapped_0(self):
1014 # Swapped only works with a single user data argument.
1015 with self.assertRaises(ValueError):
1016 self.run_connect_test(
1017 [GLib.MAXINT64],
1018 user_data=[],
1019 flags=GObject.ConnectFlags.AFTER | GObject.ConnectFlags.SWAPPED,
1020 )
1021
1022 def test_after_and_swapped_1(self):
1023 # Notice obj and data are reversed in the return.
1024 data, value, obj = self.run_connect_test(
1025 [GLib.MAXINT64],
1026 user_data=["mydata"],
1027 flags=GObject.ConnectFlags.AFTER | GObject.ConnectFlags.SWAPPED,
1028 )
1029 self.assertIsInstance(obj, self.Object)
1030 self.assertEqual(value, GLib.MAXINT64)
1031 self.assertEqual(data, "mydata")
1032
1033 def test_after_and_swapped_2(self):
1034 # Swapped only works with a single user data argument.
1035 with self.assertRaises(ValueError):
1036 self.run_connect_test(
1037 [GLib.MAXINT64],
1038 user_data=[],
1039 flags=GObject.ConnectFlags.AFTER | GObject.ConnectFlags.SWAPPED,
1040 )
1041
1042
1043 class TestConnectDataNonIntrospected(unittest.TestCase, _ConnectDataTestBase):
1044 # This tests connect_data with non-introspected signals
1045 # (created in Python in this case).
1046 class Object(GObject.Object):
1047 test = GObject.Signal()
1048 sig_with_int64_prop = GObject.Signal(
1049 return_type=GObject.TYPE_INT64,
1050 arg_types=[GObject.TYPE_INT64],
1051 flags=GObject.SignalFlags.RUN_LAST,
1052 )
1053
1054
1055 class TestConnectDataIntrospected(unittest.TestCase, _ConnectDataTestBase):
1056 # This tests connect_data with introspected signals brought in from Regress.
1057 Object = Regress.TestObj
1058
1059
1060 class TestInstallSignals(unittest.TestCase):
1061 # These tests only test how signalhelper.install_signals works
1062 # with the __gsignals__ dict and therefore does not need to use
1063 # GObject as a base class because that would automatically call
1064 # install_signals within the meta-class.
1065 class Base:
1066 __gsignals__ = {"test": (0, None, ())}
1067
1068 class Sub1(Base):
1069 pass
1070
1071 class Sub2(Base):
1072 @GObject.Signal
1073 def sub2test(self):
1074 pass
1075
1076 def setUp(self):
1077 self.assertEqual(len(self.Base.__gsignals__), 1)
1078 signalhelper.install_signals(self.Base)
1079 self.assertEqual(len(self.Base.__gsignals__), 1)
1080
1081 def test_subclass_gets_empty_gsignals_dict(self):
1082 # Installing signals will add the __gsignals__ dict to a class
1083 # if it doesn't already exists.
1084 self.assertFalse("__gsignals__" in self.Sub1.__dict__)
1085 signalhelper.install_signals(self.Sub1)
1086 self.assertTrue("__gsignals__" in self.Sub1.__dict__)
1087 # Sub1 should only contain an empty signals dict, this tests:
1088 # https://bugzilla.gnome.org/show_bug.cgi?id=686496
1089 self.assertEqual(self.Sub1.__dict__["__gsignals__"], {})
1090
1091 def test_subclass_with_decorator_gets_gsignals_dict(self):
1092 self.assertFalse("__gsignals__" in self.Sub2.__dict__)
1093 signalhelper.install_signals(self.Sub2)
1094 self.assertTrue("__gsignals__" in self.Sub2.__dict__)
1095 self.assertEqual(len(self.Base.__gsignals__), 1)
1096 self.assertEqual(len(self.Sub2.__gsignals__), 1)
1097 self.assertTrue("sub2test" in self.Sub2.__gsignals__)
1098
1099 # Make sure the vfunc was added
1100 self.assertTrue(hasattr(self.Sub2, "do_sub2test"))
1101
1102
1103 class TestPython3Signals(unittest.TestCase):
1104 class AnnotatedClass(GObject.GObject):
1105 @GObject.Signal
1106 def sig1(self, a: int, b: float):
1107 pass
1108
1109 @GObject.Signal(flags=GObject.SignalFlags.RUN_LAST)
1110 def sig2_with_return(self, a: int, b: float) -> str:
1111 return "test"
1112
1113 def test_annotations(self):
1114 self.assertEqual(
1115 signalhelper.get_signal_annotations(self.AnnotatedClass.sig1.func),
1116 (None, (int, float)),
1117 )
1118 self.assertEqual(
1119 signalhelper.get_signal_annotations(
1120 self.AnnotatedClass.sig2_with_return.func
1121 ),
1122 (str, (int, float)),
1123 )
1124
1125 self.assertEqual(
1126 self.AnnotatedClass.sig2_with_return.get_signal_args(),
1127 (GObject.SignalFlags.RUN_LAST, str, (int, float), None, None),
1128 )
1129 self.assertEqual(self.AnnotatedClass.sig2_with_return.arg_types, (int, float))
1130 self.assertEqual(self.AnnotatedClass.sig2_with_return.return_type, str)
1131
1132 def test_emit_return(self):
1133 obj = self.AnnotatedClass()
1134 self.assertEqual(obj.sig2_with_return.emit(1, 2.0), "test")
1135
1136
1137 class TestSignalModuleLevelFunctions(unittest.TestCase):
1138 def test_signal_list_ids_with_invalid_type(self):
1139 with self.assertRaisesRegex(
1140 TypeError, "type must be instantiable or an interface.*"
1141 ):
1142 GObject.signal_list_ids(GObject.TYPE_INVALID)
1143
1144 def test_signal_list_ids(self):
1145 with self.assertRaisesRegex(
1146 TypeError, "type must be instantiable or an interface.*"
1147 ):
1148 GObject.signal_list_ids(GObject.TYPE_INT)
1149
1150 ids = GObject.signal_list_ids(C)
1151 self.assertEqual(len(ids), 1)
1152 # Note canonicalized names
1153 self.assertEqual(GObject.signal_name(ids[0]), "my-signal")
1154 # There is no signal 0 in gobject
1155 self.assertEqual(GObject.signal_name(0), None)
1156
1157 def test_signal_lookup_with_invalid_type(self):
1158 with self.assertRaisesRegex(
1159 TypeError, "type must be instantiable or an interface.*"
1160 ):
1161 GObject.signal_lookup("NOT_A_SIGNAL_NAME", GObject.TYPE_INVALID)
1162
1163 def test_signal_lookup(self):
1164 ids = GObject.signal_list_ids(C)
1165 self.assertEqual(ids[0], GObject.signal_lookup("my_signal", C))
1166 self.assertEqual(ids[0], GObject.signal_lookup("my-signal", C))
1167
1168 with self.assertRaisesRegex(
1169 TypeError, "type must be instantiable or an interface.*"
1170 ):
1171 GObject.signal_lookup("NOT_A_SIGNAL_NAME", GObject.TYPE_INT)
1172
1173 # Invalid signal names return 0 instead of raising
1174 self.assertEqual(GObject.signal_lookup("NOT_A_SIGNAL_NAME", C), 0)
1175
1176 def test_signal_query(self):
1177 (my_signal_id,) = GObject.signal_list_ids(C)
1178
1179 # Form is: (id, name, gtype, arg_count, return_type, (arg_type1, ...))
1180 my_signal_expected_query_result = [
1181 my_signal_id,
1182 "my-signal",
1183 C.__gtype__,
1184 GObject.SignalFlags.RUN_FIRST,
1185 GObject.TYPE_NONE,
1186 (GObject.TYPE_INT,),
1187 ]
1188 # signal_query(name, type)
1189 self.assertEqual(
1190 list(GObject.signal_query("my-signal", C)), my_signal_expected_query_result
1191 )
1192 # signal_query(signal_id)
1193 self.assertEqual(
1194 list(GObject.signal_query(my_signal_id)), my_signal_expected_query_result
1195 )
1196 # invalid query returns None instead of raising
1197 self.assertEqual(GObject.signal_query(0), None)
1198 self.assertEqual(GObject.signal_query("NOT_A_SIGNAL", C), None)
1199
1200
1201 class TestIntrospectedSignals(unittest.TestCase):
1202 def test_object_param_signal(self):
1203 obj = Regress.TestObj()
1204
1205 def callback(obj, obj_param):
1206 self.assertEqual(obj_param.props.int, 3)
1207 self.assertGreater(obj_param.__grefcount__, 1)
1208 obj.called = True
1209
1210 obj.called = False
1211 obj.connect("sig-with-obj", callback)
1212 obj.emit_sig_with_obj()
1213 self.assertTrue(obj.called)
1214
1215 def test_connect_after(self):
1216 obj = Regress.TestObj()
1217
1218 def callback(obj, obj_param):
1219 obj.called = True
1220
1221 obj.called = False
1222 obj.connect_after("sig-with-obj", callback)
1223 obj.emit_sig_with_obj()
1224 self.assertTrue(obj.called)
1225
1226 def test_int64_param_from_py(self):
1227 obj = Regress.TestObj()
1228
1229 def callback(obj, i):
1230 obj.callback_i = i
1231 return i
1232
1233 obj.callback_i = None
1234 obj.connect("sig-with-int64-prop", callback)
1235 rv = obj.emit("sig-with-int64-prop", GLib.MAXINT64)
1236 self.assertEqual(rv, GLib.MAXINT64)
1237 self.assertEqual(obj.callback_i, GLib.MAXINT64)
1238
1239 def test_uint64_param_from_py(self):
1240 obj = Regress.TestObj()
1241
1242 def callback(obj, i):
1243 obj.callback_i = i
1244 return i
1245
1246 obj.callback_i = None
1247 obj.connect("sig-with-uint64-prop", callback)
1248 rv = obj.emit("sig-with-uint64-prop", GLib.MAXUINT64)
1249 self.assertEqual(rv, GLib.MAXUINT64)
1250 self.assertEqual(obj.callback_i, GLib.MAXUINT64)
1251
1252 def test_int64_param_from_c(self):
1253 obj = Regress.TestObj()
1254
1255 def callback(obj, i):
1256 obj.callback_i = i
1257 return i
1258
1259 obj.callback_i = None
1260
1261 obj.connect("sig-with-int64-prop", callback)
1262 obj.emit_sig_with_int64()
1263 self.assertEqual(obj.callback_i, GLib.MAXINT64)
1264
1265 def test_uint64_param_from_c(self):
1266 obj = Regress.TestObj()
1267
1268 def callback(obj, i):
1269 obj.callback_i = i
1270 return i
1271
1272 obj.callback_i = None
1273
1274 obj.connect("sig-with-uint64-prop", callback)
1275 obj.emit_sig_with_uint64()
1276 self.assertEqual(obj.callback_i, GLib.MAXUINT64)
1277
1278 def test_intarray_ret(self):
1279 obj = Regress.TestObj()
1280
1281 def callback(obj, i):
1282 obj.callback_i = i
1283 return [i, i + 1]
1284
1285 obj.callback_i = None
1286
1287 try:
1288 obj.connect("sig-with-intarray-ret", callback)
1289 except TypeError as e:
1290 # compat with g-i 1.34.x
1291 if "unknown signal" in str(e):
1292 return
1293 raise
1294
1295 rv = obj.emit("sig-with-intarray-ret", 42)
1296 self.assertEqual(obj.callback_i, 42)
1297 self.assertEqual(type(rv), GLib.Array)
1298 self.assertEqual(rv.len, 2)
1299
1300 @unittest.skip("https://bugzilla.gnome.org/show_bug.cgi?id=669496")
1301 def test_array_parm(self):
1302 obj = Regress.TestObj()
1303
1304 def callback(obj, arr):
1305 obj.callback_arr = arr
1306
1307 obj.connect("sig-with-array-prop", callback)
1308 obj.callback_arr = None
1309 self.assertEqual(obj.emit("sig-with-array-prop", [1, 2, GLib.MAXUINT]), None)
1310 self.assertEqual(obj.callback_arr, [1, 2, GLib.MAXUINT])
1311
1312 def test_held_struct_ref(self):
1313 held_structs = []
1314
1315 def callback(obj, struct):
1316 # The struct held by Python will become a copy after this callback exits.
1317 struct.some_int = 42
1318 struct.some_int8 = 42
1319 held_structs.append(struct)
1320
1321 struct = Regress.TestSimpleBoxedA()
1322 obj = Regress.TestObj()
1323
1324 self.assertEqual(struct.some_int, 0)
1325 self.assertEqual(struct.some_int8, 0)
1326
1327 obj.connect("test-with-static-scope-arg", callback)
1328 obj.emit("test-with-static-scope-arg", struct)
1329
1330 # The held struct will be a copy of the modified struct.
1331 self.assertEqual(len(held_structs), 1)
1332 held_struct = held_structs[0]
1333 self.assertEqual(held_struct.some_int, 42)
1334 self.assertEqual(held_struct.some_int8, 42)
1335
1336 # Boxed equality checks pointers by default.
1337 self.assertNotEqual(struct, held_struct)
1338
1339 def test_action(self):
1340 obj = Regress.TestAction()
1341 other_obj = obj.emit("action")
1342 self.assertEqual(other_obj.__grefcount__, 1)
1343 other_obj2 = obj.emit("action2")
1344 self.assertIsNone(other_obj2)
1345
1346
1347 class TestIntrospectedSignalsIssue158(unittest.TestCase):
1348 """The test for https://gitlab.gnome.org/GNOME/pygobject/issues/158."""
1349
1350 _obj_sig_names = [
1351 sig.get_name() for sig in repo.find_by_name("Regress", "TestObj").get_signals()
1352 ]
1353
1354 def __init__(self, *args):
1355 unittest.TestCase.__init__(self, *args)
1356 self._gc_thread_stop = False
1357
1358 def _gc_thread(self):
1359 while not self._gc_thread_stop:
1360 gc.collect()
1361 time.sleep(0.010)
1362
1363 def _callback(self, *args):
1364 pass
1365
1366 def test_run(self):
1367 """Manually trigger GC from a different thread periodicaly
1368 while the main thread keeps connecting/disconnecting to/from signals.
1369
1370 It takes a lot of time to reproduce the issue. It is possible to make it
1371 fail reliably by changing the code of pygobject_unwatch_closure slightly from:
1372 PyGObjectData *inst_data = data;
1373 inst_data->closures = g_slist_remove (inst_data->closures, closure);
1374 to
1375 PyGObjectData *inst_data = data;
1376 GSList *tmp = g_slist_remove (inst_data->closures, closure);
1377 g_usleep(G_USEC_PER_SEC/10);
1378 inst_data->closures = tmp;
1379 """
1380 obj = Regress.TestObj()
1381 gc_thread = threading.Thread(target=self._gc_thread)
1382 gc_thread.start()
1383
1384 for _ in range(8):
1385 handlers = [obj.connect(sig, self._callback) for sig in self._obj_sig_names]
1386 time.sleep(0.010)
1387 while len(handlers) > 0:
1388 obj.disconnect(handlers.pop())
1389
1390 self._gc_thread_stop = True
1391 gc_thread.join()
1392
1393
1394 class _ConnectObjectTestBase:
1395 # Notes:
1396 # - self.Object is overridden in sub-classes.
1397 # - Numeric suffixes indicate the number of user data args passed in.
1398 Object = None
1399 SwapObject = None
1400
1401 def run_connect_test(self, emit_args, user_data, flags=0):
1402 obj = self.Object()
1403 callback_args = []
1404 swap_obj = self.SwapObject()
1405
1406 def callback(*args):
1407 callback_args.append(args)
1408 return 0
1409
1410 if flags & GObject.ConnectFlags.AFTER:
1411 connect_func = obj.connect_object_after
1412 else:
1413 connect_func = obj.connect_object
1414
1415 with capture_gi_deprecation_warnings():
1416 connect_func("sig-with-int64-prop", callback, swap_obj, *user_data)
1417 obj.emit("sig-with-int64-prop", *emit_args)
1418 self.assertEqual(len(callback_args), 1)
1419 return callback_args[0]
1420
1421 def test_0(self):
1422 obj, value = self.run_connect_test([GLib.MAXINT64], user_data=[])
1423 self.assertIsInstance(obj, self.SwapObject)
1424 self.assertEqual(value, GLib.MAXINT64)
1425
1426 def test_1(self):
1427 obj, value, data = self.run_connect_test([GLib.MAXINT64], user_data=["mydata"])
1428 self.assertIsInstance(obj, self.SwapObject)
1429 self.assertEqual(value, GLib.MAXINT64)
1430 self.assertEqual(data, "mydata")
1431
1432 def test_2(self):
1433 obj, value, data1, data2 = self.run_connect_test(
1434 [GLib.MAXINT64], user_data=["mydata1", "mydata2"]
1435 )
1436 self.assertIsInstance(obj, self.SwapObject)
1437 self.assertEqual(value, GLib.MAXINT64)
1438 self.assertEqual(data1, "mydata1")
1439 self.assertEqual(data2, "mydata2")
1440
1441 def test_after_0(self):
1442 obj, value = self.run_connect_test(
1443 [GLib.MAXINT64], user_data=[], flags=GObject.ConnectFlags.AFTER
1444 )
1445 self.assertIsInstance(obj, self.SwapObject)
1446 self.assertEqual(value, GLib.MAXINT64)
1447
1448 def test_after_1(self):
1449 obj, value, data = self.run_connect_test(
1450 [GLib.MAXINT64], user_data=["mydata"], flags=GObject.ConnectFlags.AFTER
1451 )
1452 self.assertIsInstance(obj, self.SwapObject)
1453 self.assertEqual(value, GLib.MAXINT64)
1454 self.assertEqual(data, "mydata")
1455
1456 def test_after_2(self):
1457 obj, value, data1, data2 = self.run_connect_test(
1458 [GLib.MAXINT64],
1459 user_data=["mydata1", "mydata2"],
1460 flags=GObject.ConnectFlags.AFTER,
1461 )
1462 self.assertIsInstance(obj, self.SwapObject)
1463 self.assertEqual(value, GLib.MAXINT64)
1464 self.assertEqual(data1, "mydata1")
1465 self.assertEqual(data2, "mydata2")
1466
1467
1468 class TestConnectGObjectNonIntrospected(unittest.TestCase, _ConnectObjectTestBase):
1469 # This tests connect_object with non-introspected signals
1470 # (created in Python in this case).
1471 class Object(GObject.Object):
1472 test = GObject.Signal()
1473 sig_with_int64_prop = GObject.Signal(
1474 return_type=GObject.TYPE_INT64,
1475 arg_types=[GObject.TYPE_INT64],
1476 flags=GObject.SignalFlags.RUN_LAST,
1477 )
1478
1479 # Object passed for swapping is GObject based.
1480 class SwapObject(GObject.Object):
1481 pass
1482
1483
1484 class TestConnectGObjectIntrospected(unittest.TestCase, _ConnectObjectTestBase):
1485 # This tests connect_object with introspected signals brought in from Regress.
1486 Object = Regress.TestObj
1487
1488 # Object passed for swapping is GObject based.
1489 class SwapObject(GObject.Object):
1490 pass
1491
1492
1493 class TestConnectPyObjectNonIntrospected(unittest.TestCase, _ConnectObjectTestBase):
1494 # This tests connect_object with non-introspected signals
1495 # (created in Python in this case).
1496 class Object(GObject.Object):
1497 test = GObject.Signal()
1498 sig_with_int64_prop = GObject.Signal(
1499 return_type=GObject.TYPE_INT64,
1500 arg_types=[GObject.TYPE_INT64],
1501 flags=GObject.SignalFlags.RUN_LAST,
1502 )
1503
1504 # Object passed for swapping is pure Python
1505 SwapObject = object
1506
1507
1508 class TestConnectPyObjectIntrospected(unittest.TestCase, _ConnectObjectTestBase):
1509 # This tests connect_object with introspected signals brought in from Regress.
1510 Object = Regress.TestObj
1511
1512 # Object passed for swapping is pure Python
1513 SwapObject = object
1514
1515
1516 class _RefCountTestBase:
1517 # NOTE: ref counts are always one more than expected because the getrefcount()
1518 # function adds a ref for the input argument.
1519
1520 # Sub-classes set this
1521 Object = None
1522
1523 class PyData:
1524 pass
1525
1526 @unittest.skipUnless(hasattr(sys, "getrefcount"), "no sys.getrefcount")
1527 def test_callback_ref_count_del(self):
1528 def callback(obj, value):
1529 return value // 2
1530
1531 callback_ref = weakref.ref(callback)
1532 self.assertEqual(
1533 sys.getrefcount(callback), 2 if sys.version_info < (3, 14) else 1
1534 )
1535
1536 obj = self.Object()
1537 obj.connect("sig-with-int64-prop", callback)
1538 self.assertEqual(
1539 sys.getrefcount(callback), 3 if sys.version_info < (3, 14) else 2
1540 )
1541
1542 del callback
1543 self.assertEqual(sys.getrefcount(callback_ref()), 2)
1544
1545 res = obj.emit("sig-with-int64-prop", 42)
1546 self.assertEqual(res, 21)
1547 self.assertEqual(
1548 sys.getrefcount(callback_ref), 2 if sys.version_info < (3, 14) else 1
1549 )
1550
1551 del obj
1552 self.assertIsNone(callback_ref())
1553
1554 @unittest.skipUnless(hasattr(sys, "getrefcount"), "no sys.getrefcount")
1555 def test_callback_ref_count_disconnect(self):
1556 def callback(obj, value):
1557 return value // 2
1558
1559 callback_ref = weakref.ref(callback)
1560 self.assertEqual(
1561 sys.getrefcount(callback), 2 if sys.version_info < (3, 14) else 1
1562 )
1563
1564 obj = self.Object()
1565 handler_id = obj.connect("sig-with-int64-prop", callback)
1566 self.assertEqual(
1567 sys.getrefcount(callback), 3 if sys.version_info < (3, 14) else 2
1568 )
1569
1570 del callback
1571 self.assertEqual(sys.getrefcount(callback_ref()), 2)
1572
1573 res = obj.emit("sig-with-int64-prop", 42)
1574 self.assertEqual(res, 21)
1575 self.assertEqual(
1576 sys.getrefcount(callback_ref), 2 if sys.version_info < (3, 14) else 1
1577 )
1578
1579 obj.disconnect(handler_id)
1580 self.assertIsNone(callback_ref())
1581
1582 @unittest.skipUnless(hasattr(sys, "getrefcount"), "no sys.getrefcount")
1583 def test_callback_ref_count_disconnect_by_func(self):
1584 def callback(obj, value):
1585 return value // 2
1586
1587 callback_ref = weakref.ref(callback)
1588 self.assertEqual(
1589 sys.getrefcount(callback), 2 if sys.version_info < (3, 14) else 1
1590 )
1591
1592 obj = self.Object()
1593 obj.connect("sig-with-int64-prop", callback)
1594 self.assertEqual(
1595 sys.getrefcount(callback), 3 if sys.version_info < (3, 14) else 2
1596 )
1597
1598 del callback
1599 self.assertEqual(sys.getrefcount(callback_ref()), 2)
1600
1601 res = obj.emit("sig-with-int64-prop", 42)
1602 self.assertEqual(res, 21)
1603 self.assertEqual(
1604 sys.getrefcount(callback_ref), 2 if sys.version_info < (3, 14) else 1
1605 )
1606
1607 obj.disconnect_by_func(callback_ref())
1608 self.assertIsNone(callback_ref())
1609
1610 @unittest.skipUnless(hasattr(sys, "getrefcount"), "no sys.getrefcount")
1611 def test_user_data_ref_count(self):
1612 def callback(obj, value, data):
1613 return value // 2
1614
1615 data = self.PyData()
1616 data_ref = weakref.ref(data)
1617 self.assertEqual(sys.getrefcount(data), 2 if sys.version_info < (3, 14) else 1)
1618
1619 obj = self.Object()
1620 obj.connect("sig-with-int64-prop", callback, data)
1621 self.assertEqual(sys.getrefcount(data), 3 if sys.version_info < (3, 14) else 2)
1622
1623 del data
1624 self.assertEqual(sys.getrefcount(data_ref()), 2)
1625
1626 res = obj.emit("sig-with-int64-prop", 42)
1627 self.assertEqual(res, 21)
1628 self.assertEqual(sys.getrefcount(data_ref()), 2)
1629
1630 del obj
1631 self.assertIsNone(data_ref())
1632
1633 @unittest.skipUnless(hasattr(sys, "getrefcount"), "no sys.getrefcount")
1634 @unittest.expectedFailure # https://bugzilla.gnome.org/show_bug.cgi?id=688064
1635 def test_object_ref_count(self):
1636 # connect_object() should only weakly reference the object passed in
1637 # and auto-disconnect the signal when the object is destroyed.
1638 def callback(data, value):
1639 return value // 2
1640
1641 data = GObject.Object()
1642 data_ref = weakref.ref(data)
1643 self.assertEqual(sys.getrefcount(data), 2)
1644
1645 obj = self.Object()
1646 handler_id = obj.connect_object("sig-with-int64-prop", callback, data)
1647 self.assertEqual(sys.getrefcount(data), 2)
1648
1649 res = obj.emit("sig-with-int64-prop", 42)
1650 self.assertEqual(res, 21)
1651 self.assertEqual(sys.getrefcount(data), 2)
1652
1653 del data
1654
1655 self.assertIsNone(data_ref())
1656 self.assertFalse(obj.handler_is_connected(handler_id))
1657
1658
1659 class TestRefCountsNonIntrospected(unittest.TestCase, _RefCountTestBase):
1660 class Object(GObject.Object):
1661 sig_with_int64_prop = GObject.Signal(
1662 return_type=GObject.TYPE_INT64,
1663 arg_types=[GObject.TYPE_INT64],
1664 flags=GObject.SignalFlags.RUN_LAST,
1665 )
1666
1667
1668 class TestRefCountsIntrospected(unittest.TestCase, _RefCountTestBase):
1669 Object = Regress.TestObj
1670
1671
1672 class TestClosureRefCycle(unittest.TestCase):
1673 def test_closure_ref_cycle_unreachable(self):
1674 # https://bugzilla.gnome.org/show_bug.cgi?id=731501
1675
1676 called = []
1677
1678 def on_add(store, *args):
1679 called.append(store)
1680
1681 store = Gio.ListStore()
1682 store.connect_object("items-changed", on_add, store)
1683
1684 # Remove all Python references to the object and keep it alive
1685 # on the C level.
1686 x = Gio.FileInfo()
1687 x.set_attribute_object("store", store)
1688 del store
1689 gc.collect()
1690
1691 # get it back and trigger the signal
1692 x.get_attribute_object("store").append(Gio.FileInfo())
1693
1694 self.assertEqual(len(called), 1)
1695 self.assertTrue(called[0].__grefcount__ > 0)