Debian Codegraph @

pypy/interpreter/test/test_typedef.py

raw symbols SCIP
1 import gc
2 from pypy.interpreter import typedef
3 from rpython.tool.udir import udir
4 from pypy.interpreter.baseobjspace import W_Root
5 from pypy.interpreter.gateway import ObjSpace, interp2app
6
7 # this test isn't so much to test that the objspace interface *works*
8 # -- it's more to test that it's *there*
9
10 class AppTestTraceBackAttributes:
11
12 def test_newstring(self):
13 # XXX why is this called newstring?
14 import sys
15 def f():
16 raise TypeError("hello")
17
18 def g():
19 f()
20
21 try:
22 g()
23 except:
24 typ,val,tb = sys.exc_info()
25 else:
26 raise AssertionError("should have raised")
27 assert hasattr(tb, 'tb_frame')
28 assert hasattr(tb, 'tb_lasti')
29 assert hasattr(tb, 'tb_lineno')
30 assert hasattr(tb, 'tb_next')
31
32 def test_descr_dict(self):
33 def f():
34 pass
35 dictdescr = type(f).__dict__['__dict__'] # only for functions
36 assert dictdescr.__get__(f) is f.__dict__
37 raises(TypeError, dictdescr.__get__, 5)
38 d = {}
39 dictdescr.__set__(f, d)
40 assert f.__dict__ is d
41 raises(TypeError, dictdescr.__set__, f, "not a dict")
42 raises(TypeError, dictdescr.__set__, 5, d)
43 # in PyPy, the following descr applies to any object that has a dict,
44 # but not to objects without a dict, obviously
45 dictdescr = type.__dict__['__dict__']
46 raises(TypeError, dictdescr.__get__, 5)
47 # TypeError on CPython because descr applies only to its
48 # __objclass__
49 raises((AttributeError, TypeError), dictdescr.__set__, 5, d)
50
51 def test_descr_member_descriptor(self):
52 class X(object):
53 __slots__ = ['x']
54 member = X.x
55 assert member.__name__ == 'x'
56 assert member.__objclass__ is X
57 raises(AttributeError, "member.__name__ = 'x'")
58 raises(AttributeError, "member.__objclass__ = X")
59
60 def test_descr_member_errormsg(self):
61 class X(object):
62 __slots__ = ['a']
63 with raises(AttributeError) as info:
64 X().a
65 assert str(info.value) == "'X' object has no attribute 'a'"
66 class Y(X):
67 pass
68 with raises(AttributeError) as info:
69 Y().a
70 assert str(info.value) == "'Y' object has no attribute 'a'"
71
72 def test_descr_getsetproperty(self):
73 from types import FrameType
74 assert FrameType.f_lineno.__name__ == 'f_lineno'
75 assert FrameType.f_lineno.__qualname__ == 'frame.f_lineno'
76 assert FrameType.f_lineno.__objclass__ is FrameType
77 class A(object):
78 pass
79 assert A.__dict__['__dict__'].__name__ == '__dict__'
80
81
82 class TestTypeDef:
83
84 def test_subclass_cache(self):
85 # check that we don't create more than 6 subclasses of a
86 # given W_XxxObject (instead of the 16 that follow from
87 # all combinations)
88 space = self.space
89 sources = []
90 for hasdict in [False, True]:
91 for wants_slots in [False, True]:
92 for needsdel in [False, True]:
93 for weakrefable in [False, True]:
94 print 'Testing case', hasdict, wants_slots,
95 print needsdel, weakrefable
96 slots = []
97 checks = []
98
99 if hasdict:
100 slots.append('__dict__')
101 checks.append('x.foo=5; x.__dict__')
102 else:
103 checks.append('raises(AttributeError, "x.foo=5");'
104 'raises(AttributeError, "x.__dict__")')
105
106 if wants_slots:
107 slots.append('a')
108 checks.append('x.a=5; assert X.a.__get__(x)==5')
109 else:
110 checks.append('')
111
112 if weakrefable:
113 slots.append('__weakref__')
114 checks.append('import _weakref;_weakref.ref(x)')
115 else:
116 checks.append('')
117
118 if needsdel:
119 methodname = '__del__'
120 checks.append('X();X();X();'
121 'import gc;gc.collect();'
122 'assert seen')
123 else:
124 methodname = 'spam'
125 checks.append('assert "Del" not in irepr')
126
127 assert len(checks) == 4
128 space.appexec([], """():
129 seen = []
130 class X(list):
131 __slots__ = %r
132 def %s(self):
133 seen.append(1)
134 x = X()
135 import __pypy__
136 irepr = __pypy__.internal_repr(x)
137 print(irepr)
138 %s
139 %s
140 %s
141 %s
142 """ % (slots, methodname, checks[0], checks[1],
143 checks[2], checks[3]))
144 subclasses = {}
145 for cls, subcls in typedef._unique_subclass_cache.items():
146 subclasses.setdefault(cls, {})
147 prevsubcls = subclasses[cls].setdefault(subcls.__name__, subcls)
148 assert subcls is prevsubcls
149 for cls, set in subclasses.items():
150 assert len(set) <= 6, "%s has %d subclasses:\n%r" % (
151 cls, len(set), list(set))
152
153 def test_getsetproperty(self):
154 class W_SomeType(W_Root):
155 pass
156 def fget(self, space, w_self):
157 assert self is prop
158 # NB. this GetSetProperty is not copied when creating the
159 # W_TypeObject because of 'cls'. Without it, a duplicate of the
160 # GetSetProperty is taken and it is given the w_objclass that is
161 # the W_TypeObject
162 prop = typedef.GetSetProperty(fget, use_closure=True, cls=W_SomeType)
163 W_SomeType.typedef = typedef.TypeDef(
164 'some_type',
165 x=prop)
166 w_obj = self.space.wrap(W_SomeType())
167 assert self.space.getattr(w_obj, self.space.wrap('x')) is self.space.w_None
168
169 def test_getsetproperty_arguments(self):
170 class W_SomeType(W_Root):
171 def fget1(space, w_self):
172 assert isinstance(space, ObjSpace)
173 assert isinstance(w_self, W_SomeType)
174 def fget2(self, space):
175 assert isinstance(space, ObjSpace)
176 assert isinstance(self, W_SomeType)
177 W_SomeType.typedef = typedef.TypeDef(
178 'some_type',
179 x1=typedef.GetSetProperty(W_SomeType.fget1),
180 x2=typedef.GetSetProperty(W_SomeType.fget2),
181 )
182 space = self.space
183 w_obj = space.wrap(W_SomeType())
184 assert space.getattr(w_obj, space.wrap('x1')) == space.w_None
185 assert space.getattr(w_obj, space.wrap('x2')) == space.w_None
186
187 def test_unhashable(self):
188 class W_SomeType(W_Root):
189 pass
190 W_SomeType.typedef = typedef.TypeDef(
191 'some_type',
192 __hash__ = None)
193 w_obj = self.space.wrap(W_SomeType())
194 self.space.appexec([w_obj], """(obj):
195 assert type(obj).__hash__ is None
196 err = raises(TypeError, hash, obj)
197 assert str(err.value) == "unhashable type: 'some_type'"
198 """)
199
200 def test_destructor(self):
201 space = self.space
202 class W_Level1(W_Root):
203 def __init__(self, space1):
204 assert space1 is space
205 self.register_finalizer(space)
206 def _finalize_(self):
207 space.call_method(w_seen, 'append', space.wrap(1))
208 W_Level1.typedef = typedef.TypeDef(
209 'level1',
210 __new__ = typedef.generic_new_descr(W_Level1))
211 #
212 w_seen = space.newlist([])
213 W_Level1(space)
214 gc.collect(); gc.collect()
215 assert space.text_w(space.repr(w_seen)) == "[]" # not called yet
216 ec = space.getexecutioncontext()
217 self.space.user_del_action.perform(ec, None)
218 assert space.unwrap(w_seen) == [1] # called by user_del_action
219 #
220 w_seen = space.newlist([])
221 self.space.appexec([self.space.gettypeobject(W_Level1.typedef)],
222 """(level1):
223 class A3(level1):
224 pass
225 A3()
226 """)
227 gc.collect(); gc.collect()
228 self.space.user_del_action.perform(ec, None)
229 assert space.unwrap(w_seen) == [1]
230 #
231 w_seen = space.newlist([])
232 self.space.appexec([self.space.gettypeobject(W_Level1.typedef),
233 w_seen],
234 """(level1, seen):
235 class A4(level1):
236 def __del__(self):
237 seen.append(4)
238 A4()
239 """)
240 gc.collect(); gc.collect()
241 self.space.user_del_action.perform(ec, None)
242 assert space.unwrap(w_seen) == [4, 1] # user __del__, and _finalize_
243 #
244 w_seen = space.newlist([])
245 self.space.appexec([self.space.gettypeobject(W_Level1.typedef)],
246 """(level2):
247 class A5(level2):
248 pass
249 A5()
250 """)
251 gc.collect(); gc.collect()
252 self.space.user_del_action.perform(ec, None)
253 assert space.unwrap(w_seen) == [1] # _finalize_ only
254
255 def test_multiple_inheritance(self):
256 class W_A(W_Root):
257 a = 1
258 b = 2
259 class W_C(W_A):
260 b = 3
261 W_A.typedef = typedef.TypeDef("A",
262 a = typedef.interp_attrproperty("a", cls=W_A,
263 wrapfn="newint"),
264 b = typedef.interp_attrproperty("b", cls=W_A,
265 wrapfn="newint"),
266 )
267 class W_B(W_Root):
268 pass
269 def standalone_method(space, w_obj):
270 if isinstance(w_obj, W_A):
271 return space.w_True
272 else:
273 return space.w_False
274 W_B.typedef = typedef.TypeDef("B",
275 c = interp2app(standalone_method)
276 )
277 W_C.typedef = typedef.TypeDef("C", (W_A.typedef, W_B.typedef,))
278
279 w_o1 = self.space.wrap(W_C())
280 w_o2 = self.space.wrap(W_B())
281 w_c = self.space.gettypefor(W_C)
282 w_b = self.space.gettypefor(W_B)
283 w_a = self.space.gettypefor(W_A)
284 assert w_c.mro_w == [
285 w_c,
286 w_a,
287 w_b,
288 self.space.w_object,
289 ]
290 for w_tp in w_c.mro_w:
291 assert self.space.isinstance_w(w_o1, w_tp)
292 def assert_attr(w_obj, name, value):
293 assert self.space.unwrap(self.space.getattr(w_obj, self.space.wrap(name))) == value
294 def assert_method(w_obj, name, value):
295 assert self.space.unwrap(self.space.call_method(w_obj, name)) == value
296 assert_attr(w_o1, "a", 1)
297 assert_attr(w_o1, "b", 3)
298 assert_method(w_o1, "c", True)
299 assert_method(w_o2, "c", False)
300
301 def test_class_attr(self):
302 class W_SomeType(W_Root):
303 pass
304
305 seen = []
306 def make_me(space):
307 seen.append(1)
308 return space.wrap("foobar")
309
310 W_SomeType.typedef = typedef.TypeDef(
311 'some_type',
312 abc = typedef.ClassAttr(make_me)
313 )
314 assert seen == []
315 self.space.appexec([W_SomeType()], """(x):
316 assert type(x).abc == "foobar"
317 assert x.abc == "foobar"
318 assert type(x).abc == "foobar"
319 """)
320 assert seen == [1]
321
322 def test_mapdict_number_of_slots(self):
323 space = self.space
324 a, b, c = space.unpackiterable(space.appexec([], """():
325 class A(object):
326 pass
327 a = A()
328 a.x = 1
329 class B:
330 pass
331 b = B()
332 b.x = 1
333 class C(int):
334 pass
335 c = C(1)
336 c.x = 1
337 return a, b, c
338 """), 3)
339 assert not hasattr(a, "storage")
340 assert not hasattr(b, "storage")
341 assert hasattr(c, "storage")
342
343 class AppTestTypeDef:
344
345 spaceconfig = dict(usemodules=['array'])
346
347 def setup_class(cls):
348 path = udir.join('AppTestTypeDef.txt')
349 path.write('hello world\n')
350 cls.w_path = cls.space.wrap(str(path))
351
352 def test_destructor(self):
353 import gc, array
354 seen = []
355 class MyArray(array.array):
356 def __del__(self):
357 # here we check that we can still access the array, i.e. that
358 # the interp-level __del__ has not been called yet
359 seen.append(10)
360 seen.append(self[0])
361 a = MyArray('i')
362 a.append(42)
363 seen.append(a[0])
364 del a
365 gc.collect(); gc.collect(); gc.collect()
366 lst = seen[:]
367 print(lst)
368 assert lst == [42, 10, 42]
369
370 def test_method_attrs(self):
371 import sys
372 class A(object):
373 def m(self):
374 "aaa"
375 m.x = 3
376 class B(A):
377 pass
378
379 obj = B()
380 bm = obj.m
381 assert bm.__func__ is A.m
382 assert bm.__self__ is obj
383 assert bm.__doc__ == "aaa"
384 assert bm.x == 3
385 assert type(bm).__doc__ == "Create a method object."
386 raises(AttributeError, setattr, bm, 'x', 15)
387 l = []
388 assert l.append.__self__ is l
389 assert l.__add__.__self__ is l
390 # note: 'l.__add__.__objclass__' is not defined in pypy
391 # because it's a regular method, and .__objclass__
392 # differs from .im_class in case the method is
393 # defined in some parent class of l's actual class
394
395 def test_func_closure(self):
396 x = 2
397 def f():
398 return x
399 assert f.__closure__[0].cell_contents is x
400
401 def test_get_with_none_arg(self):
402 raises(TypeError, type.__dict__['__mro__'].__get__, None)
403 raises(TypeError, type.__dict__['__mro__'].__get__, None, None)
404
405 def test_builtin_readonly_property(self):
406 import sys
407 x = lambda: 5
408 e = raises(AttributeError, 'x.__globals__ = {}')
409 if '__pypy__' in sys.builtin_module_names:
410 assert str(e.value) == "readonly attribute '__globals__'"
411
412 def test_del_doc(self):
413 class X:
414 "hi there"
415 assert X.__doc__ == 'hi there'
416 with raises(AttributeError) as exc:
417 del X.__doc__
418 assert "cannot delete '__doc__' attribute" in str(exc.value), str(exc.value)