test_descr.py 119 KB
Newer Older
1
# Test enhancements related to descriptors and new-style classes
2

3
from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout, run_doctest
4
from copy import deepcopy
Tim Peters's avatar
Tim Peters committed
5 6 7 8
import warnings

warnings.filterwarnings("ignore",
         r'complex divmod\(\), // and % are deprecated$',
9
         DeprecationWarning, r'(<string>|%s)$' % __name__)
10

11 12 13 14
def veris(a, b):
    if a is not b:
        raise TestFailed, "%r is %r" % (a, b)

15 16 17
def testunop(a, res, expr="len(a)", meth="__len__"):
    if verbose: print "checking", expr
    dict = {'a': a}
18
    vereq(eval(expr, dict), res)
19 20
    t = type(a)
    m = getattr(t, meth)
21 22
    while meth not in t.__dict__:
        t = t.__bases__[0]
23 24
    vereq(m, t.__dict__[meth])
    vereq(m(a), res)
25
    bm = getattr(a, meth)
26
    vereq(bm(), res)
27 28 29 30

def testbinop(a, b, res, expr="a+b", meth="__add__"):
    if verbose: print "checking", expr
    dict = {'a': a, 'b': b}
Tim Peters's avatar
Tim Peters committed
31 32 33 34 35

    # XXX Hack so this passes before 2.3 when -Qnew is specified.
    if meth == "__div__" and 1/2 == 0.5:
        meth = "__truediv__"

36
    vereq(eval(expr, dict), res)
37 38
    t = type(a)
    m = getattr(t, meth)
39 40
    while meth not in t.__dict__:
        t = t.__bases__[0]
41 42
    vereq(m, t.__dict__[meth])
    vereq(m(a, b), res)
43
    bm = getattr(a, meth)
44
    vereq(bm(b), res)
45 46 47 48

def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
    if verbose: print "checking", expr
    dict = {'a': a, 'b': b, 'c': c}
49
    vereq(eval(expr, dict), res)
50 51
    t = type(a)
    m = getattr(t, meth)
52 53
    while meth not in t.__dict__:
        t = t.__bases__[0]
54 55
    vereq(m, t.__dict__[meth])
    vereq(m(a, b, c), res)
56
    bm = getattr(a, meth)
57
    vereq(bm(b, c), res)
58 59 60 61 62

def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
    if verbose: print "checking", stmt
    dict = {'a': deepcopy(a), 'b': b}
    exec stmt in dict
63
    vereq(dict['a'], res)
64 65
    t = type(a)
    m = getattr(t, meth)
66 67
    while meth not in t.__dict__:
        t = t.__bases__[0]
68
    vereq(m, t.__dict__[meth])
69 70
    dict['a'] = deepcopy(a)
    m(dict['a'], b)
71
    vereq(dict['a'], res)
72 73 74
    dict['a'] = deepcopy(a)
    bm = getattr(dict['a'], meth)
    bm(b)
75
    vereq(dict['a'], res)
76 77 78 79 80

def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
    if verbose: print "checking", stmt
    dict = {'a': deepcopy(a), 'b': b, 'c': c}
    exec stmt in dict
81
    vereq(dict['a'], res)
82 83
    t = type(a)
    m = getattr(t, meth)
84 85
    while meth not in t.__dict__:
        t = t.__bases__[0]
86
    vereq(m, t.__dict__[meth])
87 88
    dict['a'] = deepcopy(a)
    m(dict['a'], b, c)
89
    vereq(dict['a'], res)
90 91 92
    dict['a'] = deepcopy(a)
    bm = getattr(dict['a'], meth)
    bm(b, c)
93
    vereq(dict['a'], res)
94 95 96 97 98

def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
    if verbose: print "checking", stmt
    dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
    exec stmt in dict
99
    vereq(dict['a'], res)
100
    t = type(a)
101 102
    while meth not in t.__dict__:
        t = t.__bases__[0]
103
    m = getattr(t, meth)
104
    vereq(m, t.__dict__[meth])
105 106
    dict['a'] = deepcopy(a)
    m(dict['a'], b, c, d)
107
    vereq(dict['a'], res)
108 109 110
    dict['a'] = deepcopy(a)
    bm = getattr(dict['a'], meth)
    bm(b, c, d)
111
    vereq(dict['a'], res)
112

113 114 115
def class_docstrings():
    class Classic:
        "A classic docstring."
116 117
    vereq(Classic.__doc__, "A classic docstring.")
    vereq(Classic.__dict__['__doc__'], "A classic docstring.")
118 119 120 121 122

    class Classic2:
        pass
    verify(Classic2.__doc__ is None)

123
    class NewStatic(object):
124
        "Another docstring."
125 126
    vereq(NewStatic.__doc__, "Another docstring.")
    vereq(NewStatic.__dict__['__doc__'], "Another docstring.")
127

128
    class NewStatic2(object):
129 130 131
        pass
    verify(NewStatic2.__doc__ is None)

132
    class NewDynamic(object):
133
        "Another docstring."
134 135
    vereq(NewDynamic.__doc__, "Another docstring.")
    vereq(NewDynamic.__dict__['__doc__'], "Another docstring.")
136

137
    class NewDynamic2(object):
138 139 140
        pass
    verify(NewDynamic2.__doc__ is None)

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
def lists():
    if verbose: print "Testing list operations..."
    testbinop([1], [2], [1,2], "a+b", "__add__")
    testbinop([1,2,3], 2, 1, "b in a", "__contains__")
    testbinop([1,2,3], 4, 0, "b in a", "__contains__")
    testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
    testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
    testsetop([1], [2], [1,2], "a+=b", "__iadd__")
    testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
    testunop([1,2,3], 3, "len(a)", "__len__")
    testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
    testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
    testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
    testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")

def dicts():
    if verbose: print "Testing dict operations..."
    testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
    testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
    testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
    testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
    d = {1:2,3:4}
    l1 = []
    for i in d.keys(): l1.append(i)
    l = []
    for i in iter(d): l.append(i)
167
    vereq(l, l1)
168 169
    l = []
    for i in d.__iter__(): l.append(i)
170
    vereq(l, l1)
171
    l = []
172
    for i in dict.__iter__(d): l.append(i)
173
    vereq(l, l1)
174 175
    d = {1:2, 3:4}
    testunop(d, 2, "len(a)", "__len__")
176 177
    vereq(eval(repr(d), {}), d)
    vereq(eval(d.__repr__(), {}), d)
178 179
    testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")

180 181
def dict_constructor():
    if verbose:
182 183
        print "Testing dict constructor ..."
    d = dict()
184
    vereq(d, {})
185
    d = dict({})
186
    vereq(d, {})
187
    d = dict({1: 2, 'a': 'b'})
188
    vereq(d, {1: 2, 'a': 'b'})
189
    vereq(d, dict(d.items()))
190 191 192 193 194 195 196 197
    vereq(d, dict(d.iteritems()))
    d = dict({'one':1, 'two':2})
    vereq(d, dict(one=1, two=2))
    vereq(d, dict(**d))
    vereq(d, dict({"one": 1}, two=2))
    vereq(d, dict([("two", 2)], one=1))
    vereq(d, dict([("one", 100), ("two", 200)], **d))
    verify(d is not dict(**d))
198 199
    for badarg in 0, 0L, 0j, "0", [0], (0,):
        try:
200
            dict(badarg)
201 202
        except TypeError:
            pass
203 204 205 206 207 208 209
        except ValueError:
            if badarg == "0":
                # It's a sequence, and its elements are also sequences (gotta
                # love strings <wink>), but they aren't of length 2, so this
                # one seemed better as a ValueError than a TypeError.
                pass
            else:
210
                raise TestFailed("no TypeError from dict(%r)" % badarg)
211
        else:
212
            raise TestFailed("no TypeError from dict(%r)" % badarg)
213 214

    try:
215
        dict({}, {})
216 217 218
    except TypeError:
        pass
    else:
219
        raise TestFailed("no TypeError from dict({}, {})")
220 221

    class Mapping:
222
        # Lacks a .keys() method; will be added later.
223 224 225
        dict = {1:2, 3:4, 'a':1j}

    try:
226
        dict(Mapping())
227 228 229
    except TypeError:
        pass
    else:
230
        raise TestFailed("no TypeError from dict(incomplete mapping)")
231 232

    Mapping.keys = lambda self: self.dict.keys()
233
    Mapping.__getitem__ = lambda self, i: self.dict[i]
234
    d = dict(Mapping())
235
    vereq(d, Mapping.dict)
236

237 238 239 240 241 242 243 244
    # Init from sequence of iterable objects, each producing a 2-sequence.
    class AddressBookEntry:
        def __init__(self, first, last):
            self.first = first
            self.last = last
        def __iter__(self):
            return iter([self.first, self.last])

245
    d = dict([AddressBookEntry('Tim', 'Warsaw'),
246 247 248
              AddressBookEntry('Barry', 'Peters'),
              AddressBookEntry('Tim', 'Peters'),
              AddressBookEntry('Barry', 'Warsaw')])
249 250
    vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})

251 252
    d = dict(zip(range(4), range(1, 5)))
    vereq(d, dict([(i, i+1) for i in range(4)]))
253 254

    # Bad sequence lengths.
255
    for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
256
        try:
257
            dict(bad)
258 259 260
        except ValueError:
            pass
        else:
261
            raise TestFailed("no ValueError from dict(%r)" % bad)
262

263 264 265 266
def test_dir():
    if verbose:
        print "Testing dir() ..."
    junk = 12
267
    vereq(dir(), ['junk'])
268 269 270 271 272 273
    del junk

    # Just make sure these don't blow up!
    for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
        dir(arg)

274
    # Try classic classes.
275 276 277 278 279
    class C:
        Cdata = 1
        def Cmethod(self): pass

    cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
280
    vereq(dir(C), cstuff)
281
    verify('im_self' in dir(C.Cmethod))
282 283

    c = C()  # c.__doc__ is an odd thing to see here; ditto c.__module__.
284
    vereq(dir(c), cstuff)
285 286 287

    c.cdata = 2
    c.cmethod = lambda self: 0
288
    vereq(dir(c), cstuff + ['cdata', 'cmethod'])
289
    verify('im_self' in dir(c.Cmethod))
290 291 292 293

    class A(C):
        Adata = 1
        def Amethod(self): pass
294 295

    astuff = ['Adata', 'Amethod'] + cstuff
296
    vereq(dir(A), astuff)
297
    verify('im_self' in dir(A.Amethod))
298
    a = A()
299
    vereq(dir(a), astuff)
300
    verify('im_self' in dir(a.Amethod))
301 302
    a.adata = 42
    a.amethod = lambda self: 3
303
    vereq(dir(a), astuff + ['adata', 'amethod'])
304 305 306 307 308

    # The same, but with new-style classes.  Since these have object as a
    # base class, a lot more gets sucked in.
    def interesting(strings):
        return [s for s in strings if not s.startswith('_')]
309 310 311 312

    class C(object):
        Cdata = 1
        def Cmethod(self): pass
313 314

    cstuff = ['Cdata', 'Cmethod']
315
    vereq(interesting(dir(C)), cstuff)
316 317

    c = C()
318
    vereq(interesting(dir(c)), cstuff)
319
    verify('im_self' in dir(C.Cmethod))
320 321 322

    c.cdata = 2
    c.cmethod = lambda self: 0
323
    vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
324
    verify('im_self' in dir(c.Cmethod))
325

326 327 328
    class A(C):
        Adata = 1
        def Amethod(self): pass
329 330

    astuff = ['Adata', 'Amethod'] + cstuff
331
    vereq(interesting(dir(A)), astuff)
332
    verify('im_self' in dir(A.Amethod))
333
    a = A()
334
    vereq(interesting(dir(a)), astuff)
335 336
    a.adata = 42
    a.amethod = lambda self: 3
337
    vereq(interesting(dir(a)), astuff + ['adata', 'amethod'])
338
    verify('im_self' in dir(a.Amethod))
339

340 341 342 343
    # Try a module subclass.
    import sys
    class M(type(sys)):
        pass
344
    minstance = M("m")
345 346
    minstance.b = 2
    minstance.a = 1
347 348
    names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
    vereq(names, ['a', 'b'])
349 350 351 352 353 354

    class M2(M):
        def getdict(self):
            return "Not a dict!"
        __dict__ = property(getdict)

355
    m2instance = M2("m2")
356 357
    m2instance.b = 2
    m2instance.a = 1
358
    vereq(m2instance.__dict__, "Not a dict!")
359 360 361 362 363
    try:
        dir(m2instance)
    except TypeError:
        pass

364 365 366 367
    # Two essentially featureless objects, just inheriting stuff from
    # object.
    vereq(dir(None), dir(Ellipsis))

368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
    # Nasty test case for proxied objects
    class Wrapper(object):
        def __init__(self, obj):
            self.__obj = obj
        def __repr__(self):
            return "Wrapper(%s)" % repr(self.__obj)
        def __getitem__(self, key):
            return Wrapper(self.__obj[key])
        def __len__(self):
            return len(self.__obj)
        def __getattr__(self, name):
            return Wrapper(getattr(self.__obj, name))

    class C(object):
        def __getclass(self):
            return Wrapper(type(self))
        __class__ = property(__getclass)

    dir(C()) # This used to segfault

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 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
binops = {
    'add': '+',
    'sub': '-',
    'mul': '*',
    'div': '/',
    'mod': '%',
    'divmod': 'divmod',
    'pow': '**',
    'lshift': '<<',
    'rshift': '>>',
    'and': '&',
    'xor': '^',
    'or': '|',
    'cmp': 'cmp',
    'lt': '<',
    'le': '<=',
    'eq': '==',
    'ne': '!=',
    'gt': '>',
    'ge': '>=',
    }

for name, expr in binops.items():
    if expr.islower():
        expr = expr + "(a, b)"
    else:
        expr = 'a %s b' % expr
    binops[name] = expr

unops = {
    'pos': '+',
    'neg': '-',
    'abs': 'abs',
    'invert': '~',
    'int': 'int',
    'long': 'long',
    'float': 'float',
    'oct': 'oct',
    'hex': 'hex',
    }

for name, expr in unops.items():
    if expr.islower():
        expr = expr + "(a)"
    else:
        expr = '%s a' % expr
    unops[name] = expr

def numops(a, b, skip=[]):
    dict = {'a': a, 'b': b}
    for name, expr in binops.items():
        if name not in skip:
            name = "__%s__" % name
            if hasattr(a, name):
                res = eval(expr, dict)
                testbinop(a, b, res, expr, name)
    for name, expr in unops.items():
445 446 447 448 449
        if name not in skip:
            name = "__%s__" % name
            if hasattr(a, name):
                res = eval(expr, dict)
                testunop(a, res, expr, name)
450 451 452 453

def ints():
    if verbose: print "Testing int operations..."
    numops(100, 3)
Guido van Rossum's avatar
Guido van Rossum committed
454 455 456
    # The following crashes in Python 2.2
    vereq((1).__nonzero__(), 1)
    vereq((0).__nonzero__(), 0)
457 458 459 460
    # This returns 'NotImplemented' in Python 2.2
    class C(int):
        def __add__(self, other):
            return NotImplemented
461
    vereq(C(5L), 5)
462 463 464 465 466
    try:
        C() + ""
    except TypeError:
        pass
    else:
Neal Norwitz's avatar
Neal Norwitz committed
467
        raise TestFailed, "NotImplemented should have caused TypeError"
468 469 470 471 472 473 474
    import sys
    try:
        C(sys.maxint+1)
    except OverflowError:
        pass
    else:
        raise TestFailed, "should have raised OverflowError"
475 476 477 478 479 480 481 482 483 484 485

def longs():
    if verbose: print "Testing long operations..."
    numops(100L, 3L)

def floats():
    if verbose: print "Testing float operations..."
    numops(100.0, 3.0)

def complexes():
    if verbose: print "Testing complex operations..."
486
    numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
487 488
    class Number(complex):
        __slots__ = ['prec']
489 490 491 492
        def __new__(cls, *args, **kwds):
            result = complex.__new__(cls, *args)
            result.prec = kwds.get('prec', 12)
            return result
493 494 495 496 497 498 499 500
        def __repr__(self):
            prec = self.prec
            if self.imag == 0.0:
                return "%.*g" % (prec, self.real)
            if self.real == 0.0:
                return "%.*gj" % (prec, self.imag)
            return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
        __str__ = __repr__
501

502
    a = Number(3.14, prec=6)
503
    vereq(repr(a), "3.14")
504
    vereq(a.prec, 6)
505

506
    a = Number(a, prec=2)
507
    vereq(repr(a), "3.1")
508
    vereq(a.prec, 2)
509 510

    a = Number(234.5)
511
    vereq(repr(a), "234.5")
512
    vereq(a.prec, 12)
513

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
def spamlists():
    if verbose: print "Testing spamlist operations..."
    import copy, xxsubtype as spam
    def spamlist(l, memo=None):
        import xxsubtype as spam
        return spam.spamlist(l)
    # This is an ugly hack:
    copy._deepcopy_dispatch[spam.spamlist] = spamlist

    testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
    testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
    testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
    testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
    testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
               "a[b:c]", "__getslice__")
    testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
              "a+=b", "__iadd__")
    testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
    testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
    testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
    testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
    testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
    testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
               spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
    # Test subclassing
    class C(spam.spamlist):
        def foo(self): return 1
    a = C()
542 543
    vereq(a, [])
    vereq(a.foo(), 1)
544
    a.append(100)
545 546
    vereq(a, [100])
    vereq(a.getstate(), 0)
547
    a.setstate(42)
548
    vereq(a.getstate(), 42)
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569

def spamdicts():
    if verbose: print "Testing spamdict operations..."
    import copy, xxsubtype as spam
    def spamdict(d, memo=None):
        import xxsubtype as spam
        sd = spam.spamdict()
        for k, v in d.items(): sd[k] = v
        return sd
    # This is an ugly hack:
    copy._deepcopy_dispatch[spam.spamdict] = spamdict

    testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
    testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
    testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
    testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
    d = spamdict({1:2,3:4})
    l1 = []
    for i in d.keys(): l1.append(i)
    l = []
    for i in iter(d): l.append(i)
570
    vereq(l, l1)
571 572
    l = []
    for i in d.__iter__(): l.append(i)
573
    vereq(l, l1)
574 575
    l = []
    for i in type(spamdict({})).__iter__(d): l.append(i)
576
    vereq(l, l1)
577 578 579 580 581 582 583 584 585 586
    straightd = {1:2, 3:4}
    spamd = spamdict(straightd)
    testunop(spamd, 2, "len(a)", "__len__")
    testunop(spamd, repr(straightd), "repr(a)", "__repr__")
    testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
               "a[b]=c", "__setitem__")
    # Test subclassing
    class C(spam.spamdict):
        def foo(self): return 1
    a = C()
587 588
    vereq(a.items(), [])
    vereq(a.foo(), 1)
589
    a['foo'] = 'bar'
590 591
    vereq(a.items(), [('foo', 'bar')])
    vereq(a.getstate(), 0)
592
    a.setstate(100)
593
    vereq(a.getstate(), 100)
594 595 596

def pydicts():
    if verbose: print "Testing Python subclass of dict..."
597 598 599
    verify(issubclass(dict, dict))
    verify(isinstance({}, dict))
    d = dict()
600
    vereq(d, {})
601 602 603
    verify(d.__class__ is dict)
    verify(isinstance(d, dict))
    class C(dict):
604 605 606
        state = -1
        def __init__(self, *a, **kw):
            if a:
607
                vereq(len(a), 1)
608 609 610 611 612 613
                self.state = a[0]
            if kw:
                for k, v in kw.items(): self[v] = k
        def __getitem__(self, key):
            return self.get(key, 0)
        def __setitem__(self, key, value):
614
            verify(isinstance(key, type(0)))
615
            dict.__setitem__(self, key, value)
616 617 618 619
        def setstate(self, state):
            self.state = state
        def getstate(self):
            return self.state
620
    verify(issubclass(C, dict))
621
    a1 = C(12)
622
    vereq(a1.state, 12)
623
    a2 = C(foo=1, bar=2)
624
    vereq(a2[1] == 'foo' and a2[2], 'bar')
625
    a = C()
626 627
    vereq(a.state, -1)
    vereq(a.getstate(), -1)
628
    a.setstate(0)
629 630
    vereq(a.state, 0)
    vereq(a.getstate(), 0)
631
    a.setstate(10)
632 633 634
    vereq(a.state, 10)
    vereq(a.getstate(), 10)
    vereq(a[42], 0)
635
    a[42] = 24
636
    vereq(a[42], 24)
637 638 639 640 641 642 643 644
    if verbose: print "pydict stress test ..."
    N = 50
    for i in range(N):
        a[i] = C()
        for j in range(N):
            a[i][j] = i*j
    for i in range(N):
        for j in range(N):
645
            vereq(a[i][j], i*j)
646 647 648 649 650 651 652 653 654 655

def pylists():
    if verbose: print "Testing Python subclass of list..."
    class C(list):
        def __getitem__(self, i):
            return list.__getitem__(self, i) + 100
        def __getslice__(self, i, j):
            return (i, j)
    a = C()
    a.extend([0,1,2])
656 657 658 659
    vereq(a[0], 100)
    vereq(a[1], 101)
    vereq(a[2], 102)
    vereq(a[100:200], (100,200))
660 661 662 663 664 665 666 667 668 669 670 671

def metaclass():
    if verbose: print "Testing __metaclass__..."
    class C:
        __metaclass__ = type
        def __init__(self):
            self.__state = 0
        def getstate(self):
            return self.__state
        def setstate(self, state):
            self.__state = state
    a = C()
672
    vereq(a.getstate(), 0)
673
    a.setstate(10)
674
    vereq(a.getstate(), 10)
675 676 677
    class D:
        class __metaclass__(type):
            def myself(cls): return cls
678
    vereq(D.myself(), D)
679 680 681 682 683 684 685 686
    d = D()
    verify(d.__class__ is D)
    class M1(type):
        def __new__(cls, name, bases, dict):
            dict['__spam__'] = 1
            return type.__new__(cls, name, bases, dict)
    class C:
        __metaclass__ = M1
687
    vereq(C.__spam__, 1)
688
    c = C()
689
    vereq(c.__spam__, 1)
690

691 692 693
    class _instance(object):
        pass
    class M2(object):
Guido van Rossum's avatar
Guido van Rossum committed
694
        @staticmethod
695 696 697 698 699 700 701 702
        def __new__(cls, name, bases, dict):
            self = object.__new__(cls)
            self.name = name
            self.bases = bases
            self.dict = dict
            return self
        def __call__(self):
            it = _instance()
703 704 705 706 707
            # Early binding of methods
            for key in self.dict:
                if key.startswith("__"):
                    continue
                setattr(it, key, self.dict[key].__get__(it, self))
708 709 710 711 712
            return it
    class C:
        __metaclass__ = M2
        def spam(self):
            return 42
713 714
    vereq(C.name, 'C')
    vereq(C.bases, ())
715 716
    verify('spam' in C.dict)
    c = C()
717
    vereq(c.spam(), 42)
718

719 720 721 722 723 724 725 726
    # More metaclass examples

    class autosuper(type):
        # Automatically add __super to the class
        # This trick only works for dynamic classes
        def __new__(metaclass, name, bases, dict):
            cls = super(autosuper, metaclass).__new__(metaclass,
                                                      name, bases, dict)
727
            # Name mangling for __super removes leading underscores
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
            while name[:1] == "_":
                name = name[1:]
            if name:
                name = "_%s__super" % name
            else:
                name = "__super"
            setattr(cls, name, super(cls))
            return cls
    class A:
        __metaclass__ = autosuper
        def meth(self):
            return "A"
    class B(A):
        def meth(self):
            return "B" + self.__super.meth()
    class C(A):
        def meth(self):
            return "C" + self.__super.meth()
    class D(C, B):
        def meth(self):
            return "D" + self.__super.meth()
749
    vereq(D().meth(), "DCBA")
750 751 752
    class E(B, C):
        def meth(self):
            return "E" + self.__super.meth()
753
    vereq(E().meth(), "EBCA")
754

755 756
    class autoproperty(type):
        # Automatically create property attributes when methods
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
        # named _get_x and/or _set_x are found
        def __new__(metaclass, name, bases, dict):
            hits = {}
            for key, val in dict.iteritems():
                if key.startswith("_get_"):
                    key = key[5:]
                    get, set = hits.get(key, (None, None))
                    get = val
                    hits[key] = get, set
                elif key.startswith("_set_"):
                    key = key[5:]
                    get, set = hits.get(key, (None, None))
                    set = val
                    hits[key] = get, set
            for key, (get, set) in hits.iteritems():
772 773
                dict[key] = property(get, set)
            return super(autoproperty, metaclass).__new__(metaclass,
774 775
                                                        name, bases, dict)
    class A:
776
        __metaclass__ = autoproperty
777 778 779 780 781 782 783
        def _get_x(self):
            return -self.__x
        def _set_x(self, x):
            self.__x = -x
    a = A()
    verify(not hasattr(a, "x"))
    a.x = 12
784 785
    vereq(a.x, 12)
    vereq(a._A__x, -12)
786

787
    class multimetaclass(autoproperty, autosuper):
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
        # Merge of multiple cooperating metaclasses
        pass
    class A:
        __metaclass__ = multimetaclass
        def _get_x(self):
            return "A"
    class B(A):
        def _get_x(self):
            return "B" + self.__super._get_x()
    class C(A):
        def _get_x(self):
            return "C" + self.__super._get_x()
    class D(C, B):
        def _get_x(self):
            return "D" + self.__super._get_x()
803
    vereq(D().x, "DCBA")
804

805 806 807 808 809 810 811 812 813 814 815 816
    # Make sure type(x) doesn't call x.__class__.__init__
    class T(type):
        counter = 0
        def __init__(self, *args):
            T.counter += 1
    class C:
        __metaclass__ = T
    vereq(T.counter, 1)
    a = C()
    vereq(type(a), C)
    vereq(T.counter, 1)

817 818 819 820
    class C(object): pass
    c = C()
    try: c()
    except TypeError: pass
821
    else: raise TestFailed, "calling object w/o call method should raise TypeError"
822

823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
    # Testing code to find most derived baseclass
    class A(type):
        def __new__(*args, **kwargs):
            return type.__new__(*args, **kwargs)

    class B(object):
        pass

    class C(object):
        __metaclass__ = A

    # The most derived metaclass of D is A rather than type.
    class D(B, C):
        pass


839 840 841
def pymods():
    if verbose: print "Testing Python subclass of module..."
    log = []
842 843
    import sys
    MT = type(sys)
844
    class MM(MT):
845 846
        def __init__(self, name):
            MT.__init__(self, name)
847
        def __getattribute__(self, name):
848
            log.append(("getattr", name))
849
            return MT.__getattribute__(self, name)
850 851 852 853 854 855
        def __setattr__(self, name, value):
            log.append(("setattr", name, value))
            MT.__setattr__(self, name, value)
        def __delattr__(self, name):
            log.append(("delattr", name))
            MT.__delattr__(self, name)
856
    a = MM("a")
857 858 859
    a.foo = 12
    x = a.foo
    del a.foo
860 861 862
    vereq(log, [("setattr", "foo", 12),
                ("getattr", "foo"),
                ("delattr", "foo")])
863 864 865 866 867 868 869 870 871 872 873

def multi():
    if verbose: print "Testing multiple inheritance..."
    class C(object):
        def __init__(self):
            self.__state = 0
        def getstate(self):
            return self.__state
        def setstate(self, state):
            self.__state = state
    a = C()
874
    vereq(a.getstate(), 0)
875
    a.setstate(10)
876
    vereq(a.getstate(), 10)
877
    class D(dict, C):
878 879 880 881
        def __init__(self):
            type({}).__init__(self)
            C.__init__(self)
    d = D()
882
    vereq(d.keys(), [])
883
    d["hello"] = "world"
884 885 886
    vereq(d.items(), [("hello", "world")])
    vereq(d["hello"], "world")
    vereq(d.getstate(), 0)
887
    d.setstate(10)
888
    vereq(d.getstate(), 10)
889
    vereq(D.__mro__, (D, dict, C, object))
890

891 892 893 894 895 896 897 898 899
    # SF bug #442833
    class Node(object):
        def __int__(self):
            return int(self.foo())
        def foo(self):
            return "23"
    class Frag(Node, list):
        def foo(self):
            return "42"
900 901 902 903
    vereq(Node().__int__(), 23)
    vereq(int(Node()), 23)
    vereq(Frag().__int__(), 42)
    vereq(int(Frag()), 42)
904

905
    # MI mixing classic and new-style classes.
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933

    class A:
        x = 1

    class B(A):
        pass

    class C(A):
        x = 2

    class D(B, C):
        pass
    vereq(D.x, 1)

    # Classic MRO is preserved for a classic base class.
    class E(D, object):
        pass
    vereq(E.__mro__, (E, D, B, A, C, object))
    vereq(E.x, 1)

    # But with a mix of classic bases, their MROs are combined using
    # new-style MRO.
    class F(B, C, object):
        pass
    vereq(F.__mro__, (F, B, C, A, object))
    vereq(F.x, 2)

    # Try something else.
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
    class C:
        def cmethod(self):
            return "C a"
        def all_method(self):
            return "C b"

    class M1(C, object):
        def m1method(self):
            return "M1 a"
        def all_method(self):
            return "M1 b"

    vereq(M1.__mro__, (M1, C, object))
    m = M1()
    vereq(m.cmethod(), "C a")
    vereq(m.m1method(), "M1 a")
    vereq(m.all_method(), "M1 b")

    class D(C):
        def dmethod(self):
            return "D a"
        def all_method(self):
            return "D b"

958
    class M2(D, object):
959 960 961 962 963
        def m2method(self):
            return "M2 a"
        def all_method(self):
            return "M2 b"

964
    vereq(M2.__mro__, (M2, D, C, object))
965 966 967 968 969 970
    m = M2()
    vereq(m.cmethod(), "C a")
    vereq(m.dmethod(), "D a")
    vereq(m.m2method(), "M2 a")
    vereq(m.all_method(), "M2 b")

971
    class M3(M1, M2, object):
972 973 974 975
        def m3method(self):
            return "M3 a"
        def all_method(self):
            return "M3 b"
976
    vereq(M3.__mro__, (M3, M1, M2, D, C, object))
977 978 979 980 981 982 983
    m = M3()
    vereq(m.cmethod(), "C a")
    vereq(m.dmethod(), "D a")
    vereq(m.m1method(), "M1 a")
    vereq(m.m2method(), "M2 a")
    vereq(m.m3method(), "M3 a")
    vereq(m.all_method(), "M3 b")
984

Guido van Rossum's avatar
Guido van Rossum committed
985 986 987 988 989 990 991 992 993 994
    class Classic:
        pass
    try:
        class New(Classic):
            __metaclass__ = type
    except TypeError:
        pass
    else:
        raise TestFailed, "new class with only classic bases - shouldn't be"

995 996 997 998
def diamond():
    if verbose: print "Testing multiple inheritance special cases..."
    class A(object):
        def spam(self): return "A"
999
    vereq(A().spam(), "A")
1000 1001 1002
    class B(A):
        def boo(self): return "B"
        def spam(self): return "B"
1003 1004
    vereq(B().spam(), "B")
    vereq(B().boo(), "B")
1005 1006
    class C(A):
        def boo(self): return "C"
1007 1008
    vereq(C().spam(), "A")
    vereq(C().boo(), "C")
1009
    class D(B, C): pass
1010 1011 1012
    vereq(D().spam(), "B")
    vereq(D().boo(), "B")
    vereq(D.__mro__, (D, B, C, A, object))
1013
    class E(C, B): pass
1014 1015 1016
    vereq(E().spam(), "B")
    vereq(E().boo(), "C")
    vereq(E.__mro__, (E, C, B, A, object))
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
    # MRO order disagreement
    try:
        class F(D, E): pass
    except TypeError:
        pass
    else:
        raise TestFailed, "expected MRO order disagreement (F)"
    try:
        class G(E, D): pass
    except TypeError:
        pass
    else:
        raise TestFailed, "expected MRO order disagreement (G)"


# see thread python-dev/2002-October/029035.html
def ex5():
    if verbose: print "Testing ex5 from C3 switch discussion..."
    class A(object): pass
    class B(object): pass
    class C(object): pass
    class X(A): pass
    class Y(A): pass
    class Z(X,B,Y,C): pass
    vereq(Z.__mro__, (Z, X, B, Y, A, C, object))

# see "A Monotonic Superclass Linearization for Dylan",
# by Kim Barrett et al. (OOPSLA 1996)
def monotonicity():
    if verbose: print "Testing MRO monotonicity..."
    class Boat(object): pass
    class DayBoat(Boat): pass
    class WheelBoat(Boat): pass
    class EngineLess(DayBoat): pass
    class SmallMultihull(DayBoat): pass
    class PedalWheelBoat(EngineLess,WheelBoat): pass
    class SmallCatamaran(SmallMultihull): pass
    class Pedalo(PedalWheelBoat,SmallCatamaran): pass

    vereq(PedalWheelBoat.__mro__,
          (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat,
           object))
    vereq(SmallCatamaran.__mro__,
          (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))

    vereq(Pedalo.__mro__,
          (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
           SmallMultihull, DayBoat, WheelBoat, Boat, object))

# see "A Monotonic Superclass Linearization for Dylan",
# by Kim Barrett et al. (OOPSLA 1996)
def consistency_with_epg():
    if verbose: print "Testing consistentcy with EPG..."
    class Pane(object): pass
    class ScrollingMixin(object): pass
    class EditingMixin(object): pass
    class ScrollablePane(Pane,ScrollingMixin): pass
    class EditablePane(Pane,EditingMixin): pass
    class EditableScrollablePane(ScrollablePane,EditablePane): pass

    vereq(EditableScrollablePane.__mro__,
          (EditableScrollablePane, ScrollablePane, EditablePane,
           Pane, ScrollingMixin, EditingMixin, object))
1080

1081 1082
mro_err_msg = """Cannot create a consistent method resolution
order (MRO) for bases """
1083

1084 1085 1086 1087 1088 1089
def mro_disagreement():
    if verbose: print "Testing error messages for MRO disagreement..."
    def raises(exc, expected, callable, *args):
        try:
            callable(*args)
        except exc, msg:
1090
            if not str(msg).startswith(expected):
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
                raise TestFailed, "Message %r, expected %r" % (str(msg),
                                                               expected)
        else:
            raise TestFailed, "Expected %s" % exc
    class A(object): pass
    class B(A): pass
    class C(object): pass
    # Test some very simple errors
    raises(TypeError, "duplicate base class A",
           type, "X", (A, A), {})
1101
    raises(TypeError, mro_err_msg,
1102
           type, "X", (A, B), {})
1103
    raises(TypeError, mro_err_msg,
1104 1105 1106 1107 1108 1109 1110
           type, "X", (A, C, B), {})
    # Test a slightly more complex error
    class GridLayout(object): pass
    class HorizontalGrid(GridLayout): pass
    class VerticalGrid(GridLayout): pass
    class HVGrid(HorizontalGrid, VerticalGrid): pass
    class VHGrid(VerticalGrid, HorizontalGrid): pass
1111
    raises(TypeError, mro_err_msg,
1112 1113
           type, "ConfusedGrid", (HVGrid, VHGrid), {})

1114 1115 1116
def objects():
    if verbose: print "Testing object class..."
    a = object()
1117 1118
    vereq(a.__class__, object)
    vereq(type(a), object)
1119 1120 1121 1122 1123
    b = object()
    verify(a is not b)
    verify(not hasattr(a, "foo"))
    try:
        a.foo = 12
1124
    except (AttributeError, TypeError):
1125 1126 1127 1128 1129 1130 1131 1132
        pass
    else:
        verify(0, "object() should not allow setting a foo attribute")
    verify(not hasattr(object(), "__dict__"))

    class Cdict(object):
        pass
    x = Cdict()
1133
    vereq(x.__dict__, {})
1134
    x.foo = 1
1135 1136
    vereq(x.foo, 1)
    vereq(x.__dict__, {'foo': 1})
1137

1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
def slots():
    if verbose: print "Testing __slots__..."
    class C0(object):
        __slots__ = []
    x = C0()
    verify(not hasattr(x, "__dict__"))
    verify(not hasattr(x, "foo"))

    class C1(object):
        __slots__ = ['a']
    x = C1()
    verify(not hasattr(x, "__dict__"))
1150
    verify(not hasattr(x, "a"))
1151
    x.a = 1
1152
    vereq(x.a, 1)
1153 1154
    x.a = None
    veris(x.a, None)
1155
    del x.a
1156
    verify(not hasattr(x, "a"))
1157 1158 1159 1160 1161

    class C3(object):
        __slots__ = ['a', 'b', 'c']
    x = C3()
    verify(not hasattr(x, "__dict__"))
1162 1163 1164
    verify(not hasattr(x, 'a'))
    verify(not hasattr(x, 'b'))
    verify(not hasattr(x, 'c'))
1165 1166 1167
    x.a = 1
    x.b = 2
    x.c = 3
1168 1169 1170
    vereq(x.a, 1)
    vereq(x.b, 2)
    vereq(x.c, 3)
1171

1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
    class C4(object):
        """Validate name mangling"""
        __slots__ = ['__a']
        def __init__(self, value):
            self.__a = value
        def get(self):
            return self.__a
    x = C4(5)
    verify(not hasattr(x, '__dict__'))
    verify(not hasattr(x, '__a'))
    vereq(x.get(), 5)
    try:
        x.__a = 6
    except AttributeError:
        pass
    else:
        raise TestFailed, "Double underscored names not mangled"

1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
    # Make sure slot names are proper identifiers
    try:
        class C(object):
            __slots__ = [None]
    except TypeError:
        pass
    else:
        raise TestFailed, "[None] slots not caught"
    try:
        class C(object):
            __slots__ = ["foo bar"]
    except TypeError:
        pass
    else:
        raise TestFailed, "['foo bar'] slots not caught"
    try:
        class C(object):
            __slots__ = ["foo\0bar"]
    except TypeError:
        pass
    else:
        raise TestFailed, "['foo\\0bar'] slots not caught"
    try:
        class C(object):
            __slots__ = ["1"]
    except TypeError:
        pass
    else:
        raise TestFailed, "['1'] slots not caught"
    try:
        class C(object):
            __slots__ = [""]
    except TypeError:
        pass
    else:
        raise TestFailed, "[''] slots not caught"
    class C(object):
        __slots__ = ["a", "a_b", "_a", "A0123456789Z"]

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
    # Test unicode slot names
    try:
        unichr
    except NameError:
        pass
    else:
        # _unicode_to_string used to modify slots in certain circumstances 
        slots = (unicode("foo"), unicode("bar"))
        class C(object):
            __slots__ = slots
        x = C()
        x.foo = 5
        vereq(x.foo, 5)
        veris(type(slots[0]), unicode)
        # this used to leak references
        try:
            class C(object):
                __slots__ = [unichr(128)]
        except (TypeError, UnicodeEncodeError):
            pass
        else:
            raise TestFailed, "[unichr(128)] slots not caught" 

1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
    # Test leaks
    class Counted(object):
        counter = 0    # counts the number of instances alive
        def __init__(self):
            Counted.counter += 1
        def __del__(self):
            Counted.counter -= 1
    class C(object):
        __slots__ = ['a', 'b', 'c']
    x = C()
    x.a = Counted()
    x.b = Counted()
    x.c = Counted()
    vereq(Counted.counter, 3)
    del x
    vereq(Counted.counter, 0)
    class D(C):
        pass
    x = D()
    x.a = Counted()
    x.z = Counted()
    vereq(Counted.counter, 2)
    del x
    vereq(Counted.counter, 0)
    class E(D):
        __slots__ = ['e']
    x = E()
    x.a = Counted()
    x.z = Counted()
    x.e = Counted()
    vereq(Counted.counter, 3)
    del x
    vereq(Counted.counter, 0)

1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
    # Test cyclical leaks [SF bug 519621]
    class F(object):
        __slots__ = ['a', 'b']
    log = []
    s = F()
    s.a = [Counted(), s]
    vereq(Counted.counter, 1)
    s = None
    import gc
    gc.collect()
    vereq(Counted.counter, 0)

1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
    # Test lookup leaks [SF bug 572567]
    import sys,gc
    class G(object):
        def __cmp__(self, other):
            return 0
    g = G()
    orig_objects = len(gc.get_objects())
    for i in xrange(10):
        g==g
    new_objects = len(gc.get_objects())
    vereq(orig_objects, new_objects)
Neal Norwitz's avatar
Neal Norwitz committed
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
    class H(object):
        __slots__ = ['a', 'b']
        def __init__(self):
            self.a = 1
            self.b = 2
        def __del__(self):
            assert self.a == 1
            assert self.b == 2

    save_stderr = sys.stderr
    sys.stderr = sys.stdout
    h = H()
    try:
        del h
    finally:
        sys.stderr = save_stderr
1325

1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
def slotspecials():
    if verbose: print "Testing __dict__ and __weakref__ in __slots__..."

    class D(object):
        __slots__ = ["__dict__"]
    a = D()
    verify(hasattr(a, "__dict__"))
    verify(not hasattr(a, "__weakref__"))
    a.foo = 42
    vereq(a.__dict__, {"foo": 42})

    class W(object):
        __slots__ = ["__weakref__"]
    a = W()
    verify(hasattr(a, "__weakref__"))
    verify(not hasattr(a, "__dict__"))
    try:
        a.foo = 42
    except AttributeError:
        pass
    else:
        raise TestFailed, "shouldn't be allowed to set a.foo"

    class C1(W, D):
        __slots__ = []
    a = C1()
    verify(hasattr(a, "__dict__"))
    verify(hasattr(a, "__weakref__"))
    a.foo = 42
    vereq(a.__dict__, {"foo": 42})

    class C2(D, W):
        __slots__ = []
    a = C2()
    verify(hasattr(a, "__dict__"))
    verify(hasattr(a, "__weakref__"))
    a.foo = 42
    vereq(a.__dict__, {"foo": 42})

1365 1366 1367 1368 1369 1370 1371
# MRO order disagreement
#
#    class C3(C1, C2):
#        __slots__ = []
#
#    class C4(C2, C1):
#        __slots__ = []
1372

1373
def dynamics():
1374
    if verbose: print "Testing class attribute propagation..."
1375 1376
    class D(object):
        pass
1377
    class E(D):
1378
        pass
1379
    class F(D):
1380 1381
        pass
    D.foo = 1
1382
    vereq(D.foo, 1)
1383
    # Test that dynamic attributes are inherited
1384 1385
    vereq(E.foo, 1)
    vereq(F.foo, 1)
1386 1387
    # Test dynamic instances
    class C(object):
1388
        pass
1389
    a = C()
1390
    verify(not hasattr(a, "foobar"))
1391
    C.foobar = 2
1392
    vereq(a.foobar, 2)
1393
    C.method = lambda self: 42
1394
    vereq(a.method(), 42)
1395
    C.__repr__ = lambda self: "C()"
1396
    vereq(repr(a), "C()")
1397
    C.__int__ = lambda self: 100
1398 1399
    vereq(int(a), 100)
    vereq(a.foobar, 2)
1400 1401 1402 1403
    verify(not hasattr(a, "spam"))
    def mygetattr(self, name):
        if name == "spam":
            return "spam"
1404 1405
        raise AttributeError
    C.__getattr__ = mygetattr
1406
    vereq(a.spam, "spam")
1407
    a.new = 12
1408
    vereq(a.new, 12)
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
    def mysetattr(self, name, value):
        if name == "spam":
            raise AttributeError
        return object.__setattr__(self, name, value)
    C.__setattr__ = mysetattr
    try:
        a.spam = "not spam"
    except AttributeError:
        pass
    else:
        verify(0, "expected AttributeError")
1420
    vereq(a.spam, "spam")
1421 1422 1423 1424
    class D(C):
        pass
    d = D()
    d.foo = 1
1425
    vereq(d.foo, 1)
1426

1427 1428
    # Test handling of int*seq and seq*int
    class I(int):
1429
        pass
1430 1431 1432 1433 1434
    vereq("a"*I(2), "aa")
    vereq(I(2)*"a", "aa")
    vereq(2*I(3), 6)
    vereq(I(3)*2, 6)
    vereq(I(3)*I(2), 6)
1435 1436 1437

    # Test handling of long*seq and seq*long
    class L(long):
1438
        pass
1439 1440 1441 1442 1443
    vereq("a"*L(2L), "aa")
    vereq(L(2L)*"a", "aa")
    vereq(2*L(3), 6)
    vereq(L(3)*2, 6)
    vereq(L(3)*L(2), 6)
1444

1445 1446
    # Test comparison of classes with dynamic metaclasses
    class dynamicmetaclass(type):
1447
        pass
1448 1449 1450 1451
    class someclass:
        __metaclass__ = dynamicmetaclass
    verify(someclass != object)

1452
def errors():
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
    """Test that type can't be placed after an instance of type in bases.

    >>> class C(list, dict):
    ...     pass
    Traceback (most recent call last):
    TypeError: Error when calling the metaclass bases
        multiple bases have instance lay-out conflict

    >>> class C(object, None):
    ...     pass
    Traceback (most recent call last):
    TypeError: Error when calling the metaclass bases
        bases must be types

    >>> class C(type(len)):
    ...     pass
    Traceback (most recent call last):
    TypeError: Error when calling the metaclass bases
        type 'builtin_function_or_method' is not an acceptable base type

    >>> class Classic:
    ...     def __init__(*args): pass
    >>> class C(object):
    ...     __metaclass__ = Classic

    >>> class C(object):
    ...     __slots__ = 1
    Traceback (most recent call last):
    TypeError: Error when calling the metaclass bases
        'int' object is not iterable

    >>> class C(object):
    ...     __slots__ = [1]
    Traceback (most recent call last):
    TypeError: Error when calling the metaclass bases
        __slots__ items must be strings, not 'int'

    >>> class A(object):
    ...     pass
Tim Peters's avatar
Tim Peters committed
1492

1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
    >>> class B(A, type):
    ...     pass
    Traceback (most recent call last):
    TypeError: Error when calling the metaclass bases
        metaclass conflict: type must occur in bases before other non-classic base classes

    Create two different metaclasses in order to setup an error where
    there is no inheritance relationship between the metaclass of a class
    and the metaclass of its bases.

    >>> class M1(type):
    ...     pass
    >>> class M2(type):
    ...     pass
    >>> class A1(object):
    ...     __metaclass__ = M1
    >>> class A2(object):
    ...     __metaclass__ = M2
    >>> class B(A1, A2):
    ...     pass
    Traceback (most recent call last):
    TypeError: Error when calling the metaclass bases
        metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
    >>> class B(A1):
    ...     pass

    Also check that assignment to bases is safe.
Tim Peters's avatar
Tim Peters committed
1520

1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
    >>> B.__bases__ = A1, A2
    Traceback (most recent call last):
    TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
    >>> B.__bases__ = A2,
    Traceback (most recent call last):
    TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

    >>> class M3(M1):
    ...     pass
    >>> class C(object):
    ...     __metaclass__ = M3
    >>> B.__bases__ = C,
    Traceback (most recent call last):
    TypeError: assignment to __bases__ may not change metatype
    """
1536 1537 1538 1539 1540 1541 1542

def classmethods():
    if verbose: print "Testing class methods..."
    class C(object):
        def foo(*a): return a
        goo = classmethod(foo)
    c = C()
1543 1544 1545
    vereq(C.goo(1), (C, 1))
    vereq(c.goo(1), (C, 1))
    vereq(c.foo(1), (c, 1))
1546 1547 1548
    class D(C):
        pass
    d = D()
1549 1550 1551 1552
    vereq(D.goo(1), (D, 1))
    vereq(d.goo(1), (D, 1))
    vereq(d.foo(1), (d, 1))
    vereq(D.foo(d, 1), (d, 1))
1553 1554 1555 1556 1557
    # Test for a specific crash (SF bug 528132)
    def f(cls, arg): return (cls, arg)
    ff = classmethod(f)
    vereq(ff.__get__(0, int)(42), (int, 42))
    vereq(ff.__get__(0)(42), (int, 42))
1558

1559 1560 1561 1562 1563 1564 1565 1566
    # Test super() with classmethods (SF bug 535444)
    veris(C.goo.im_self, C)
    veris(D.goo.im_self, D)
    veris(super(D,D).goo.im_self, D)
    veris(super(D,d).goo.im_self, D)
    vereq(super(D,D).goo(), (D,))
    vereq(super(D,d).goo(), (D,))

1567 1568 1569 1570 1571 1572 1573 1574
    # Verify that argument is checked for callability (SF bug 753451)
    try:
        classmethod(1).__get__(1)
    except TypeError:
        pass
    else:
        raise TestFailed, "classmethod should check for callability"

1575 1576 1577 1578 1579 1580 1581 1582
    # Verify that classmethod() doesn't allow keyword args
    try:
        classmethod(f, kw=1)
    except TypeError:
        pass
    else:
        raise TestFailed, "classmethod shouldn't accept keyword args"

1583 1584 1585 1586 1587 1588
def classmethods_in_c():
    if verbose: print "Testing C-based class methods..."
    import xxsubtype as spam
    a = (1, 2, 3)
    d = {'abc': 123}
    x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1589 1590
    veris(x, spam.spamlist)
    vereq(a, a1)
1591 1592
    vereq(d, d1)
    x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1593 1594
    veris(x, spam.spamlist)
    vereq(a, a1)
1595 1596
    vereq(d, d1)

1597 1598 1599 1600 1601 1602
def staticmethods():
    if verbose: print "Testing static methods..."
    class C(object):
        def foo(*a): return a
        goo = staticmethod(foo)
    c = C()
1603 1604 1605
    vereq(C.goo(1), (1,))
    vereq(c.goo(1), (1,))
    vereq(c.foo(1), (c, 1,))
1606 1607 1608
    class D(C):
        pass
    d = D()
1609 1610 1611 1612
    vereq(D.goo(1), (1,))
    vereq(d.goo(1), (1,))
    vereq(d.foo(1), (d, 1))
    vereq(D.foo(d, 1), (d, 1))
1613

1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
def staticmethods_in_c():
    if verbose: print "Testing C-based static methods..."
    import xxsubtype as spam
    a = (1, 2, 3)
    d = {"abc": 123}
    x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
    veris(x, None)
    vereq(a, a1)
    vereq(d, d1)
    x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
    veris(x, None)
    vereq(a, a1)
    vereq(d, d1)

1628 1629 1630 1631 1632 1633
def classic():
    if verbose: print "Testing classic classes..."
    class C:
        def foo(*a): return a
        goo = classmethod(foo)
    c = C()
1634 1635 1636
    vereq(C.goo(1), (C, 1))
    vereq(c.goo(1), (C, 1))
    vereq(c.foo(1), (c, 1))
1637 1638 1639
    class D(C):
        pass
    d = D()
1640 1641 1642 1643
    vereq(D.goo(1), (D, 1))
    vereq(d.goo(1), (D, 1))
    vereq(d.foo(1), (d, 1))
    vereq(D.foo(d, 1), (d, 1))
1644 1645
    class E: # *not* subclassing from C
        foo = C.foo
1646
    vereq(E().foo, C.foo) # i.e., unbound
1647
    verify(repr(C.foo.__get__(C())).startswith("<bound method "))
1648 1649 1650 1651 1652

def compattr():
    if verbose: print "Testing computed attributes..."
    class C(object):
        class computed_attribute(object):
1653
            def __init__(self, get, set=None, delete=None):
1654 1655
                self.__get = get
                self.__set = set
1656
                self.__delete = delete
1657 1658 1659 1660
            def __get__(self, obj, type=None):
                return self.__get(obj)
            def __set__(self, obj, value):
                return self.__set(obj, value)
1661 1662
            def __delete__(self, obj):
                return self.__delete(obj)
1663 1664 1665 1666 1667 1668 1669 1670
        def __init__(self):
            self.__x = 0
        def __get_x(self):
            x = self.__x
            self.__x = x+1
            return x
        def __set_x(self, x):
            self.__x = x
1671 1672 1673
        def __delete_x(self):
            del self.__x
        x = computed_attribute(__get_x, __set_x, __delete_x)
1674
    a = C()
1675 1676
    vereq(a.x, 0)
    vereq(a.x, 1)
1677
    a.x = 10
1678 1679
    vereq(a.x, 10)
    vereq(a.x, 11)
1680 1681
    del a.x
    vereq(hasattr(a, 'x'), 0)
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692

def newslot():
    if verbose: print "Testing __new__ slot override..."
    class C(list):
        def __new__(cls):
            self = list.__new__(cls)
            self.foo = 1
            return self
        def __init__(self):
            self.foo = self.foo + 2
    a = C()
1693
    vereq(a.foo, 3)
1694 1695 1696 1697
    verify(a.__class__ is C)
    class D(C):
        pass
    b = D()
1698
    vereq(b.foo, 3)
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
    verify(b.__class__ is D)

def altmro():
    if verbose: print "Testing mro() and overriding it..."
    class A(object):
        def f(self): return "A"
    class B(A):
        pass
    class C(A):
        def f(self): return "C"
    class D(B, C):
        pass
1711 1712 1713
    vereq(D.mro(), [D, B, C, A, object])
    vereq(D.__mro__, (D, B, C, A, object))
    vereq(D().f(), "C")
1714

1715 1716 1717 1718 1719
    class PerverseMetaType(type):
        def mro(cls):
            L = type.mro(cls)
            L.reverse()
            return L
1720
    class X(D,B,C,A):
1721
        __metaclass__ = PerverseMetaType
1722 1723
    vereq(X.__mro__, (object, A, C, B, D, X))
    vereq(X().f(), "A")
1724

1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
    try:
        class X(object):
            class __metaclass__(type):
                def mro(self):
                    return [self, dict, object]
    except TypeError:
        pass
    else:
        raise TestFailed, "devious mro() return not caught"

    try:
        class X(object):
            class __metaclass__(type):
                def mro(self):
                    return [1]
    except TypeError:
        pass
    else:
        raise TestFailed, "non-class mro() return not caught"

    try:
        class X(object):
            class __metaclass__(type):
                def mro(self):
                    return 1
    except TypeError:
        pass
    else:
        raise TestFailed, "non-sequence mro() return not caught"
Tim Peters's avatar
Tim Peters committed
1754

1755

1756
def overloading():
1757
    if verbose: print "Testing operator overloading..."
1758 1759 1760 1761 1762 1763

    class B(object):
        "Intermediate class because object doesn't have a __setattr__"

    class C(B):

1764
        def __getattr__(self, name):
1765 1766 1767
            if name == "foo":
                return ("getattr", name)
            else:
1768
                raise AttributeError
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
        def __setattr__(self, name, value):
            if name == "foo":
                self.setattr = (name, value)
            else:
                return B.__setattr__(self, name, value)
        def __delattr__(self, name):
            if name == "foo":
                self.delattr = name
            else:
                return B.__delattr__(self, name)

        def __getitem__(self, key):
            return ("getitem", key)
        def __setitem__(self, key, value):
            self.setitem = (key, value)
        def __delitem__(self, key):
            self.delitem = key

        def __getslice__(self, i, j):
            return ("getslice", i, j)
        def __setslice__(self, i, j, value):
            self.setslice = (i, j, value)
        def __delslice__(self, i, j):
            self.delslice = (i, j)

    a = C()
1795
    vereq(a.foo, ("getattr", "foo"))
1796
    a.foo = 12
1797
    vereq(a.setattr, ("foo", 12))
1798
    del a.foo
1799
    vereq(a.delattr, "foo")
1800

1801
    vereq(a[12], ("getitem", 12))
1802
    a[12] = 21
1803
    vereq(a.setitem, (12, 21))
1804
    del a[12]
1805
    vereq(a.delitem, 12)
1806

1807
    vereq(a[0:10], ("getslice", 0, 10))
1808
    a[0:10] = "foo"
1809
    vereq(a.setslice, (0, 10, "foo"))
1810
    del a[0:10]
1811
    vereq(a.delslice, (0, 10))
1812

1813
def methods():
1814
    if verbose: print "Testing methods..."
1815 1816 1817 1818 1819 1820
    class C(object):
        def __init__(self, x):
            self.x = x
        def foo(self):
            return self.x
    c1 = C(1)
1821
    vereq(c1.foo(), 1)
1822 1823 1824 1825
    class D(C):
        boo = C.foo
        goo = c1.foo
    d2 = D(2)
1826 1827 1828
    vereq(d2.foo(), 2)
    vereq(d2.boo(), 2)
    vereq(d2.goo(), 1)
1829 1830
    class E(object):
        foo = C.foo
1831
    vereq(E().foo, C.foo) # i.e., unbound
1832
    verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
1833

1834 1835
def specials():
    # Test operators like __hash__ for which a built-in default exists
1836
    if verbose: print "Testing special operators..."
1837 1838 1839 1840 1841 1842 1843 1844
    # Test the default behavior for static classes
    class C(object):
        def __getitem__(self, i):
            if 0 <= i < 10: return i
            raise IndexError
    c1 = C()
    c2 = C()
    verify(not not c1)
1845 1846 1847
    verify(id(c1) != id(c2))
    hash(c1)
    hash(c2)
1848 1849
    vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
    vereq(c1, c1)
1850 1851 1852
    verify(c1 != c2)
    verify(not c1 != c1)
    verify(not c1 == c2)
1853 1854
    # Note that the module name appears in str/repr, and that varies
    # depending on whether this test is run standalone or from a framework.
1855
    verify(str(c1).find('C object at ') >= 0)
1856
    vereq(str(c1), repr(c1))
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
    verify(-1 not in c1)
    for i in range(10):
        verify(i in c1)
    verify(10 not in c1)
    # Test the default behavior for dynamic classes
    class D(object):
        def __getitem__(self, i):
            if 0 <= i < 10: return i
            raise IndexError
    d1 = D()
    d2 = D()
    verify(not not d1)
1869 1870 1871
    verify(id(d1) != id(d2))
    hash(d1)
    hash(d2)
1872 1873
    vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
    vereq(d1, d1)
1874 1875 1876
    verify(d1 != d2)
    verify(not d1 != d1)
    verify(not d1 == d2)
1877 1878
    # Note that the module name appears in str/repr, and that varies
    # depending on whether this test is run standalone or from a framework.
1879
    verify(str(d1).find('D object at ') >= 0)
1880
    vereq(str(d1), repr(d1))
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
    verify(-1 not in d1)
    for i in range(10):
        verify(i in d1)
    verify(10 not in d1)
    # Test overridden behavior for static classes
    class Proxy(object):
        def __init__(self, x):
            self.x = x
        def __nonzero__(self):
            return not not self.x
        def __hash__(self):
            return hash(self.x)
        def __eq__(self, other):
            return self.x == other
        def __ne__(self, other):
            return self.x != other
        def __cmp__(self, other):
            return cmp(self.x, other.x)
        def __str__(self):
            return "Proxy:%s" % self.x
        def __repr__(self):
            return "Proxy(%r)" % self.x
        def __contains__(self, value):
            return value in self.x
    p0 = Proxy(0)
    p1 = Proxy(1)
    p_1 = Proxy(-1)
    verify(not p0)
    verify(not not p1)
1910 1911
    vereq(hash(p0), hash(0))
    vereq(p0, p0)
1912 1913
    verify(p0 != p1)
    verify(not p0 != p0)
1914 1915 1916 1917 1918 1919
    vereq(not p0, p1)
    vereq(cmp(p0, p1), -1)
    vereq(cmp(p0, p0), 0)
    vereq(cmp(p0, p_1), 1)
    vereq(str(p0), "Proxy:0")
    vereq(repr(p0), "Proxy(0)")
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949
    p10 = Proxy(range(10))
    verify(-1 not in p10)
    for i in range(10):
        verify(i in p10)
    verify(10 not in p10)
    # Test overridden behavior for dynamic classes
    class DProxy(object):
        def __init__(self, x):
            self.x = x
        def __nonzero__(self):
            return not not self.x
        def __hash__(self):
            return hash(self.x)
        def __eq__(self, other):
            return self.x == other
        def __ne__(self, other):
            return self.x != other
        def __cmp__(self, other):
            return cmp(self.x, other.x)
        def __str__(self):
            return "DProxy:%s" % self.x
        def __repr__(self):
            return "DProxy(%r)" % self.x
        def __contains__(self, value):
            return value in self.x
    p0 = DProxy(0)
    p1 = DProxy(1)
    p_1 = DProxy(-1)
    verify(not p0)
    verify(not not p1)
1950 1951
    vereq(hash(p0), hash(0))
    vereq(p0, p0)
1952 1953
    verify(p0 != p1)
    verify(not p0 != p0)
1954 1955 1956 1957 1958 1959
    vereq(not p0, p1)
    vereq(cmp(p0, p1), -1)
    vereq(cmp(p0, p0), 0)
    vereq(cmp(p0, p_1), 1)
    vereq(str(p0), "DProxy:0")
    vereq(repr(p0), "DProxy(0)")
1960 1961 1962 1963 1964
    p10 = DProxy(range(10))
    verify(-1 not in p10)
    for i in range(10):
        verify(i in p10)
    verify(10 not in p10)
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979
    # Safety test for __cmp__
    def unsafecmp(a, b):
        try:
            a.__class__.__cmp__(a, b)
        except TypeError:
            pass
        else:
            raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
                a.__class__, a, b)
    unsafecmp(u"123", "123")
    unsafecmp("123", u"123")
    unsafecmp(1, 1.0)
    unsafecmp(1.0, 1)
    unsafecmp(1, 1L)
    unsafecmp(1L, 1)
1980

1981 1982 1983 1984 1985 1986 1987 1988
    class Letter(str):
        def __new__(cls, letter):
            if letter == 'EPS':
                return str.__new__(cls)
            return str.__new__(cls, letter)
        def __str__(self):
            if not self:
                return 'EPS'
Tim Peters's avatar
Tim Peters committed
1989
            return self
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003

    # sys.stdout needs to be the original to trigger the recursion bug
    import sys
    test_stdout = sys.stdout
    sys.stdout = get_original_stdout()
    try:
        # nothing should actually be printed, this should raise an exception
        print Letter('w')
    except RuntimeError:
        pass
    else:
        raise TestFailed, "expected a RuntimeError for print recursion"
    sys.stdout = test_stdout

2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
def weakrefs():
    if verbose: print "Testing weak references..."
    import weakref
    class C(object):
        pass
    c = C()
    r = weakref.ref(c)
    verify(r() is c)
    del c
    verify(r() is None)
    del r
    class NoWeak(object):
        __slots__ = ['foo']
    no = NoWeak()
    try:
        weakref.ref(no)
    except TypeError, msg:
2021
        verify(str(msg).find("weak reference") >= 0)
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032
    else:
        verify(0, "weakref.ref(no) should be illegal")
    class Weak(object):
        __slots__ = ['foo', '__weakref__']
    yes = Weak()
    r = weakref.ref(yes)
    verify(r() is yes)
    del yes
    verify(r() is None)
    del r

2033 2034
def properties():
    if verbose: print "Testing property..."
2035 2036 2037 2038 2039 2040 2041
    class C(object):
        def getx(self):
            return self.__x
        def setx(self, value):
            self.__x = value
        def delx(self):
            del self.__x
2042
        x = property(getx, setx, delx, doc="I'm the x property.")
2043 2044 2045
    a = C()
    verify(not hasattr(a, "x"))
    a.x = 42
2046 2047
    vereq(a._C__x, 42)
    vereq(a.x, 42)
2048 2049 2050 2051
    del a.x
    verify(not hasattr(a, "x"))
    verify(not hasattr(a, "_C__x"))
    C.x.__set__(a, 100)
2052
    vereq(C.x.__get__(a), 100)
2053 2054
    C.x.__delete__(a)
    verify(not hasattr(a, "x"))
2055

2056 2057 2058 2059 2060 2061 2062 2063 2064
    raw = C.__dict__['x']
    verify(isinstance(raw, property))

    attrs = dir(raw)
    verify("__doc__" in attrs)
    verify("fget" in attrs)
    verify("fset" in attrs)
    verify("fdel" in attrs)

2065
    vereq(raw.__doc__, "I'm the x property.")
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
    verify(raw.fget is C.__dict__['getx'])
    verify(raw.fset is C.__dict__['setx'])
    verify(raw.fdel is C.__dict__['delx'])

    for attr in "__doc__", "fget", "fset", "fdel":
        try:
            setattr(raw, attr, 42)
        except TypeError, msg:
            if str(msg).find('readonly') < 0:
                raise TestFailed("when setting readonly attr %r on a "
                                 "property, got unexpected TypeError "
                                 "msg %r" % (attr, str(msg)))
        else:
            raise TestFailed("expected TypeError from trying to set "
                             "readonly %r attr on a property" % attr)

2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
    class D(object):
        __getitem__ = property(lambda s: 1/0)

    d = D()
    try:
        for i in d:
            str(i)
    except ZeroDivisionError:
        pass
    else:
        raise TestFailed, "expected ZeroDivisionError from bad property"

2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
    class E(object):
        def getter(self):
            "getter method"
            return 0
        def setter(self, value):
            "setter method"
            pass
        prop = property(getter)
        vereq(prop.__doc__, "getter method")
        prop2 = property(fset=setter)
        vereq(prop2.__doc__, None)

2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
    # this segfaulted in 2.5b2
    try:
        import _testcapi
    except ImportError:
        pass
    else:
        class X(object):
            p = property(_testcapi.test_with_docstring)


Guido van Rossum's avatar
Guido van Rossum committed
2116
def supers():
2117
    if verbose: print "Testing super..."
Guido van Rossum's avatar
Guido van Rossum committed
2118 2119 2120 2121 2122

    class A(object):
        def meth(self, a):
            return "A(%r)" % a

2123
    vereq(A().meth(1), "A(1)")
Guido van Rossum's avatar
Guido van Rossum committed
2124 2125 2126 2127 2128 2129 2130

    class B(A):
        def __init__(self):
            self.__super = super(B, self)
        def meth(self, a):
            return "B(%r)" % a + self.__super.meth(a)

2131
    vereq(B().meth(2), "B(2)A(2)")
Guido van Rossum's avatar
Guido van Rossum committed
2132 2133 2134 2135 2136 2137

    class C(A):
        def meth(self, a):
            return "C(%r)" % a + self.__super.meth(a)
    C._C__super = super(C)

2138
    vereq(C().meth(3), "C(3)A(3)")
Guido van Rossum's avatar
Guido van Rossum committed
2139 2140 2141 2142 2143

    class D(C, B):
        def meth(self, a):
            return "D(%r)" % a + super(D, self).meth(a)

2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159
    vereq(D().meth(4), "D(4)C(4)B(4)A(4)")

    # Test for subclassing super

    class mysuper(super):
        def __init__(self, *args):
            return super(mysuper, self).__init__(*args)

    class E(D):
        def meth(self, a):
            return "E(%r)" % a + mysuper(E, self).meth(a)

    vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")

    class F(E):
        def meth(self, a):
2160
            s = self.__super # == mysuper(F, self)
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194
            return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
    F._F__super = mysuper(F)

    vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")

    # Make sure certain errors are raised

    try:
        super(D, 42)
    except TypeError:
        pass
    else:
        raise TestFailed, "shouldn't allow super(D, 42)"

    try:
        super(D, C())
    except TypeError:
        pass
    else:
        raise TestFailed, "shouldn't allow super(D, C())"

    try:
        super(D).__get__(12)
    except TypeError:
        pass
    else:
        raise TestFailed, "shouldn't allow super(D).__get__(12)"

    try:
        super(D).__get__(C())
    except TypeError:
        pass
    else:
        raise TestFailed, "shouldn't allow super(D).__get__(C())"
Guido van Rossum's avatar
Guido van Rossum committed
2195

2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
    # Make sure data descriptors can be overridden and accessed via super
    # (new feature in Python 2.3)

    class DDbase(object):
        def getx(self): return 42
        x = property(getx)

    class DDsub(DDbase):
        def getx(self): return "hello"
        x = property(getx)

    dd = DDsub()
    vereq(dd.x, "hello")
    vereq(super(DDsub, dd).x, 42)

2211 2212 2213 2214 2215 2216 2217
    # Ensure that super() lookup of descriptor from classmethod
    # works (SF ID# 743627)

    class Base(object):
        aProp = property(lambda self: "foo")

    class Sub(Base):
Guido van Rossum's avatar
Guido van Rossum committed
2218
        @classmethod
2219 2220 2221 2222 2223
        def test(klass):
            return super(Sub,klass).aProp

    veris(Sub.test(), Base.aProp)

2224 2225 2226 2227 2228 2229 2230
    # Verify that super() doesn't allow keyword args
    try:
        super(Base, kw=1)
    except TypeError:
        pass
    else:
        raise TestFailed, "super shouldn't accept keyword args"
2231

2232 2233 2234 2235 2236 2237 2238 2239 2240 2241
def inherits():
    if verbose: print "Testing inheritance from basic types..."

    class hexint(int):
        def __repr__(self):
            return hex(self)
        def __add__(self, other):
            return hexint(int.__add__(self, other))
        # (Note that overriding __radd__ doesn't work,
        # because the int type gets first dibs.)
2242 2243
    vereq(repr(hexint(7) + 9), "0x10")
    vereq(repr(hexint(1000) + 7), "0x3ef")
2244
    a = hexint(12345)
2245 2246
    vereq(a, 12345)
    vereq(int(a), 12345)
2247
    verify(int(a).__class__ is int)
2248
    vereq(hash(a), hash(12345))
2249 2250 2251 2252 2253
    verify((+a).__class__ is int)
    verify((a >> 0).__class__ is int)
    verify((a << 0).__class__ is int)
    verify((hexint(0) << 12).__class__ is int)
    verify((hexint(0) >> 12).__class__ is int)
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264

    class octlong(long):
        __slots__ = []
        def __str__(self):
            s = oct(self)
            if s[-1] == 'L':
                s = s[:-1]
            return s
        def __add__(self, other):
            return self.__class__(super(octlong, self).__add__(other))
        __radd__ = __add__
2265
    vereq(str(octlong(3) + 5), "010")
2266 2267
    # (Note that overriding __radd__ here only seems to work
    # because the example uses a short int left argument.)
2268
    vereq(str(5 + octlong(3000)), "05675")
2269
    a = octlong(12345)
2270 2271 2272
    vereq(a, 12345L)
    vereq(long(a), 12345L)
    vereq(hash(a), hash(12345L))
2273
    verify(long(a).__class__ is long)
2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297
    verify((+a).__class__ is long)
    verify((-a).__class__ is long)
    verify((-octlong(0)).__class__ is long)
    verify((a >> 0).__class__ is long)
    verify((a << 0).__class__ is long)
    verify((a - 0).__class__ is long)
    verify((a * 1).__class__ is long)
    verify((a ** 1).__class__ is long)
    verify((a // 1).__class__ is long)
    verify((1 * a).__class__ is long)
    verify((a | 0).__class__ is long)
    verify((a ^ 0).__class__ is long)
    verify((a & -1L).__class__ is long)
    verify((octlong(0) << 12).__class__ is long)
    verify((octlong(0) >> 12).__class__ is long)
    verify(abs(octlong(0)).__class__ is long)

    # Because octlong overrides __add__, we can't check the absence of +0
    # optimizations using octlong.
    class longclone(long):
        pass
    a = longclone(1)
    verify((a + 0).__class__ is long)
    verify((0 + a).__class__ is long)
2298

2299 2300 2301
    # Check that negative clones don't segfault
    a = longclone(-1)
    vereq(a.__dict__, {})
2302
    vereq(long(a), -1)  # verify PyNumber_Long() copies the sign bit
2303

2304 2305 2306 2307
    class precfloat(float):
        __slots__ = ['prec']
        def __init__(self, value=0.0, prec=12):
            self.prec = int(prec)
2308
            float.__init__(self, value)
2309 2310
        def __repr__(self):
            return "%.*g" % (self.prec, self)
2311
    vereq(repr(precfloat(1.1)), "1.1")
2312
    a = precfloat(12345)
2313 2314
    vereq(a, 12345.0)
    vereq(float(a), 12345.0)
2315
    verify(float(a).__class__ is float)
2316
    vereq(hash(a), hash(12345.0))
2317
    verify((+a).__class__ is float)
2318

2319 2320 2321 2322
    class madcomplex(complex):
        def __repr__(self):
            return "%.17gj%+.17g" % (self.imag, self.real)
    a = madcomplex(-3, 4)
2323
    vereq(repr(a), "4j-3")
2324
    base = complex(-3, 4)
2325
    veris(base.__class__, complex)
2326 2327
    vereq(a, base)
    vereq(complex(a), base)
2328
    veris(complex(a).__class__, complex)
2329
    a = madcomplex(a)  # just trying another form of the constructor
2330 2331 2332
    vereq(repr(a), "4j-3")
    vereq(a, base)
    vereq(complex(a), base)
2333
    veris(complex(a).__class__, complex)
2334
    vereq(hash(a), hash(base))
2335 2336
    veris((+a).__class__, complex)
    veris((a + 0).__class__, complex)
2337
    vereq(a + 0, base)
2338
    veris((a - 0).__class__, complex)
2339
    vereq(a - 0, base)
2340
    veris((a * 1).__class__, complex)
2341
    vereq(a * 1, base)
2342
    veris((a / 1).__class__, complex)
2343
    vereq(a / 1, base)
2344

2345 2346 2347 2348 2349 2350 2351 2352 2353 2354
    class madtuple(tuple):
        _rev = None
        def rev(self):
            if self._rev is not None:
                return self._rev
            L = list(self)
            L.reverse()
            self._rev = self.__class__(L)
            return self._rev
    a = madtuple((1,2,3,4,5,6,7,8,9,0))
2355 2356 2357
    vereq(a, (1,2,3,4,5,6,7,8,9,0))
    vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
    vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2358 2359 2360 2361
    for i in range(512):
        t = madtuple(range(i))
        u = t.rev()
        v = u.rev()
2362
        vereq(v, t)
2363
    a = madtuple((1,2,3,4,5))
2364
    vereq(tuple(a), (1,2,3,4,5))
2365
    verify(tuple(a).__class__ is tuple)
2366
    vereq(hash(a), hash((1,2,3,4,5)))
Tim Peters's avatar
Tim Peters committed
2367 2368 2369 2370
    verify(a[:].__class__ is tuple)
    verify((a * 1).__class__ is tuple)
    verify((a * 0).__class__ is tuple)
    verify((a + ()).__class__ is tuple)
2371
    a = madtuple(())
2372
    vereq(tuple(a), ())
2373
    verify(tuple(a).__class__ is tuple)
Tim Peters's avatar
Tim Peters committed
2374 2375 2376 2377 2378
    verify((a + a).__class__ is tuple)
    verify((a * 0).__class__ is tuple)
    verify((a * 1).__class__ is tuple)
    verify((a * 2).__class__ is tuple)
    verify(a[:].__class__ is tuple)
2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389

    class madstring(str):
        _rev = None
        def rev(self):
            if self._rev is not None:
                return self._rev
            L = list(self)
            L.reverse()
            self._rev = self.__class__("".join(L))
            return self._rev
    s = madstring("abcdefghijklmnopqrstuvwxyz")
2390 2391 2392
    vereq(s, "abcdefghijklmnopqrstuvwxyz")
    vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
    vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2393 2394 2395 2396
    for i in range(256):
        s = madstring("".join(map(chr, range(i))))
        t = s.rev()
        u = t.rev()
2397
        vereq(u, s)
2398
    s = madstring("12345")
2399
    vereq(str(s), "12345")
2400
    verify(str(s).__class__ is str)
2401

2402 2403
    base = "\x00" * 5
    s = madstring(base)
2404 2405
    vereq(s, base)
    vereq(str(s), base)
2406
    verify(str(s).__class__ is str)
2407 2408 2409
    vereq(hash(s), hash(base))
    vereq({s: 1}[base], 1)
    vereq({base: 1}[s], 1)
2410
    verify((s + "").__class__ is str)
2411
    vereq(s + "", base)
2412
    verify(("" + s).__class__ is str)
2413
    vereq("" + s, base)
2414
    verify((s * 0).__class__ is str)
2415
    vereq(s * 0, "")
2416
    verify((s * 1).__class__ is str)
2417
    vereq(s * 1, base)
2418
    verify((s * 2).__class__ is str)
2419
    vereq(s * 2, base + base)
2420
    verify(s[:].__class__ is str)
2421
    vereq(s[:], base)
2422
    verify(s[0:0].__class__ is str)
2423
    vereq(s[0:0], "")
2424
    verify(s.strip().__class__ is str)
2425
    vereq(s.strip(), base)
2426
    verify(s.lstrip().__class__ is str)
2427
    vereq(s.lstrip(), base)
2428
    verify(s.rstrip().__class__ is str)
2429
    vereq(s.rstrip(), base)
2430 2431
    identitytab = ''.join([chr(i) for i in range(256)])
    verify(s.translate(identitytab).__class__ is str)
2432
    vereq(s.translate(identitytab), base)
2433
    verify(s.translate(identitytab, "x").__class__ is str)
2434 2435
    vereq(s.translate(identitytab, "x"), base)
    vereq(s.translate(identitytab, "\x00"), "")
2436
    verify(s.replace("x", "x").__class__ is str)
2437
    vereq(s.replace("x", "x"), base)
2438
    verify(s.ljust(len(s)).__class__ is str)
2439
    vereq(s.ljust(len(s)), base)
2440
    verify(s.rjust(len(s)).__class__ is str)
2441
    vereq(s.rjust(len(s)), base)
2442
    verify(s.center(len(s)).__class__ is str)
2443
    vereq(s.center(len(s)), base)
2444
    verify(s.lower().__class__ is str)
2445
    vereq(s.lower(), base)
2446

2447 2448 2449 2450 2451 2452 2453 2454 2455 2456
    class madunicode(unicode):
        _rev = None
        def rev(self):
            if self._rev is not None:
                return self._rev
            L = list(self)
            L.reverse()
            self._rev = self.__class__(u"".join(L))
            return self._rev
    u = madunicode("ABCDEF")
2457 2458 2459
    vereq(u, u"ABCDEF")
    vereq(u.rev(), madunicode(u"FEDCBA"))
    vereq(u.rev().rev(), madunicode(u"ABCDEF"))
2460 2461
    base = u"12345"
    u = madunicode(base)
2462
    vereq(unicode(u), base)
2463
    verify(unicode(u).__class__ is unicode)
2464 2465 2466
    vereq(hash(u), hash(base))
    vereq({u: 1}[base], 1)
    vereq({base: 1}[u], 1)
2467
    verify(u.strip().__class__ is unicode)
2468
    vereq(u.strip(), base)
2469
    verify(u.lstrip().__class__ is unicode)
2470
    vereq(u.lstrip(), base)
2471
    verify(u.rstrip().__class__ is unicode)
2472
    vereq(u.rstrip(), base)
2473
    verify(u.replace(u"x", u"x").__class__ is unicode)
2474
    vereq(u.replace(u"x", u"x"), base)
2475
    verify(u.replace(u"xy", u"xy").__class__ is unicode)
2476
    vereq(u.replace(u"xy", u"xy"), base)
2477
    verify(u.center(len(u)).__class__ is unicode)
2478
    vereq(u.center(len(u)), base)
2479
    verify(u.ljust(len(u)).__class__ is unicode)
2480
    vereq(u.ljust(len(u)), base)
2481
    verify(u.rjust(len(u)).__class__ is unicode)
2482
    vereq(u.rjust(len(u)), base)
2483
    verify(u.lower().__class__ is unicode)
2484
    vereq(u.lower(), base)
2485
    verify(u.upper().__class__ is unicode)
2486
    vereq(u.upper(), base)
2487
    verify(u.capitalize().__class__ is unicode)
2488
    vereq(u.capitalize(), base)
2489
    verify(u.title().__class__ is unicode)
2490
    vereq(u.title(), base)
2491
    verify((u + u"").__class__ is unicode)
2492
    vereq(u + u"", base)
2493
    verify((u"" + u).__class__ is unicode)
2494
    vereq(u"" + u, base)
2495
    verify((u * 0).__class__ is unicode)
2496
    vereq(u * 0, u"")
2497
    verify((u * 1).__class__ is unicode)
2498
    vereq(u * 1, base)
2499
    verify((u * 2).__class__ is unicode)
2500
    vereq(u * 2, base + base)
2501
    verify(u[:].__class__ is unicode)
2502
    vereq(u[:], base)
2503
    verify(u[0:0].__class__ is unicode)
2504
    vereq(u[0:0], u"")
2505

2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
    class sublist(list):
        pass
    a = sublist(range(5))
    vereq(a, range(5))
    a.append("hello")
    vereq(a, range(5) + ["hello"])
    a[5] = 5
    vereq(a, range(6))
    a.extend(range(6, 20))
    vereq(a, range(20))
    a[-5:] = []
    vereq(a, range(15))
    del a[10:15]
    vereq(len(a), 10)
    vereq(a, range(10))
    vereq(list(a), range(10))
    vereq(a[0], 0)
    vereq(a[9], 9)
    vereq(a[-10], 0)
    vereq(a[-1], 9)
    vereq(a[:5], range(5))

2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551
    class CountedInput(file):
        """Counts lines read by self.readline().

        self.lineno is the 0-based ordinal of the last line read, up to
        a maximum of one greater than the number of lines in the file.

        self.ateof is true if and only if the final "" line has been read,
        at which point self.lineno stops incrementing, and further calls
        to readline() continue to return "".
        """

        lineno = 0
        ateof = 0
        def readline(self):
            if self.ateof:
                return ""
            s = file.readline(self)
            # Next line works too.
            # s = super(CountedInput, self).readline()
            self.lineno += 1
            if s == "":
                self.ateof = 1
            return s

2552
    f = file(name=TESTFN, mode='w')
2553 2554 2555 2556 2557 2558 2559
    lines = ['a\n', 'b\n', 'c\n']
    try:
        f.writelines(lines)
        f.close()
        f = CountedInput(TESTFN)
        for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
            got = f.readline()
2560 2561 2562
            vereq(expected, got)
            vereq(f.lineno, i)
            vereq(f.ateof, (i > len(lines)))
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
        f.close()
    finally:
        try:
            f.close()
        except:
            pass
        try:
            import os
            os.unlink(TESTFN)
        except:
            pass

2575 2576 2577
def keywords():
    if verbose:
        print "Testing keyword args to basic type constructors ..."
2578 2579 2580 2581 2582 2583 2584 2585
    vereq(int(x=1), 1)
    vereq(float(x=2), 2.0)
    vereq(long(x=3), 3L)
    vereq(complex(imag=42, real=666), complex(666, 42))
    vereq(str(object=500), '500')
    vereq(unicode(string='abc', errors='strict'), u'abc')
    vereq(tuple(sequence=range(3)), (0, 1, 2))
    vereq(list(sequence=(0, 1, 2)), range(3))
2586
    # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2587 2588

    for constructor in (int, float, long, complex, str, unicode,
2589
                        tuple, list, file):
2590 2591 2592 2593 2594 2595 2596
        try:
            constructor(bogus_keyword_arg=1)
        except TypeError:
            pass
        else:
            raise TestFailed("expected TypeError from bogus keyword "
                             "argument to %r" % constructor)
2597

2598
def restricted():
2599 2600
    # XXX This test is disabled because rexec is not deemed safe
    return
2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640
    import rexec
    if verbose:
        print "Testing interaction with restricted execution ..."

    sandbox = rexec.RExec()

    code1 = """f = open(%r, 'w')""" % TESTFN
    code2 = """f = file(%r, 'w')""" % TESTFN
    code3 = """\
f = open(%r)
t = type(f)  # a sneaky way to get the file() constructor
f.close()
f = t(%r, 'w')  # rexec can't catch this by itself
""" % (TESTFN, TESTFN)

    f = open(TESTFN, 'w')  # Create the file so code3 can find it.
    f.close()

    try:
        for code in code1, code2, code3:
            try:
                sandbox.r_exec(code)
            except IOError, msg:
                if str(msg).find("restricted") >= 0:
                    outcome = "OK"
                else:
                    outcome = "got an exception, but not an expected one"
            else:
                outcome = "expected a restricted-execution exception"

            if outcome != "OK":
                raise TestFailed("%s, in %r" % (outcome, code))

    finally:
        try:
            import os
            os.unlink(TESTFN)
        except:
            pass

2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662
def str_subclass_as_dict_key():
    if verbose:
        print "Testing a str subclass used as dict key .."

    class cistr(str):
        """Sublcass of str that computes __eq__ case-insensitively.

        Also computes a hash code of the string in canonical form.
        """

        def __init__(self, value):
            self.canonical = value.lower()
            self.hashcode = hash(self.canonical)

        def __eq__(self, other):
            if not isinstance(other, cistr):
                other = cistr(other)
            return self.canonical == other.canonical

        def __hash__(self):
            return self.hashcode

2663 2664 2665
    vereq(cistr('ABC'), 'abc')
    vereq('aBc', cistr('ABC'))
    vereq(str(cistr('ABC')), 'ABC')
2666 2667

    d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2668 2669 2670
    vereq(d[cistr('one')], 1)
    vereq(d[cistr('tWo')], 2)
    vereq(d[cistr('THrEE')], 3)
2671
    verify(cistr('ONe') in d)
2672
    vereq(d.get(cistr('thrEE')), 3)
2673

2674 2675
def classic_comparisons():
    if verbose: print "Testing classic comparisons..."
2676 2677 2678
    class classic:
        pass
    for base in (classic, int, object):
2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691
        if verbose: print "        (base = %s)" % base
        class C(base):
            def __init__(self, value):
                self.value = int(value)
            def __cmp__(self, other):
                if isinstance(other, C):
                    return cmp(self.value, other.value)
                if isinstance(other, int) or isinstance(other, long):
                    return cmp(self.value, other)
                return NotImplemented
        c1 = C(1)
        c2 = C(2)
        c3 = C(3)
2692
        vereq(c1, 1)
2693 2694 2695 2696 2697 2698 2699 2700 2701 2702
        c = {1: c1, 2: c2, 3: c3}
        for x in 1, 2, 3:
            for y in 1, 2, 3:
                verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
                for op in "<", "<=", "==", "!=", ">", ">=":
                    verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
                           "x=%d, y=%d" % (x, y))
                verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
                verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))

2703 2704 2705
def rich_comparisons():
    if verbose:
        print "Testing rich comparisons..."
2706
    class Z(complex):
2707
        pass
2708
    z = Z(1)
2709 2710
    vereq(z, 1+0j)
    vereq(1+0j, z)
2711 2712 2713 2714 2715 2716 2717
    class ZZ(complex):
        def __eq__(self, other):
            try:
                return abs(self - other) <= 1e-6
            except:
                return NotImplemented
    zz = ZZ(1.0000003)
2718 2719
    vereq(zz, 1+0j)
    vereq(1+0j, zz)
2720

2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768
    class classic:
        pass
    for base in (classic, int, object, list):
        if verbose: print "        (base = %s)" % base
        class C(base):
            def __init__(self, value):
                self.value = int(value)
            def __cmp__(self, other):
                raise TestFailed, "shouldn't call __cmp__"
            def __eq__(self, other):
                if isinstance(other, C):
                    return self.value == other.value
                if isinstance(other, int) or isinstance(other, long):
                    return self.value == other
                return NotImplemented
            def __ne__(self, other):
                if isinstance(other, C):
                    return self.value != other.value
                if isinstance(other, int) or isinstance(other, long):
                    return self.value != other
                return NotImplemented
            def __lt__(self, other):
                if isinstance(other, C):
                    return self.value < other.value
                if isinstance(other, int) or isinstance(other, long):
                    return self.value < other
                return NotImplemented
            def __le__(self, other):
                if isinstance(other, C):
                    return self.value <= other.value
                if isinstance(other, int) or isinstance(other, long):
                    return self.value <= other
                return NotImplemented
            def __gt__(self, other):
                if isinstance(other, C):
                    return self.value > other.value
                if isinstance(other, int) or isinstance(other, long):
                    return self.value > other
                return NotImplemented
            def __ge__(self, other):
                if isinstance(other, C):
                    return self.value >= other.value
                if isinstance(other, int) or isinstance(other, long):
                    return self.value >= other
                return NotImplemented
        c1 = C(1)
        c2 = C(2)
        c3 = C(3)
2769
        vereq(c1, 1)
2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780
        c = {1: c1, 2: c2, 3: c3}
        for x in 1, 2, 3:
            for y in 1, 2, 3:
                for op in "<", "<=", "==", "!=", ">", ">=":
                    verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
                           "x=%d, y=%d" % (x, y))
                    verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
                           "x=%d, y=%d" % (x, y))
                    verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
                           "x=%d, y=%d" % (x, y))

2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797
def coercions():
    if verbose: print "Testing coercions..."
    class I(int): pass
    coerce(I(0), 0)
    coerce(0, I(0))
    class L(long): pass
    coerce(L(0), 0)
    coerce(L(0), 0L)
    coerce(0, L(0))
    coerce(0L, L(0))
    class F(float): pass
    coerce(F(0), 0)
    coerce(F(0), 0L)
    coerce(F(0), 0.)
    coerce(0, F(0))
    coerce(0L, F(0))
    coerce(0., F(0))
2798
    class C(complex): pass
2799 2800 2801 2802 2803 2804 2805 2806 2807
    coerce(C(0), 0)
    coerce(C(0), 0L)
    coerce(C(0), 0.)
    coerce(C(0), 0j)
    coerce(0, C(0))
    coerce(0L, C(0))
    coerce(0., C(0))
    coerce(0j, C(0))

2808 2809 2810
def descrdoc():
    if verbose: print "Testing descriptor doc strings..."
    def check(descr, what):
2811
        vereq(descr.__doc__, what)
2812
    check(file.closed, "True if the file is closed") # getset descriptor
2813 2814
    check(file.name, "file name") # member descriptor

2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834
def setclass():
    if verbose: print "Testing __class__ assignment..."
    class C(object): pass
    class D(object): pass
    class E(object): pass
    class F(D, E): pass
    for cls in C, D, E, F:
        for cls2 in C, D, E, F:
            x = cls()
            x.__class__ = cls2
            verify(x.__class__ is cls2)
            x.__class__ = cls
            verify(x.__class__ is cls)
    def cant(x, C):
        try:
            x.__class__ = C
        except TypeError:
            pass
        else:
            raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
2835 2836 2837 2838 2839 2840
        try:
            delattr(x, "__class__")
        except TypeError:
            pass
        else:
            raise TestFailed, "shouldn't allow del %r.__class__" % x
2841 2842 2843 2844 2845 2846
    cant(C(), list)
    cant(list(), C)
    cant(C(), 1)
    cant(C(), object)
    cant(object(), list)
    cant(list(), object)
2847 2848 2849 2850 2851
    class Int(int): __slots__ = []
    cant(2, Int)
    cant(Int(), int)
    cant(True, int)
    cant(2, bool)
2852 2853 2854 2855
    o = object()
    cant(o, type(1))
    cant(o, type(None))
    del o
2856

2857 2858 2859 2860 2861 2862 2863 2864 2865
def setdict():
    if verbose: print "Testing __dict__ assignment..."
    class C(object): pass
    a = C()
    a.__dict__ = {'b': 1}
    vereq(a.b, 1)
    def cant(x, dict):
        try:
            x.__dict__ = dict
2866
        except (AttributeError, TypeError):
2867 2868 2869 2870 2871 2872
            pass
        else:
            raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
    cant(a, None)
    cant(a, [])
    cant(a, 1)
2873
    del a.__dict__ # Deleting __dict__ is allowed
2874 2875 2876
    # Classes don't allow __dict__ assignment
    cant(C, {})

2877
def pickles():
2878 2879
    if verbose:
        print "Testing pickling and copying new-style classes and objects..."
2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899
    import pickle, cPickle

    def sorteditems(d):
        L = d.items()
        L.sort()
        return L

    global C
    class C(object):
        def __init__(self, a, b):
            super(C, self).__init__()
            self.a = a
            self.b = b
        def __repr__(self):
            return "C(%r, %r)" % (self.a, self.b)

    global C1
    class C1(list):
        def __new__(cls, a, b):
            return super(C1, cls).__new__(cls)
2900 2901
        def __getnewargs__(self):
            return (self.a, self.b)
2902 2903 2904 2905 2906 2907 2908 2909 2910 2911
        def __init__(self, a, b):
            self.a = a
            self.b = b
        def __repr__(self):
            return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))

    global C2
    class C2(int):
        def __new__(cls, a, b, val=0):
            return super(C2, cls).__new__(cls, val)
2912 2913
        def __getnewargs__(self):
            return (self.a, self.b, int(self))
2914 2915 2916 2917 2918 2919
        def __init__(self, a, b, val=0):
            self.a = a
            self.b = b
        def __repr__(self):
            return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))

2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934
    global C3
    class C3(object):
        def __init__(self, foo):
            self.foo = foo
        def __getstate__(self):
            return self.foo
        def __setstate__(self, foo):
            self.foo = foo

    global C4classic, C4
    class C4classic: # classic
        pass
    class C4(C4classic, object): # mixed inheritance
        pass

2935 2936
    for p in pickle, cPickle:
        for bin in 0, 1:
Guido van Rossum's avatar
Guido van Rossum committed
2937 2938
            if verbose:
                print p.__name__, ["text", "binary"][bin]
2939 2940 2941 2942 2943 2944 2945 2946 2947 2948

            for cls in C, C1, C2:
                s = p.dumps(cls, bin)
                cls2 = p.loads(s)
                verify(cls2 is cls)

            a = C1(1, 2); a.append(42); a.append(24)
            b = C2("hello", "world", 42)
            s = p.dumps((a, b), bin)
            x, y = p.loads(s)
2949 2950 2951 2952
            vereq(x.__class__, a.__class__)
            vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
            vereq(y.__class__, b.__class__)
            vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
2953 2954
            vereq(repr(x), repr(a))
            vereq(repr(y), repr(b))
2955 2956 2957
            if verbose:
                print "a = x =", a
                print "b = y =", b
2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970
            # Test for __getstate__ and __setstate__ on new style class
            u = C3(42)
            s = p.dumps(u, bin)
            v = p.loads(s)
            veris(u.__class__, v.__class__)
            vereq(u.foo, v.foo)
            # Test for picklability of hybrid class
            u = C4()
            u.foo = 42
            s = p.dumps(u, bin)
            v = p.loads(s)
            veris(u.__class__, v.__class__)
            vereq(u.foo, v.foo)
2971

Guido van Rossum's avatar
Guido van Rossum committed
2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982
    # Testing copy.deepcopy()
    if verbose:
        print "deepcopy"
    import copy
    for cls in C, C1, C2:
        cls2 = copy.deepcopy(cls)
        verify(cls2 is cls)

    a = C1(1, 2); a.append(42); a.append(24)
    b = C2("hello", "world", 42)
    x, y = copy.deepcopy((a, b))
2983 2984 2985 2986
    vereq(x.__class__, a.__class__)
    vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
    vereq(y.__class__, b.__class__)
    vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
2987 2988
    vereq(repr(x), repr(a))
    vereq(repr(y), repr(b))
Guido van Rossum's avatar
Guido van Rossum committed
2989 2990 2991
    if verbose:
        print "a = x =", a
        print "b = y =", b
2992

2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
def pickleslots():
    if verbose: print "Testing pickling of classes with __slots__ ..."
    import pickle, cPickle
    # Pickling of classes with __slots__ but without __getstate__ should fail
    global B, C, D, E
    class B(object):
        pass
    for base in [object, B]:
        class C(base):
            __slots__ = ['a']
        class D(C):
            pass
        try:
            pickle.dumps(C())
        except TypeError:
            pass
        else:
            raise TestFailed, "should fail: pickle C instance - %s" % base
        try:
            cPickle.dumps(C())
        except TypeError:
            pass
        else:
            raise TestFailed, "should fail: cPickle C instance - %s" % base
        try:
            pickle.dumps(C())
        except TypeError:
            pass
        else:
            raise TestFailed, "should fail: pickle D instance - %s" % base
        try:
            cPickle.dumps(D())
        except TypeError:
            pass
        else:
            raise TestFailed, "should fail: cPickle D instance - %s" % base
3029
        # Give C a nice generic __getstate__ and __setstate__
3030 3031 3032 3033 3034 3035 3036
        class C(base):
            __slots__ = ['a']
            def __getstate__(self):
                try:
                    d = self.__dict__.copy()
                except AttributeError:
                    d = {}
3037 3038 3039 3040 3041 3042
                for cls in self.__class__.__mro__:
                    for sn in cls.__dict__.get('__slots__', ()):
                        try:
                            d[sn] = getattr(self, sn)
                        except AttributeError:
                            pass
3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066
                return d
            def __setstate__(self, d):
                for k, v in d.items():
                    setattr(self, k, v)
        class D(C):
            pass
        # Now it should work
        x = C()
        y = pickle.loads(pickle.dumps(x))
        vereq(hasattr(y, 'a'), 0)
        y = cPickle.loads(cPickle.dumps(x))
        vereq(hasattr(y, 'a'), 0)
        x.a = 42
        y = pickle.loads(pickle.dumps(x))
        vereq(y.a, 42)
        y = cPickle.loads(cPickle.dumps(x))
        vereq(y.a, 42)
        x = D()
        x.a = 42
        x.b = 100
        y = pickle.loads(pickle.dumps(x))
        vereq(y.a + y.b, 142)
        y = cPickle.loads(cPickle.dumps(x))
        vereq(y.a + y.b, 142)
3067
        # A subclass that adds a slot should also work
3068 3069
        class E(C):
            __slots__ = ['b']
3070 3071 3072 3073 3074 3075 3076 3077 3078
        x = E()
        x.a = 42
        x.b = "foo"
        y = pickle.loads(pickle.dumps(x))
        vereq(y.a, x.a)
        vereq(y.b, x.b)
        y = cPickle.loads(cPickle.dumps(x))
        vereq(y.a, x.a)
        vereq(y.b, x.b)
3079

3080 3081 3082 3083 3084 3085 3086 3087 3088
def copies():
    if verbose: print "Testing copy.copy() and copy.deepcopy()..."
    import copy
    class C(object):
        pass

    a = C()
    a.foo = 12
    b = copy.copy(a)
3089
    vereq(b.__dict__, a.__dict__)
3090 3091 3092

    a.bar = [1,2,3]
    c = copy.copy(a)
3093
    vereq(c.bar, a.bar)
3094 3095 3096
    verify(c.bar is a.bar)

    d = copy.deepcopy(a)
3097
    vereq(d.__dict__, a.__dict__)
3098
    a.bar.append(4)
3099
    vereq(d.bar, [1,2,3])
3100

3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118
def binopoverride():
    if verbose: print "Testing overrides of binary operations..."
    class I(int):
        def __repr__(self):
            return "I(%r)" % int(self)
        def __add__(self, other):
            return I(int(self) + int(other))
        __radd__ = __add__
        def __pow__(self, other, mod=None):
            if mod is None:
                return I(pow(int(self), int(other)))
            else:
                return I(pow(int(self), int(other), int(mod)))
        def __rpow__(self, other, mod=None):
            if mod is None:
                return I(pow(int(other), int(self), mod))
            else:
                return I(pow(int(other), int(self), int(mod)))
3119

3120 3121 3122 3123 3124 3125 3126
    vereq(repr(I(1) + I(2)), "I(3)")
    vereq(repr(I(1) + 2), "I(3)")
    vereq(repr(1 + I(2)), "I(3)")
    vereq(repr(I(2) ** I(3)), "I(8)")
    vereq(repr(2 ** I(3)), "I(8)")
    vereq(repr(I(2) ** 3), "I(8)")
    vereq(repr(pow(I(2), I(3), I(5))), "I(3)")
3127 3128 3129 3130
    class S(str):
        def __eq__(self, other):
            return self.lower() == other.lower()

3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141
def subclasspropagation():
    if verbose: print "Testing propagation of slot functions to subclasses..."
    class A(object):
        pass
    class B(A):
        pass
    class C(A):
        pass
    class D(B, C):
        pass
    d = D()
3142
    orig_hash = hash(d) # related to id(d) in platform-dependent ways
3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157
    A.__hash__ = lambda self: 42
    vereq(hash(d), 42)
    C.__hash__ = lambda self: 314
    vereq(hash(d), 314)
    B.__hash__ = lambda self: 144
    vereq(hash(d), 144)
    D.__hash__ = lambda self: 100
    vereq(hash(d), 100)
    del D.__hash__
    vereq(hash(d), 144)
    del B.__hash__
    vereq(hash(d), 314)
    del C.__hash__
    vereq(hash(d), 42)
    del A.__hash__
3158
    vereq(hash(d), orig_hash)
3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189
    d.foo = 42
    d.bar = 42
    vereq(d.foo, 42)
    vereq(d.bar, 42)
    def __getattribute__(self, name):
        if name == "foo":
            return 24
        return object.__getattribute__(self, name)
    A.__getattribute__ = __getattribute__
    vereq(d.foo, 24)
    vereq(d.bar, 42)
    def __getattr__(self, name):
        if name in ("spam", "foo", "bar"):
            return "hello"
        raise AttributeError, name
    B.__getattr__ = __getattr__
    vereq(d.spam, "hello")
    vereq(d.foo, 24)
    vereq(d.bar, 42)
    del A.__getattribute__
    vereq(d.foo, 42)
    del d.foo
    vereq(d.foo, "hello")
    vereq(d.bar, 42)
    del B.__getattr__
    try:
        d.foo
    except AttributeError:
        pass
    else:
        raise TestFailed, "d.foo should be undefined now"
3190

3191 3192 3193 3194 3195 3196 3197 3198 3199 3200
    # Test a nasty bug in recurse_down_subclasses()
    import gc
    class A(object):
        pass
    class B(A):
        pass
    del B
    gc.collect()
    A.__setitem__ = lambda *a: None # crash

3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230
def buffer_inherit():
    import binascii
    # SF bug [#470040] ParseTuple t# vs subclasses.
    if verbose:
        print "Testing that buffer interface is inherited ..."

    class MyStr(str):
        pass
    base = 'abc'
    m = MyStr(base)
    # b2a_hex uses the buffer interface to get its argument's value, via
    # PyArg_ParseTuple 't#' code.
    vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))

    # It's not clear that unicode will continue to support the character
    # buffer interface, and this test will fail if that's taken away.
    class MyUni(unicode):
        pass
    base = u'abc'
    m = MyUni(base)
    vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))

    class MyInt(int):
        pass
    m = MyInt(42)
    try:
        binascii.b2a_hex(m)
        raise TestFailed('subclass of int should not have a buffer interface')
    except TypeError:
        pass
3231

3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261
def str_of_str_subclass():
    import binascii
    import cStringIO

    if verbose:
        print "Testing __str__ defined in subclass of str ..."

    class octetstring(str):
        def __str__(self):
            return binascii.b2a_hex(self)
        def __repr__(self):
            return self + " repr"

    o = octetstring('A')
    vereq(type(o), octetstring)
    vereq(type(str(o)), str)
    vereq(type(repr(o)), str)
    vereq(ord(o), 0x41)
    vereq(str(o), '41')
    vereq(repr(o), 'A repr')
    vereq(o.__str__(), '41')
    vereq(o.__repr__(), 'A repr')

    capture = cStringIO.StringIO()
    # Calling str() or not exercises different internal paths.
    print >> capture, o
    print >> capture, str(o)
    vereq(capture.getvalue(), '41\n41\n')
    capture.close()

3262 3263 3264 3265 3266 3267
def kwdargs():
    if verbose: print "Testing keyword arguments to __init__, __call__..."
    def f(a): return a
    vereq(f.__call__(a=42), 42)
    a = []
    list.__init__(a, sequence=[0, 1, 2])
3268
    vereq(a, [0, 1, 2])
3269

3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284
def recursive__call__():
    if verbose: print ("Testing recursive __call__() by setting to instance of "
                        "class ...")
    class A(object):
        pass

    A.__call__ = A()
    try:
        A()()
    except RuntimeError:
        pass
    else:
        raise TestFailed("Recursion limit should have been reached for "
                         "__call__()")

3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295
def delhook():
    if verbose: print "Testing __del__ hook..."
    log = []
    class C(object):
        def __del__(self):
            log.append(1)
    c = C()
    vereq(log, [])
    del c
    vereq(log, [1])

3296 3297 3298 3299 3300 3301
    class D(object): pass
    d = D()
    try: del d[0]
    except TypeError: pass
    else: raise TestFailed, "invalid del() didn't raise TypeError"

3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324
def hashinherit():
    if verbose: print "Testing hash of mutable subclasses..."

    class mydict(dict):
        pass
    d = mydict()
    try:
        hash(d)
    except TypeError:
        pass
    else:
        raise TestFailed, "hash() of dict subclass should fail"

    class mylist(list):
        pass
    d = mylist()
    try:
        hash(d)
    except TypeError:
        pass
    else:
        raise TestFailed, "hash() of list subclass should fail"

3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370
def strops():
    try: 'a' + 5
    except TypeError: pass
    else: raise TestFailed, "'' + 5 doesn't raise TypeError"

    try: ''.split('')
    except ValueError: pass
    else: raise TestFailed, "''.split('') doesn't raise ValueError"

    try: ''.join([0])
    except TypeError: pass
    else: raise TestFailed, "''.join([0]) doesn't raise TypeError"

    try: ''.rindex('5')
    except ValueError: pass
    else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"

    try: '%(n)s' % None
    except TypeError: pass
    else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"

    try: '%(n' % {}
    except ValueError: pass
    else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"

    try: '%*s' % ('abc')
    except TypeError: pass
    else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"

    try: '%*.*s' % ('abc', 5)
    except TypeError: pass
    else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"

    try: '%s' % (1, 2)
    except TypeError: pass
    else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"

    try: '%' % None
    except ValueError: pass
    else: raise TestFailed, "'%' % None doesn't raise ValueError"

    vereq('534253'.isdigit(), 1)
    vereq('534253x'.isdigit(), 0)
    vereq('%c' % 5, '\x05')
    vereq('%c' % '5', '5')

3371 3372 3373 3374 3375 3376 3377 3378 3379
def deepcopyrecursive():
    if verbose: print "Testing deepcopy of recursive objects..."
    class Node:
        pass
    a = Node()
    b = Node()
    a.b = b
    b.a = a
    z = deepcopy(a) # This blew up before
3380

3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391
def modules():
    if verbose: print "Testing uninitialized module objects..."
    from types import ModuleType as M
    m = M.__new__(M)
    str(m)
    vereq(hasattr(m, "__name__"), 0)
    vereq(hasattr(m, "__file__"), 0)
    vereq(hasattr(m, "foo"), 0)
    vereq(m.__dict__, None)
    m.foo = 1
    vereq(m.__dict__, {"foo": 1})
3392

3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418
def dictproxyiterkeys():
    class C(object):
        def meth(self):
            pass
    if verbose: print "Testing dict-proxy iterkeys..."
    keys = [ key for key in C.__dict__.iterkeys() ]
    keys.sort()
    vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])

def dictproxyitervalues():
    class C(object):
        def meth(self):
            pass
    if verbose: print "Testing dict-proxy itervalues..."
    values = [ values for values in C.__dict__.itervalues() ]
    vereq(len(values), 5)

def dictproxyiteritems():
    class C(object):
        def meth(self):
            pass
    if verbose: print "Testing dict-proxy iteritems..."
    keys = [ key for (key, value) in C.__dict__.iteritems() ]
    keys.sort()
    vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])

3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439
def funnynew():
    if verbose: print "Testing __new__ returning something unexpected..."
    class C(object):
        def __new__(cls, arg):
            if isinstance(arg, str): return [1, 2, 3]
            elif isinstance(arg, int): return object.__new__(D)
            else: return object.__new__(cls)
    class D(C):
        def __init__(self, arg):
            self.foo = arg
    vereq(C("1"), [1, 2, 3])
    vereq(D("1"), [1, 2, 3])
    d = D(None)
    veris(d.foo, None)
    d = C(1)
    vereq(isinstance(d, D), True)
    vereq(d.foo, 1)
    d = D(1)
    vereq(isinstance(d, D), True)
    vereq(d.foo, 1)

Guido van Rossum's avatar
Guido van Rossum committed
3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465
def imulbug():
    # SF bug 544647
    if verbose: print "Testing for __imul__ problems..."
    class C(object):
        def __imul__(self, other):
            return (self, other)
    x = C()
    y = x
    y *= 1.0
    vereq(y, (x, 1.0))
    y = x
    y *= 2
    vereq(y, (x, 2))
    y = x
    y *= 3L
    vereq(y, (x, 3L))
    y = x
    y *= 1L<<100
    vereq(y, (x, 1L<<100))
    y = x
    y *= None
    vereq(y, (x, None))
    y = x
    y *= "foo"
    vereq(y, (x, "foo"))

Guido van Rossum's avatar
Guido van Rossum committed
3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484
def docdescriptor():
    # SF bug 542984
    if verbose: print "Testing __doc__ descriptor..."
    class DocDescr(object):
        def __get__(self, object, otype):
            if object:
                object = object.__class__.__name__ + ' instance'
            if otype:
                otype = otype.__name__
            return 'object=%s; type=%s' % (object, otype)
    class OldClass:
        __doc__ = DocDescr()
    class NewClass(object):
        __doc__ = DocDescr()
    vereq(OldClass.__doc__, 'object=None; type=OldClass')
    vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
    vereq(NewClass.__doc__, 'object=None; type=NewClass')
    vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')

3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512
def copy_setstate():
    if verbose:
        print "Testing that copy.*copy() correctly uses __setstate__..."
    import copy
    class C(object):
        def __init__(self, foo=None):
            self.foo = foo
            self.__foo = foo
        def setfoo(self, foo=None):
            self.foo = foo
        def getfoo(self):
            return self.__foo
        def __getstate__(self):
            return [self.foo]
        def __setstate__(self, lst):
            assert len(lst) == 1
            self.__foo = self.foo = lst[0]
    a = C(42)
    a.setfoo(24)
    vereq(a.foo, 24)
    vereq(a.getfoo(), 42)
    b = copy.copy(a)
    vereq(b.foo, 24)
    vereq(b.getfoo(), 24)
    b = copy.deepcopy(a)
    vereq(b.foo, 24)
    vereq(b.getfoo(), 24)

3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556
def slices():
    if verbose:
        print "Testing cases with slices and overridden __getitem__ ..."
    # Strings
    vereq("hello"[:4], "hell")
    vereq("hello"[slice(4)], "hell")
    vereq(str.__getitem__("hello", slice(4)), "hell")
    class S(str):
        def __getitem__(self, x):
            return str.__getitem__(self, x)
    vereq(S("hello")[:4], "hell")
    vereq(S("hello")[slice(4)], "hell")
    vereq(S("hello").__getitem__(slice(4)), "hell")
    # Tuples
    vereq((1,2,3)[:2], (1,2))
    vereq((1,2,3)[slice(2)], (1,2))
    vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
    class T(tuple):
        def __getitem__(self, x):
            return tuple.__getitem__(self, x)
    vereq(T((1,2,3))[:2], (1,2))
    vereq(T((1,2,3))[slice(2)], (1,2))
    vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
    # Lists
    vereq([1,2,3][:2], [1,2])
    vereq([1,2,3][slice(2)], [1,2])
    vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
    class L(list):
        def __getitem__(self, x):
            return list.__getitem__(self, x)
    vereq(L([1,2,3])[:2], [1,2])
    vereq(L([1,2,3])[slice(2)], [1,2])
    vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
    # Now do lists and __setitem__
    a = L([1,2,3])
    a[slice(1, 3)] = [3,2]
    vereq(a, [1,3,2])
    a[slice(0, 2, 1)] = [3,1]
    vereq(a, [3,1,2])
    a.__setitem__(slice(1, 3), [2,1])
    vereq(a, [3,2,1])
    a.__setitem__(slice(0, 2, 1), [2,3])
    vereq(a, [2,3,1])

3557 3558
def subtype_resurrection():
    if verbose:
3559
        print "Testing resurrection of new-style instance..."
3560 3561 3562 3563 3564 3565 3566 3567 3568 3569

    class C(object):
        container = []

        def __del__(self):
            # resurrect the instance
            C.container.append(self)

    c = C()
    c.attr = 42
3570
    # The most interesting thing here is whether this blows up, due to flawed
3571
    #  GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
3572
    del c
3573 3574 3575 3576 3577 3578 3579

    # If that didn't blow up, it's also interesting to see whether clearing
    # the last container slot works:  that will attempt to delete c again,
    # which will cause c to get appended back to the container again "during"
    # the del.
    del C.container[-1]
    vereq(len(C.container), 1)
3580
    vereq(C.container[-1].attr, 42)
3581

3582 3583 3584 3585
    # Make c mortal again, so that the test framework with -l doesn't report
    # it as a leak.
    del C.__del__

3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598
def slottrash():
    # Deallocating deeply nested slotted trash caused stack overflows
    if verbose:
        print "Testing slot trash..."
    class trash(object):
        __slots__ = ['x']
        def __init__(self, x):
            self.x = x
    o = None
    for i in xrange(50000):
        o = trash(o)
    del o

3599 3600 3601 3602 3603 3604 3605 3606
def slotmultipleinheritance():
    # SF bug 575229, multiple inheritance w/ slots dumps core
    class A(object):
        __slots__=()
    class B(object):
        pass
    class C(A,B) :
        __slots__=()
3607 3608 3609 3610
    vereq(C.__basicsize__, B.__basicsize__)
    verify(hasattr(C, '__dict__'))
    verify(hasattr(C, '__weakref__'))
    C().x = 2
3611

3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626
def testrmul():
    # SF patch 592646
    if verbose:
        print "Testing correct invocation of __rmul__..."
    class C(object):
        def __mul__(self, other):
            return "mul"
        def __rmul__(self, other):
            return "rmul"
    a = C()
    vereq(a*2, "mul")
    vereq(a*2.2, "mul")
    vereq(2*a, "rmul")
    vereq(2.2*a, "rmul")

3627 3628 3629 3630 3631 3632 3633 3634 3635 3636
def testipow():
    # [SF bug 620179]
    if verbose:
        print "Testing correct invocation of __ipow__..."
    class C(object):
        def __ipow__(self, other):
            pass
    a = C()
    a **= 2

3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651
def do_this_first():
    if verbose:
        print "Testing SF bug 551412 ..."
    # This dumps core when SF bug 551412 isn't fixed --
    # but only when test_descr.py is run separately.
    # (That can't be helped -- as soon as PyType_Ready()
    # is called for PyLong_Type, the bug is gone.)
    class UserLong(object):
        def __pow__(self, *args):
            pass
    try:
        pow(0L, UserLong(), 0L)
    except:
        pass

3652 3653 3654 3655 3656 3657
    if verbose:
        print "Testing SF bug 570483..."
    # Another segfault only when run early
    # (before PyType_Ready(tuple) is called)
    type.mro(tuple)

3658
def test_mutable_bases():
3659 3660
    if verbose:
        print "Testing mutable bases..."
Michael W. Hudson's avatar
Michael W. Hudson committed
3661 3662 3663 3664 3665 3666 3667 3668
    # stuff that should work:
    class C(object):
        pass
    class C2(object):
        def __getattribute__(self, attr):
            if attr == 'a':
                return 2
            else:
Tim Peters's avatar
Tim Peters committed
3669
                return super(C2, self).__getattribute__(attr)
Michael W. Hudson's avatar
Michael W. Hudson committed
3670 3671 3672 3673 3674 3675 3676 3677
        def meth(self):
            return 1
    class D(C):
        pass
    class E(D):
        pass
    d = D()
    e = E()
3678
    D.__bases__ = (C,)
Michael W. Hudson's avatar
Michael W. Hudson committed
3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703
    D.__bases__ = (C2,)
    vereq(d.meth(), 1)
    vereq(e.meth(), 1)
    vereq(d.a, 2)
    vereq(e.a, 2)
    vereq(C2.__subclasses__(), [D])

    # stuff that shouldn't:
    class L(list):
        pass

    try:
        L.__bases__ = (dict,)
    except TypeError:
        pass
    else:
        raise TestFailed, "shouldn't turn list subclass into dict subclass"

    try:
        list.__bases__ = (dict,)
    except TypeError:
        pass
    else:
        raise TestFailed, "shouldn't be able to assign to list.__bases__"

3704 3705 3706 3707 3708 3709 3710
    try:
        D.__bases__ = (C2, list)
    except TypeError:
        pass
    else:
        assert 0, "best_base calculation found wanting"

Michael W. Hudson's avatar
Michael W. Hudson committed
3711 3712 3713 3714 3715 3716 3717
    try:
        del D.__bases__
    except TypeError:
        pass
    else:
        raise TestFailed, "shouldn't be able to delete .__bases__"

3718 3719 3720 3721 3722 3723 3724 3725
    try:
        D.__bases__ = ()
    except TypeError, msg:
        if str(msg) == "a new-style class can't have only classic bases":
            raise TestFailed, "wrong error message for .__bases__ = ()"
    else:
        raise TestFailed, "shouldn't be able to set .__bases__ to ()"

Michael W. Hudson's avatar
Michael W. Hudson committed
3726 3727 3728 3729 3730 3731 3732 3733
    try:
        D.__bases__ = (D,)
    except TypeError:
        pass
    else:
        # actually, we'll have crashed by here...
        raise TestFailed, "shouldn't be able to create inheritance cycles"

3734 3735 3736 3737 3738 3739 3740
    try:
        D.__bases__ = (C, C)
    except TypeError:
        pass
    else:
        raise TestFailed, "didn't detect repeated base classes"

3741 3742 3743 3744 3745 3746 3747
    try:
        D.__bases__ = (E,)
    except TypeError:
        pass
    else:
        raise TestFailed, "shouldn't be able to create inheritance cycles"

Michael W. Hudson's avatar
Michael W. Hudson committed
3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770
    # let's throw a classic class into the mix:
    class Classic:
        def meth2(self):
            return 3

    D.__bases__ = (C, Classic)

    vereq(d.meth2(), 3)
    vereq(e.meth2(), 3)
    try:
        d.a
    except AttributeError:
        pass
    else:
        raise TestFailed, "attribute should have vanished"

    try:
        D.__bases__ = (Classic,)
    except TypeError:
        pass
    else:
        raise TestFailed, "new-style class must have a new-style base"

3771
def test_mutable_bases_with_failing_mro():
3772 3773
    if verbose:
        print "Testing mutable bases with failing mro..."
3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813
    class WorkOnce(type):
        def __new__(self, name, bases, ns):
            self.flag = 0
            return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
        def mro(self):
            if self.flag > 0:
                raise RuntimeError, "bozo"
            else:
                self.flag += 1
                return type.mro(self)

    class WorkAlways(type):
        def mro(self):
            # this is here to make sure that .mro()s aren't called
            # with an exception set (which was possible at one point).
            # An error message will be printed in a debug build.
            # What's a good way to test for this?
            return type.mro(self)

    class C(object):
        pass

    class C2(object):
        pass

    class D(C):
        pass

    class E(D):
        pass

    class F(D):
        __metaclass__ = WorkOnce

    class G(D):
        __metaclass__ = WorkAlways

    # Immediate subclasses have their mro's adjusted in alphabetical
    # order, so E's will get adjusted before adjusting F's fails.  We
    # check here that E's gets restored.
Tim Peters's avatar
Tim Peters committed
3814

3815
    E_mro_before = E.__mro__
3816
    D_mro_before = D.__mro__
3817 3818 3819 3820 3821

    try:
        D.__bases__ = (C2,)
    except RuntimeError:
        vereq(E.__mro__, E_mro_before)
3822
        vereq(D.__mro__, D_mro_before)
3823 3824 3825 3826
    else:
        raise TestFailed, "exception not propagated"

def test_mutable_bases_catch_mro_conflict():
3827 3828
    if verbose:
        print "Testing mutable bases catch mro conflict..."
3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849
    class A(object):
        pass

    class B(object):
        pass

    class C(A, B):
        pass

    class D(A, B):
        pass

    class E(C, D):
        pass

    try:
        C.__bases__ = (B, A)
    except TypeError:
        pass
    else:
        raise TestFailed, "didn't catch MRO conflict"
Tim Peters's avatar
Tim Peters committed
3850

Michael W. Hudson's avatar
Michael W. Hudson committed
3851
def mutable_names():
3852 3853
    if verbose:
        print "Testing mutable names..."
Michael W. Hudson's avatar
Michael W. Hudson committed
3854 3855 3856
    class C(object):
        pass

3857 3858
    # C.__module__ could be 'test_descr' or '__main__'
    mod = C.__module__
Tim Peters's avatar
Tim Peters committed
3859

3860 3861 3862 3863 3864
    C.__name__ = 'D'
    vereq((C.__module__, C.__name__), (mod, 'D'))

    C.__name__ = 'D.E'
    vereq((C.__module__, C.__name__), (mod, 'D.E'))
Tim Peters's avatar
Tim Peters committed
3865

3866 3867 3868 3869 3870 3871 3872 3873 3874 3875
def subclass_right_op():
    if verbose:
        print "Testing correct dispatch of subclass overloading __r<op>__..."

    # This code tests various cases where right-dispatch of a subclass
    # should be preferred over left-dispatch of a base class.

    # Case 1: subclass of int; this tests code in abstract.c::binary_op1()

    class B(int):
3876 3877 3878 3879
        def __floordiv__(self, other):
            return "B.__floordiv__"
        def __rfloordiv__(self, other):
            return "B.__rfloordiv__"
3880

3881 3882
    vereq(B(1) // 1, "B.__floordiv__")
    vereq(1 // B(1), "B.__rfloordiv__")
3883 3884 3885 3886

    # Case 2: subclass of object; this is just the baseline for case 3

    class C(object):
3887 3888 3889 3890
        def __floordiv__(self, other):
            return "C.__floordiv__"
        def __rfloordiv__(self, other):
            return "C.__rfloordiv__"
3891

3892 3893
    vereq(C() // 1, "C.__floordiv__")
    vereq(1 // C(), "C.__rfloordiv__")
3894 3895 3896 3897

    # Case 3: subclass of new-style class; here it gets interesting

    class D(C):
3898 3899 3900 3901
        def __floordiv__(self, other):
            return "D.__floordiv__"
        def __rfloordiv__(self, other):
            return "D.__rfloordiv__"
3902

3903 3904
    vereq(D() // C(), "D.__floordiv__")
    vereq(C() // D(), "D.__rfloordiv__")
3905 3906 3907 3908 3909 3910

    # Case 4: this didn't work right in 2.2.2 and 2.3a1

    class E(C):
        pass

3911
    vereq(E.__rfloordiv__, C.__rfloordiv__)
3912

3913 3914 3915 3916
    vereq(E() // 1, "C.__floordiv__")
    vereq(1 // E(), "C.__rfloordiv__")
    vereq(E() // C(), "C.__floordiv__")
    vereq(C() // E(), "C.__floordiv__") # This one would fail
3917

3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930
def dict_type_with_metaclass():
    if verbose:
        print "Testing type of __dict__ when __metaclass__ set..."

    class B(object):
        pass
    class M(type):
        pass
    class C:
        # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
        __metaclass__ = M
    veris(type(C.__dict__), type(B.__dict__))

3931 3932
def meth_class_get():
    # Full coverage of descrobject.c::classmethod_get()
3933 3934
    if verbose:
        print "Testing __get__ method of METH_CLASS C methods..."
3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970
    # Baseline
    arg = [1, 2, 3]
    res = {1: None, 2: None, 3: None}
    vereq(dict.fromkeys(arg), res)
    vereq({}.fromkeys(arg), res)
    # Now get the descriptor
    descr = dict.__dict__["fromkeys"]
    # More baseline using the descriptor directly
    vereq(descr.__get__(None, dict)(arg), res)
    vereq(descr.__get__({})(arg), res)
    # Now check various error cases
    try:
        descr.__get__(None, None)
    except TypeError:
        pass
    else:
        raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
    try:
        descr.__get__(42)
    except TypeError:
        pass
    else:
        raise TestFailed, "shouldn't have allowed descr.__get__(42)"
    try:
        descr.__get__(None, 42)
    except TypeError:
        pass
    else:
        raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
    try:
        descr.__get__(None, int)
    except TypeError:
        pass
    else:
        raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"

3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988
def isinst_isclass():
    if verbose:
        print "Testing proxy isinstance() and isclass()..."
    class Proxy(object):
        def __init__(self, obj):
            self.__obj = obj
        def __getattribute__(self, name):
            if name.startswith("_Proxy__"):
                return object.__getattribute__(self, name)
            else:
                return getattr(self.__obj, name)
    # Test with a classic class
    class C:
        pass
    a = C()
    pa = Proxy(a)
    verify(isinstance(a, C))  # Baseline
    verify(isinstance(pa, C)) # Test
3989 3990 3991 3992 3993 3994 3995
    # Test with a classic subclass
    class D(C):
        pass
    a = D()
    pa = Proxy(a)
    verify(isinstance(a, C))  # Baseline
    verify(isinstance(pa, C)) # Test
3996 3997 3998 3999 4000 4001 4002
    # Test with a new-style class
    class C(object):
        pass
    a = C()
    pa = Proxy(a)
    verify(isinstance(a, C))  # Baseline
    verify(isinstance(pa, C)) # Test
4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033
    # Test with a new-style subclass
    class D(C):
        pass
    a = D()
    pa = Proxy(a)
    verify(isinstance(a, C))  # Baseline
    verify(isinstance(pa, C)) # Test

def proxysuper():
    if verbose:
        print "Testing super() for a proxy object..."
    class Proxy(object):
        def __init__(self, obj):
            self.__obj = obj
        def __getattribute__(self, name):
            if name.startswith("_Proxy__"):
                return object.__getattribute__(self, name)
            else:
                return getattr(self.__obj, name)

    class B(object):
        def f(self):
            return "B.f"

    class C(B):
        def f(self):
            return super(C, self).f() + "->C.f"

    obj = C()
    p = Proxy(obj)
    vereq(C.__dict__["f"](p), "B.f->C.f")
4034

4035
def carloverre():
4036
    if verbose:
4037
        print "Testing prohibition of Carlo Verre's hack..."
4038 4039 4040 4041 4042
    try:
        object.__setattr__(str, "foo", 42)
    except TypeError:
        pass
    else:
4043
        raise TestFailed, "Carlo Verre __setattr__ suceeded!"
4044 4045 4046 4047 4048
    try:
        object.__delattr__(str, "lower")
    except TypeError:
        pass
    else:
4049
        raise TestFailed, "Carlo Verre __delattr__ succeeded!"
4050

Guido van Rossum's avatar
Guido van Rossum committed
4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071
def weakref_segfault():
    # SF 742911
    if verbose:
        print "Testing weakref segfault..."

    import weakref

    class Provoker:
        def __init__(self, referrent):
            self.ref = weakref.ref(referrent)

        def __del__(self):
            x = self.ref()

    class Oops(object):
        pass

    o = Oops()
    o.whatever = Provoker(o)
    del o

4072 4073 4074 4075 4076 4077 4078
def wrapper_segfault():
    # SF 927248: deeply nested wrappers could cause stack overflow
    f = lambda:None
    for i in xrange(1000000):
        f = f.__call__
    f = None

4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092
# Fix SF #762455, segfault when sys.stdout is changed in getattr
def filefault():
    if verbose:
        print "Testing sys.stdout is changed in getattr..."
    import sys
    class StdoutGuard:
        def __getattr__(self, attr):
            sys.stdout = sys.__stdout__
            raise RuntimeError("Premature access to sys.stdout.%s" % attr)
    sys.stdout = StdoutGuard()
    try:
        print "Oops!"
    except RuntimeError:
        pass
Michael W. Hudson's avatar
Michael W. Hudson committed
4093

Michael W. Hudson's avatar
Fix for  
Michael W. Hudson committed
4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121
def vicious_descriptor_nonsense():
    # A potential segfault spotted by Thomas Wouters in mail to
    # python-dev 2003-04-17, turned into an example & fixed by Michael
    # Hudson just less than four months later...
    if verbose:
        print "Testing vicious_descriptor_nonsense..."

    class Evil(object):
        def __hash__(self):
            return hash('attr')
        def __eq__(self, other):
            del C.attr
            return 0

    class Descr(object):
        def __get__(self, ob, type=None):
            return 1

    class C(object):
        attr = Descr()

    c = C()
    c.__dict__[Evil()] = 0

    vereq(c.attr, 1)
    # this makes a crash more likely:
    import gc; gc.collect()
    vereq(hasattr(c, 'attr'), False)
Tim Peters's avatar
Tim Peters committed
4122

4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134
def test_init():
    # SF 1155938
    class Foo(object):
        def __init__(self):
            return 10
    try:
        Foo()
    except TypeError:
        pass
    else:
        raise TestFailed, "did not test __init__() for None return"

4135 4136 4137 4138 4139 4140 4141
def methodwrapper():
    # <type 'method-wrapper'> did not support any reflection before 2.5
    if verbose:
        print "Testing method-wrapper objects..."

    l = []
    vereq(l.__add__, l.__add__)
Armin Rigo's avatar
Armin Rigo committed
4142 4143 4144
    vereq(l.__add__, [].__add__)
    verify(l.__add__ != [5].__add__)
    verify(l.__add__ != l.__mul__)
4145 4146 4147 4148
    verify(l.__add__.__name__ == '__add__')
    verify(l.__add__.__self__ is l)
    verify(l.__add__.__objclass__ is list)
    vereq(l.__add__.__doc__, list.__add__.__doc__)
Armin Rigo's avatar
Armin Rigo committed
4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159
    try:
        hash(l.__add__)
    except TypeError:
        pass
    else:
        raise TestFailed("no TypeError from hash([].__add__)")

    t = ()
    t += (7,)
    vereq(t.__add__, (7,).__add__)
    vereq(hash(t.__add__), hash((7,).__add__))
Michael W. Hudson's avatar
Fix for  
Michael W. Hudson committed
4160

Armin Rigo's avatar
Armin Rigo committed
4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231
def notimplemented():
    # all binary methods should be able to return a NotImplemented
    if verbose:
        print "Testing NotImplemented..."

    import sys
    import types
    import operator

    def specialmethod(self, other):
        return NotImplemented

    def check(expr, x, y):
        try:
            exec expr in {'x': x, 'y': y, 'operator': operator}
        except TypeError:
            pass
        else:
            raise TestFailed("no TypeError from %r" % (expr,))

    N1 = sys.maxint + 1L    # might trigger OverflowErrors instead of TypeErrors
    N2 = sys.maxint         # if sizeof(int) < sizeof(long), might trigger
                            #   ValueErrors instead of TypeErrors
    for metaclass in [type, types.ClassType]:
        for name, expr, iexpr in [
                ('__add__',      'x + y',                   'x += y'),
                ('__sub__',      'x - y',                   'x -= y'),
                ('__mul__',      'x * y',                   'x *= y'),
                ('__truediv__',  'operator.truediv(x, y)',  None),
                ('__floordiv__', 'operator.floordiv(x, y)', None),
                ('__div__',      'x / y',                   'x /= y'),
                ('__mod__',      'x % y',                   'x %= y'),
                ('__divmod__',   'divmod(x, y)',            None),
                ('__pow__',      'x ** y',                  'x **= y'),
                ('__lshift__',   'x << y',                  'x <<= y'),
                ('__rshift__',   'x >> y',                  'x >>= y'),
                ('__and__',      'x & y',                   'x &= y'),
                ('__or__',       'x | y',                   'x |= y'),
                ('__xor__',      'x ^ y',                   'x ^= y'),
                ('__coerce__',   'coerce(x, y)',            None)]:
            if name == '__coerce__':
                rname = name
            else:
                rname = '__r' + name[2:]
            A = metaclass('A', (), {name: specialmethod})
            B = metaclass('B', (), {rname: specialmethod})
            a = A()
            b = B()
            check(expr, a, a)
            check(expr, a, b)
            check(expr, b, a)
            check(expr, b, b)
            check(expr, a, N1)
            check(expr, a, N2)
            check(expr, N1, b)
            check(expr, N2, b)
            if iexpr:
                check(iexpr, a, a)
                check(iexpr, a, b)
                check(iexpr, b, a)
                check(iexpr, b, b)
                check(iexpr, a, N1)
                check(iexpr, a, N2)
                iname = '__i' + name[2:]
                C = metaclass('C', (), {iname: specialmethod})
                c = C()
                check(iexpr, c, a)
                check(iexpr, c, b)
                check(iexpr, c, N1)
                check(iexpr, c, N2)

4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244
def test_assign_slice():
    # ceval.c's assign_slice used to check for
    # tp->tp_as_sequence->sq_slice instead of
    # tp->tp_as_sequence->sq_ass_slice

    class C(object):
        def __setslice__(self, start, stop, value):
            self.value = value

    c = C()
    c[1:2] = 3
    vereq(c.value, 3)

4245
def test_main():
Guido van Rossum's avatar
Guido van Rossum committed
4246
    weakref_segfault() # Must be first, somehow
4247
    wrapper_segfault()
4248
    do_this_first()
4249
    class_docstrings()
4250 4251
    lists()
    dicts()
4252
    dict_constructor()
4253
    test_dir()
4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264
    ints()
    longs()
    floats()
    complexes()
    spamlists()
    spamdicts()
    pydicts()
    pylists()
    metaclass()
    pymods()
    multi()
4265
    mro_disagreement()
4266
    diamond()
4267 4268 4269
    ex5()
    monotonicity()
    consistency_with_epg()
4270
    objects()
4271
    slots()
4272
    slotspecials()
4273 4274
    dynamics()
    classmethods()
4275
    classmethods_in_c()
4276
    staticmethods()
4277
    staticmethods_in_c()
4278 4279 4280 4281 4282
    classic()
    compattr()
    newslot()
    altmro()
    overloading()
4283
    methods()
4284
    specials()
4285
    weakrefs()
4286
    properties()
Guido van Rossum's avatar
Guido van Rossum committed
4287
    supers()
4288
    inherits()
4289
    keywords()
4290
    restricted()
4291
    str_subclass_as_dict_key()
4292
    classic_comparisons()
4293
    rich_comparisons()
4294
    coercions()
4295
    descrdoc()
4296
    setclass()
4297
    setdict()
4298
    pickles()
4299
    copies()
4300
    binopoverride()
4301
    subclasspropagation()
4302
    buffer_inherit()
4303
    str_of_str_subclass()
4304
    kwdargs()
4305
    recursive__call__()
4306
    delhook()
4307
    hashinherit()
4308
    strops()
4309
    deepcopyrecursive()
4310
    modules()
4311 4312 4313
    dictproxyiterkeys()
    dictproxyitervalues()
    dictproxyiteritems()
4314
    pickleslots()
4315
    funnynew()
Guido van Rossum's avatar
Guido van Rossum committed
4316
    imulbug()
Guido van Rossum's avatar
Guido van Rossum committed
4317
    docdescriptor()
4318
    copy_setstate()
4319
    slices()
4320
    subtype_resurrection()
4321
    slottrash()
4322
    slotmultipleinheritance()
4323
    testrmul()
4324
    testipow()
4325 4326 4327
    test_mutable_bases()
    test_mutable_bases_with_failing_mro()
    test_mutable_bases_catch_mro_conflict()
Michael W. Hudson's avatar
Michael W. Hudson committed
4328
    mutable_names()
4329
    subclass_right_op()
4330
    dict_type_with_metaclass()
4331
    meth_class_get()
4332
    isinst_isclass()
4333
    proxysuper()
4334
    carloverre()
4335
    filefault()
Michael W. Hudson's avatar
Fix for  
Michael W. Hudson committed
4336
    vicious_descriptor_nonsense()
4337
    test_init()
4338
    methodwrapper()
Armin Rigo's avatar
Armin Rigo committed
4339
    notimplemented()
4340
    test_assign_slice()
4341

4342 4343 4344
    from test import test_descr
    run_doctest(test_descr, verbosity=True)

4345
    if verbose: print "All OK"
4346

4347 4348
if __name__ == "__main__":
    test_main()