Debian Codegraph @

tests/test_gobject.py

raw
1 import sys
2 import gc
3 import unittest
4 import warnings
5 import weakref
6 import platform
7
8 import pytest
9
10 from gi.repository import GObject, GLib, Gio
11 from gi import PyGIDeprecationWarning
12 from gi.module import get_introspection_module
13 from gi import _gi
14
15 import testhelper
16 from .helper import capture_glib_deprecation_warnings
17
18
19 @pytest.mark.skipif(platform.python_implementation() == "PyPy", reason="crashes")
20 def test_gobject_weak_ref():
21 called = []
22
23 def callback(*args):
24 called.extend(args)
25
26 # object gets finalized
27 obj = GObject.Object()
28 obj.weak_ref(callback, 1)
29 del obj
30 gc.collect()
31 assert called == [1]
32 del called[:]
33
34 # wrapper gets finalized first
35 obj = GObject.Object()
36 pyref = weakref.ref(obj, lambda x: callback(-2))
37 value = GObject.Value(GObject.Object, obj)
38 ref = obj.weak_ref(callback, 2)
39 del obj
40 gc.collect()
41 assert called == [-2]
42 del pyref
43 value.unset()
44 gc.collect()
45 assert called == [-2, 2]
46 del called[:]
47
48 # weakref gets unregistered first
49 obj = GObject.Object()
50 ref = obj.weak_ref(callback, 3)
51 ref.unref()
52 del obj
53 gc.collect()
54 assert not called
55
56 # weakref gets GCed
57 obj = GObject.Object()
58 obj.weak_ref(callback, 4)
59 gc.collect()
60 del obj
61 assert called == [4]
62
63
64 class TestGObjectAPI(unittest.TestCase):
65 def test_run_dispose(self):
66 class TestObject(GObject.GObject):
67 int_prop = GObject.Property(default=0, type=int)
68
69 obj = TestObject()
70 called = []
71
72 def on_notify(*args):
73 called.append(args)
74
75 obj.connect("notify::int-prop", on_notify)
76 obj.notify("int-prop")
77 obj.notify("int-prop")
78 # after this everything should be disconnected
79 obj.run_dispose()
80 obj.notify("int-prop")
81 obj.notify("int-prop")
82 assert len(called) == 2
83
84 def test_call_method_uninitialized_instance(self):
85 obj = GObject.Object.__new__(GObject.Object)
86 with self.assertRaisesRegex(RuntimeError, ".*is not initialized"):
87 obj.notify("foo")
88
89 def test_gobject_inheritance(self):
90 # GObject.Object is a class hierarchy as follows:
91 # overrides.Object -> introspection.Object -> static.GObject
92 GIObjectModule = get_introspection_module("GObject")
93 self.assertTrue(issubclass(GObject.Object, GIObjectModule.Object))
94 self.assertTrue(issubclass(GIObjectModule.Object, _gi.GObject))
95
96 self.assertEqual(_gi.GObject.__gtype__, GObject.TYPE_OBJECT)
97 self.assertEqual(GIObjectModule.Object.__gtype__, GObject.TYPE_OBJECT)
98 self.assertEqual(GObject.Object.__gtype__, GObject.TYPE_OBJECT)
99
100 # The pytype wrapper should hold the outer most Object class from overrides.
101 self.assertEqual(GObject.TYPE_OBJECT.pytype, GObject.Object)
102
103 def test_gobject_unsupported_overrides(self):
104 obj = GObject.Object()
105
106 with self.assertRaisesRegex(
107 RuntimeError, "Data access methods are unsupported.*"
108 ):
109 obj.get_data()
110
111 with self.assertRaisesRegex(
112 RuntimeError, "This method is currently unsupported.*"
113 ):
114 obj.force_floating()
115
116 def test_compat_api(self):
117 with warnings.catch_warnings(record=True) as w:
118 warnings.simplefilter("always")
119 # GObject formerly exposed a lot of GLib's functions
120 self.assertEqual(GObject.markup_escape_text("foo"), "foo")
121
122 ml = GObject.MainLoop()
123 self.assertFalse(ml.is_running())
124
125 context = GObject.main_context_default()
126 self.assertTrue(context.pending() in [False, True])
127
128 context = GObject.MainContext()
129 self.assertFalse(context.pending())
130
131 self.assertTrue(issubclass(w[0].category, PyGIDeprecationWarning))
132 self.assertTrue("GLib.markup_escape_text" in str(w[0]), str(w[0]))
133
134 self.assertLess(GObject.PRIORITY_HIGH, GObject.PRIORITY_DEFAULT)
135
136 def test_min_max_int(self):
137 with warnings.catch_warnings():
138 warnings.simplefilter("ignore", PyGIDeprecationWarning)
139
140 self.assertEqual(GObject.G_MAXINT16, 2**15 - 1)
141 self.assertEqual(GObject.G_MININT16, -(2**15))
142 self.assertEqual(GObject.G_MAXUINT16, 2**16 - 1)
143
144 self.assertEqual(GObject.G_MAXINT32, 2**31 - 1)
145 self.assertEqual(GObject.G_MININT32, -(2**31))
146 self.assertEqual(GObject.G_MAXUINT32, 2**32 - 1)
147
148 self.assertEqual(GObject.G_MAXINT64, 2**63 - 1)
149 self.assertEqual(GObject.G_MININT64, -(2**63))
150 self.assertEqual(GObject.G_MAXUINT64, 2**64 - 1)
151
152
153 class TestReferenceCounting(unittest.TestCase):
154 def test_regular_object(self):
155 obj = GObject.GObject()
156 self.assertEqual(obj.__grefcount__, 1)
157
158 obj = GObject.new(GObject.GObject)
159 self.assertEqual(obj.__grefcount__, 1)
160
161 def test_floating(self):
162 obj = testhelper.Floating()
163 self.assertEqual(obj.__grefcount__, 1)
164
165 obj = GObject.new(testhelper.Floating)
166 self.assertEqual(obj.__grefcount__, 1)
167
168 def test_owned_by_library(self):
169 # Upon creation, the refcount of the object should be 2:
170 # - someone already has a reference on the new object.
171 # - the python wrapper should hold its own reference.
172 obj = testhelper.OwnedByLibrary()
173 self.assertEqual(obj.__grefcount__, 2)
174
175 # We ask the library to release its reference, so the only
176 # remaining ref should be our wrapper's. Once the wrapper
177 # will run out of scope, the object will get finalized.
178 obj.release()
179 self.assertEqual(obj.__grefcount__, 1)
180
181 def test_owned_by_library_out_of_scope(self):
182 obj = testhelper.OwnedByLibrary()
183 self.assertEqual(obj.__grefcount__, 2)
184
185 # We are manually taking the object out of scope. This means
186 # that our wrapper has been freed, and its reference dropped. We
187 # cannot check it but the refcount should now be 1 (the ref held
188 # by the library is still there, we didn't call release()
189 obj = None
190
191 # When we get the object back from the lib, the wrapper is
192 # re-created, so our refcount will be 2 once again.
193 obj = testhelper.owned_by_library_get_instance_list()[0]
194 self.assertEqual(obj.__grefcount__, 2)
195
196 obj.release()
197 self.assertEqual(obj.__grefcount__, 1)
198
199 def test_owned_by_library_using_gobject_new(self):
200 # Upon creation, the refcount of the object should be 2:
201 # - someone already has a reference on the new object.
202 # - the python wrapper should hold its own reference.
203 obj = GObject.new(testhelper.OwnedByLibrary)
204 self.assertEqual(obj.__grefcount__, 2)
205
206 # We ask the library to release its reference, so the only
207 # remaining ref should be our wrapper's. Once the wrapper
208 # will run out of scope, the object will get finalized.
209 obj.release()
210 self.assertEqual(obj.__grefcount__, 1)
211
212 def test_owned_by_library_out_of_scope_using_gobject_new(self):
213 obj = GObject.new(testhelper.OwnedByLibrary)
214 self.assertEqual(obj.__grefcount__, 2)
215
216 # We are manually taking the object out of scope. This means
217 # that our wrapper has been freed, and its reference dropped. We
218 # cannot check it but the refcount should now be 1 (the ref held
219 # by the library is still there, we didn't call release()
220 obj = None
221
222 # When we get the object back from the lib, the wrapper is
223 # re-created, so our refcount will be 2 once again.
224 obj = testhelper.owned_by_library_get_instance_list()[0]
225 self.assertEqual(obj.__grefcount__, 2)
226
227 obj.release()
228 self.assertEqual(obj.__grefcount__, 1)
229
230 def test_floating_and_sunk(self):
231 # Upon creation, the refcount of the object should be 2:
232 # - someone already has a reference on the new object.
233 # - the python wrapper should hold its own reference.
234 obj = testhelper.FloatingAndSunk()
235 self.assertEqual(obj.__grefcount__, 2)
236
237 # We ask the library to release its reference, so the only
238 # remaining ref should be our wrapper's. Once the wrapper
239 # will run out of scope, the object will get finalized.
240 obj.release()
241 self.assertEqual(obj.__grefcount__, 1)
242
243 def test_floating_and_sunk_out_of_scope(self):
244 obj = testhelper.FloatingAndSunk()
245 self.assertEqual(obj.__grefcount__, 2)
246
247 # We are manually taking the object out of scope. This means
248 # that our wrapper has been freed, and its reference dropped. We
249 # cannot check it but the refcount should now be 1 (the ref held
250 # by the library is still there, we didn't call release()
251 obj = None
252
253 # When we get the object back from the lib, the wrapper is
254 # re-created, so our refcount will be 2 once again.
255 obj = testhelper.floating_and_sunk_get_instance_list()[0]
256 self.assertEqual(obj.__grefcount__, 2)
257
258 obj.release()
259 self.assertEqual(obj.__grefcount__, 1)
260
261 def test_floating_and_sunk_using_gobject_new(self):
262 # Upon creation, the refcount of the object should be 2:
263 # - someone already has a reference on the new object.
264 # - the python wrapper should hold its own reference.
265 obj = GObject.new(testhelper.FloatingAndSunk)
266 self.assertEqual(obj.__grefcount__, 2)
267
268 # We ask the library to release its reference, so the only
269 # remaining ref should be our wrapper's. Once the wrapper
270 # will run out of scope, the object will get finalized.
271 obj.release()
272 self.assertEqual(obj.__grefcount__, 1)
273
274 def test_floating_and_sunk_out_of_scope_using_gobject_new(self):
275 obj = GObject.new(testhelper.FloatingAndSunk)
276 self.assertEqual(obj.__grefcount__, 2)
277
278 # We are manually taking the object out of scope. This means
279 # that our wrapper has been freed, and its reference dropped. We
280 # cannot check it but the refcount should now be 1 (the ref held
281 # by the library is still there, we didn't call release()
282 obj = None
283
284 # When we get the object back from the lib, the wrapper is
285 # re-created, so our refcount will be 2 once again.
286 obj = testhelper.floating_and_sunk_get_instance_list()[0]
287 self.assertEqual(obj.__grefcount__, 2)
288
289 obj.release()
290 self.assertEqual(obj.__grefcount__, 1)
291
292 def test_uninitialized_object(self):
293 class Obj(GObject.GObject):
294 def __init__(self):
295 x = self.__grefcount__
296 super().__init__()
297 assert x >= 0
298
299 # Accessing __grefcount__ before the object is initialized is wrong.
300 # Ensure we get a proper exception instead of a crash.
301 self.assertRaises(TypeError, Obj)
302
303
304 class A(GObject.GObject):
305 def __init__(self):
306 super().__init__()
307
308
309 class TestPythonReferenceCounting(unittest.TestCase):
310 # Newly created instances should always have two references: one for
311 # the GC, and one for the bound variable in the local scope.
312
313 def test_new_instance_has_two_refs(self):
314 obj = GObject.GObject()
315 if hasattr(sys, "getrefcount"):
316 self.assertEqual(
317 sys.getrefcount(obj), 2 if sys.version_info < (3, 14) else 1
318 )
319
320 def test_new_instance_has_two_refs_using_gobject_new(self):
321 obj = GObject.new(GObject.GObject)
322 if hasattr(sys, "getrefcount"):
323 self.assertEqual(
324 sys.getrefcount(obj), 2 if sys.version_info < (3, 14) else 1
325 )
326
327 def test_new_subclass_instance_has_two_refs(self):
328 obj = A()
329 if hasattr(sys, "getrefcount"):
330 self.assertEqual(
331 sys.getrefcount(obj), 2 if sys.version_info < (3, 14) else 1
332 )
333
334 def test_new_subclass_instance_has_two_refs_using_gobject_new(self):
335 obj = GObject.new(A)
336 if hasattr(sys, "getrefcount"):
337 self.assertEqual(
338 sys.getrefcount(obj), 2 if sys.version_info < (3, 14) else 1
339 )
340
341
342 class TestContextManagers(unittest.TestCase):
343 class ContextTestObject(GObject.GObject):
344 prop = GObject.Property(default=0, type=int)
345
346 def on_prop_set(self, obj, prop):
347 # Handler which tracks property changed notifications.
348 self.tracking.append(obj.get_property(prop.name))
349
350 def setUp(self):
351 self.tracking = []
352 self.obj = self.ContextTestObject()
353 self.handler = self.obj.connect("notify::prop", self.on_prop_set)
354
355 def test_freeze_notify_context(self):
356 # Verify prop tracking list
357 self.assertEqual(self.tracking, [])
358 self.obj.props.prop = 1
359 self.assertEqual(self.tracking, [1])
360 self.obj.props.prop = 2
361 self.assertEqual(self.tracking, [1, 2])
362 self.assertEqual(self.obj.__grefcount__, 1)
363
364 if hasattr(sys, "getrefcount"):
365 pyref_count = sys.getrefcount(self.obj)
366
367 # Using the context manager the tracking list should not be affected.
368 # The GObject reference count should stay the same and the python
369 # object ref-count should go up.
370 with self.obj.freeze_notify():
371 self.assertEqual(self.obj.__grefcount__, 1)
372 if hasattr(sys, "getrefcount"):
373 self.assertEqual(sys.getrefcount(self.obj), pyref_count + 1)
374 self.obj.props.prop = 3
375 self.assertEqual(self.obj.props.prop, 3)
376 self.assertEqual(self.tracking, [1, 2])
377
378 # After the context manager, the prop should have been modified,
379 # the tracking list will be modified, and the python object ref
380 # count goes back down.
381 gc.collect()
382 self.assertEqual(self.obj.props.prop, 3)
383 self.assertEqual(self.tracking, [1, 2, 3])
384 self.assertEqual(self.obj.__grefcount__, 1)
385 if hasattr(sys, "getrefcount"):
386 self.assertEqual(sys.getrefcount(self.obj), pyref_count)
387
388 def test_handler_block_context(self):
389 # Verify prop tracking list
390 self.assertEqual(self.tracking, [])
391 self.obj.props.prop = 1
392 self.assertEqual(self.tracking, [1])
393 self.obj.props.prop = 2
394 self.assertEqual(self.tracking, [1, 2])
395 self.assertEqual(self.obj.__grefcount__, 1)
396
397 if hasattr(sys, "getrefcount"):
398 pyref_count = sys.getrefcount(self.obj)
399
400 # Using the context manager the tracking list should not be affected.
401 # The GObject reference count should stay the same and the python
402 # object ref-count should go up.
403 with self.obj.handler_block(self.handler):
404 self.assertEqual(self.obj.__grefcount__, 1)
405 if hasattr(sys, "getrefcount"):
406 self.assertEqual(sys.getrefcount(self.obj), pyref_count + 1)
407 self.obj.props.prop = 3
408 self.assertEqual(self.obj.props.prop, 3)
409 self.assertEqual(self.tracking, [1, 2])
410
411 # After the context manager, the prop should have been modified
412 # the tracking list should have stayed the same and the GObject ref
413 # count goes back down.
414 gc.collect()
415 self.assertEqual(self.obj.props.prop, 3)
416 self.assertEqual(self.tracking, [1, 2])
417 self.assertEqual(self.obj.__grefcount__, 1)
418 if hasattr(sys, "getrefcount"):
419 self.assertEqual(sys.getrefcount(self.obj), pyref_count)
420
421 def test_freeze_notify_context_nested(self):
422 self.assertEqual(self.tracking, [])
423 with self.obj.freeze_notify():
424 self.obj.props.prop = 1
425 self.assertEqual(self.tracking, [])
426
427 with self.obj.freeze_notify():
428 self.obj.props.prop = 2
429 self.assertEqual(self.tracking, [])
430
431 with self.obj.freeze_notify():
432 self.obj.props.prop = 3
433 self.assertEqual(self.tracking, [])
434 self.assertEqual(self.tracking, [])
435 self.assertEqual(self.tracking, [])
436
437 # Finally after last context, the notifications should have collapsed
438 # and the last one sent.
439 self.assertEqual(self.tracking, [3])
440
441 def test_handler_block_context_nested(self):
442 self.assertEqual(self.tracking, [])
443 with self.obj.handler_block(self.handler):
444 self.obj.props.prop = 1
445 self.assertEqual(self.tracking, [])
446
447 with self.obj.handler_block(self.handler):
448 self.obj.props.prop = 2
449 self.assertEqual(self.tracking, [])
450
451 with self.obj.handler_block(self.handler):
452 self.obj.props.prop = 3
453 self.assertEqual(self.tracking, [])
454 self.assertEqual(self.tracking, [])
455 self.assertEqual(self.tracking, [])
456
457 # Finally after last context, the notifications should have collapsed
458 # and the last one sent.
459 self.assertEqual(self.obj.props.prop, 3)
460 self.assertEqual(self.tracking, [])
461
462 def test_freeze_notify_normal_usage_ref_counts(self):
463 # Ensure ref counts without using methods as context managers
464 # maintain the same count.
465 self.assertEqual(self.obj.__grefcount__, 1)
466 self.obj.freeze_notify()
467 self.assertEqual(self.obj.__grefcount__, 1)
468 self.obj.thaw_notify()
469 self.assertEqual(self.obj.__grefcount__, 1)
470
471 def test_handler_block_normal_usage_ref_counts(self):
472 self.assertEqual(self.obj.__grefcount__, 1)
473 self.obj.handler_block(self.handler)
474 self.assertEqual(self.obj.__grefcount__, 1)
475 self.obj.handler_unblock(self.handler)
476 self.assertEqual(self.obj.__grefcount__, 1)
477
478 def test_freeze_notify_context_error(self):
479 # Test an exception occurring within a freeze context exits the context
480 try:
481 with self.obj.freeze_notify():
482 self.obj.props.prop = 1
483 self.assertEqual(self.tracking, [])
484 raise ValueError("Simulation")
485 except ValueError:
486 pass
487
488 # Verify the property set within the context called notify.
489 self.assertEqual(self.obj.props.prop, 1)
490 self.assertEqual(self.tracking, [1])
491
492 # Verify we are still not in a frozen context.
493 self.obj.props.prop = 2
494 self.assertEqual(self.tracking, [1, 2])
495
496 def test_handler_block_context_error(self):
497 # Test an exception occurring within a handler block exits the context
498 try:
499 with self.obj.handler_block(self.handler):
500 self.obj.props.prop = 1
501 self.assertEqual(self.tracking, [])
502 raise ValueError("Simulation")
503 except ValueError:
504 pass
505
506 # Verify the property set within the context didn't call notify.
507 self.assertEqual(self.obj.props.prop, 1)
508 self.assertEqual(self.tracking, [])
509
510 # Verify we are still not in a handler block context.
511 self.obj.props.prop = 2
512 self.assertEqual(self.tracking, [2])
513
514
515 class TestPropertyBindings(unittest.TestCase):
516 class TestObject(GObject.GObject):
517 int_prop = GObject.Property(default=0, type=int)
518
519 def setUp(self):
520 self.source = self.TestObject()
521 self.target = self.TestObject()
522
523 def test_default_binding(self):
524 binding = self.source.bind_property(
525 "int_prop", self.target, "int_prop", GObject.BindingFlags.DEFAULT
526 )
527 binding = binding
528
529 # Test setting value on source gets pushed to target
530 self.source.int_prop = 1
531 self.assertEqual(self.source.int_prop, 1)
532 self.assertEqual(self.target.int_prop, 1)
533
534 # Test setting value on target does not change source
535 self.target.props.int_prop = 2
536 self.assertEqual(self.source.int_prop, 1)
537 self.assertEqual(self.target.int_prop, 2)
538
539 def test_call_binding(self):
540 binding = self.source.bind_property(
541 "int_prop", self.target, "int_prop", GObject.BindingFlags.DEFAULT
542 )
543 with capture_glib_deprecation_warnings() as warn:
544 result = binding()
545 assert len(warn)
546 assert result is binding
547
548 def test_bidirectional_binding(self):
549 binding = self.source.bind_property(
550 "int_prop", self.target, "int_prop", GObject.BindingFlags.BIDIRECTIONAL
551 )
552 binding = binding
553
554 # Test setting value on source gets pushed to target
555 self.source.int_prop = 1
556 self.assertEqual(self.source.int_prop, 1)
557 self.assertEqual(self.target.int_prop, 1)
558
559 # Test setting value on target also changes source
560 self.target.props.int_prop = 2
561 self.assertEqual(self.source.int_prop, 2)
562 self.assertEqual(self.target.int_prop, 2)
563
564 def test_transform_to_only(self):
565 def transform_to(binding, value, user_data=None):
566 self.assertEqual(user_data, "test-data")
567 return value * 2
568
569 binding = self.source.bind_property(
570 "int_prop",
571 self.target,
572 "int_prop",
573 GObject.BindingFlags.DEFAULT,
574 transform_to,
575 user_data="test-data",
576 )
577 binding = binding
578
579 self.source.int_prop = 1
580 self.assertEqual(self.source.int_prop, 1)
581 self.assertEqual(self.target.int_prop, 2)
582
583 self.target.props.int_prop = 1
584 self.assertEqual(self.source.int_prop, 1)
585 self.assertEqual(self.target.int_prop, 1)
586
587 def test_transform_from_only(self):
588 def transform_from(binding, value, user_data=None):
589 self.assertEqual(user_data, None)
590 return value * 2
591
592 binding = self.source.bind_property(
593 "int_prop",
594 self.target,
595 "int_prop",
596 GObject.BindingFlags.BIDIRECTIONAL,
597 transform_from=transform_from,
598 )
599 binding = binding
600
601 self.source.int_prop = 1
602 self.assertEqual(self.source.int_prop, 1)
603 self.assertEqual(self.target.int_prop, 1)
604
605 self.target.props.int_prop = 1
606 self.assertEqual(self.source.int_prop, 2)
607 self.assertEqual(self.target.int_prop, 1)
608
609 def test_transform_bidirectional(self):
610 test_data = object()
611
612 def transform_to(binding, value, user_data=None):
613 self.assertEqual(user_data, test_data)
614 return value * 2
615
616 def transform_from(binding, value, user_data=None):
617 self.assertEqual(user_data, test_data)
618 return value // 2
619
620 if hasattr(sys, "getrefcount"):
621 test_data_ref_count = sys.getrefcount(test_data)
622 transform_to_ref_count = sys.getrefcount(transform_to)
623 transform_from_ref_count = sys.getrefcount(transform_from)
624
625 # bidirectional bindings
626 binding = self.source.bind_property(
627 "int_prop",
628 self.target,
629 "int_prop",
630 GObject.BindingFlags.BIDIRECTIONAL,
631 transform_to,
632 transform_from,
633 test_data,
634 )
635 binding = binding
636 if hasattr(sys, "getrefcount"):
637 binding_ref_count = sys.getrefcount(binding)
638 binding_gref_count = binding.__grefcount__
639
640 self.source.int_prop = 1
641 self.assertEqual(self.source.int_prop, 1)
642 self.assertEqual(self.target.int_prop, 2)
643
644 self.target.props.int_prop = 4
645 self.assertEqual(self.source.int_prop, 2)
646 self.assertEqual(self.target.int_prop, 4)
647
648 if hasattr(sys, "getrefcount"):
649 self.assertEqual(sys.getrefcount(binding), binding_ref_count)
650 self.assertEqual(binding.__grefcount__, binding_gref_count)
651
652 # test_data ref count increases by 2, once for each callback.
653 if hasattr(sys, "getrefcount"):
654 self.assertEqual(sys.getrefcount(test_data), test_data_ref_count + 2)
655 self.assertEqual(sys.getrefcount(transform_to), transform_to_ref_count + 1)
656 self.assertEqual(
657 sys.getrefcount(transform_from), transform_from_ref_count + 1
658 )
659
660 # Unbind should clear out the binding and its transforms
661 binding.unbind()
662
663 # Setting source or target should not change the other.
664 self.target.int_prop = 3
665 self.source.int_prop = 5
666 self.assertEqual(self.target.int_prop, 3)
667 self.assertEqual(self.source.int_prop, 5)
668
669 if hasattr(sys, "getrefcount"):
670 self.assertEqual(sys.getrefcount(test_data), test_data_ref_count)
671 self.assertEqual(sys.getrefcount(transform_to), transform_to_ref_count)
672 self.assertEqual(sys.getrefcount(transform_from), transform_from_ref_count)
673
674 def test_explicit_unbind_clears_connection(self):
675 self.assertEqual(self.source.int_prop, 0)
676 self.assertEqual(self.target.int_prop, 0)
677
678 # Test deleting binding reference removes binding.
679 binding = self.source.bind_property("int_prop", self.target, "int_prop")
680 self.source.int_prop = 1
681 self.assertEqual(self.source.int_prop, 1)
682 self.assertEqual(self.target.int_prop, 1)
683
684 # unbind should clear out the bindings self reference
685 binding.unbind()
686 self.assertEqual(binding.__grefcount__, 1)
687
688 self.source.int_prop = 10
689 self.assertEqual(self.source.int_prop, 10)
690 self.assertEqual(self.target.int_prop, 1)
691
692 for i in range(10):
693 binding.unbind()
694
695 def test_reference_counts(self):
696 self.assertEqual(self.source.__grefcount__, 1)
697 self.assertEqual(self.target.__grefcount__, 1)
698
699 # Binding ref count will be 2 do to the initial ref implicitly held by
700 # the act of binding and the ref incurred by using __call__ to generate
701 # a wrapper from the weak binding ref within python.
702 binding = self.source.bind_property("int_prop", self.target, "int_prop")
703 self.assertEqual(binding.__grefcount__, 2)
704
705 # Creating a binding does not inc refs on source and target (they are weak
706 # on the binding object itself)
707 self.assertEqual(self.source.__grefcount__, 1)
708 self.assertEqual(self.target.__grefcount__, 1)
709
710 # Use GObject.get_property because the "props" accessor leaks.
711 # Note property names are canonicalized.
712 self.assertEqual(binding.get_property("source"), self.source)
713 self.assertEqual(binding.get_property("source_property"), "int-prop")
714 self.assertEqual(binding.get_property("target"), self.target)
715 self.assertEqual(binding.get_property("target_property"), "int-prop")
716 self.assertEqual(binding.get_property("flags"), GObject.BindingFlags.DEFAULT)
717
718 # Delete reference to source or target and the binding will remove its own
719 # "self reference".
720 ref = self.source.weak_ref()
721 del self.source
722 gc.collect()
723 self.assertEqual(ref(), None)
724 self.assertEqual(binding.__grefcount__, 1)
725
726 # Finally clear out the last ref held by the python wrapper
727 ref = binding.weak_ref()
728 del binding
729 gc.collect()
730 self.assertEqual(ref(), None)
731
732
733 class TestGValue(unittest.TestCase):
734 def test_type_constant(self):
735 self.assertEqual(GObject.TYPE_VALUE, GObject.Value.__gtype__)
736 self.assertEqual(GObject.type_name(GObject.TYPE_VALUE), "GValue")
737
738 def test_no_type(self):
739 value = GObject.Value()
740 self.assertEqual(value.g_type, GObject.TYPE_INVALID)
741 self.assertRaises(TypeError, value.set_value, 23)
742 self.assertEqual(value.get_value(), None)
743
744 def test_int(self):
745 value = GObject.Value(GObject.TYPE_UINT)
746 self.assertEqual(value.g_type, GObject.TYPE_UINT)
747 value.set_value(23)
748 self.assertEqual(value.get_value(), 23)
749 value.set_value(42.0)
750 self.assertEqual(value.get_value(), 42)
751
752 def test_string(self):
753 value = GObject.Value(str, "foo_bar")
754 self.assertEqual(value.g_type, GObject.TYPE_STRING)
755 self.assertEqual(value.get_value(), "foo_bar")
756
757 def test_float(self):
758 # python float is G_TYPE_DOUBLE
759 value = GObject.Value(float, 23.4)
760 self.assertEqual(value.g_type, GObject.TYPE_DOUBLE)
761 value.set_value(1e50)
762 self.assertAlmostEqual(value.get_value(), 1e50)
763
764 value = GObject.Value(GObject.TYPE_FLOAT, 23.4)
765 self.assertEqual(value.g_type, GObject.TYPE_FLOAT)
766 self.assertRaises(TypeError, value.set_value, "string")
767 self.assertRaises(OverflowError, value.set_value, 1e50)
768
769 def test_float_inf_nan(self):
770 nan = float("nan")
771 for type_ in [GObject.TYPE_FLOAT, GObject.TYPE_DOUBLE]:
772 for x in [float("inf"), float("-inf"), nan]:
773 value = GObject.Value(type_, x)
774 # assertEqual() is False for (nan, nan)
775 if x is nan:
776 self.assertEqual(str(value.get_value()), "nan")
777 else:
778 self.assertEqual(value.get_value(), x)
779
780 def test_enum(self):
781 value = GObject.Value(Gio.FileType, Gio.FileType.DIRECTORY)
782 self.assertEqual(value.get_value(), Gio.FileType.DIRECTORY)
783
784 def test_flags(self):
785 value = GObject.Value(Gio.FileCopyFlags, Gio.FileCopyFlags.OVERWRITE)
786 self.assertEqual(value.get_value(), Gio.FileCopyFlags.OVERWRITE)
787
788 def test_object(self):
789 class TestObject(GObject.Object):
790 pass
791
792 obj = TestObject()
793 value = GObject.Value(GObject.TYPE_OBJECT, obj)
794 self.assertEqual(value.get_value(), obj)
795
796 def test_value_array(self):
797 value = GObject.Value(GObject.ValueArray)
798 self.assertEqual(value.g_type, GObject.type_from_name("GValueArray"))
799 value.set_value([32, "foo_bar", 0.3])
800 self.assertEqual(value.get_value(), [32, "foo_bar", 0.3])
801
802 def test_value_array_from_gvalue_list(self):
803 value = GObject.Value(
804 GObject.ValueArray,
805 [
806 GObject.Value(GObject.TYPE_UINT, 0xFFFFFFFF),
807 GObject.Value(GObject.TYPE_STRING, "foo_bar"),
808 ],
809 )
810 self.assertEqual(value.g_type, GObject.type_from_name("GValueArray"))
811 self.assertEqual(value.get_value(), [0xFFFFFFFF, "foo_bar"])
812 self.assertEqual(
813 testhelper.value_array_get_nth_type(value, 0), GObject.TYPE_UINT
814 )
815 self.assertEqual(
816 testhelper.value_array_get_nth_type(value, 1), GObject.TYPE_STRING
817 )
818
819 def test_value_array_append_gvalue(self):
820 with warnings.catch_warnings():
821 warnings.simplefilter("ignore", DeprecationWarning)
822
823 arr = GObject.ValueArray.new(0)
824 arr.append(GObject.Value(GObject.TYPE_UINT, 0xFFFFFFFF))
825 arr.append(GObject.Value(GObject.TYPE_STRING, "foo_bar"))
826 self.assertEqual(arr.get_nth(0), 0xFFFFFFFF)
827 self.assertEqual(arr.get_nth(1), "foo_bar")
828 self.assertEqual(
829 testhelper.value_array_get_nth_type(arr, 0), GObject.TYPE_UINT
830 )
831 self.assertEqual(
832 testhelper.value_array_get_nth_type(arr, 1), GObject.TYPE_STRING
833 )
834
835 def test_gerror_boxing(self):
836 error = GLib.Error("test message", domain="mydomain", code=42)
837 value = GObject.Value(GLib.Error, error)
838 self.assertEqual(value.g_type, GObject.type_from_name("GError"))
839
840 unboxed = value.get_value()
841 self.assertEqual(unboxed.message, error.message)
842 self.assertEqual(unboxed.domain, error.domain)
843 self.assertEqual(unboxed.code, error.code)
844
845 def test_gerror_novalue(self):
846 GLib.Error("test message", domain="mydomain", code=42)
847 value = GObject.Value(GLib.Error)
848 self.assertEqual(value.g_type, GObject.type_from_name("GError"))
849 self.assertEqual(value.get_value(), None)
850
851
852 class TestDispose(unittest.TestCase):
853 def test_dispose(self):
854 class TestObject(GObject.Object):
855 def __init__(self):
856 super().__init__()
857 self.dispose_invoked = False
858
859 def do_dispose(self):
860 self.dispose_invoked = True
861 super().do_dispose()
862
863 obj = TestObject()
864 obj.run_dispose()
865
866 assert obj.dispose_invoked
867
868 def test_dispose_with_python_base_class(self):
869 class TestBaseObject(GObject.Object):
870 def __init__(self):
871 super().__init__()
872 self.dispose_invoked_base = False
873
874 def do_dispose(self):
875 self.dispose_invoked_base = True
876 super().do_dispose()
877
878 class TestObject(TestBaseObject):
879 def __init__(self):
880 super().__init__()
881 self.dispose_invoked = False
882
883 def do_dispose(self):
884 self.dispose_invoked = True
885 super().do_dispose()
886
887 obj = TestObject()
888 obj.run_dispose()
889
890 assert obj.dispose_invoked_base
891 assert obj.dispose_invoked
892
893 @unittest.skipIf(platform.python_implementation() == "PyPy", "CPython only")
894 def test_dispose_on_object_destruction(self):
895 dispose_invoked = False
896
897 class TestObject(GObject.Object):
898 def do_dispose(self):
899 nonlocal dispose_invoked
900 dispose_invoked = True
901 super().do_dispose()
902
903 TestObject()
904
905 assert dispose_invoked
906
907 @unittest.skipIf(platform.python_implementation() == "PyPy", "CPython only")
908 def test_dispose_on_floating_object(self):
909 dispose_invoked = False
910
911 class TestObject(GObject.Object):
912 def do_dispose(self):
913 nonlocal dispose_invoked
914 dispose_invoked = True
915 super().do_dispose()
916
917 with warnings.catch_warnings(record=True):
918 warnings.simplefilter("always")
919 TestObject()._force_floating()
920
921 assert dispose_invoked
922
923 def test_only_call_do_dispose_if_defined_on_class(self):
924 dispose_invoked = False
925
926 def do_dispose(self):
927 nonlocal dispose_invoked
928 dispose_invoked = True
929
930 class TestObject(GObject.Object):
931 def __init__(self):
932 self.do_dispose = do_dispose
933 super().__init__()
934
935 TestObject()
936
937 assert not dispose_invoked
938
939 @unittest.skipIf(platform.python_implementation() == "PyPy", "CPython only")
940 def test_access_members_objects_from_dispose(self):
941 dispose_invoked = False
942
943 class TestObject(GObject.Object):
944 def __init__(self, a, b):
945 super().__init__()
946 self.a = a
947 self.b = b
948
949 def do_dispose(self):
950 nonlocal dispose_invoked
951 # access members: do_dispose should be called before they're removed
952 self.a.val
953 self.b.val
954 dispose_invoked = True
955
956 class TestMember:
957 def __init__(self, val):
958 self.val = val
959
960 a = TestMember("a")
961 b = TestMember("b")
962 o = TestObject(a, b)
963 a.o = o
964 del a, b, o
965
966 gc.collect()
967
968 assert dispose_invoked
969
970
971 def test_list_properties():
972 def find_param(props, name):
973 for param in props:
974 if param.name == name:
975 return param
976 return None
977
978 list_props = GObject.list_properties
979
980 props = list_props(Gio.Action)
981 param = find_param(props, "enabled")
982 assert param
983 assert param.value_type == GObject.TYPE_BOOLEAN
984 assert list_props("GAction") == list_props(Gio.Action)
985 assert list_props(Gio.Action.__gtype__) == list_props(Gio.Action)
986
987 props = list_props(Gio.SimpleAction)
988 assert find_param(props, "enabled")
989
990 def names(props):
991 return [p.name for p in props]
992
993 assert set(names(list_props(Gio.Action))) <= set(
994 names(list_props(Gio.SimpleAction))
995 )
996
997 props = list_props(Gio.FileIcon)
998 param = find_param(props, "file")
999 assert param
1000 assert param.value_type == Gio.File.__gtype__
1001
1002 assert list_props("GFileIcon") == list_props(Gio.FileIcon)
1003 assert list_props(Gio.FileIcon.__gtype__) == list_props(Gio.FileIcon)
1004 assert list_props(Gio.FileIcon(file=Gio.File.new_for_path("."))) == list_props(
1005 Gio.FileIcon
1006 )
1007
1008 for obj in [Gio.ActionEntry, Gio.DBusError, 0, object()]:
1009 with pytest.raises(TypeError):
1010 list_props(obj)
1011
1012
1013 def test_custom_class_update():
1014 # Example from Gaupol <https://github.com/otsaloma/gaupol>
1015
1016 class CustomAction(Gio.SimpleAction):
1017 def __new__(cls):
1018 action = Gio.SimpleAction.new("custom-action")
1019 action.__class__ = cls
1020 return action
1021
1022 action = CustomAction()
1023 assert type(action) is CustomAction
1024
1025 group = Gio.SimpleActionGroup()
1026 group.insert(action)
1027 del action
1028 new_action = group.lookup("custom-action")
1029
1030 assert type(new_action) is CustomAction