|
| 1 | +# Test weakref.finalize() functionality requiring gc.collect(). |
| 2 | + |
| 3 | +try: |
| 4 | + import weakref |
| 5 | +except ImportError: |
| 6 | + print("SKIP") |
| 7 | + raise SystemExit |
| 8 | + |
| 9 | +# gc module must be available if weakref is. |
| 10 | +import gc |
| 11 | + |
| 12 | + |
| 13 | +class A: |
| 14 | + def __str__(self): |
| 15 | + return "<A object>" |
| 16 | + |
| 17 | + |
| 18 | +def callback(*args, **kwargs): |
| 19 | + print("callback({}, {})".format(args, kwargs)) |
| 20 | + return 42 |
| 21 | + |
| 22 | + |
| 23 | +def test(): |
| 24 | + print("test basic use of finalize() with a simple callback") |
| 25 | + a = A() |
| 26 | + f = weakref.finalize(a, callback) |
| 27 | + a = None |
| 28 | + clean_the_stack = [0, 0, 0, 0] |
| 29 | + gc.collect() |
| 30 | + print("alive", f.alive) |
| 31 | + print("peek", f.peek()) |
| 32 | + print("detach", f.detach()) |
| 33 | + print("call", f()) |
| 34 | + |
| 35 | + print("test that a callback is passed the correct values") |
| 36 | + a = A() |
| 37 | + f = weakref.finalize(a, callback, 1, 2, kwarg=3) |
| 38 | + a = None |
| 39 | + clean_the_stack = [0, 0, 0, 0] |
| 40 | + gc.collect() |
| 41 | + print("alive", f.alive) |
| 42 | + print("peek", f.peek()) |
| 43 | + print("detach", f.detach()) |
| 44 | + print("call", f()) |
| 45 | + |
| 46 | + print("test that calling the finalizer cancels the finalizer") |
| 47 | + a = A() |
| 48 | + f = weakref.finalize(a, callback) |
| 49 | + print(f()) |
| 50 | + print(a) |
| 51 | + a = None |
| 52 | + clean_the_stack = [0, 0, 0, 0] |
| 53 | + gc.collect() |
| 54 | + |
| 55 | + print("test that calling detach cancels the finalizer") |
| 56 | + a = A() |
| 57 | + f = weakref.finalize(a, callback) |
| 58 | + print(len(f.detach())) |
| 59 | + print(a) |
| 60 | + a = None |
| 61 | + clean_the_stack = [0, 0, 0, 0] |
| 62 | + gc.collect() |
| 63 | + |
| 64 | + print("test that finalize does not get collected before its ref does") |
| 65 | + a = A() |
| 66 | + weakref.finalize(a, callback) |
| 67 | + clean_the_stack = [0, 0, 0, 0] |
| 68 | + gc.collect() |
| 69 | + print("free a") |
| 70 | + a = None |
| 71 | + clean_the_stack = [0, 0, 0, 0] |
| 72 | + gc.collect() |
| 73 | + |
| 74 | + |
| 75 | +test() |
0 commit comments