|
1 | 1 | # Test cases for weakrefs (compile and run) |
2 | 2 |
|
3 | 3 | [case testWeakrefRef] |
4 | | -from weakref import ref |
| 4 | +# mypy: disable-error-code="union-attr" |
| 5 | +from weakref import proxy, ref |
5 | 6 | from mypy_extensions import mypyc_attr |
| 7 | +from testutil import assertRaises |
| 8 | +from typing import Optional |
6 | 9 |
|
7 | 10 | @mypyc_attr(native_class=False) |
8 | 11 | class Object: |
9 | 12 | """some random weakreffable object""" |
10 | | - pass |
| 13 | + def some_meth(self) -> int: |
| 14 | + return 1 |
11 | 15 |
|
12 | | -def test_weakref_ref(): |
13 | | - obj = Object() |
| 16 | +_callback_called_cache = {"ref": False, "proxy": False} |
| 17 | + |
| 18 | +def test_weakref_ref() -> None: |
| 19 | + obj: Optional[Object] = Object() |
14 | 20 | r = ref(obj) |
15 | 21 | assert r() is obj |
16 | 22 | obj = None |
17 | 23 | assert r() is None, r() |
18 | 24 |
|
19 | | -def test_weakref_ref_with_callback(): |
20 | | - obj = Object() |
21 | | - r = ref(obj, lambda x: x) |
| 25 | +def test_weakref_ref_with_callback() -> None: |
| 26 | + obj: Optional[Object] = Object() |
| 27 | + r = ref(obj, lambda x: _callback_called_cache.__setitem__("ref", True)) |
22 | 28 | assert r() is obj |
23 | 29 | obj = None |
24 | 30 | assert r() is None, r() |
| 31 | + assert _callback_called_cache["ref"] is True |
25 | 32 |
|
26 | | -[file driver.py] |
27 | | -from native import test_weakref_ref, test_weakref_ref_with_callback |
| 33 | +def test_weakref_proxy() -> None: |
| 34 | + obj: Optional[Object] = Object() |
| 35 | + p = proxy(obj) |
| 36 | + assert obj.some_meth() == 1 |
| 37 | + assert p.some_meth() == 1 |
| 38 | + obj.some_meth() |
| 39 | + obj = None |
| 40 | + with assertRaises(ReferenceError): |
| 41 | + p.some_meth() |
28 | 42 |
|
29 | | -test_weakref_ref() |
30 | | -test_weakref_ref_with_callback() |
| 43 | +def test_weakref_proxy_with_callback() -> None: |
| 44 | + obj: Optional[Object] = Object() |
| 45 | + p = proxy(obj, lambda x: _callback_called_cache.__setitem__("proxy", True)) |
| 46 | + assert obj.some_meth() == 1 |
| 47 | + assert p.some_meth() == 1 |
| 48 | + obj.some_meth() |
| 49 | + obj = None |
| 50 | + with assertRaises(ReferenceError): |
| 51 | + p.some_meth() |
| 52 | + assert _callback_called_cache["proxy"] is True |
0 commit comments