| 1 |
# Test cases for weakrefs (compile and run) |
| 2 |
|
| 3 |
[case testWeakrefRef] |
| 4 |
# mypy: disable-error-code="union-attr" |
| 5 |
from weakref import proxy, ref |
| 6 |
from mypy_extensions import mypyc_attr |
| 7 |
from testutil import assertRaises |
| 8 |
from typing import Optional |
| 9 |
|
| 10 |
@mypyc_attr(native_class=False) |
| 11 |
class Object: |
| 12 |
"""some random weakreffable object""" |
| 13 |
def some_meth(self) -> int: |
| 14 |
return 1 |
| 15 |
|
| 16 |
_callback_called_cache = {"ref": False, "proxy": False} |
| 17 |
|
| 18 |
def test_weakref_ref() -> None: |
| 19 |
obj: Optional[Object] = Object() |
| 20 |
r = ref(obj) |
| 21 |
assert r() is obj |
| 22 |
obj = None |
| 23 |
assert r() is None, r() |
| 24 |
|
| 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)) |
| 28 |
assert r() is obj |
| 29 |
obj = None |
| 30 |
assert r() is None, r() |
| 31 |
assert _callback_called_cache["ref"] is True |
| 32 |
|
| 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() |
| 42 |
|
| 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 |