1. Pypy
  2. Untitled project
  3. pypy

Source

pypy / pypy / interpreter / test / test_typedef.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import gc
from pypy.interpreter import typedef
from rpython.tool.udir import udir
from pypy.interpreter.baseobjspace import W_Root
from pypy.interpreter.gateway import ObjSpace, interp2app

# this test isn't so much to test that the objspace interface *works*
# -- it's more to test that it's *there*

class AppTestTraceBackAttributes:

    def test_newstring(self):
        # XXX why is this called newstring?
        import sys
        def f():
            raise TypeError, "hello"

        def g():
            f()

        try:
            g()
        except:
            typ,val,tb = sys.exc_info()
        else:
            raise AssertionError, "should have raised"
        assert hasattr(tb, 'tb_frame')
        assert hasattr(tb, 'tb_lasti')
        assert hasattr(tb, 'tb_lineno')
        assert hasattr(tb, 'tb_next')

    def test_descr_dict(self):
        def f():
            pass
        dictdescr = type(f).__dict__['__dict__']   # only for functions
        assert dictdescr.__get__(f) is f.__dict__
        raises(TypeError, dictdescr.__get__, 5)
        d = {}
        dictdescr.__set__(f, d)
        assert f.__dict__ is d
        raises(TypeError, dictdescr.__set__, f, "not a dict")
        raises(TypeError, dictdescr.__set__, 5, d)
        # in PyPy, the following descr applies to any object that has a dict,
        # but not to objects without a dict, obviously
        dictdescr = type.__dict__['__dict__']
        raises(TypeError, dictdescr.__get__, 5)
        raises(TypeError, dictdescr.__set__, 5, d)

    def test_descr_member_descriptor(self):
        class X(object):
            __slots__ = ['x']
        member = X.x
        assert member.__name__ == 'x'
        assert member.__objclass__ is X
        raises((TypeError, AttributeError), "member.__name__ = 'x'")
        raises((TypeError, AttributeError), "member.__objclass__ = X")

    def test_descr_getsetproperty(self):
        from types import FrameType
        assert FrameType.f_lineno.__name__ == 'f_lineno'
        assert FrameType.f_lineno.__objclass__ is FrameType
        class A(object):
            pass
        assert A.__dict__['__dict__'].__name__ == '__dict__'


class TestTypeDef:

    def test_subclass_cache(self):
        # check that we don't create more than 6 subclasses of a
        # given W_XxxObject (instead of the 16 that follow from
        # all combinations)
        space = self.space
        sources = []
        for hasdict in [False, True]:
            for wants_slots in [False, True]:
                for needsdel in [False, True]:
                    for weakrefable in [False, True]:
                        print 'Testing case', hasdict, wants_slots,
                        print needsdel, weakrefable
                        slots = []
                        checks = []

                        if hasdict:
                            slots.append('__dict__')
                            checks.append('x.foo=5; x.__dict__')
                        else:
                            checks.append('raises(AttributeError, "x.foo=5");'
                                        'raises(AttributeError, "x.__dict__")')

                        if wants_slots:
                            slots.append('a')
                            checks.append('x.a=5; assert X.a.__get__(x)==5')
                        else:
                            checks.append('')

                        if weakrefable:
                            slots.append('__weakref__')
                            checks.append('import _weakref;_weakref.ref(x)')
                        else:
                            checks.append('')

                        if needsdel:
                            methodname = '__del__'
                            checks.append('X();X();X();'
                                          'import gc;gc.collect();'
                                          'assert seen')
                        else:
                            methodname = 'spam'
                            checks.append('assert "Del" not in irepr')

                        assert len(checks) == 4
                        space.appexec([], """():
                            seen = []
                            class X(list):
                                __slots__ = %r
                                def %s(self):
                                    seen.append(1)
                            x = X()
                            import __pypy__
                            irepr = __pypy__.internal_repr(x)
                            print irepr
                            %s
                            %s
                            %s
                            %s
                        """ % (slots, methodname, checks[0], checks[1],
                               checks[2], checks[3]))
        subclasses = {}
        for key, subcls in typedef._subclass_cache.items():
            if key[0] is not space.config:
                continue
            cls = key[1]
            subclasses.setdefault(cls, {})
            prevsubcls = subclasses[cls].setdefault(subcls.__name__, subcls)
            assert subcls is prevsubcls
        for cls, set in subclasses.items():
            assert len(set) <= 6, "%s has %d subclasses:\n%r" % (
                cls, len(set), list(set))

    def test_getsetproperty(self):
        class W_SomeType(W_Root):
            pass
        def fget(self, space, w_self):
            assert self is prop
        prop = typedef.GetSetProperty(fget, use_closure=True)
        W_SomeType.typedef = typedef.TypeDef(
            'some_type',
            x=prop)
        w_obj = self.space.wrap(W_SomeType())
        assert self.space.getattr(w_obj, self.space.wrap('x')) is self.space.w_None

    def test_getsetproperty_arguments(self):
        class W_SomeType(W_Root):
            def fget1(space, w_self):
                assert isinstance(space, ObjSpace)
                assert isinstance(w_self, W_SomeType)
            def fget2(self, space):
                assert isinstance(space, ObjSpace)
                assert isinstance(self, W_SomeType)
        W_SomeType.typedef = typedef.TypeDef(
            'some_type',
            x1=typedef.GetSetProperty(W_SomeType.fget1),
            x2=typedef.GetSetProperty(W_SomeType.fget2),
            )
        space = self.space
        w_obj = space.wrap(W_SomeType())
        assert space.getattr(w_obj, space.wrap('x1')) == space.w_None
        assert space.getattr(w_obj, space.wrap('x2')) == space.w_None

    def test_unhashable(self):
        class W_SomeType(W_Root):
            pass
        W_SomeType.typedef = typedef.TypeDef(
            'some_type',
            __hash__ = None)
        w_obj = self.space.wrap(W_SomeType())
        self.space.appexec([w_obj], """(obj):
            assert type(obj).__hash__ is None
            err = raises(TypeError, hash, obj)
            assert err.value.message == "'some_type' objects are unhashable"
            """)

    def test_destructor(self):
        space = self.space
        class W_Level1(W_Root):
            def __init__(self, space1):
                assert space1 is space
            def __del__(self):
                space.call_method(w_seen, 'append', space.wrap(1))
        class W_Level2(W_Root):
            def __init__(self, space1):
                assert space1 is space
            def __del__(self):
                self.enqueue_for_destruction(space, W_Level2.destructormeth,
                                             'FOO ')
            def destructormeth(self):
                space.call_method(w_seen, 'append', space.wrap(2))
        W_Level1.typedef = typedef.TypeDef(
            'level1',
            __new__ = typedef.generic_new_descr(W_Level1))
        W_Level2.typedef = typedef.TypeDef(
            'level2',
            __new__ = typedef.generic_new_descr(W_Level2))
        #
        w_seen = space.newlist([])
        W_Level1(space)
        gc.collect(); gc.collect()
        assert space.unwrap(w_seen) == [1]
        #
        w_seen = space.newlist([])
        W_Level2(space)
        gc.collect(); gc.collect()
        assert space.str_w(space.repr(w_seen)) == "[]"  # not called yet
        ec = space.getexecutioncontext()
        self.space.user_del_action.perform(ec, None)
        assert space.unwrap(w_seen) == [2]
        #
        w_seen = space.newlist([])
        self.space.appexec([self.space.gettypeobject(W_Level1.typedef)],
        """(level1):
            class A3(level1):
                pass
            A3()
        """)
        gc.collect(); gc.collect()
        assert space.unwrap(w_seen) == [1]
        #
        w_seen = space.newlist([])
        self.space.appexec([self.space.gettypeobject(W_Level1.typedef),
                            w_seen],
        """(level1, seen):
            class A4(level1):
                def __del__(self):
                    seen.append(4)
            A4()
        """)
        gc.collect(); gc.collect()
        assert space.unwrap(w_seen) == [4, 1]
        #
        w_seen = space.newlist([])
        self.space.appexec([self.space.gettypeobject(W_Level2.typedef)],
        """(level2):
            class A5(level2):
                pass
            A5()
        """)
        gc.collect(); gc.collect()
        assert space.unwrap(w_seen) == [2]
        #
        w_seen = space.newlist([])
        self.space.appexec([self.space.gettypeobject(W_Level2.typedef),
                            w_seen],
        """(level2, seen):
            class A6(level2):
                def __del__(self):
                    seen.append(6)
            A6()
        """)
        gc.collect(); gc.collect()
        assert space.unwrap(w_seen) == [6, 2]

    def test_multiple_inheritance(self):
        class W_A(W_Root):
            a = 1
            b = 2
        class W_C(W_A):
            b = 3
        W_A.typedef = typedef.TypeDef("A",
            a = typedef.interp_attrproperty("a", cls=W_A),
            b = typedef.interp_attrproperty("b", cls=W_A),
        )
        class W_B(W_Root):
            pass
        def standalone_method(space, w_obj):
            if isinstance(w_obj, W_A):
                return space.w_True
            else:
                return space.w_False
        W_B.typedef = typedef.TypeDef("B",
            c = interp2app(standalone_method)
        )
        W_C.typedef = typedef.TypeDef("C", (W_A.typedef, W_B.typedef,))

        w_o1 = self.space.wrap(W_C())
        w_o2 = self.space.wrap(W_B())
        w_c = self.space.gettypefor(W_C)
        w_b = self.space.gettypefor(W_B)
        w_a = self.space.gettypefor(W_A)
        assert w_c.mro_w == [
            w_c,
            w_a,
            w_b,
            self.space.w_object,
        ]
        for w_tp in w_c.mro_w:
            assert self.space.isinstance_w(w_o1, w_tp)
        def assert_attr(w_obj, name, value):
            assert self.space.unwrap(self.space.getattr(w_obj, self.space.wrap(name))) == value
        def assert_method(w_obj, name, value):
            assert self.space.unwrap(self.space.call_method(w_obj, name)) == value
        assert_attr(w_o1, "a", 1)
        assert_attr(w_o1, "b", 3)
        assert_method(w_o1, "c", True)
        assert_method(w_o2, "c", False)

    def test_total_ordering(self):
        class W_SomeType(W_Root):
            def __init__(self, space, x):
                self.space = space
                self.x = x

            def descr__lt(self, w_other):
                assert isinstance(w_other, W_SomeType)
                return self.space.wrap(self.x < w_other.x)

            def descr__eq(self, w_other):
                assert isinstance(w_other, W_SomeType)
                return self.space.wrap(self.x == w_other.x)

        W_SomeType.typedef = typedef.TypeDef(
            'some_type',
            __total_ordering__ = 'auto',
            __lt__ = interp2app(W_SomeType.descr__lt),
            __eq__ = interp2app(W_SomeType.descr__eq),
            )
        space = self.space
        w_b = space.wrap(W_SomeType(space, 2))
        w_c = space.wrap(W_SomeType(space, 2))
        w_a = space.wrap(W_SomeType(space, 1))
        # explicitly defined
        assert space.is_true(space.lt(w_a, w_b))
        assert not space.is_true(space.eq(w_a, w_b))
        assert space.is_true(space.eq(w_b, w_c))
        # automatically defined
        assert space.is_true(space.le(w_a, w_b))
        assert space.is_true(space.le(w_b, w_c))
        assert space.is_true(space.gt(w_b, w_a))
        assert space.is_true(space.ge(w_b, w_a))
        assert space.is_true(space.ge(w_b, w_c))
        assert space.is_true(space.ne(w_a, w_b))
        assert not space.is_true(space.ne(w_b, w_c))

    def test_class_attr(self):
        class W_SomeType(W_Root):
            pass

        seen = []
        def make_me(space):
            seen.append(1)
            return space.wrap("foobar")

        W_SomeType.typedef = typedef.TypeDef(
            'some_type',
            abc = typedef.ClassAttr(make_me)
            )
        assert seen == []
        self.space.appexec([W_SomeType()], """(x):
            assert type(x).abc == "foobar"
            assert x.abc == "foobar"
            assert type(x).abc == "foobar"
        """)
        assert seen == [1]


class AppTestTypeDef:

    def setup_class(cls):
        path = udir.join('AppTestTypeDef.txt')
        path.write('hello world\n')
        cls.w_path = cls.space.wrap(str(path))

    def test_destructor(self):
        import gc, os
        seen = []
        class MyFile(file):
            def __del__(self):
                seen.append(10)
                seen.append(os.lseek(self.fileno(), 2, 0))
        f = MyFile(self.path, 'r')
        fd = f.fileno()
        seen.append(os.lseek(fd, 5, 0))
        del f
        gc.collect(); gc.collect(); gc.collect()
        lst = seen[:]
        assert lst == [5, 10, 2]
        raises(OSError, os.lseek, fd, 7, 0)

    def test_method_attrs(self):
        import sys
        class A(object):
            def m(self):
                "aaa"
            m.x = 3
        class B(A):
            pass

        bm = B().m
        assert bm.__func__ is bm.im_func
        assert bm.__self__ is bm.im_self
        assert bm.im_class is B
        assert bm.__doc__ == "aaa"
        assert bm.x == 3
        assert type(bm).__doc__ == "instancemethod(function, instance, class)\n\nCreate an instance method object."
        raises(AttributeError, setattr, bm, 'x', 15)
        l = []
        assert l.append.__self__ is l
        assert l.__add__.__self__ is l
        # note: 'l.__add__.__objclass__' is not defined in pypy
        # because it's a regular method, and .__objclass__
        # differs from .im_class in case the method is
        # defined in some parent class of l's actual class

    def test_classmethod_im_class(self):
        class Foo(object):
            @classmethod
            def bar(cls):
                pass
        assert Foo.bar.im_class is type

    def test_func_closure(self):
        x = 2
        def f():
            return x
        assert f.__closure__[0].cell_contents is x