|
| 1 | +// Test weakref.finalize() functionality requiring gc.collect(). |
| 2 | +// Should be kept in sync with tests/basics/weakref_finalize_collect.py. |
| 3 | +// |
| 4 | +// This needs custom testing on the webassembly port since the GC can only |
| 5 | +// run when Python code returns to JavaScript. |
| 6 | + |
| 7 | +const mp = await (await import(process.argv[2])).loadMicroPython(); |
| 8 | + |
| 9 | +// Set up. |
| 10 | +mp.runPython(` |
| 11 | +import gc, weakref |
| 12 | +
|
| 13 | +class A: |
| 14 | + def __str__(self): |
| 15 | + return "<A object>" |
| 16 | +
|
| 17 | +def callback(*args, **kwargs): |
| 18 | + print("callback({}, {})".format(args, kwargs)) |
| 19 | + return 42 |
| 20 | +`); |
| 21 | + |
| 22 | +console.log("test basic use of finalize() with a simple callback"); |
| 23 | +mp.runPython(` |
| 24 | + a = A() |
| 25 | + f = weakref.finalize(a, callback) |
| 26 | + a = None |
| 27 | + gc.collect() |
| 28 | +`); |
| 29 | +console.log("(outside Python)"); |
| 30 | +mp.runPython(` |
| 31 | + print("alive", f.alive) |
| 32 | + print("peek", f.peek()) |
| 33 | + print("detach", f.detach()) |
| 34 | + print("call", f()) |
| 35 | +`); |
| 36 | + |
| 37 | +console.log("test that a callback is passed the correct values"); |
| 38 | +mp.runPython(` |
| 39 | + a = A() |
| 40 | + f = weakref.finalize(a, callback, 1, 2, kwarg=3) |
| 41 | + a = None |
| 42 | + gc.collect() |
| 43 | +`); |
| 44 | +console.log("(outside Python)"); |
| 45 | +mp.runPython(` |
| 46 | + print("alive", f.alive) |
| 47 | + print("peek", f.peek()) |
| 48 | + print("detach", f.detach()) |
| 49 | + print("call", f()) |
| 50 | +`); |
| 51 | + |
| 52 | +console.log("test that calling the finalizer cancels the finalizer"); |
| 53 | +mp.runPython(` |
| 54 | + a = A() |
| 55 | + f = weakref.finalize(a, callback) |
| 56 | + print(f()) |
| 57 | + print(a) |
| 58 | + a = None |
| 59 | + gc.collect() |
| 60 | +`); |
| 61 | +console.log("(outside Python)"); |
| 62 | + |
| 63 | +console.log("test that calling detach cancels the finalizer"); |
| 64 | +mp.runPython(` |
| 65 | + a = A() |
| 66 | + f = weakref.finalize(a, callback) |
| 67 | + print(len(f.detach())) |
| 68 | + print(a) |
| 69 | + a = None |
| 70 | + gc.collect() |
| 71 | +`); |
| 72 | +console.log("(outside Python)"); |
| 73 | + |
| 74 | +console.log("test that finalize does not get collected before its ref does"); |
| 75 | +mp.runPython(` |
| 76 | + a = A() |
| 77 | + weakref.finalize(a, callback) |
| 78 | + gc.collect() |
| 79 | +`); |
| 80 | +console.log("(outside Python)"); |
| 81 | +mp.runPython(` |
| 82 | + print("free a") |
| 83 | + a = None |
| 84 | + gc.collect() |
| 85 | +`); |
| 86 | +console.log("(outside Python)"); |
0 commit comments