| 1 | |
| 2 | """ test proxy on functions and other crazy goodies |
| 3 | """ |
| 4 | |
| 5 | from pypy.objspace.std.test.test_proxy import AppProxyBasic |
| 6 | |
| 7 | class AppTestProxyFunction(object): |
| 8 | spaceconfig = {"objspace.std.withtproxy": True} |
| 9 | |
| 10 | def setup_method(self, meth): |
| 11 | self.w_get_proxy = self.space.appexec([], """(): |
| 12 | class Controller(object): |
| 13 | def __init__(self, obj): |
| 14 | self.obj = obj |
| 15 | |
| 16 | def perform(self, name, *args, **kwargs): |
| 17 | return getattr(self.obj, name)(*args, **kwargs) |
| 18 | def get_proxy(f): |
| 19 | import types |
| 20 | from __pypy__ import tproxy as proxy |
| 21 | return proxy(types.FunctionType, Controller(f).perform) |
| 22 | return get_proxy |
| 23 | """) |
| 24 | |
| 25 | def test_function_noargs(self): |
| 26 | def f(): |
| 27 | return 3 |
| 28 | |
| 29 | fun = self.get_proxy(f) |
| 30 | assert fun() == f() |
| 31 | |
| 32 | def test_simple_function(self): |
| 33 | def f(x): |
| 34 | return x |
| 35 | |
| 36 | fun = self.get_proxy(f) |
| 37 | assert fun(3) == f(3) |
| 38 | |
| 39 | def test_function_args(self): |
| 40 | def f(x, y): |
| 41 | return x |
| 42 | |
| 43 | fun = self.get_proxy(f) |
| 44 | raises(TypeError, "fun(3)") |
| 45 | assert fun(1,2) == 1 |
| 46 | |
| 47 | def test_method_bind(self): |
| 48 | def f(self): |
| 49 | return 3 |
| 50 | |
| 51 | class A(object): |
| 52 | pass |
| 53 | |
| 54 | fun = self.get_proxy(f) |
| 55 | assert fun.__get__(A())() == 3 |
| 56 | |
| 57 | def test_function_repr(self): |
| 58 | def f(): |
| 59 | pass |
| 60 | |
| 61 | fun = self.get_proxy(f) |
| 62 | assert repr(fun).startswith("<function test_function_repr.<locals>.f") |
| 63 | |
| 64 | def test_func_code(self): |
| 65 | def f(): |
| 66 | pass |
| 67 | |
| 68 | fun = self.get_proxy(f) |
| 69 | assert fun.__code__ is f.__code__ |
| 70 | |
| 71 | def test_funct_prop_setter_del(self): |
| 72 | def f(): |
| 73 | pass |
| 74 | |
| 75 | fun = self.get_proxy(f) |
| 76 | fun.__doc__ = "aaa" |
| 77 | assert f.__doc__ == 'aaa' |
| 78 | del fun.__doc__ |
| 79 | assert f.__doc__ is None |
| 80 | |
| 81 | def test_proxy_bind_method(self): |
| 82 | class A(object): |
| 83 | pass |
| 84 | |
| 85 | def f(self): |
| 86 | return 3 |
| 87 | |
| 88 | class AA(object): |
| 89 | pass |
| 90 | |
| 91 | from __pypy__ import tproxy as proxy |
| 92 | a = A() |
| 93 | class X(object): |
| 94 | def __init__(self, x): |
| 95 | self.x = x |
| 96 | def f(self, name, *args, **kwargs): |
| 97 | return getattr(self.x, name)(*args, **kwargs) |
| 98 | |
| 99 | y = proxy(type(f), X(f).f) |
| 100 | x = proxy(AA, X(a).f) |
| 101 | AA.f = y |
| 102 | assert x.f() == 3 |