Debian Codegraph @

lib-python/3/test/test_finalization.py

raw symbols SCIP
1 """
2 Tests for object finalization semantics, as outlined in PEP 442.
3 """
4
5 import contextlib
6 import gc
7 import unittest
8 import weakref
9
10 try:
11 from _testcapi import with_tp_del
12 except ImportError:
13 def with_tp_del(cls):
14 class C(object):
15 def __new__(cls, *args, **kwargs):
16 raise TypeError('requires _testcapi.with_tp_del')
17 return C
18
19 try:
20 from _testcapi import without_gc
21 except ImportError:
22 def without_gc(cls):
23 class C:
24 def __new__(cls, *args, **kwargs):
25 raise TypeError('requires _testcapi.without_gc')
26 return C
27
28 from test import support
29
30
31 class NonGCSimpleBase:
32 """
33 The base class for all the objects under test, equipped with various
34 testing features.
35 """
36
37 survivors = []
38 del_calls = []
39 tp_del_calls = []
40 errors = []
41
42 _cleaning = False
43
44 __slots__ = ()
45
46 @classmethod
47 def _cleanup(cls):
48 cls.survivors.clear()
49 cls.errors.clear()
50 gc.garbage.clear()
51 gc.collect()
52 cls.del_calls.clear()
53 cls.tp_del_calls.clear()
54
55 @classmethod
56 @contextlib.contextmanager
57 def test(cls):
58 """
59 A context manager to use around all finalization tests.
60 """
61 with support.disable_gc():
62 cls.del_calls.clear()
63 cls.tp_del_calls.clear()
64 NonGCSimpleBase._cleaning = False
65 try:
66 yield
67 if cls.errors:
68 raise cls.errors[0]
69 finally:
70 NonGCSimpleBase._cleaning = True
71 cls._cleanup()
72
73 def check_sanity(self):
74 """
75 Check the object is sane (non-broken).
76 """
77
78 def __del__(self):
79 """
80 PEP 442 finalizer. Record that this was called, check the
81 object is in a sane state, and invoke a side effect.
82 """
83 try:
84 if not self._cleaning:
85 self.del_calls.append(id(self))
86 self.check_sanity()
87 self.side_effect()
88 except Exception as e:
89 self.errors.append(e)
90
91 def side_effect(self):
92 """
93 A side effect called on destruction.
94 """
95
96
97 class SimpleBase(NonGCSimpleBase):
98
99 def __init__(self):
100 self.id_ = id(self)
101
102 def check_sanity(self):
103 assert self.id_ == id(self)
104
105
106 @without_gc
107 class NonGC(NonGCSimpleBase):
108 __slots__ = ()
109
110 @without_gc
111 class NonGCResurrector(NonGCSimpleBase):
112 __slots__ = ()
113
114 def side_effect(self):
115 """
116 Resurrect self by storing self in a class-wide list.
117 """
118 self.survivors.append(self)
119
120 class Simple(SimpleBase):
121 pass
122
123 # Can't inherit from NonGCResurrector, in case importing without_gc fails.
124 class SimpleResurrector(SimpleBase):
125
126 def side_effect(self):
127 """
128 Resurrect self by storing self in a class-wide list.
129 """
130 self.survivors.append(self)
131
132
133 class TestBase:
134
135 def setUp(self):
136 self.old_garbage = gc.garbage[:]
137 gc.garbage[:] = []
138
139 def tearDown(self):
140 # None of the tests here should put anything in gc.garbage
141 try:
142 self.assertEqual(gc.garbage, [])
143 finally:
144 del self.old_garbage
145 gc.collect()
146
147 def assert_del_calls(self, ids):
148 self.assertEqual(sorted(SimpleBase.del_calls), sorted(ids))
149
150 def assert_tp_del_calls(self, ids):
151 self.assertEqual(sorted(SimpleBase.tp_del_calls), sorted(ids))
152
153 def assert_survivors(self, ids):
154 self.assertEqual(sorted(id(x) for x in SimpleBase.survivors), sorted(ids))
155
156 def assert_garbage(self, ids):
157 self.assertEqual(sorted(id(x) for x in gc.garbage), sorted(ids))
158
159 def clear_survivors(self):
160 SimpleBase.survivors.clear()
161
162
163 class SimpleFinalizationTest(TestBase, unittest.TestCase):
164 """
165 Test finalization without refcycles.
166 """
167
168 def test_simple(self):
169 with SimpleBase.test():
170 s = Simple()
171 ids = [id(s)]
172 wr = weakref.ref(s)
173 del s
174 gc.collect()
175 self.assert_del_calls(ids)
176 self.assert_survivors([])
177 self.assertIs(wr(), None)
178 gc.collect()
179 self.assert_del_calls(ids)
180 self.assert_survivors([])
181
182 def test_simple_resurrect(self):
183 with SimpleBase.test():
184 s = SimpleResurrector()
185 ids = [id(s)]
186 wr = weakref.ref(s)
187 del s
188 gc.collect()
189 self.assert_del_calls(ids)
190 self.assert_survivors(ids)
191 if support.check_impl_detail():
192 # CPython >= 3.4 changed this, but not in all cases
193 # (see the similar test in SelfCycleFinalizationTest).
194 # PyPy cannot tell apart the two cases, so we picked the
195 # cycle behavior, as it is the historical one.
196 self.assertIsNot(wr(), None)
197 self.clear_survivors()
198 gc.collect()
199 self.assert_del_calls(ids)
200 self.assert_survivors([])
201 self.assertIs(wr(), None)
202
203 @support.cpython_only
204 def test_non_gc(self):
205 with SimpleBase.test():
206 s = NonGC()
207 if support.check_impl_detail():
208 self.assertFalse(gc.is_tracked(s))
209 ids = [id(s)]
210 del s
211 gc.collect()
212 self.assert_del_calls(ids)
213 self.assert_survivors([])
214 gc.collect()
215 self.assert_del_calls(ids)
216 self.assert_survivors([])
217
218 @support.cpython_only
219 def test_non_gc_resurrect(self):
220 with SimpleBase.test():
221 s = NonGCResurrector()
222 if support.check_impl_detail():
223 self.assertFalse(gc.is_tracked(s))
224 ids = [id(s)]
225 del s
226 gc.collect()
227 self.assert_del_calls(ids)
228 self.assert_survivors(ids)
229 self.clear_survivors()
230 gc.collect()
231 if support.check_impl_detail():
232 # CPython: the __del__ method has been called again
233 self.assert_del_calls(ids * 2)
234 self.assert_survivors(ids)
235 else:
236 # PyPy (and likely others): the __del__ method is only
237 # called once
238 self.assert_del_calls(ids)
239 self.assert_survivors([])
240
241
242 class SelfCycleBase:
243
244 def __init__(self):
245 super().__init__()
246 self.ref = self
247
248 def check_sanity(self):
249 super().check_sanity()
250 assert self.ref is self
251
252 class SimpleSelfCycle(SelfCycleBase, Simple):
253 pass
254
255 class SelfCycleResurrector(SelfCycleBase, SimpleResurrector):
256 pass
257
258 class SuicidalSelfCycle(SelfCycleBase, Simple):
259
260 def side_effect(self):
261 """
262 Explicitly break the reference cycle.
263 """
264 self.ref = None
265
266
267 class SelfCycleFinalizationTest(TestBase, unittest.TestCase):
268 """
269 Test finalization of an object having a single cyclic reference to
270 itself.
271 """
272
273 def test_simple(self):
274 with SimpleBase.test():
275 s = SimpleSelfCycle()
276 ids = [id(s)]
277 wr = weakref.ref(s)
278 del s
279 gc.collect()
280 self.assert_del_calls(ids)
281 self.assert_survivors([])
282 self.assertIs(wr(), None)
283 gc.collect()
284 self.assert_del_calls(ids)
285 self.assert_survivors([])
286
287 def test_simple_resurrect(self):
288 # Test that __del__ can resurrect the object being finalized.
289 with SimpleBase.test():
290 s = SelfCycleResurrector()
291 ids = [id(s)]
292 wr = weakref.ref(s)
293 del s
294 gc.collect()
295 self.assert_del_calls(ids)
296 self.assert_survivors(ids)
297 # XXX is this desirable?
298 self.assertIs(wr(), None)
299 # When trying to destroy the object a second time, __del__
300 # isn't called anymore (and the object isn't resurrected).
301 self.clear_survivors()
302 gc.collect()
303 self.assert_del_calls(ids)
304 self.assert_survivors([])
305 self.assertIs(wr(), None)
306
307 def test_simple_suicide(self):
308 # Test the GC is able to deal with an object that kills its last
309 # reference during __del__.
310 with SimpleBase.test():
311 s = SuicidalSelfCycle()
312 ids = [id(s)]
313 wr = weakref.ref(s)
314 del s
315 gc.collect()
316 self.assert_del_calls(ids)
317 self.assert_survivors([])
318 self.assertIs(wr(), None)
319 gc.collect()
320 self.assert_del_calls(ids)
321 self.assert_survivors([])
322 self.assertIs(wr(), None)
323
324
325 class ChainedBase:
326
327 def chain(self, left):
328 self.suicided = False
329 self.left = left
330 left.right = self
331
332 def check_sanity(self):
333 super().check_sanity()
334 if self.suicided:
335 assert self.left is None
336 assert self.right is None
337 else:
338 left = self.left
339 if left.suicided:
340 assert left.right is None
341 else:
342 assert left.right is self
343 right = self.right
344 if right.suicided:
345 assert right.left is None
346 else:
347 assert right.left is self
348
349 class SimpleChained(ChainedBase, Simple):
350 pass
351
352 class ChainedResurrector(ChainedBase, SimpleResurrector):
353 pass
354
355 class SuicidalChained(ChainedBase, Simple):
356
357 def side_effect(self):
358 """
359 Explicitly break the reference cycle.
360 """
361 self.suicided = True
362 self.left = None
363 self.right = None
364
365
366 class CycleChainFinalizationTest(TestBase, unittest.TestCase):
367 """
368 Test finalization of a cyclic chain. These tests are similar in
369 spirit to the self-cycle tests above, but the collectable object
370 graph isn't trivial anymore.
371 """
372
373 def build_chain(self, classes):
374 nodes = [cls() for cls in classes]
375 for i in range(len(nodes)):
376 nodes[i].chain(nodes[i-1])
377 return nodes
378
379 def check_non_resurrecting_chain(self, classes):
380 N = len(classes)
381 with SimpleBase.test():
382 nodes = self.build_chain(classes)
383 ids = [id(s) for s in nodes]
384 wrs = [weakref.ref(s) for s in nodes]
385 del nodes
386 for cls in classes: # PyPy: needs several collections for a chain
387 gc.collect() # of objects all with a __del__()
388 self.assert_del_calls(ids)
389 self.assert_survivors([])
390 self.assertEqual([wr() for wr in wrs], [None] * N)
391 gc.collect()
392 self.assert_del_calls(ids)
393
394 def check_resurrecting_chain(self, classes):
395 if support.check_impl_detail(pypy=True):
396 self.skipTest("in CPython, in a cycle of objects with __del__(), "
397 "all the __del__() are called even if some of them "
398 "resurrect. In PyPy the recurrection will stop "
399 "the other objects from being considered as dead.")
400 N = len(classes)
401 with SimpleBase.test():
402 nodes = self.build_chain(classes)
403 N = len(nodes)
404 ids = [id(s) for s in nodes]
405 survivor_ids = [id(s) for s in nodes if isinstance(s, SimpleResurrector)]
406 wrs = [weakref.ref(s) for s in nodes]
407 del nodes
408 gc.collect()
409 self.assert_del_calls(ids)
410 self.assert_survivors(survivor_ids)
411 # XXX desirable?
412 self.assertEqual([wr() for wr in wrs], [None] * N)
413 self.clear_survivors()
414 gc.collect()
415 self.assert_del_calls(ids)
416 self.assert_survivors([])
417
418 def test_homogenous(self):
419 self.check_non_resurrecting_chain([SimpleChained] * 3)
420
421 def test_homogenous_resurrect(self):
422 self.check_resurrecting_chain([ChainedResurrector] * 3)
423
424 def test_homogenous_suicidal(self):
425 self.check_non_resurrecting_chain([SuicidalChained] * 3)
426
427 def test_heterogenous_suicidal_one(self):
428 self.check_non_resurrecting_chain([SuicidalChained, SimpleChained] * 2)
429
430 def test_heterogenous_suicidal_two(self):
431 self.check_non_resurrecting_chain(
432 [SuicidalChained] * 2 + [SimpleChained] * 2)
433
434 def test_heterogenous_resurrect_one(self):
435 self.check_resurrecting_chain([ChainedResurrector, SimpleChained] * 2)
436
437 def test_heterogenous_resurrect_two(self):
438 self.check_resurrecting_chain(
439 [ChainedResurrector, SimpleChained, SuicidalChained] * 2)
440
441 def test_heterogenous_resurrect_three(self):
442 self.check_resurrecting_chain(
443 [ChainedResurrector] * 2 + [SimpleChained] * 2 + [SuicidalChained] * 2)
444
445
446 # NOTE: the tp_del slot isn't automatically inherited, so we have to call
447 # with_tp_del() for each instantiated class.
448
449 class LegacyBase(SimpleBase):
450
451 def __del__(self):
452 try:
453 # Do not invoke side_effect here, since we are now exercising
454 # the tp_del slot.
455 if not self._cleaning:
456 self.del_calls.append(id(self))
457 self.check_sanity()
458 except Exception as e:
459 self.errors.append(e)
460
461 def __tp_del__(self):
462 """
463 Legacy (pre-PEP 442) finalizer, mapped to a tp_del slot.
464 """
465 try:
466 if not self._cleaning:
467 self.tp_del_calls.append(id(self))
468 self.check_sanity()
469 self.side_effect()
470 except Exception as e:
471 self.errors.append(e)
472
473 @with_tp_del
474 class Legacy(LegacyBase):
475 pass
476
477 @with_tp_del
478 class LegacyResurrector(LegacyBase):
479
480 def side_effect(self):
481 """
482 Resurrect self by storing self in a class-wide list.
483 """
484 self.survivors.append(self)
485
486 @with_tp_del
487 class LegacySelfCycle(SelfCycleBase, LegacyBase):
488 pass
489
490
491 @support.cpython_only
492 class LegacyFinalizationTest(TestBase, unittest.TestCase):
493 """
494 Test finalization of objects with a tp_del.
495 """
496
497 def tearDown(self):
498 # These tests need to clean up a bit more, since they create
499 # uncollectable objects.
500 gc.garbage.clear()
501 gc.collect()
502 super().tearDown()
503
504 def test_legacy(self):
505 with SimpleBase.test():
506 s = Legacy()
507 ids = [id(s)]
508 wr = weakref.ref(s)
509 del s
510 gc.collect()
511 self.assert_del_calls(ids)
512 self.assert_tp_del_calls(ids)
513 self.assert_survivors([])
514 self.assertIs(wr(), None)
515 gc.collect()
516 self.assert_del_calls(ids)
517 self.assert_tp_del_calls(ids)
518
519 def test_legacy_resurrect(self):
520 with SimpleBase.test():
521 s = LegacyResurrector()
522 ids = [id(s)]
523 wr = weakref.ref(s)
524 del s
525 gc.collect()
526 self.assert_del_calls(ids)
527 self.assert_tp_del_calls(ids)
528 self.assert_survivors(ids)
529 # weakrefs are cleared before tp_del is called.
530 self.assertIs(wr(), None)
531 self.clear_survivors()
532 gc.collect()
533 self.assert_del_calls(ids)
534 self.assert_tp_del_calls(ids * 2)
535 self.assert_survivors(ids)
536 self.assertIs(wr(), None)
537
538 def test_legacy_self_cycle(self):
539 # Self-cycles with legacy finalizers end up in gc.garbage.
540 with SimpleBase.test():
541 s = LegacySelfCycle()
542 ids = [id(s)]
543 wr = weakref.ref(s)
544 del s
545 gc.collect()
546 self.assert_del_calls([])
547 self.assert_tp_del_calls([])
548 self.assert_survivors([])
549 self.assert_garbage(ids)
550 self.assertIsNot(wr(), None)
551 # Break the cycle to allow collection
552 gc.garbage[0].ref = None
553 self.assert_garbage([])
554 self.assertIs(wr(), None)
555
556
557 if __name__ == "__main__":
558 unittest.main()