1import __builtin__
2import gc
3import sys
4import types
5import unittest
6import weakref
7
8from copy import deepcopy
9from test import test_support
10
11
12class OperatorsTest(unittest.TestCase):
13
14    def __init__(self, *args, **kwargs):
15        unittest.TestCase.__init__(self, *args, **kwargs)
16        self.binops = {
17            'add': '+',
18            'sub': '-',
19            'mul': '*',
20            'div': '/',
21            'divmod': 'divmod',
22            'pow': '**',
23            'lshift': '<<',
24            'rshift': '>>',
25            'and': '&',
26            'xor': '^',
27            'or': '|',
28            'cmp': 'cmp',
29            'lt': '<',
30            'le': '<=',
31            'eq': '==',
32            'ne': '!=',
33            'gt': '>',
34            'ge': '>=',
35        }
36
37        for name, expr in self.binops.items():
38            if expr.islower():
39                expr = expr + "(a, b)"
40            else:
41                expr = 'a %s b' % expr
42            self.binops[name] = expr
43
44        self.unops = {
45            'pos': '+',
46            'neg': '-',
47            'abs': 'abs',
48            'invert': '~',
49            'int': 'int',
50            'long': 'long',
51            'float': 'float',
52            'oct': 'oct',
53            'hex': 'hex',
54        }
55
56        for name, expr in self.unops.items():
57            if expr.islower():
58                expr = expr + "(a)"
59            else:
60                expr = '%s a' % expr
61            self.unops[name] = expr
62
63    def unop_test(self, a, res, expr="len(a)", meth="__len__"):
64        d = {'a': a}
65        self.assertEqual(eval(expr, d), res)
66        t = type(a)
67        m = getattr(t, meth)
68
69        # Find method in parent class
70        while meth not in t.__dict__:
71            t = t.__bases__[0]
72        # in some implementations (e.g. PyPy), 'm' can be a regular unbound
73        # method object; the getattr() below obtains its underlying function.
74        self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
75        self.assertEqual(m(a), res)
76        bm = getattr(a, meth)
77        self.assertEqual(bm(), res)
78
79    def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
80        d = {'a': a, 'b': b}
81
82        # XXX Hack so this passes before 2.3 when -Qnew is specified.
83        if meth == "__div__" and 1/2 == 0.5:
84            meth = "__truediv__"
85
86        if meth == '__divmod__': pass
87
88        self.assertEqual(eval(expr, d), res)
89        t = type(a)
90        m = getattr(t, meth)
91        while meth not in t.__dict__:
92            t = t.__bases__[0]
93        # in some implementations (e.g. PyPy), 'm' can be a regular unbound
94        # method object; the getattr() below obtains its underlying function.
95        self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
96        self.assertEqual(m(a, b), res)
97        bm = getattr(a, meth)
98        self.assertEqual(bm(b), res)
99
100    def ternop_test(self, a, b, c, res, expr="a[b:c]", meth="__getslice__"):
101        d = {'a': a, 'b': b, 'c': c}
102        self.assertEqual(eval(expr, d), res)
103        t = type(a)
104        m = getattr(t, meth)
105        while meth not in t.__dict__:
106            t = t.__bases__[0]
107        # in some implementations (e.g. PyPy), 'm' can be a regular unbound
108        # method object; the getattr() below obtains its underlying function.
109        self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
110        self.assertEqual(m(a, b, c), res)
111        bm = getattr(a, meth)
112        self.assertEqual(bm(b, c), res)
113
114    def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
115        d = {'a': deepcopy(a), 'b': b}
116        exec stmt in d
117        self.assertEqual(d['a'], res)
118        t = type(a)
119        m = getattr(t, meth)
120        while meth not in t.__dict__:
121            t = t.__bases__[0]
122        # in some implementations (e.g. PyPy), 'm' can be a regular unbound
123        # method object; the getattr() below obtains its underlying function.
124        self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
125        d['a'] = deepcopy(a)
126        m(d['a'], b)
127        self.assertEqual(d['a'], res)
128        d['a'] = deepcopy(a)
129        bm = getattr(d['a'], meth)
130        bm(b)
131        self.assertEqual(d['a'], res)
132
133    def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
134        d = {'a': deepcopy(a), 'b': b, 'c': c}
135        exec stmt in d
136        self.assertEqual(d['a'], res)
137        t = type(a)
138        m = getattr(t, meth)
139        while meth not in t.__dict__:
140            t = t.__bases__[0]
141        # in some implementations (e.g. PyPy), 'm' can be a regular unbound
142        # method object; the getattr() below obtains its underlying function.
143        self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
144        d['a'] = deepcopy(a)
145        m(d['a'], b, c)
146        self.assertEqual(d['a'], res)
147        d['a'] = deepcopy(a)
148        bm = getattr(d['a'], meth)
149        bm(b, c)
150        self.assertEqual(d['a'], res)
151
152    def set3op_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
153        dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
154        exec stmt in dictionary
155        self.assertEqual(dictionary['a'], res)
156        t = type(a)
157        while meth not in t.__dict__:
158            t = t.__bases__[0]
159        m = getattr(t, meth)
160        # in some implementations (e.g. PyPy), 'm' can be a regular unbound
161        # method object; the getattr() below obtains its underlying function.
162        self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
163        dictionary['a'] = deepcopy(a)
164        m(dictionary['a'], b, c, d)
165        self.assertEqual(dictionary['a'], res)
166        dictionary['a'] = deepcopy(a)
167        bm = getattr(dictionary['a'], meth)
168        bm(b, c, d)
169        self.assertEqual(dictionary['a'], res)
170
171    def test_lists(self):
172        # Testing list operations...
173        # Asserts are within individual test methods
174        self.binop_test([1], [2], [1,2], "a+b", "__add__")
175        self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
176        self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
177        self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
178        self.ternop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
179        self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
180        self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
181        self.unop_test([1,2,3], 3, "len(a)", "__len__")
182        self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
183        self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
184        self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
185        self.set3op_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
186                        "__setslice__")
187
188    def test_dicts(self):
189        # Testing dict operations...
190        if hasattr(dict, '__cmp__'):   # PyPy has only rich comparison on dicts
191            self.binop_test({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
192        else:
193            self.binop_test({1:2}, {2:1}, True, "a < b", "__lt__")
194        self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
195        self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
196        self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
197
198        d = {1:2, 3:4}
199        l1 = []
200        for i in d.keys():
201            l1.append(i)
202        l = []
203        for i in iter(d):
204            l.append(i)
205        self.assertEqual(l, l1)
206        l = []
207        for i in d.__iter__():
208            l.append(i)
209        self.assertEqual(l, l1)
210        l = []
211        for i in dict.__iter__(d):
212            l.append(i)
213        self.assertEqual(l, l1)
214        d = {1:2, 3:4}
215        self.unop_test(d, 2, "len(a)", "__len__")
216        self.assertEqual(eval(repr(d), {}), d)
217        self.assertEqual(eval(d.__repr__(), {}), d)
218        self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
219                        "__setitem__")
220
221    # Tests for unary and binary operators
222    def number_operators(self, a, b, skip=[]):
223        dict = {'a': a, 'b': b}
224
225        for name, expr in self.binops.items():
226            if name not in skip:
227                name = "__%s__" % name
228                if hasattr(a, name):
229                    res = eval(expr, dict)
230                    self.binop_test(a, b, res, expr, name)
231
232        for name, expr in self.unops.items():
233            if name not in skip:
234                name = "__%s__" % name
235                if hasattr(a, name):
236                    res = eval(expr, dict)
237                    self.unop_test(a, res, expr, name)
238
239    def test_ints(self):
240        # Testing int operations...
241        self.number_operators(100, 3)
242        # The following crashes in Python 2.2
243        self.assertEqual((1).__nonzero__(), 1)
244        self.assertEqual((0).__nonzero__(), 0)
245        # This returns 'NotImplemented' in Python 2.2
246        class C(int):
247            def __add__(self, other):
248                return NotImplemented
249        self.assertEqual(C(5L), 5)
250        try:
251            C() + ""
252        except TypeError:
253            pass
254        else:
255            self.fail("NotImplemented should have caused TypeError")
256        try:
257            C(sys.maxint+1)
258        except OverflowError:
259            pass
260        else:
261            self.fail("should have raised OverflowError")
262
263    def test_longs(self):
264        # Testing long operations...
265        self.number_operators(100L, 3L)
266
267    def test_floats(self):
268        # Testing float operations...
269        self.number_operators(100.0, 3.0)
270
271    def test_complexes(self):
272        # Testing complex operations...
273        self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
274                                                  'int', 'long', 'float'])
275
276        class Number(complex):
277            __slots__ = ['prec']
278            def __new__(cls, *args, **kwds):
279                result = complex.__new__(cls, *args)
280                result.prec = kwds.get('prec', 12)
281                return result
282            def __repr__(self):
283                prec = self.prec
284                if self.imag == 0.0:
285                    return "%.*g" % (prec, self.real)
286                if self.real == 0.0:
287                    return "%.*gj" % (prec, self.imag)
288                return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
289            __str__ = __repr__
290
291        a = Number(3.14, prec=6)
292        self.assertEqual(repr(a), "3.14")
293        self.assertEqual(a.prec, 6)
294
295        a = Number(a, prec=2)
296        self.assertEqual(repr(a), "3.1")
297        self.assertEqual(a.prec, 2)
298
299        a = Number(234.5)
300        self.assertEqual(repr(a), "234.5")
301        self.assertEqual(a.prec, 12)
302
303    @test_support.impl_detail("the module 'xxsubtype' is internal")
304    def test_spam_lists(self):
305        # Testing spamlist operations...
306        import copy, xxsubtype as spam
307
308        def spamlist(l, memo=None):
309            import xxsubtype as spam
310            return spam.spamlist(l)
311
312        # This is an ugly hack:
313        copy._deepcopy_dispatch[spam.spamlist] = spamlist
314
315        self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
316                       "__add__")
317        self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
318        self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
319        self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
320        self.ternop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
321                        "__getslice__")
322        self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
323                       "__iadd__")
324        self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
325                       "__imul__")
326        self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
327        self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
328                       "__mul__")
329        self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
330                       "__rmul__")
331        self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
332                        "__setitem__")
333        self.set3op_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
334                   spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
335        # Test subclassing
336        class C(spam.spamlist):
337            def foo(self): return 1
338        a = C()
339        self.assertEqual(a, [])
340        self.assertEqual(a.foo(), 1)
341        a.append(100)
342        self.assertEqual(a, [100])
343        self.assertEqual(a.getstate(), 0)
344        a.setstate(42)
345        self.assertEqual(a.getstate(), 42)
346
347    @test_support.impl_detail("the module 'xxsubtype' is internal")
348    def test_spam_dicts(self):
349        # Testing spamdict operations...
350        import copy, xxsubtype as spam
351        def spamdict(d, memo=None):
352            import xxsubtype as spam
353            sd = spam.spamdict()
354            for k, v in d.items():
355                sd[k] = v
356            return sd
357        # This is an ugly hack:
358        copy._deepcopy_dispatch[spam.spamdict] = spamdict
359
360        self.binop_test(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)",
361                       "__cmp__")
362        self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
363        self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
364        self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
365        d = spamdict({1:2,3:4})
366        l1 = []
367        for i in d.keys():
368            l1.append(i)
369        l = []
370        for i in iter(d):
371            l.append(i)
372        self.assertEqual(l, l1)
373        l = []
374        for i in d.__iter__():
375            l.append(i)
376        self.assertEqual(l, l1)
377        l = []
378        for i in type(spamdict({})).__iter__(d):
379            l.append(i)
380        self.assertEqual(l, l1)
381        straightd = {1:2, 3:4}
382        spamd = spamdict(straightd)
383        self.unop_test(spamd, 2, "len(a)", "__len__")
384        self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
385        self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
386                   "a[b]=c", "__setitem__")
387        # Test subclassing
388        class C(spam.spamdict):
389            def foo(self): return 1
390        a = C()
391        self.assertEqual(a.items(), [])
392        self.assertEqual(a.foo(), 1)
393        a['foo'] = 'bar'
394        self.assertEqual(a.items(), [('foo', 'bar')])
395        self.assertEqual(a.getstate(), 0)
396        a.setstate(100)
397        self.assertEqual(a.getstate(), 100)
398
399class ClassPropertiesAndMethods(unittest.TestCase):
400
401    def test_python_dicts(self):
402        # Testing Python subclass of dict...
403        self.assertTrue(issubclass(dict, dict))
404        self.assertIsInstance({}, dict)
405        d = dict()
406        self.assertEqual(d, {})
407        self.assertTrue(d.__class__ is dict)
408        self.assertIsInstance(d, dict)
409        class C(dict):
410            state = -1
411            def __init__(self_local, *a, **kw):
412                if a:
413                    self.assertEqual(len(a), 1)
414                    self_local.state = a[0]
415                if kw:
416                    for k, v in kw.items():
417                        self_local[v] = k
418            def __getitem__(self, key):
419                return self.get(key, 0)
420            def __setitem__(self_local, key, value):
421                self.assertIsInstance(key, type(0))
422                dict.__setitem__(self_local, key, value)
423            def setstate(self, state):
424                self.state = state
425            def getstate(self):
426                return self.state
427        self.assertTrue(issubclass(C, dict))
428        a1 = C(12)
429        self.assertEqual(a1.state, 12)
430        a2 = C(foo=1, bar=2)
431        self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
432        a = C()
433        self.assertEqual(a.state, -1)
434        self.assertEqual(a.getstate(), -1)
435        a.setstate(0)
436        self.assertEqual(a.state, 0)
437        self.assertEqual(a.getstate(), 0)
438        a.setstate(10)
439        self.assertEqual(a.state, 10)
440        self.assertEqual(a.getstate(), 10)
441        self.assertEqual(a[42], 0)
442        a[42] = 24
443        self.assertEqual(a[42], 24)
444        N = 50
445        for i in range(N):
446            a[i] = C()
447            for j in range(N):
448                a[i][j] = i*j
449        for i in range(N):
450            for j in range(N):
451                self.assertEqual(a[i][j], i*j)
452
453    def test_python_lists(self):
454        # Testing Python subclass of list...
455        class C(list):
456            def __getitem__(self, i):
457                return list.__getitem__(self, i) + 100
458            def __getslice__(self, i, j):
459                return (i, j)
460        a = C()
461        a.extend([0,1,2])
462        self.assertEqual(a[0], 100)
463        self.assertEqual(a[1], 101)
464        self.assertEqual(a[2], 102)
465        self.assertEqual(a[100:200], (100,200))
466
467    def test_metaclass(self):
468        # Testing __metaclass__...
469        class C:
470            __metaclass__ = type
471            def __init__(self):
472                self.__state = 0
473            def getstate(self):
474                return self.__state
475            def setstate(self, state):
476                self.__state = state
477        a = C()
478        self.assertEqual(a.getstate(), 0)
479        a.setstate(10)
480        self.assertEqual(a.getstate(), 10)
481        class D:
482            class __metaclass__(type):
483                def myself(cls): return cls
484        self.assertEqual(D.myself(), D)
485        d = D()
486        self.assertEqual(d.__class__, D)
487        class M1(type):
488            def __new__(cls, name, bases, dict):
489                dict['__spam__'] = 1
490                return type.__new__(cls, name, bases, dict)
491        class C:
492            __metaclass__ = M1
493        self.assertEqual(C.__spam__, 1)
494        c = C()
495        self.assertEqual(c.__spam__, 1)
496
497        class _instance(object):
498            pass
499        class M2(object):
500            @staticmethod
501            def __new__(cls, name, bases, dict):
502                self = object.__new__(cls)
503                self.name = name
504                self.bases = bases
505                self.dict = dict
506                return self
507            def __call__(self):
508                it = _instance()
509                # Early binding of methods
510                for key in self.dict:
511                    if key.startswith("__"):
512                        continue
513                    setattr(it, key, self.dict[key].__get__(it, self))
514                return it
515        class C:
516            __metaclass__ = M2
517            def spam(self):
518                return 42
519        self.assertEqual(C.name, 'C')
520        self.assertEqual(C.bases, ())
521        self.assertIn('spam', C.dict)
522        c = C()
523        self.assertEqual(c.spam(), 42)
524
525        # More metaclass examples
526
527        class autosuper(type):
528            # Automatically add __super to the class
529            # This trick only works for dynamic classes
530            def __new__(metaclass, name, bases, dict):
531                cls = super(autosuper, metaclass).__new__(metaclass,
532                                                          name, bases, dict)
533                # Name mangling for __super removes leading underscores
534                while name[:1] == "_":
535                    name = name[1:]
536                if name:
537                    name = "_%s__super" % name
538                else:
539                    name = "__super"
540                setattr(cls, name, super(cls))
541                return cls
542        class A:
543            __metaclass__ = autosuper
544            def meth(self):
545                return "A"
546        class B(A):
547            def meth(self):
548                return "B" + self.__super.meth()
549        class C(A):
550            def meth(self):
551                return "C" + self.__super.meth()
552        class D(C, B):
553            def meth(self):
554                return "D" + self.__super.meth()
555        self.assertEqual(D().meth(), "DCBA")
556        class E(B, C):
557            def meth(self):
558                return "E" + self.__super.meth()
559        self.assertEqual(E().meth(), "EBCA")
560
561        class autoproperty(type):
562            # Automatically create property attributes when methods
563            # named _get_x and/or _set_x are found
564            def __new__(metaclass, name, bases, dict):
565                hits = {}
566                for key, val in dict.iteritems():
567                    if key.startswith("_get_"):
568                        key = key[5:]
569                        get, set = hits.get(key, (None, None))
570                        get = val
571                        hits[key] = get, set
572                    elif key.startswith("_set_"):
573                        key = key[5:]
574                        get, set = hits.get(key, (None, None))
575                        set = val
576                        hits[key] = get, set
577                for key, (get, set) in hits.iteritems():
578                    dict[key] = property(get, set)
579                return super(autoproperty, metaclass).__new__(metaclass,
580                                                            name, bases, dict)
581        class A:
582            __metaclass__ = autoproperty
583            def _get_x(self):
584                return -self.__x
585            def _set_x(self, x):
586                self.__x = -x
587        a = A()
588        self.assertTrue(not hasattr(a, "x"))
589        a.x = 12
590        self.assertEqual(a.x, 12)
591        self.assertEqual(a._A__x, -12)
592
593        class multimetaclass(autoproperty, autosuper):
594            # Merge of multiple cooperating metaclasses
595            pass
596        class A:
597            __metaclass__ = multimetaclass
598            def _get_x(self):
599                return "A"
600        class B(A):
601            def _get_x(self):
602                return "B" + self.__super._get_x()
603        class C(A):
604            def _get_x(self):
605                return "C" + self.__super._get_x()
606        class D(C, B):
607            def _get_x(self):
608                return "D" + self.__super._get_x()
609        self.assertEqual(D().x, "DCBA")
610
611        # Make sure type(x) doesn't call x.__class__.__init__
612        class T(type):
613            counter = 0
614            def __init__(self, *args):
615                T.counter += 1
616        class C:
617            __metaclass__ = T
618        self.assertEqual(T.counter, 1)
619        a = C()
620        self.assertEqual(type(a), C)
621        self.assertEqual(T.counter, 1)
622
623        class C(object): pass
624        c = C()
625        try: c()
626        except TypeError: pass
627        else: self.fail("calling object w/o call method should raise "
628                        "TypeError")
629
630        # Testing code to find most derived baseclass
631        class A(type):
632            def __new__(*args, **kwargs):
633                return type.__new__(*args, **kwargs)
634
635        class B(object):
636            pass
637
638        class C(object):
639            __metaclass__ = A
640
641        # The most derived metaclass of D is A rather than type.
642        class D(B, C):
643            pass
644
645    def test_module_subclasses(self):
646        # Testing Python subclass of module...
647        log = []
648        MT = type(sys)
649        class MM(MT):
650            def __init__(self, name):
651                MT.__init__(self, name)
652            def __getattribute__(self, name):
653                log.append(("getattr", name))
654                return MT.__getattribute__(self, name)
655            def __setattr__(self, name, value):
656                log.append(("setattr", name, value))
657                MT.__setattr__(self, name, value)
658            def __delattr__(self, name):
659                log.append(("delattr", name))
660                MT.__delattr__(self, name)
661        a = MM("a")
662        a.foo = 12
663        x = a.foo
664        del a.foo
665        self.assertEqual(log, [("setattr", "foo", 12),
666                               ("getattr", "foo"),
667                               ("delattr", "foo")])
668
669        # http://python.org/sf/1174712
670        try:
671            class Module(types.ModuleType, str):
672                pass
673        except TypeError:
674            pass
675        else:
676            self.fail("inheriting from ModuleType and str at the same time "
677                      "should fail")
678
679    def test_multiple_inheritence(self):
680        # Testing multiple inheritance...
681        class C(object):
682            def __init__(self):
683                self.__state = 0
684            def getstate(self):
685                return self.__state
686            def setstate(self, state):
687                self.__state = state
688        a = C()
689        self.assertEqual(a.getstate(), 0)
690        a.setstate(10)
691        self.assertEqual(a.getstate(), 10)
692        class D(dict, C):
693            def __init__(self):
694                type({}).__init__(self)
695                C.__init__(self)
696        d = D()
697        self.assertEqual(d.keys(), [])
698        d["hello"] = "world"
699        self.assertEqual(d.items(), [("hello", "world")])
700        self.assertEqual(d["hello"], "world")
701        self.assertEqual(d.getstate(), 0)
702        d.setstate(10)
703        self.assertEqual(d.getstate(), 10)
704        self.assertEqual(D.__mro__, (D, dict, C, object))
705
706        # SF bug #442833
707        class Node(object):
708            def __int__(self):
709                return int(self.foo())
710            def foo(self):
711                return "23"
712        class Frag(Node, list):
713            def foo(self):
714                return "42"
715        self.assertEqual(Node().__int__(), 23)
716        self.assertEqual(int(Node()), 23)
717        self.assertEqual(Frag().__int__(), 42)
718        self.assertEqual(int(Frag()), 42)
719
720        # MI mixing classic and new-style classes.
721
722        class A:
723            x = 1
724
725        class B(A):
726            pass
727
728        class C(A):
729            x = 2
730
731        class D(B, C):
732            pass
733        self.assertEqual(D.x, 1)
734
735        # Classic MRO is preserved for a classic base class.
736        class E(D, object):
737            pass
738        self.assertEqual(E.__mro__, (E, D, B, A, C, object))
739        self.assertEqual(E.x, 1)
740
741        # But with a mix of classic bases, their MROs are combined using
742        # new-style MRO.
743        class F(B, C, object):
744            pass
745        self.assertEqual(F.__mro__, (F, B, C, A, object))
746        self.assertEqual(F.x, 2)
747
748        # Try something else.
749        class C:
750            def cmethod(self):
751                return "C a"
752            def all_method(self):
753                return "C b"
754
755        class M1(C, object):
756            def m1method(self):
757                return "M1 a"
758            def all_method(self):
759                return "M1 b"
760
761        self.assertEqual(M1.__mro__, (M1, C, object))
762        m = M1()
763        self.assertEqual(m.cmethod(), "C a")
764        self.assertEqual(m.m1method(), "M1 a")
765        self.assertEqual(m.all_method(), "M1 b")
766
767        class D(C):
768            def dmethod(self):
769                return "D a"
770            def all_method(self):
771                return "D b"
772
773        class M2(D, object):
774            def m2method(self):
775                return "M2 a"
776            def all_method(self):
777                return "M2 b"
778
779        self.assertEqual(M2.__mro__, (M2, D, C, object))
780        m = M2()
781        self.assertEqual(m.cmethod(), "C a")
782        self.assertEqual(m.dmethod(), "D a")
783        self.assertEqual(m.m2method(), "M2 a")
784        self.assertEqual(m.all_method(), "M2 b")
785
786        class M3(M1, M2, object):
787            def m3method(self):
788                return "M3 a"
789            def all_method(self):
790                return "M3 b"
791        self.assertEqual(M3.__mro__, (M3, M1, M2, D, C, object))
792        m = M3()
793        self.assertEqual(m.cmethod(), "C a")
794        self.assertEqual(m.dmethod(), "D a")
795        self.assertEqual(m.m1method(), "M1 a")
796        self.assertEqual(m.m2method(), "M2 a")
797        self.assertEqual(m.m3method(), "M3 a")
798        self.assertEqual(m.all_method(), "M3 b")
799
800        class Classic:
801            pass
802        try:
803            class New(Classic):
804                __metaclass__ = type
805        except TypeError:
806            pass
807        else:
808            self.fail("new class with only classic bases - shouldn't be")
809
810    def test_diamond_inheritence(self):
811        # Testing multiple inheritance special cases...
812        class A(object):
813            def spam(self): return "A"
814        self.assertEqual(A().spam(), "A")
815        class B(A):
816            def boo(self): return "B"
817            def spam(self): return "B"
818        self.assertEqual(B().spam(), "B")
819        self.assertEqual(B().boo(), "B")
820        class C(A):
821            def boo(self): return "C"
822        self.assertEqual(C().spam(), "A")
823        self.assertEqual(C().boo(), "C")
824        class D(B, C): pass
825        self.assertEqual(D().spam(), "B")
826        self.assertEqual(D().boo(), "B")
827        self.assertEqual(D.__mro__, (D, B, C, A, object))
828        class E(C, B): pass
829        self.assertEqual(E().spam(), "B")
830        self.assertEqual(E().boo(), "C")
831        self.assertEqual(E.__mro__, (E, C, B, A, object))
832        # MRO order disagreement
833        try:
834            class F(D, E): pass
835        except TypeError:
836            pass
837        else:
838            self.fail("expected MRO order disagreement (F)")
839        try:
840            class G(E, D): pass
841        except TypeError:
842            pass
843        else:
844            self.fail("expected MRO order disagreement (G)")
845
846    # see thread python-dev/2002-October/029035.html
847    def test_ex5_from_c3_switch(self):
848        # Testing ex5 from C3 switch discussion...
849        class A(object): pass
850        class B(object): pass
851        class C(object): pass
852        class X(A): pass
853        class Y(A): pass
854        class Z(X,B,Y,C): pass
855        self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
856
857    # see "A Monotonic Superclass Linearization for Dylan",
858    # by Kim Barrett et al. (OOPSLA 1996)
859    def test_monotonicity(self):
860        # Testing MRO monotonicity...
861        class Boat(object): pass
862        class DayBoat(Boat): pass
863        class WheelBoat(Boat): pass
864        class EngineLess(DayBoat): pass
865        class SmallMultihull(DayBoat): pass
866        class PedalWheelBoat(EngineLess,WheelBoat): pass
867        class SmallCatamaran(SmallMultihull): pass
868        class Pedalo(PedalWheelBoat,SmallCatamaran): pass
869
870        self.assertEqual(PedalWheelBoat.__mro__,
871              (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
872        self.assertEqual(SmallCatamaran.__mro__,
873              (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
874        self.assertEqual(Pedalo.__mro__,
875              (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
876               SmallMultihull, DayBoat, WheelBoat, Boat, object))
877
878    # see "A Monotonic Superclass Linearization for Dylan",
879    # by Kim Barrett et al. (OOPSLA 1996)
880    def test_consistency_with_epg(self):
881        # Testing consistency with EPG...
882        class Pane(object): pass
883        class ScrollingMixin(object): pass
884        class EditingMixin(object): pass
885        class ScrollablePane(Pane,ScrollingMixin): pass
886        class EditablePane(Pane,EditingMixin): pass
887        class EditableScrollablePane(ScrollablePane,EditablePane): pass
888
889        self.assertEqual(EditableScrollablePane.__mro__,
890              (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
891                ScrollingMixin, EditingMixin, object))
892
893    def test_mro_disagreement(self):
894        # Testing error messages for MRO disagreement...
895        mro_err_msg = """Cannot create a consistent method resolution
896order (MRO) for bases """
897
898        def raises(exc, expected, callable, *args):
899            try:
900                callable(*args)
901            except exc, msg:
902                # the exact msg is generally considered an impl detail
903                if test_support.check_impl_detail():
904                    if not str(msg).startswith(expected):
905                        self.fail("Message %r, expected %r" %
906                                  (str(msg), expected))
907            else:
908                self.fail("Expected %s" % exc)
909
910        class A(object): pass
911        class B(A): pass
912        class C(object): pass
913
914        # Test some very simple errors
915        raises(TypeError, "duplicate base class A",
916               type, "X", (A, A), {})
917        raises(TypeError, mro_err_msg,
918               type, "X", (A, B), {})
919        raises(TypeError, mro_err_msg,
920               type, "X", (A, C, B), {})
921        # Test a slightly more complex error
922        class GridLayout(object): pass
923        class HorizontalGrid(GridLayout): pass
924        class VerticalGrid(GridLayout): pass
925        class HVGrid(HorizontalGrid, VerticalGrid): pass
926        class VHGrid(VerticalGrid, HorizontalGrid): pass
927        raises(TypeError, mro_err_msg,
928               type, "ConfusedGrid", (HVGrid, VHGrid), {})
929
930    def test_object_class(self):
931        # Testing object class...
932        a = object()
933        self.assertEqual(a.__class__, object)
934        self.assertEqual(type(a), object)
935        b = object()
936        self.assertNotEqual(a, b)
937        self.assertFalse(hasattr(a, "foo"))
938        try:
939            a.foo = 12
940        except (AttributeError, TypeError):
941            pass
942        else:
943            self.fail("object() should not allow setting a foo attribute")
944        self.assertFalse(hasattr(object(), "__dict__"))
945
946        class Cdict(object):
947            pass
948        x = Cdict()
949        self.assertEqual(x.__dict__, {})
950        x.foo = 1
951        self.assertEqual(x.foo, 1)
952        self.assertEqual(x.__dict__, {'foo': 1})
953
954    def test_slots(self):
955        # Testing __slots__...
956        class C0(object):
957            __slots__ = []
958        x = C0()
959        self.assertFalse(hasattr(x, "__dict__"))
960        self.assertFalse(hasattr(x, "foo"))
961
962        class C1(object):
963            __slots__ = ['a']
964        x = C1()
965        self.assertFalse(hasattr(x, "__dict__"))
966        self.assertFalse(hasattr(x, "a"))
967        x.a = 1
968        self.assertEqual(x.a, 1)
969        x.a = None
970        self.assertEqual(x.a, None)
971        del x.a
972        self.assertFalse(hasattr(x, "a"))
973
974        class C3(object):
975            __slots__ = ['a', 'b', 'c']
976        x = C3()
977        self.assertFalse(hasattr(x, "__dict__"))
978        self.assertFalse(hasattr(x, 'a'))
979        self.assertFalse(hasattr(x, 'b'))
980        self.assertFalse(hasattr(x, 'c'))
981        x.a = 1
982        x.b = 2
983        x.c = 3
984        self.assertEqual(x.a, 1)
985        self.assertEqual(x.b, 2)
986        self.assertEqual(x.c, 3)
987
988        class C4(object):
989            """Validate name mangling"""
990            __slots__ = ['__a']
991            def __init__(self, value):
992                self.__a = value
993            def get(self):
994                return self.__a
995        x = C4(5)
996        self.assertFalse(hasattr(x, '__dict__'))
997        self.assertFalse(hasattr(x, '__a'))
998        self.assertEqual(x.get(), 5)
999        try:
1000            x.__a = 6
1001        except AttributeError:
1002            pass
1003        else:
1004            self.fail("Double underscored names not mangled")
1005
1006        # Make sure slot names are proper identifiers
1007        try:
1008            class C(object):
1009                __slots__ = [None]
1010        except TypeError:
1011            pass
1012        else:
1013            self.fail("[None] slots not caught")
1014        try:
1015            class C(object):
1016                __slots__ = ["foo bar"]
1017        except TypeError:
1018            pass
1019        else:
1020            self.fail("['foo bar'] slots not caught")
1021        try:
1022            class C(object):
1023                __slots__ = ["foo\0bar"]
1024        except TypeError:
1025            pass
1026        else:
1027            self.fail("['foo\\0bar'] slots not caught")
1028        try:
1029            class C(object):
1030                __slots__ = ["1"]
1031        except TypeError:
1032            pass
1033        else:
1034            self.fail("['1'] slots not caught")
1035        try:
1036            class C(object):
1037                __slots__ = [""]
1038        except TypeError:
1039            pass
1040        else:
1041            self.fail("[''] slots not caught")
1042        class C(object):
1043            __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1044        # XXX(nnorwitz): was there supposed to be something tested
1045        # from the class above?
1046
1047        # Test a single string is not expanded as a sequence.
1048        class C(object):
1049            __slots__ = "abc"
1050        c = C()
1051        c.abc = 5
1052        self.assertEqual(c.abc, 5)
1053
1054        # Test unicode slot names
1055        try:
1056            unicode
1057        except NameError:
1058            pass
1059        else:
1060            # Test a single unicode string is not expanded as a sequence.
1061            class C(object):
1062                __slots__ = unicode("abc")
1063            c = C()
1064            c.abc = 5
1065            self.assertEqual(c.abc, 5)
1066
1067            # _unicode_to_string used to modify slots in certain circumstances
1068            slots = (unicode("foo"), unicode("bar"))
1069            class C(object):
1070                __slots__ = slots
1071            x = C()
1072            x.foo = 5
1073            self.assertEqual(x.foo, 5)
1074            self.assertEqual(type(slots[0]), unicode)
1075            # this used to leak references
1076            try:
1077                class C(object):
1078                    __slots__ = [unichr(128)]
1079            except (TypeError, UnicodeEncodeError):
1080                pass
1081            else:
1082                self.fail("[unichr(128)] slots not caught")
1083
1084        # Test leaks
1085        class Counted(object):
1086            counter = 0    # counts the number of instances alive
1087            def __init__(self):
1088                Counted.counter += 1
1089            def __del__(self):
1090                Counted.counter -= 1
1091        class C(object):
1092            __slots__ = ['a', 'b', 'c']
1093        x = C()
1094        x.a = Counted()
1095        x.b = Counted()
1096        x.c = Counted()
1097        self.assertEqual(Counted.counter, 3)
1098        del x
1099        test_support.gc_collect()
1100        self.assertEqual(Counted.counter, 0)
1101        class D(C):
1102            pass
1103        x = D()
1104        x.a = Counted()
1105        x.z = Counted()
1106        self.assertEqual(Counted.counter, 2)
1107        del x
1108        test_support.gc_collect()
1109        self.assertEqual(Counted.counter, 0)
1110        class E(D):
1111            __slots__ = ['e']
1112        x = E()
1113        x.a = Counted()
1114        x.z = Counted()
1115        x.e = Counted()
1116        self.assertEqual(Counted.counter, 3)
1117        del x
1118        test_support.gc_collect()
1119        self.assertEqual(Counted.counter, 0)
1120
1121        # Test cyclical leaks [SF bug 519621]
1122        class F(object):
1123            __slots__ = ['a', 'b']
1124        s = F()
1125        s.a = [Counted(), s]
1126        self.assertEqual(Counted.counter, 1)
1127        s = None
1128        test_support.gc_collect()
1129        self.assertEqual(Counted.counter, 0)
1130
1131        # Test lookup leaks [SF bug 572567]
1132        if hasattr(gc, 'get_objects'):
1133            class G(object):
1134                def __cmp__(self, other):
1135                    return 0
1136                __hash__ = None # Silence Py3k warning
1137            g = G()
1138            orig_objects = len(gc.get_objects())
1139            for i in xrange(10):
1140                g==g
1141            new_objects = len(gc.get_objects())
1142            self.assertEqual(orig_objects, new_objects)
1143
1144        class H(object):
1145            __slots__ = ['a', 'b']
1146            def __init__(self):
1147                self.a = 1
1148                self.b = 2
1149            def __del__(self_):
1150                self.assertEqual(self_.a, 1)
1151                self.assertEqual(self_.b, 2)
1152        with test_support.captured_output('stderr') as s:
1153            h = H()
1154            del h
1155        self.assertEqual(s.getvalue(), '')
1156
1157        class X(object):
1158            __slots__ = "a"
1159        with self.assertRaises(AttributeError):
1160            del X().a
1161
1162    def test_slots_special(self):
1163        # Testing __dict__ and __weakref__ in __slots__...
1164        class D(object):
1165            __slots__ = ["__dict__"]
1166        a = D()
1167        self.assertTrue(hasattr(a, "__dict__"))
1168        self.assertFalse(hasattr(a, "__weakref__"))
1169        a.foo = 42
1170        self.assertEqual(a.__dict__, {"foo": 42})
1171
1172        class W(object):
1173            __slots__ = ["__weakref__"]
1174        a = W()
1175        self.assertTrue(hasattr(a, "__weakref__"))
1176        self.assertFalse(hasattr(a, "__dict__"))
1177        try:
1178            a.foo = 42
1179        except AttributeError:
1180            pass
1181        else:
1182            self.fail("shouldn't be allowed to set a.foo")
1183
1184        class C1(W, D):
1185            __slots__ = []
1186        a = C1()
1187        self.assertTrue(hasattr(a, "__dict__"))
1188        self.assertTrue(hasattr(a, "__weakref__"))
1189        a.foo = 42
1190        self.assertEqual(a.__dict__, {"foo": 42})
1191
1192        class C2(D, W):
1193            __slots__ = []
1194        a = C2()
1195        self.assertTrue(hasattr(a, "__dict__"))
1196        self.assertTrue(hasattr(a, "__weakref__"))
1197        a.foo = 42
1198        self.assertEqual(a.__dict__, {"foo": 42})
1199
1200    def test_slots_descriptor(self):
1201        # Issue2115: slot descriptors did not correctly check
1202        # the type of the given object
1203        import abc
1204        class MyABC:
1205            __metaclass__ = abc.ABCMeta
1206            __slots__ = "a"
1207
1208        class Unrelated(object):
1209            pass
1210        MyABC.register(Unrelated)
1211
1212        u = Unrelated()
1213        self.assertIsInstance(u, MyABC)
1214
1215        # This used to crash
1216        self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1217
1218    def test_metaclass_cmp(self):
1219        # See bug 7491.
1220        class M(type):
1221            def __cmp__(self, other):
1222                return -1
1223        class X(object):
1224            __metaclass__ = M
1225        self.assertTrue(X < M)
1226
1227    def test_dynamics(self):
1228        # Testing class attribute propagation...
1229        class D(object):
1230            pass
1231        class E(D):
1232            pass
1233        class F(D):
1234            pass
1235        D.foo = 1
1236        self.assertEqual(D.foo, 1)
1237        # Test that dynamic attributes are inherited
1238        self.assertEqual(E.foo, 1)
1239        self.assertEqual(F.foo, 1)
1240        # Test dynamic instances
1241        class C(object):
1242            pass
1243        a = C()
1244        self.assertFalse(hasattr(a, "foobar"))
1245        C.foobar = 2
1246        self.assertEqual(a.foobar, 2)
1247        C.method = lambda self: 42
1248        self.assertEqual(a.method(), 42)
1249        C.__repr__ = lambda self: "C()"
1250        self.assertEqual(repr(a), "C()")
1251        C.__int__ = lambda self: 100
1252        self.assertEqual(int(a), 100)
1253        self.assertEqual(a.foobar, 2)
1254        self.assertFalse(hasattr(a, "spam"))
1255        def mygetattr(self, name):
1256            if name == "spam":
1257                return "spam"
1258            raise AttributeError
1259        C.__getattr__ = mygetattr
1260        self.assertEqual(a.spam, "spam")
1261        a.new = 12
1262        self.assertEqual(a.new, 12)
1263        def mysetattr(self, name, value):
1264            if name == "spam":
1265                raise AttributeError
1266            return object.__setattr__(self, name, value)
1267        C.__setattr__ = mysetattr
1268        try:
1269            a.spam = "not spam"
1270        except AttributeError:
1271            pass
1272        else:
1273            self.fail("expected AttributeError")
1274        self.assertEqual(a.spam, "spam")
1275        class D(C):
1276            pass
1277        d = D()
1278        d.foo = 1
1279        self.assertEqual(d.foo, 1)
1280
1281        # Test handling of int*seq and seq*int
1282        class I(int):
1283            pass
1284        self.assertEqual("a"*I(2), "aa")
1285        self.assertEqual(I(2)*"a", "aa")
1286        self.assertEqual(2*I(3), 6)
1287        self.assertEqual(I(3)*2, 6)
1288        self.assertEqual(I(3)*I(2), 6)
1289
1290        # Test handling of long*seq and seq*long
1291        class L(long):
1292            pass
1293        self.assertEqual("a"*L(2L), "aa")
1294        self.assertEqual(L(2L)*"a", "aa")
1295        self.assertEqual(2*L(3), 6)
1296        self.assertEqual(L(3)*2, 6)
1297        self.assertEqual(L(3)*L(2), 6)
1298
1299        # Test comparison of classes with dynamic metaclasses
1300        class dynamicmetaclass(type):
1301            pass
1302        class someclass:
1303            __metaclass__ = dynamicmetaclass
1304        self.assertNotEqual(someclass, object)
1305
1306    def test_errors(self):
1307        # Testing errors...
1308        try:
1309            class C(list, dict):
1310                pass
1311        except TypeError:
1312            pass
1313        else:
1314            self.fail("inheritance from both list and dict should be illegal")
1315
1316        try:
1317            class C(object, None):
1318                pass
1319        except TypeError:
1320            pass
1321        else:
1322            self.fail("inheritance from non-type should be illegal")
1323        class Classic:
1324            pass
1325
1326        try:
1327            class C(type(len)):
1328                pass
1329        except TypeError:
1330            pass
1331        else:
1332            self.fail("inheritance from CFunction should be illegal")
1333
1334        try:
1335            class C(object):
1336                __slots__ = 1
1337        except TypeError:
1338            pass
1339        else:
1340            self.fail("__slots__ = 1 should be illegal")
1341
1342        try:
1343            class C(object):
1344                __slots__ = [1]
1345        except TypeError:
1346            pass
1347        else:
1348            self.fail("__slots__ = [1] should be illegal")
1349
1350        class M1(type):
1351            pass
1352        class M2(type):
1353            pass
1354        class A1(object):
1355            __metaclass__ = M1
1356        class A2(object):
1357            __metaclass__ = M2
1358        try:
1359            class B(A1, A2):
1360                pass
1361        except TypeError:
1362            pass
1363        else:
1364            self.fail("finding the most derived metaclass should have failed")
1365
1366    def test_classmethods(self):
1367        # Testing class methods...
1368        class C(object):
1369            def foo(*a): return a
1370            goo = classmethod(foo)
1371        c = C()
1372        self.assertEqual(C.goo(1), (C, 1))
1373        self.assertEqual(c.goo(1), (C, 1))
1374        self.assertEqual(c.foo(1), (c, 1))
1375        class D(C):
1376            pass
1377        d = D()
1378        self.assertEqual(D.goo(1), (D, 1))
1379        self.assertEqual(d.goo(1), (D, 1))
1380        self.assertEqual(d.foo(1), (d, 1))
1381        self.assertEqual(D.foo(d, 1), (d, 1))
1382        # Test for a specific crash (SF bug 528132)
1383        def f(cls, arg): return (cls, arg)
1384        ff = classmethod(f)
1385        self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1386        self.assertEqual(ff.__get__(0)(42), (int, 42))
1387
1388        # Test super() with classmethods (SF bug 535444)
1389        self.assertEqual(C.goo.im_self, C)
1390        self.assertEqual(D.goo.im_self, D)
1391        self.assertEqual(super(D,D).goo.im_self, D)
1392        self.assertEqual(super(D,d).goo.im_self, D)
1393        self.assertEqual(super(D,D).goo(), (D,))
1394        self.assertEqual(super(D,d).goo(), (D,))
1395
1396        # Verify that a non-callable will raise
1397        meth = classmethod(1).__get__(1)
1398        self.assertRaises(TypeError, meth)
1399
1400        # Verify that classmethod() doesn't allow keyword args
1401        try:
1402            classmethod(f, kw=1)
1403        except TypeError:
1404            pass
1405        else:
1406            self.fail("classmethod shouldn't accept keyword args")
1407
1408    @test_support.impl_detail("the module 'xxsubtype' is internal")
1409    def test_classmethods_in_c(self):
1410        # Testing C-based class methods...
1411        import xxsubtype as spam
1412        a = (1, 2, 3)
1413        d = {'abc': 123}
1414        x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1415        self.assertEqual(x, spam.spamlist)
1416        self.assertEqual(a, a1)
1417        self.assertEqual(d, d1)
1418        x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1419        self.assertEqual(x, spam.spamlist)
1420        self.assertEqual(a, a1)
1421        self.assertEqual(d, d1)
1422        spam_cm = spam.spamlist.__dict__['classmeth']
1423        x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1424        self.assertEqual(x2, spam.spamlist)
1425        self.assertEqual(a2, a1)
1426        self.assertEqual(d2, d1)
1427        class SubSpam(spam.spamlist): pass
1428        x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1429        self.assertEqual(x2, SubSpam)
1430        self.assertEqual(a2, a1)
1431        self.assertEqual(d2, d1)
1432        with self.assertRaises(TypeError):
1433            spam_cm()
1434        with self.assertRaises(TypeError):
1435            spam_cm(spam.spamlist())
1436        with self.assertRaises(TypeError):
1437            spam_cm(list)
1438
1439    def test_staticmethods(self):
1440        # Testing static methods...
1441        class C(object):
1442            def foo(*a): return a
1443            goo = staticmethod(foo)
1444        c = C()
1445        self.assertEqual(C.goo(1), (1,))
1446        self.assertEqual(c.goo(1), (1,))
1447        self.assertEqual(c.foo(1), (c, 1,))
1448        class D(C):
1449            pass
1450        d = D()
1451        self.assertEqual(D.goo(1), (1,))
1452        self.assertEqual(d.goo(1), (1,))
1453        self.assertEqual(d.foo(1), (d, 1))
1454        self.assertEqual(D.foo(d, 1), (d, 1))
1455
1456    @test_support.impl_detail("the module 'xxsubtype' is internal")
1457    def test_staticmethods_in_c(self):
1458        # Testing C-based static methods...
1459        import xxsubtype as spam
1460        a = (1, 2, 3)
1461        d = {"abc": 123}
1462        x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1463        self.assertEqual(x, None)
1464        self.assertEqual(a, a1)
1465        self.assertEqual(d, d1)
1466        x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1467        self.assertEqual(x, None)
1468        self.assertEqual(a, a1)
1469        self.assertEqual(d, d1)
1470
1471    def test_classic(self):
1472        # Testing classic classes...
1473        class C:
1474            def foo(*a): return a
1475            goo = classmethod(foo)
1476        c = C()
1477        self.assertEqual(C.goo(1), (C, 1))
1478        self.assertEqual(c.goo(1), (C, 1))
1479        self.assertEqual(c.foo(1), (c, 1))
1480        class D(C):
1481            pass
1482        d = D()
1483        self.assertEqual(D.goo(1), (D, 1))
1484        self.assertEqual(d.goo(1), (D, 1))
1485        self.assertEqual(d.foo(1), (d, 1))
1486        self.assertEqual(D.foo(d, 1), (d, 1))
1487        class E: # *not* subclassing from C
1488            foo = C.foo
1489        self.assertEqual(E().foo, C.foo) # i.e., unbound
1490        self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
1491
1492    def test_compattr(self):
1493        # Testing computed attributes...
1494        class C(object):
1495            class computed_attribute(object):
1496                def __init__(self, get, set=None, delete=None):
1497                    self.__get = get
1498                    self.__set = set
1499                    self.__delete = delete
1500                def __get__(self, obj, type=None):
1501                    return self.__get(obj)
1502                def __set__(self, obj, value):
1503                    return self.__set(obj, value)
1504                def __delete__(self, obj):
1505                    return self.__delete(obj)
1506            def __init__(self):
1507                self.__x = 0
1508            def __get_x(self):
1509                x = self.__x
1510                self.__x = x+1
1511                return x
1512            def __set_x(self, x):
1513                self.__x = x
1514            def __delete_x(self):
1515                del self.__x
1516            x = computed_attribute(__get_x, __set_x, __delete_x)
1517        a = C()
1518        self.assertEqual(a.x, 0)
1519        self.assertEqual(a.x, 1)
1520        a.x = 10
1521        self.assertEqual(a.x, 10)
1522        self.assertEqual(a.x, 11)
1523        del a.x
1524        self.assertEqual(hasattr(a, 'x'), 0)
1525
1526    def test_newslots(self):
1527        # Testing __new__ slot override...
1528        class C(list):
1529            def __new__(cls):
1530                self = list.__new__(cls)
1531                self.foo = 1
1532                return self
1533            def __init__(self):
1534                self.foo = self.foo + 2
1535        a = C()
1536        self.assertEqual(a.foo, 3)
1537        self.assertEqual(a.__class__, C)
1538        class D(C):
1539            pass
1540        b = D()
1541        self.assertEqual(b.foo, 3)
1542        self.assertEqual(b.__class__, D)
1543
1544    def test_altmro(self):
1545        # Testing mro() and overriding it...
1546        class A(object):
1547            def f(self): return "A"
1548        class B(A):
1549            pass
1550        class C(A):
1551            def f(self): return "C"
1552        class D(B, C):
1553            pass
1554        self.assertEqual(D.mro(), [D, B, C, A, object])
1555        self.assertEqual(D.__mro__, (D, B, C, A, object))
1556        self.assertEqual(D().f(), "C")
1557
1558        class PerverseMetaType(type):
1559            def mro(cls):
1560                L = type.mro(cls)
1561                L.reverse()
1562                return L
1563        class X(D,B,C,A):
1564            __metaclass__ = PerverseMetaType
1565        self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1566        self.assertEqual(X().f(), "A")
1567
1568        try:
1569            class X(object):
1570                class __metaclass__(type):
1571                    def mro(self):
1572                        return [self, dict, object]
1573            # In CPython, the class creation above already raises
1574            # TypeError, as a protection against the fact that
1575            # instances of X would segfault it.  In other Python
1576            # implementations it would be ok to let the class X
1577            # be created, but instead get a clean TypeError on the
1578            # __setitem__ below.
1579            x = object.__new__(X)
1580            x[5] = 6
1581        except TypeError:
1582            pass
1583        else:
1584            self.fail("devious mro() return not caught")
1585
1586        try:
1587            class X(object):
1588                class __metaclass__(type):
1589                    def mro(self):
1590                        return [1]
1591        except TypeError:
1592            pass
1593        else:
1594            self.fail("non-class mro() return not caught")
1595
1596        try:
1597            class X(object):
1598                class __metaclass__(type):
1599                    def mro(self):
1600                        return 1
1601        except TypeError:
1602            pass
1603        else:
1604            self.fail("non-sequence mro() return not caught")
1605
1606    def test_overloading(self):
1607        # Testing operator overloading...
1608
1609        class B(object):
1610            "Intermediate class because object doesn't have a __setattr__"
1611
1612        class C(B):
1613            def __getattr__(self, name):
1614                if name == "foo":
1615                    return ("getattr", name)
1616                else:
1617                    raise AttributeError
1618            def __setattr__(self, name, value):
1619                if name == "foo":
1620                    self.setattr = (name, value)
1621                else:
1622                    return B.__setattr__(self, name, value)
1623            def __delattr__(self, name):
1624                if name == "foo":
1625                    self.delattr = name
1626                else:
1627                    return B.__delattr__(self, name)
1628
1629            def __getitem__(self, key):
1630                return ("getitem", key)
1631            def __setitem__(self, key, value):
1632                self.setitem = (key, value)
1633            def __delitem__(self, key):
1634                self.delitem = key
1635
1636            def __getslice__(self, i, j):
1637                return ("getslice", i, j)
1638            def __setslice__(self, i, j, value):
1639                self.setslice = (i, j, value)
1640            def __delslice__(self, i, j):
1641                self.delslice = (i, j)
1642
1643        a = C()
1644        self.assertEqual(a.foo, ("getattr", "foo"))
1645        a.foo = 12
1646        self.assertEqual(a.setattr, ("foo", 12))
1647        del a.foo
1648        self.assertEqual(a.delattr, "foo")
1649
1650        self.assertEqual(a[12], ("getitem", 12))
1651        a[12] = 21
1652        self.assertEqual(a.setitem, (12, 21))
1653        del a[12]
1654        self.assertEqual(a.delitem, 12)
1655
1656        self.assertEqual(a[0:10], ("getslice", 0, 10))
1657        a[0:10] = "foo"
1658        self.assertEqual(a.setslice, (0, 10, "foo"))
1659        del a[0:10]
1660        self.assertEqual(a.delslice, (0, 10))
1661
1662    def test_methods(self):
1663        # Testing methods...
1664        class C(object):
1665            def __init__(self, x):
1666                self.x = x
1667            def foo(self):
1668                return self.x
1669        c1 = C(1)
1670        self.assertEqual(c1.foo(), 1)
1671        class D(C):
1672            boo = C.foo
1673            goo = c1.foo
1674        d2 = D(2)
1675        self.assertEqual(d2.foo(), 2)
1676        self.assertEqual(d2.boo(), 2)
1677        self.assertEqual(d2.goo(), 1)
1678        class E(object):
1679            foo = C.foo
1680        self.assertEqual(E().foo, C.foo) # i.e., unbound
1681        self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
1682
1683    def test_special_method_lookup(self):
1684        # The lookup of special methods bypasses __getattr__ and
1685        # __getattribute__, but they still can be descriptors.
1686
1687        def run_context(manager):
1688            with manager:
1689                pass
1690        def iden(self):
1691            return self
1692        def hello(self):
1693            return "hello"
1694        def empty_seq(self):
1695            return []
1696        def zero(self):
1697            return 0
1698        def complex_num(self):
1699            return 1j
1700        def stop(self):
1701            raise StopIteration
1702        def return_true(self, thing=None):
1703            return True
1704        def do_isinstance(obj):
1705            return isinstance(int, obj)
1706        def do_issubclass(obj):
1707            return issubclass(int, obj)
1708        def swallow(*args):
1709            pass
1710        def do_dict_missing(checker):
1711            class DictSub(checker.__class__, dict):
1712                pass
1713            self.assertEqual(DictSub()["hi"], 4)
1714        def some_number(self_, key):
1715            self.assertEqual(key, "hi")
1716            return 4
1717        def format_impl(self, spec):
1718            return "hello"
1719
1720        # It would be nice to have every special method tested here, but I'm
1721        # only listing the ones I can remember outside of typeobject.c, since it
1722        # does it right.
1723        specials = [
1724            ("__unicode__", unicode, hello, set(), {}),
1725            ("__reversed__", reversed, empty_seq, set(), {}),
1726            ("__length_hint__", list, zero, set(),
1727             {"__iter__" : iden, "next" : stop}),
1728            ("__sizeof__", sys.getsizeof, zero, set(), {}),
1729            ("__instancecheck__", do_isinstance, return_true, set(), {}),
1730            ("__missing__", do_dict_missing, some_number,
1731             set(("__class__",)), {}),
1732            ("__subclasscheck__", do_issubclass, return_true,
1733             set(("__bases__",)), {}),
1734            ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1735            ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
1736            ("__complex__", complex, complex_num, set(), {}),
1737            ("__format__", format, format_impl, set(), {}),
1738            ("__dir__", dir, empty_seq, set(), {}),
1739            ]
1740
1741        class Checker(object):
1742            def __getattr__(self, attr, test=self):
1743                test.fail("__getattr__ called with {0}".format(attr))
1744            def __getattribute__(self, attr, test=self):
1745                if attr not in ok:
1746                    test.fail("__getattribute__ called with {0}".format(attr))
1747                return object.__getattribute__(self, attr)
1748        class SpecialDescr(object):
1749            def __init__(self, impl):
1750                self.impl = impl
1751            def __get__(self, obj, owner):
1752                record.append(1)
1753                return self.impl.__get__(obj, owner)
1754        class MyException(Exception):
1755            pass
1756        class ErrDescr(object):
1757            def __get__(self, obj, owner):
1758                raise MyException
1759
1760        for name, runner, meth_impl, ok, env in specials:
1761            class X(Checker):
1762                pass
1763            for attr, obj in env.iteritems():
1764                setattr(X, attr, obj)
1765            setattr(X, name, meth_impl)
1766            runner(X())
1767
1768            record = []
1769            class X(Checker):
1770                pass
1771            for attr, obj in env.iteritems():
1772                setattr(X, attr, obj)
1773            setattr(X, name, SpecialDescr(meth_impl))
1774            runner(X())
1775            self.assertEqual(record, [1], name)
1776
1777            class X(Checker):
1778                pass
1779            for attr, obj in env.iteritems():
1780                setattr(X, attr, obj)
1781            setattr(X, name, ErrDescr())
1782            try:
1783                runner(X())
1784            except MyException:
1785                pass
1786            else:
1787                self.fail("{0!r} didn't raise".format(name))
1788
1789    def test_specials(self):
1790        # Testing special operators...
1791        # Test operators like __hash__ for which a built-in default exists
1792
1793        # Test the default behavior for static classes
1794        class C(object):
1795            def __getitem__(self, i):
1796                if 0 <= i < 10: return i
1797                raise IndexError
1798        c1 = C()
1799        c2 = C()
1800        self.assertTrue(not not c1) # What?
1801        self.assertNotEqual(id(c1), id(c2))
1802        hash(c1)
1803        hash(c2)
1804        self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
1805        self.assertEqual(c1, c1)
1806        self.assertTrue(c1 != c2)
1807        self.assertTrue(not c1 != c1)
1808        self.assertTrue(not c1 == c2)
1809        # Note that the module name appears in str/repr, and that varies
1810        # depending on whether this test is run standalone or from a framework.
1811        self.assertTrue(str(c1).find('C object at ') >= 0)
1812        self.assertEqual(str(c1), repr(c1))
1813        self.assertNotIn(-1, c1)
1814        for i in range(10):
1815            self.assertIn(i, c1)
1816        self.assertNotIn(10, c1)
1817        # Test the default behavior for dynamic classes
1818        class D(object):
1819            def __getitem__(self, i):
1820                if 0 <= i < 10: return i
1821                raise IndexError
1822        d1 = D()
1823        d2 = D()
1824        self.assertTrue(not not d1)
1825        self.assertNotEqual(id(d1), id(d2))
1826        hash(d1)
1827        hash(d2)
1828        self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2)))
1829        self.assertEqual(d1, d1)
1830        self.assertNotEqual(d1, d2)
1831        self.assertTrue(not d1 != d1)
1832        self.assertTrue(not d1 == d2)
1833        # Note that the module name appears in str/repr, and that varies
1834        # depending on whether this test is run standalone or from a framework.
1835        self.assertTrue(str(d1).find('D object at ') >= 0)
1836        self.assertEqual(str(d1), repr(d1))
1837        self.assertNotIn(-1, d1)
1838        for i in range(10):
1839            self.assertIn(i, d1)
1840        self.assertNotIn(10, d1)
1841        # Test overridden behavior for static classes
1842        class Proxy(object):
1843            def __init__(self, x):
1844                self.x = x
1845            def __nonzero__(self):
1846                return not not self.x
1847            def __hash__(self):
1848                return hash(self.x)
1849            def __eq__(self, other):
1850                return self.x == other
1851            def __ne__(self, other):
1852                return self.x != other
1853            def __cmp__(self, other):
1854                return cmp(self.x, other.x)
1855            def __str__(self):
1856                return "Proxy:%s" % self.x
1857            def __repr__(self):
1858                return "Proxy(%r)" % self.x
1859            def __contains__(self, value):
1860                return value in self.x
1861        p0 = Proxy(0)
1862        p1 = Proxy(1)
1863        p_1 = Proxy(-1)
1864        self.assertFalse(p0)
1865        self.assertTrue(not not p1)
1866        self.assertEqual(hash(p0), hash(0))
1867        self.assertEqual(p0, p0)
1868        self.assertNotEqual(p0, p1)
1869        self.assertTrue(not p0 != p0)
1870        self.assertEqual(not p0, p1)
1871        self.assertEqual(cmp(p0, p1), -1)
1872        self.assertEqual(cmp(p0, p0), 0)
1873        self.assertEqual(cmp(p0, p_1), 1)
1874        self.assertEqual(str(p0), "Proxy:0")
1875        self.assertEqual(repr(p0), "Proxy(0)")
1876        p10 = Proxy(range(10))
1877        self.assertNotIn(-1, p10)
1878        for i in range(10):
1879            self.assertIn(i, p10)
1880        self.assertNotIn(10, p10)
1881        # Test overridden behavior for dynamic classes
1882        class DProxy(object):
1883            def __init__(self, x):
1884                self.x = x
1885            def __nonzero__(self):
1886                return not not self.x
1887            def __hash__(self):
1888                return hash(self.x)
1889            def __eq__(self, other):
1890                return self.x == other
1891            def __ne__(self, other):
1892                return self.x != other
1893            def __cmp__(self, other):
1894                return cmp(self.x, other.x)
1895            def __str__(self):
1896                return "DProxy:%s" % self.x
1897            def __repr__(self):
1898                return "DProxy(%r)" % self.x
1899            def __contains__(self, value):
1900                return value in self.x
1901        p0 = DProxy(0)
1902        p1 = DProxy(1)
1903        p_1 = DProxy(-1)
1904        self.assertFalse(p0)
1905        self.assertTrue(not not p1)
1906        self.assertEqual(hash(p0), hash(0))
1907        self.assertEqual(p0, p0)
1908        self.assertNotEqual(p0, p1)
1909        self.assertNotEqual(not p0, p0)
1910        self.assertEqual(not p0, p1)
1911        self.assertEqual(cmp(p0, p1), -1)
1912        self.assertEqual(cmp(p0, p0), 0)
1913        self.assertEqual(cmp(p0, p_1), 1)
1914        self.assertEqual(str(p0), "DProxy:0")
1915        self.assertEqual(repr(p0), "DProxy(0)")
1916        p10 = DProxy(range(10))
1917        self.assertNotIn(-1, p10)
1918        for i in range(10):
1919            self.assertIn(i, p10)
1920        self.assertNotIn(10, p10)
1921
1922        # Safety test for __cmp__
1923        def unsafecmp(a, b):
1924            if not hasattr(a, '__cmp__'):
1925                return   # some types don't have a __cmp__ any more (so the
1926                         # test doesn't make sense any more), or maybe they
1927                         # never had a __cmp__ at all, e.g. in PyPy
1928            try:
1929                a.__class__.__cmp__(a, b)
1930            except TypeError:
1931                pass
1932            else:
1933                self.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
1934                    a.__class__, a, b))
1935
1936        unsafecmp(u"123", "123")
1937        unsafecmp("123", u"123")
1938        unsafecmp(1, 1.0)
1939        unsafecmp(1.0, 1)
1940        unsafecmp(1, 1L)
1941        unsafecmp(1L, 1)
1942
1943    @test_support.impl_detail("custom logic for printing to real file objects")
1944    def test_recursions_1(self):
1945        # Testing recursion checks ...
1946        class Letter(str):
1947            def __new__(cls, letter):
1948                if letter == 'EPS':
1949                    return str.__new__(cls)
1950                return str.__new__(cls, letter)
1951            def __str__(self):
1952                if not self:
1953                    return 'EPS'
1954                return self
1955        # sys.stdout needs to be the original to trigger the recursion bug
1956        test_stdout = sys.stdout
1957        sys.stdout = test_support.get_original_stdout()
1958        try:
1959            # nothing should actually be printed, this should raise an exception
1960            print Letter('w')
1961        except RuntimeError:
1962            pass
1963        else:
1964            self.fail("expected a RuntimeError for print recursion")
1965        finally:
1966            sys.stdout = test_stdout
1967
1968    def test_recursions_2(self):
1969        # Bug #1202533.
1970        class A(object):
1971            pass
1972        A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
1973        try:
1974            A()*2
1975        except RuntimeError:
1976            pass
1977        else:
1978            self.fail("expected a RuntimeError")
1979
1980    def test_weakrefs(self):
1981        # Testing weak references...
1982        import weakref
1983        class C(object):
1984            pass
1985        c = C()
1986        r = weakref.ref(c)
1987        self.assertEqual(r(), c)
1988        del c
1989        test_support.gc_collect()
1990        self.assertEqual(r(), None)
1991        del r
1992        class NoWeak(object):
1993            __slots__ = ['foo']
1994        no = NoWeak()
1995        try:
1996            weakref.ref(no)
1997        except TypeError, msg:
1998            self.assertTrue(str(msg).find("weak reference") >= 0)
1999        else:
2000            self.fail("weakref.ref(no) should be illegal")
2001        class Weak(object):
2002            __slots__ = ['foo', '__weakref__']
2003        yes = Weak()
2004        r = weakref.ref(yes)
2005        self.assertEqual(r(), yes)
2006        del yes
2007        test_support.gc_collect()
2008        self.assertEqual(r(), None)
2009        del r
2010
2011    def test_properties(self):
2012        # Testing property...
2013        class C(object):
2014            def getx(self):
2015                return self.__x
2016            def setx(self, value):
2017                self.__x = value
2018            def delx(self):
2019                del self.__x
2020            x = property(getx, setx, delx, doc="I'm the x property.")
2021        a = C()
2022        self.assertFalse(hasattr(a, "x"))
2023        a.x = 42
2024        self.assertEqual(a._C__x, 42)
2025        self.assertEqual(a.x, 42)
2026        del a.x
2027        self.assertFalse(hasattr(a, "x"))
2028        self.assertFalse(hasattr(a, "_C__x"))
2029        C.x.__set__(a, 100)
2030        self.assertEqual(C.x.__get__(a), 100)
2031        C.x.__delete__(a)
2032        self.assertFalse(hasattr(a, "x"))
2033
2034        raw = C.__dict__['x']
2035        self.assertIsInstance(raw, property)
2036
2037        attrs = dir(raw)
2038        self.assertIn("__doc__", attrs)
2039        self.assertIn("fget", attrs)
2040        self.assertIn("fset", attrs)
2041        self.assertIn("fdel", attrs)
2042
2043        self.assertEqual(raw.__doc__, "I'm the x property.")
2044        self.assertTrue(raw.fget is C.__dict__['getx'])
2045        self.assertTrue(raw.fset is C.__dict__['setx'])
2046        self.assertTrue(raw.fdel is C.__dict__['delx'])
2047
2048        for attr in "__doc__", "fget", "fset", "fdel":
2049            try:
2050                setattr(raw, attr, 42)
2051            except TypeError, msg:
2052                if str(msg).find('readonly') < 0:
2053                    self.fail("when setting readonly attr %r on a property, "
2054                                     "got unexpected TypeError msg %r" % (attr, str(msg)))
2055            else:
2056                self.fail("expected TypeError from trying to set readonly %r "
2057                                 "attr on a property" % attr)
2058
2059        class D(object):
2060            __getitem__ = property(lambda s: 1/0)
2061
2062        d = D()
2063        try:
2064            for i in d:
2065                str(i)
2066        except ZeroDivisionError:
2067            pass
2068        else:
2069            self.fail("expected ZeroDivisionError from bad property")
2070
2071    @unittest.skipIf(sys.flags.optimize >= 2,
2072                     "Docstrings are omitted with -O2 and above")
2073    def test_properties_doc_attrib(self):
2074        class E(object):
2075            def getter(self):
2076                "getter method"
2077                return 0
2078            def setter(self_, value):
2079                "setter method"
2080                pass
2081            prop = property(getter)
2082            self.assertEqual(prop.__doc__, "getter method")
2083            prop2 = property(fset=setter)
2084            self.assertEqual(prop2.__doc__, None)
2085
2086    def test_testcapi_no_segfault(self):
2087        # this segfaulted in 2.5b2
2088        try:
2089            import _testcapi
2090        except ImportError:
2091            pass
2092        else:
2093            class X(object):
2094                p = property(_testcapi.test_with_docstring)
2095
2096    def test_properties_plus(self):
2097        class C(object):
2098            foo = property(doc="hello")
2099            @foo.getter
2100            def foo(self):
2101                return self._foo
2102            @foo.setter
2103            def foo(self, value):
2104                self._foo = abs(value)
2105            @foo.deleter
2106            def foo(self):
2107                del self._foo
2108        c = C()
2109        self.assertEqual(C.foo.__doc__, "hello")
2110        self.assertFalse(hasattr(c, "foo"))
2111        c.foo = -42
2112        self.assertTrue(hasattr(c, '_foo'))
2113        self.assertEqual(c._foo, 42)
2114        self.assertEqual(c.foo, 42)
2115        del c.foo
2116        self.assertFalse(hasattr(c, '_foo'))
2117        self.assertFalse(hasattr(c, "foo"))
2118
2119        class D(C):
2120            @C.foo.deleter
2121            def foo(self):
2122                try:
2123                    del self._foo
2124                except AttributeError:
2125                    pass
2126        d = D()
2127        d.foo = 24
2128        self.assertEqual(d.foo, 24)
2129        del d.foo
2130        del d.foo
2131
2132        class E(object):
2133            @property
2134            def foo(self):
2135                return self._foo
2136            @foo.setter
2137            def foo(self, value):
2138                raise RuntimeError
2139            @foo.setter
2140            def foo(self, value):
2141                self._foo = abs(value)
2142            @foo.deleter
2143            def foo(self, value=None):
2144                del self._foo
2145
2146        e = E()
2147        e.foo = -42
2148        self.assertEqual(e.foo, 42)
2149        del e.foo
2150
2151        class F(E):
2152            @E.foo.deleter
2153            def foo(self):
2154                del self._foo
2155            @foo.setter
2156            def foo(self, value):
2157                self._foo = max(0, value)
2158        f = F()
2159        f.foo = -10
2160        self.assertEqual(f.foo, 0)
2161        del f.foo
2162
2163    def test_dict_constructors(self):
2164        # Testing dict constructor ...
2165        d = dict()
2166        self.assertEqual(d, {})
2167        d = dict({})
2168        self.assertEqual(d, {})
2169        d = dict({1: 2, 'a': 'b'})
2170        self.assertEqual(d, {1: 2, 'a': 'b'})
2171        self.assertEqual(d, dict(d.items()))
2172        self.assertEqual(d, dict(d.iteritems()))
2173        d = dict({'one':1, 'two':2})
2174        self.assertEqual(d, dict(one=1, two=2))
2175        self.assertEqual(d, dict(**d))
2176        self.assertEqual(d, dict({"one": 1}, two=2))
2177        self.assertEqual(d, dict([("two", 2)], one=1))
2178        self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2179        self.assertEqual(d, dict(**d))
2180
2181        for badarg in 0, 0L, 0j, "0", [0], (0,):
2182            try:
2183                dict(badarg)
2184            except TypeError:
2185                pass
2186            except ValueError:
2187                if badarg == "0":
2188                    # It's a sequence, and its elements are also sequences (gotta
2189                    # love strings <wink>), but they aren't of length 2, so this
2190                    # one seemed better as a ValueError than a TypeError.
2191                    pass
2192                else:
2193                    self.fail("no TypeError from dict(%r)" % badarg)
2194            else:
2195                self.fail("no TypeError from dict(%r)" % badarg)
2196
2197        try:
2198            dict({}, {})
2199        except TypeError:
2200            pass
2201        else:
2202            self.fail("no TypeError from dict({}, {})")
2203
2204        class Mapping:
2205            # Lacks a .keys() method; will be added later.
2206            dict = {1:2, 3:4, 'a':1j}
2207
2208        try:
2209            dict(Mapping())
2210        except TypeError:
2211            pass
2212        else:
2213            self.fail("no TypeError from dict(incomplete mapping)")
2214
2215        Mapping.keys = lambda self: self.dict.keys()
2216        Mapping.__getitem__ = lambda self, i: self.dict[i]
2217        d = dict(Mapping())
2218        self.assertEqual(d, Mapping.dict)
2219
2220        # Init from sequence of iterable objects, each producing a 2-sequence.
2221        class AddressBookEntry:
2222            def __init__(self, first, last):
2223                self.first = first
2224                self.last = last
2225            def __iter__(self):
2226                return iter([self.first, self.last])
2227
2228        d = dict([AddressBookEntry('Tim', 'Warsaw'),
2229                  AddressBookEntry('Barry', 'Peters'),
2230                  AddressBookEntry('Tim', 'Peters'),
2231                  AddressBookEntry('Barry', 'Warsaw')])
2232        self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2233
2234        d = dict(zip(range(4), range(1, 5)))
2235        self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2236
2237        # Bad sequence lengths.
2238        for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2239            try:
2240                dict(bad)
2241            except ValueError:
2242                pass
2243            else:
2244                self.fail("no ValueError from dict(%r)" % bad)
2245
2246    def test_dir(self):
2247        # Testing dir() ...
2248        junk = 12
2249        self.assertEqual(dir(), ['junk', 'self'])
2250        del junk
2251
2252        # Just make sure these don't blow up!
2253        for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, self.test_dir:
2254            dir(arg)
2255
2256        # Try classic classes.
2257        class C:
2258            Cdata = 1
2259            def Cmethod(self): pass
2260
2261        cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
2262        self.assertEqual(dir(C), cstuff)
2263        self.assertIn('im_self', dir(C.Cmethod))
2264
2265        c = C()  # c.__doc__ is an odd thing to see here; ditto c.__module__.
2266        self.assertEqual(dir(c), cstuff)
2267
2268        c.cdata = 2
2269        c.cmethod = lambda self: 0
2270        self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
2271        self.assertIn('im_self', dir(c.Cmethod))
2272
2273        class A(C):
2274            Adata = 1
2275            def Amethod(self): pass
2276
2277        astuff = ['Adata', 'Amethod'] + cstuff
2278        self.assertEqual(dir(A), astuff)
2279        self.assertIn('im_self', dir(A.Amethod))
2280        a = A()
2281        self.assertEqual(dir(a), astuff)
2282        self.assertIn('im_self', dir(a.Amethod))
2283        a.adata = 42
2284        a.amethod = lambda self: 3
2285        self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
2286
2287        # The same, but with new-style classes.  Since these have object as a
2288        # base class, a lot more gets sucked in.
2289        def interesting(strings):
2290            return [s for s in strings if not s.startswith('_')]
2291
2292        class C(object):
2293            Cdata = 1
2294            def Cmethod(self): pass
2295
2296        cstuff = ['Cdata', 'Cmethod']
2297        self.assertEqual(interesting(dir(C)), cstuff)
2298
2299        c = C()
2300        self.assertEqual(interesting(dir(c)), cstuff)
2301        self.assertIn('im_self', dir(C.Cmethod))
2302
2303        c.cdata = 2
2304        c.cmethod = lambda self: 0
2305        self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
2306        self.assertIn('im_self', dir(c.Cmethod))
2307
2308        class A(C):
2309            Adata = 1
2310            def Amethod(self): pass
2311
2312        astuff = ['Adata', 'Amethod'] + cstuff
2313        self.assertEqual(interesting(dir(A)), astuff)
2314        self.assertIn('im_self', dir(A.Amethod))
2315        a = A()
2316        self.assertEqual(interesting(dir(a)), astuff)
2317        a.adata = 42
2318        a.amethod = lambda self: 3
2319        self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
2320        self.assertIn('im_self', dir(a.Amethod))
2321
2322        # Try a module subclass.
2323        class M(type(sys)):
2324            pass
2325        minstance = M("m")
2326        minstance.b = 2
2327        minstance.a = 1
2328        names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2329        self.assertEqual(names, ['a', 'b'])
2330
2331        class M2(M):
2332            def getdict(self):
2333                return "Not a dict!"
2334            __dict__ = property(getdict)
2335
2336        m2instance = M2("m2")
2337        m2instance.b = 2
2338        m2instance.a = 1
2339        self.assertEqual(m2instance.__dict__, "Not a dict!")
2340        try:
2341            dir(m2instance)
2342        except TypeError:
2343            pass
2344
2345        # Two essentially featureless objects, just inheriting stuff from
2346        # object.
2347        self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2348        if test_support.check_impl_detail():
2349            # None differs in PyPy: it has a __nonzero__
2350            self.assertEqual(dir(None), dir(Ellipsis))
2351
2352        # Nasty test case for proxied objects
2353        class Wrapper(object):
2354            def __init__(self, obj):
2355                self.__obj = obj
2356            def __repr__(self):
2357                return "Wrapper(%s)" % repr(self.__obj)
2358            def __getitem__(self, key):
2359                return Wrapper(self.__obj[key])
2360            def __len__(self):
2361                return len(self.__obj)
2362            def __getattr__(self, name):
2363                return Wrapper(getattr(self.__obj, name))
2364
2365        class C(object):
2366            def __getclass(self):
2367                return Wrapper(type(self))
2368            __class__ = property(__getclass)
2369
2370        dir(C()) # This used to segfault
2371
2372    def test_supers(self):
2373        # Testing super...
2374
2375        class A(object):
2376            def meth(self, a):
2377                return "A(%r)" % a
2378
2379        self.assertEqual(A().meth(1), "A(1)")
2380
2381        class B(A):
2382            def __init__(self):
2383                self.__super = super(B, self)
2384            def meth(self, a):
2385                return "B(%r)" % a + self.__super.meth(a)
2386
2387        self.assertEqual(B().meth(2), "B(2)A(2)")
2388
2389        class C(A):
2390            def meth(self, a):
2391                return "C(%r)" % a + self.__super.meth(a)
2392        C._C__super = super(C)
2393
2394        self.assertEqual(C().meth(3), "C(3)A(3)")
2395
2396        class D(C, B):
2397            def meth(self, a):
2398                return "D(%r)" % a + super(D, self).meth(a)
2399
2400        self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2401
2402        # Test for subclassing super
2403
2404        class mysuper(super):
2405            def __init__(self, *args):
2406                return super(mysuper, self).__init__(*args)
2407
2408        class E(D):
2409            def meth(self, a):
2410                return "E(%r)" % a + mysuper(E, self).meth(a)
2411
2412        self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2413
2414        class F(E):
2415            def meth(self, a):
2416                s = self.__super # == mysuper(F, self)
2417                return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2418        F._F__super = mysuper(F)
2419
2420        self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2421
2422        # Make sure certain errors are raised
2423
2424        try:
2425            super(D, 42)
2426        except TypeError:
2427            pass
2428        else:
2429            self.fail("shouldn't allow super(D, 42)")
2430
2431        try:
2432            super(D, C())
2433        except TypeError:
2434            pass
2435        else:
2436            self.fail("shouldn't allow super(D, C())")
2437
2438        try:
2439            super(D).__get__(12)
2440        except TypeError:
2441            pass
2442        else:
2443            self.fail("shouldn't allow super(D).__get__(12)")
2444
2445        try:
2446            super(D).__get__(C())
2447        except TypeError:
2448            pass
2449        else:
2450            self.fail("shouldn't allow super(D).__get__(C())")
2451
2452        # Make sure data descriptors can be overridden and accessed via super
2453        # (new feature in Python 2.3)
2454
2455        class DDbase(object):
2456            def getx(self): return 42
2457            x = property(getx)
2458
2459        class DDsub(DDbase):
2460            def getx(self): return "hello"
2461            x = property(getx)
2462
2463        dd = DDsub()
2464        self.assertEqual(dd.x, "hello")
2465        self.assertEqual(super(DDsub, dd).x, 42)
2466
2467        # Ensure that super() lookup of descriptor from classmethod
2468        # works (SF ID# 743627)
2469
2470        class Base(object):
2471            aProp = property(lambda self: "foo")
2472
2473        class Sub(Base):
2474            @classmethod
2475            def test(klass):
2476                return super(Sub,klass).aProp
2477
2478        self.assertEqual(Sub.test(), Base.aProp)
2479
2480        # Verify that super() doesn't allow keyword args
2481        try:
2482            super(Base, kw=1)
2483        except TypeError:
2484            pass
2485        else:
2486            self.assertEqual("super shouldn't accept keyword args")
2487
2488    def test_basic_inheritance(self):
2489        # Testing inheritance from basic types...
2490
2491        class hexint(int):
2492            def __repr__(self):
2493                return hex(self)
2494            def __add__(self, other):
2495                return hexint(int.__add__(self, other))
2496            # (Note that overriding __radd__ doesn't work,
2497            # because the int type gets first dibs.)
2498        self.assertEqual(repr(hexint(7) + 9), "0x10")
2499        self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2500        a = hexint(12345)
2501        self.assertEqual(a, 12345)
2502        self.assertEqual(int(a), 12345)
2503        self.assertTrue(int(a).__class__ is int)
2504        self.assertEqual(hash(a), hash(12345))
2505        self.assertTrue((+a).__class__ is int)
2506        self.assertTrue((a >> 0).__class__ is int)
2507        self.assertTrue((a << 0).__class__ is int)
2508        self.assertTrue((hexint(0) << 12).__class__ is int)
2509        self.assertTrue((hexint(0) >> 12).__class__ is int)
2510
2511        class octlong(long):
2512            __slots__ = []
2513            def __str__(self):
2514                s = oct(self)
2515                if s[-1] == 'L':
2516                    s = s[:-1]
2517                return s
2518            def __add__(self, other):
2519                return self.__class__(super(octlong, self).__add__(other))
2520            __radd__ = __add__
2521        self.assertEqual(str(octlong(3) + 5), "010")
2522        # (Note that overriding __radd__ here only seems to work
2523        # because the example uses a short int left argument.)
2524        self.assertEqual(str(5 + octlong(3000)), "05675")
2525        a = octlong(12345)
2526        self.assertEqual(a, 12345L)
2527        self.assertEqual(long(a), 12345L)
2528        self.assertEqual(hash(a), hash(12345L))
2529        self.assertTrue(long(a).__class__ is long)
2530        self.assertTrue((+a).__class__ is long)
2531        self.assertTrue((-a).__class__ is long)
2532        self.assertTrue((-octlong(0)).__class__ is long)
2533        self.assertTrue((a >> 0).__class__ is long)
2534        self.assertTrue((a << 0).__class__ is long)
2535        self.assertTrue((a - 0).__class__ is long)
2536        self.assertTrue((a * 1).__class__ is long)
2537        self.assertTrue((a ** 1).__class__ is long)
2538        self.assertTrue((a // 1).__class__ is long)
2539        self.assertTrue((1 * a).__class__ is long)
2540        self.assertTrue((a | 0).__class__ is long)
2541        self.assertTrue((a ^ 0).__class__ is long)
2542        self.assertTrue((a & -1L).__class__ is long)
2543        self.assertTrue((octlong(0) << 12).__class__ is long)
2544        self.assertTrue((octlong(0) >> 12).__class__ is long)
2545        self.assertTrue(abs(octlong(0)).__class__ is long)
2546
2547        # Because octlong overrides __add__, we can't check the absence of +0
2548        # optimizations using octlong.
2549        class longclone(long):
2550            pass
2551        a = longclone(1)
2552        self.assertTrue((a + 0).__class__ is long)
2553        self.assertTrue((0 + a).__class__ is long)
2554
2555        # Check that negative clones don't segfault
2556        a = longclone(-1)
2557        self.assertEqual(a.__dict__, {})
2558        self.assertEqual(long(a), -1)  # self.assertTrue PyNumber_Long() copies the sign bit
2559
2560        class precfloat(float):
2561            __slots__ = ['prec']
2562            def __init__(self, value=0.0, prec=12):
2563                self.prec = int(prec)
2564            def __repr__(self):
2565                return "%.*g" % (self.prec, self)
2566        self.assertEqual(repr(precfloat(1.1)), "1.1")
2567        a = precfloat(12345)
2568        self.assertEqual(a, 12345.0)
2569        self.assertEqual(float(a), 12345.0)
2570        self.assertTrue(float(a).__class__ is float)
2571        self.assertEqual(hash(a), hash(12345.0))
2572        self.assertTrue((+a).__class__ is float)
2573
2574        class madcomplex(complex):
2575            def __repr__(self):
2576                return "%.17gj%+.17g" % (self.imag, self.real)
2577        a = madcomplex(-3, 4)
2578        self.assertEqual(repr(a), "4j-3")
2579        base = complex(-3, 4)
2580        self.assertEqual(base.__class__, complex)
2581        self.assertEqual(a, base)
2582        self.assertEqual(complex(a), base)
2583        self.assertEqual(complex(a).__class__, complex)
2584        a = madcomplex(a)  # just trying another form of the constructor
2585        self.assertEqual(repr(a), "4j-3")
2586        self.assertEqual(a, base)
2587        self.assertEqual(complex(a), base)
2588        self.assertEqual(complex(a).__class__, complex)
2589        self.assertEqual(hash(a), hash(base))
2590        self.assertEqual((+a).__class__, complex)
2591        self.assertEqual((a + 0).__class__, complex)
2592        self.assertEqual(a + 0, base)
2593        self.assertEqual((a - 0).__class__, complex)
2594        self.assertEqual(a - 0, base)
2595        self.assertEqual((a * 1).__class__, complex)
2596        self.assertEqual(a * 1, base)
2597        self.assertEqual((a / 1).__class__, complex)
2598        self.assertEqual(a / 1, base)
2599
2600        class madtuple(tuple):
2601            _rev = None
2602            def rev(self):
2603                if self._rev is not None:
2604                    return self._rev
2605                L = list(self)
2606                L.reverse()
2607                self._rev = self.__class__(L)
2608                return self._rev
2609        a = madtuple((1,2,3,4,5,6,7,8,9,0))
2610        self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2611        self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2612        self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2613        for i in range(512):
2614            t = madtuple(range(i))
2615            u = t.rev()
2616            v = u.rev()
2617            self.assertEqual(v, t)
2618        a = madtuple((1,2,3,4,5))
2619        self.assertEqual(tuple(a), (1,2,3,4,5))
2620        self.assertTrue(tuple(a).__class__ is tuple)
2621        self.assertEqual(hash(a), hash((1,2,3,4,5)))
2622        self.assertTrue(a[:].__class__ is tuple)
2623        self.assertTrue((a * 1).__class__ is tuple)
2624        self.assertTrue((a * 0).__class__ is tuple)
2625        self.assertTrue((a + ()).__class__ is tuple)
2626        a = madtuple(())
2627        self.assertEqual(tuple(a), ())
2628        self.assertTrue(tuple(a).__class__ is tuple)
2629        self.assertTrue((a + a).__class__ is tuple)
2630        self.assertTrue((a * 0).__class__ is tuple)
2631        self.assertTrue((a * 1).__class__ is tuple)
2632        self.assertTrue((a * 2).__class__ is tuple)
2633        self.assertTrue(a[:].__class__ is tuple)
2634
2635        class madstring(str):
2636            _rev = None
2637            def rev(self):
2638                if self._rev is not None:
2639                    return self._rev
2640                L = list(self)
2641                L.reverse()
2642                self._rev = self.__class__("".join(L))
2643                return self._rev
2644        s = madstring("abcdefghijklmnopqrstuvwxyz")
2645        self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2646        self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2647        self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2648        for i in range(256):
2649            s = madstring("".join(map(chr, range(i))))
2650            t = s.rev()
2651            u = t.rev()
2652            self.assertEqual(u, s)
2653        s = madstring("12345")
2654        self.assertEqual(str(s), "12345")
2655        self.assertTrue(str(s).__class__ is str)
2656
2657        base = "\x00" * 5
2658        s = madstring(base)
2659        self.assertEqual(s, base)
2660        self.assertEqual(str(s), base)
2661        self.assertTrue(str(s).__class__ is str)
2662        self.assertEqual(hash(s), hash(base))
2663        self.assertEqual({s: 1}[base], 1)
2664        self.assertEqual({base: 1}[s], 1)
2665        self.assertTrue((s + "").__class__ is str)
2666        self.assertEqual(s + "", base)
2667        self.assertTrue(("" + s).__class__ is str)
2668        self.assertEqual("" + s, base)
2669        self.assertTrue((s * 0).__class__ is str)
2670        self.assertEqual(s * 0, "")
2671        self.assertTrue((s * 1).__class__ is str)
2672        self.assertEqual(s * 1, base)
2673        self.assertTrue((s * 2).__class__ is str)
2674        self.assertEqual(s * 2, base + base)
2675        self.assertTrue(s[:].__class__ is str)
2676        self.assertEqual(s[:], base)
2677        self.assertTrue(s[0:0].__class__ is str)
2678        self.assertEqual(s[0:0], "")
2679        self.assertTrue(s.strip().__class__ is str)
2680        self.assertEqual(s.strip(), base)
2681        self.assertTrue(s.lstrip().__class__ is str)
2682        self.assertEqual(s.lstrip(), base)
2683        self.assertTrue(s.rstrip().__class__ is str)
2684        self.assertEqual(s.rstrip(), base)
2685        identitytab = ''.join([chr(i) for i in range(256)])
2686        self.assertTrue(s.translate(identitytab).__class__ is str)
2687        self.assertEqual(s.translate(identitytab), base)
2688        self.assertTrue(s.translate(identitytab, "x").__class__ is str)
2689        self.assertEqual(s.translate(identitytab, "x"), base)
2690        self.assertEqual(s.translate(identitytab, "\x00"), "")
2691        self.assertTrue(s.replace("x", "x").__class__ is str)
2692        self.assertEqual(s.replace("x", "x"), base)
2693        self.assertTrue(s.ljust(len(s)).__class__ is str)
2694        self.assertEqual(s.ljust(len(s)), base)
2695        self.assertTrue(s.rjust(len(s)).__class__ is str)
2696        self.assertEqual(s.rjust(len(s)), base)
2697        self.assertTrue(s.center(len(s)).__class__ is str)
2698        self.assertEqual(s.center(len(s)), base)
2699        self.assertTrue(s.lower().__class__ is str)
2700        self.assertEqual(s.lower(), base)
2701
2702        class madunicode(unicode):
2703            _rev = None
2704            def rev(self):
2705                if self._rev is not None:
2706                    return self._rev
2707                L = list(self)
2708                L.reverse()
2709                self._rev = self.__class__(u"".join(L))
2710                return self._rev
2711        u = madunicode("ABCDEF")
2712        self.assertEqual(u, u"ABCDEF")
2713        self.assertEqual(u.rev(), madunicode(u"FEDCBA"))
2714        self.assertEqual(u.rev().rev(), madunicode(u"ABCDEF"))
2715        base = u"12345"
2716        u = madunicode(base)
2717        self.assertEqual(unicode(u), base)
2718        self.assertTrue(unicode(u).__class__ is unicode)
2719        self.assertEqual(hash(u), hash(base))
2720        self.assertEqual({u: 1}[base], 1)
2721        self.assertEqual({base: 1}[u], 1)
2722        self.assertTrue(u.strip().__class__ is unicode)
2723        self.assertEqual(u.strip(), base)
2724        self.assertTrue(u.lstrip().__class__ is unicode)
2725        self.assertEqual(u.lstrip(), base)
2726        self.assertTrue(u.rstrip().__class__ is unicode)
2727        self.assertEqual(u.rstrip(), base)
2728        self.assertTrue(u.replace(u"x", u"x").__class__ is unicode)
2729        self.assertEqual(u.replace(u"x", u"x"), base)
2730        self.assertTrue(u.replace(u"xy", u"xy").__class__ is unicode)
2731        self.assertEqual(u.replace(u"xy", u"xy"), base)
2732        self.assertTrue(u.center(len(u)).__class__ is unicode)
2733        self.assertEqual(u.center(len(u)), base)
2734        self.assertTrue(u.ljust(len(u)).__class__ is unicode)
2735        self.assertEqual(u.ljust(len(u)), base)
2736        self.assertTrue(u.rjust(len(u)).__class__ is unicode)
2737        self.assertEqual(u.rjust(len(u)), base)
2738        self.assertTrue(u.lower().__class__ is unicode)
2739        self.assertEqual(u.lower(), base)
2740        self.assertTrue(u.upper().__class__ is unicode)
2741        self.assertEqual(u.upper(), base)
2742        self.assertTrue(u.capitalize().__class__ is unicode)
2743        self.assertEqual(u.capitalize(), base)
2744        self.assertTrue(u.title().__class__ is unicode)
2745        self.assertEqual(u.title(), base)
2746        self.assertTrue((u + u"").__class__ is unicode)
2747        self.assertEqual(u + u"", base)
2748        self.assertTrue((u"" + u).__class__ is unicode)
2749        self.assertEqual(u"" + u, base)
2750        self.assertTrue((u * 0).__class__ is unicode)
2751        self.assertEqual(u * 0, u"")
2752        self.assertTrue((u * 1).__class__ is unicode)
2753        self.assertEqual(u * 1, base)
2754        self.assertTrue((u * 2).__class__ is unicode)
2755        self.assertEqual(u * 2, base + base)
2756        self.assertTrue(u[:].__class__ is unicode)
2757        self.assertEqual(u[:], base)
2758        self.assertTrue(u[0:0].__class__ is unicode)
2759        self.assertEqual(u[0:0], u"")
2760
2761        class sublist(list):
2762            pass
2763        a = sublist(range(5))
2764        self.assertEqual(a, range(5))
2765        a.append("hello")
2766        self.assertEqual(a, range(5) + ["hello"])
2767        a[5] = 5
2768        self.assertEqual(a, range(6))
2769        a.extend(range(6, 20))
2770        self.assertEqual(a, range(20))
2771        a[-5:] = []
2772        self.assertEqual(a, range(15))
2773        del a[10:15]
2774        self.assertEqual(len(a), 10)
2775        self.assertEqual(a, range(10))
2776        self.assertEqual(list(a), range(10))
2777        self.assertEqual(a[0], 0)
2778        self.assertEqual(a[9], 9)
2779        self.assertEqual(a[-10], 0)
2780        self.assertEqual(a[-1], 9)
2781        self.assertEqual(a[:5], range(5))
2782
2783        class CountedInput(file):
2784            """Counts lines read by self.readline().
2785
2786            self.lineno is the 0-based ordinal of the last line read, up to
2787            a maximum of one greater than the number of lines in the file.
2788
2789            self.ateof is true if and only if the final "" line has been read,
2790            at which point self.lineno stops incrementing, and further calls
2791            to readline() continue to return "".
2792            """
2793
2794            lineno = 0
2795            ateof = 0
2796            def readline(self):
2797                if self.ateof:
2798                    return ""
2799                s = file.readline(self)
2800                # Next line works too.
2801                # s = super(CountedInput, self).readline()
2802                self.lineno += 1
2803                if s == "":
2804                    self.ateof = 1
2805                return s
2806
2807        f = file(name=test_support.TESTFN, mode='w')
2808        lines = ['a\n', 'b\n', 'c\n']
2809        try:
2810            f.writelines(lines)
2811            f.close()
2812            f = CountedInput(test_support.TESTFN)
2813            for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2814                got = f.readline()
2815                self.assertEqual(expected, got)
2816                self.assertEqual(f.lineno, i)
2817                self.assertEqual(f.ateof, (i > len(lines)))
2818            f.close()
2819        finally:
2820            try:
2821                f.close()
2822            except:
2823                pass
2824            test_support.unlink(test_support.TESTFN)
2825
2826    def test_keywords(self):
2827        # Testing keyword args to basic type constructors ...
2828        self.assertEqual(int(x=1), 1)
2829        self.assertEqual(float(x=2), 2.0)
2830        self.assertEqual(long(x=3), 3L)
2831        self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2832        self.assertEqual(str(object=500), '500')
2833        self.assertEqual(unicode(string='abc', errors='strict'), u'abc')
2834        self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2835        self.assertEqual(list(sequence=(0, 1, 2)), range(3))
2836        # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2837
2838        for constructor in (int, float, long, complex, str, unicode,
2839                            tuple, list, file):
2840            try:
2841                constructor(bogus_keyword_arg=1)
2842            except TypeError:
2843                pass
2844            else:
2845                self.fail("expected TypeError from bogus keyword argument to %r"
2846                            % constructor)
2847
2848    def test_str_subclass_as_dict_key(self):
2849        # Testing a str subclass used as dict key ..
2850
2851        class cistr(str):
2852            """Sublcass of str that computes __eq__ case-insensitively.
2853
2854            Also computes a hash code of the string in canonical form.
2855            """
2856
2857            def __init__(self, value):
2858                self.canonical = value.lower()
2859                self.hashcode = hash(self.canonical)
2860
2861            def __eq__(self, other):
2862                if not isinstance(other, cistr):
2863                    other = cistr(other)
2864                return self.canonical == other.canonical
2865
2866            def __hash__(self):
2867                return self.hashcode
2868
2869        self.assertEqual(cistr('ABC'), 'abc')
2870        self.assertEqual('aBc', cistr('ABC'))
2871        self.assertEqual(str(cistr('ABC')), 'ABC')
2872
2873        d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2874        self.assertEqual(d[cistr('one')], 1)
2875        self.assertEqual(d[cistr('tWo')], 2)
2876        self.assertEqual(d[cistr('THrEE')], 3)
2877        self.assertIn(cistr('ONe'), d)
2878        self.assertEqual(d.get(cistr('thrEE')), 3)
2879
2880    def test_classic_comparisons(self):
2881        # Testing classic comparisons...
2882        class classic:
2883            pass
2884
2885        for base in (classic, int, object):
2886            class C(base):
2887                def __init__(self, value):
2888                    self.value = int(value)
2889                def __cmp__(self, other):
2890                    if isinstance(other, C):
2891                        return cmp(self.value, other.value)
2892                    if isinstance(other, int) or isinstance(other, long):
2893                        return cmp(self.value, other)
2894                    return NotImplemented
2895                __hash__ = None # Silence Py3k warning
2896
2897            c1 = C(1)
2898            c2 = C(2)
2899            c3 = C(3)
2900            self.assertEqual(c1, 1)
2901            c = {1: c1, 2: c2, 3: c3}
2902            for x in 1, 2, 3:
2903                for y in 1, 2, 3:
2904                    self.assertTrue(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2905                    for op in "<", "<=", "==", "!=", ">", ">=":
2906                        self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2907                               "x=%d, y=%d" % (x, y))
2908                    self.assertTrue(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2909                    self.assertTrue(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2910
2911    def test_rich_comparisons(self):
2912        # Testing rich comparisons...
2913        class Z(complex):
2914            pass
2915        z = Z(1)
2916        self.assertEqual(z, 1+0j)
2917        self.assertEqual(1+0j, z)
2918        class ZZ(complex):
2919            def __eq__(self, other):
2920                try:
2921                    return abs(self - other) <= 1e-6
2922                except:
2923                    return NotImplemented
2924            __hash__ = None # Silence Py3k warning
2925        zz = ZZ(1.0000003)
2926        self.assertEqual(zz, 1+0j)
2927        self.assertEqual(1+0j, zz)
2928
2929        class classic:
2930            pass
2931        for base in (classic, int, object, list):
2932            class C(base):
2933                def __init__(self, value):
2934                    self.value = int(value)
2935                def __cmp__(self_, other):
2936                    self.fail("shouldn't call __cmp__")
2937                __hash__ = None # Silence Py3k warning
2938                def __eq__(self, other):
2939                    if isinstance(other, C):
2940                        return self.value == other.value
2941                    if isinstance(other, int) or isinstance(other, long):
2942                        return self.value == other
2943                    return NotImplemented
2944                def __ne__(self, other):
2945                    if isinstance(other, C):
2946                        return self.value != other.value
2947                    if isinstance(other, int) or isinstance(other, long):
2948                        return self.value != other
2949                    return NotImplemented
2950                def __lt__(self, other):
2951                    if isinstance(other, C):
2952                        return self.value < other.value
2953                    if isinstance(other, int) or isinstance(other, long):
2954                        return self.value < other
2955                    return NotImplemented
2956                def __le__(self, other):
2957                    if isinstance(other, C):
2958                        return self.value <= other.value
2959                    if isinstance(other, int) or isinstance(other, long):
2960                        return self.value <= other
2961                    return NotImplemented
2962                def __gt__(self, other):
2963                    if isinstance(other, C):
2964                        return self.value > other.value
2965                    if isinstance(other, int) or isinstance(other, long):
2966                        return self.value > other
2967                    return NotImplemented
2968                def __ge__(self, other):
2969                    if isinstance(other, C):
2970                        return self.value >= other.value
2971                    if isinstance(other, int) or isinstance(other, long):
2972                        return self.value >= other
2973                    return NotImplemented
2974            c1 = C(1)
2975            c2 = C(2)
2976            c3 = C(3)
2977            self.assertEqual(c1, 1)
2978            c = {1: c1, 2: c2, 3: c3}
2979            for x in 1, 2, 3:
2980                for y in 1, 2, 3:
2981                    for op in "<", "<=", "==", "!=", ">", ">=":
2982                        self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2983                               "x=%d, y=%d" % (x, y))
2984                        self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op),
2985                               "x=%d, y=%d" % (x, y))
2986                        self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op),
2987                               "x=%d, y=%d" % (x, y))
2988
2989    def test_coercions(self):
2990        # Testing coercions...
2991        class I(int): pass
2992        coerce(I(0), 0)
2993        coerce(0, I(0))
2994        class L(long): pass
2995        coerce(L(0), 0)
2996        coerce(L(0), 0L)
2997        coerce(0, L(0))
2998        coerce(0L, L(0))
2999        class F(float): pass
3000        coerce(F(0), 0)
3001        coerce(F(0), 0L)
3002        coerce(F(0), 0.)
3003        coerce(0, F(0))
3004        coerce(0L, F(0))
3005        coerce(0., F(0))
3006        class C(complex): pass
3007        coerce(C(0), 0)
3008        coerce(C(0), 0L)
3009        coerce(C(0), 0.)
3010        coerce(C(0), 0j)
3011        coerce(0, C(0))
3012        coerce(0L, C(0))
3013        coerce(0., C(0))
3014        coerce(0j, C(0))
3015
3016    def test_descrdoc(self):
3017        # Testing descriptor doc strings...
3018        def check(descr, what):
3019            self.assertEqual(descr.__doc__, what)
3020        check(file.closed, "True if the file is closed") # getset descriptor
3021        check(file.name, "file name") # member descriptor
3022
3023    def test_doc_descriptor(self):
3024        # Testing __doc__ descriptor...
3025        # SF bug 542984
3026        class DocDescr(object):
3027            def __get__(self, object, otype):
3028                if object:
3029                    object = object.__class__.__name__ + ' instance'
3030                if otype:
3031                    otype = otype.__name__
3032                return 'object=%s; type=%s' % (object, otype)
3033        class OldClass:
3034            __doc__ = DocDescr()
3035        class NewClass(object):
3036            __doc__ = DocDescr()
3037        self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3038        self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3039        self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3040        self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3041
3042    def test_set_class(self):
3043        # Testing __class__ assignment...
3044        class C(object): pass
3045        class D(object): pass
3046        class E(object): pass
3047        class F(D, E): pass
3048        for cls in C, D, E, F:
3049            for cls2 in C, D, E, F:
3050                x = cls()
3051                x.__class__ = cls2
3052                self.assertTrue(x.__class__ is cls2)
3053                x.__class__ = cls
3054                self.assertTrue(x.__class__ is cls)
3055        def cant(x, C):
3056            try:
3057                x.__class__ = C
3058            except TypeError:
3059                pass
3060            else:
3061                self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3062            try:
3063                delattr(x, "__class__")
3064            except (TypeError, AttributeError):
3065                pass
3066            else:
3067                self.fail("shouldn't allow del %r.__class__" % x)
3068        cant(C(), list)
3069        cant(list(), C)
3070        cant(C(), 1)
3071        cant(C(), object)
3072        cant(object(), list)
3073        cant(list(), object)
3074        class Int(int): __slots__ = []
3075        cant(2, Int)
3076        cant(Int(), int)
3077        cant(True, int)
3078        cant(2, bool)
3079        o = object()
3080        cant(o, type(1))
3081        cant(o, type(None))
3082        del o
3083        class G(object):
3084            __slots__ = ["a", "b"]
3085        class H(object):
3086            __slots__ = ["b", "a"]
3087        try:
3088            unicode
3089        except NameError:
3090            class I(object):
3091                __slots__ = ["a", "b"]
3092        else:
3093            class I(object):
3094                __slots__ = [unicode("a"), unicode("b")]
3095        class J(object):
3096            __slots__ = ["c", "b"]
3097        class K(object):
3098            __slots__ = ["a", "b", "d"]
3099        class L(H):
3100            __slots__ = ["e"]
3101        class M(I):
3102            __slots__ = ["e"]
3103        class N(J):
3104            __slots__ = ["__weakref__"]
3105        class P(J):
3106            __slots__ = ["__dict__"]
3107        class Q(J):
3108            pass
3109        class R(J):
3110            __slots__ = ["__dict__", "__weakref__"]
3111
3112        for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3113            x = cls()
3114            x.a = 1
3115            x.__class__ = cls2
3116            self.assertTrue(x.__class__ is cls2,
3117                   "assigning %r as __class__ for %r silently failed" % (cls2, x))
3118            self.assertEqual(x.a, 1)
3119            x.__class__ = cls
3120            self.assertTrue(x.__class__ is cls,
3121                   "assigning %r as __class__ for %r silently failed" % (cls, x))
3122            self.assertEqual(x.a, 1)
3123        for cls in G, J, K, L, M, N, P, R, list, Int:
3124            for cls2 in G, J, K, L, M, N, P, R, list, Int:
3125                if cls is cls2:
3126                    continue
3127                cant(cls(), cls2)
3128
3129        # Issue5283: when __class__ changes in __del__, the wrong
3130        # type gets DECREF'd.
3131        class O(object):
3132            pass
3133        class A(object):
3134            def __del__(self):
3135                self.__class__ = O
3136        l = [A() for x in range(100)]
3137        del l
3138
3139    def test_set_dict(self):
3140        # Testing __dict__ assignment...
3141        class C(object): pass
3142        a = C()
3143        a.__dict__ = {'b': 1}
3144        self.assertEqual(a.b, 1)
3145        def cant(x, dict):
3146            try:
3147                x.__dict__ = dict
3148            except (AttributeError, TypeError):
3149                pass
3150            else:
3151                self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3152        cant(a, None)
3153        cant(a, [])
3154        cant(a, 1)
3155        del a.__dict__ # Deleting __dict__ is allowed
3156
3157        class Base(object):
3158            pass
3159        def verify_dict_readonly(x):
3160            """
3161            x has to be an instance of a class inheriting from Base.
3162            """
3163            cant(x, {})
3164            try:
3165                del x.__dict__
3166            except (AttributeError, TypeError):
3167                pass
3168            else:
3169                self.fail("shouldn't allow del %r.__dict__" % x)
3170            dict_descr = Base.__dict__["__dict__"]
3171            try:
3172                dict_descr.__set__(x, {})
3173            except (AttributeError, TypeError):
3174                pass
3175            else:
3176                self.fail("dict_descr allowed access to %r's dict" % x)
3177
3178        # Classes don't allow __dict__ assignment and have readonly dicts
3179        class Meta1(type, Base):
3180            pass
3181        class Meta2(Base, type):
3182            pass
3183        class D(object):
3184            __metaclass__ = Meta1
3185        class E(object):
3186            __metaclass__ = Meta2
3187        for cls in C, D, E:
3188            verify_dict_readonly(cls)
3189            class_dict = cls.__dict__
3190            try:
3191                class_dict["spam"] = "eggs"
3192            except TypeError:
3193                pass
3194            else:
3195                self.fail("%r's __dict__ can be modified" % cls)
3196
3197        # Modules also disallow __dict__ assignment
3198        class Module1(types.ModuleType, Base):
3199            pass
3200        class Module2(Base, types.ModuleType):
3201            pass
3202        for ModuleType in Module1, Module2:
3203            mod = ModuleType("spam")
3204            verify_dict_readonly(mod)
3205            mod.__dict__["spam"] = "eggs"
3206
3207        # Exception's __dict__ can be replaced, but not deleted
3208        # (at least not any more than regular exception's __dict__ can
3209        # be deleted; on CPython it is not the case, whereas on PyPy they
3210        # can, just like any other new-style instance's __dict__.)
3211        def can_delete_dict(e):
3212            try:
3213                del e.__dict__
3214            except (TypeError, AttributeError):
3215                return False
3216            else:
3217                return True
3218        class Exception1(Exception, Base):
3219            pass
3220        class Exception2(Base, Exception):
3221            pass
3222        for ExceptionType in Exception, Exception1, Exception2:
3223            e = ExceptionType()
3224            e.__dict__ = {"a": 1}
3225            self.assertEqual(e.a, 1)
3226            self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
3227
3228    def test_pickles(self):
3229        # Testing pickling and copying new-style classes and objects...
3230        import pickle, cPickle
3231
3232        def sorteditems(d):
3233            L = d.items()
3234            L.sort()
3235            return L
3236
3237        global C
3238        class C(object):
3239            def __init__(self, a, b):
3240                super(C, self).__init__()
3241                self.a = a
3242                self.b = b
3243            def __repr__(self):
3244                return "C(%r, %r)" % (self.a, self.b)
3245
3246        global C1
3247        class C1(list):
3248            def __new__(cls, a, b):
3249                return super(C1, cls).__new__(cls)
3250            def __getnewargs__(self):
3251                return (self.a, self.b)
3252            def __init__(self, a, b):
3253                self.a = a
3254                self.b = b
3255            def __repr__(self):
3256                return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3257
3258        global C2
3259        class C2(int):
3260            def __new__(cls, a, b, val=0):
3261                return super(C2, cls).__new__(cls, val)
3262            def __getnewargs__(self):
3263                return (self.a, self.b, int(self))
3264            def __init__(self, a, b, val=0):
3265                self.a = a
3266                self.b = b
3267            def __repr__(self):
3268                return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3269
3270        global C3
3271        class C3(object):
3272            def __init__(self, foo):
3273                self.foo = foo
3274            def __getstate__(self):
3275                return self.foo
3276            def __setstate__(self, foo):
3277                self.foo = foo
3278
3279        global C4classic, C4
3280        class C4classic: # classic
3281            pass
3282        class C4(C4classic, object): # mixed inheritance
3283            pass
3284
3285        for p in pickle, cPickle:
3286            for bin in 0, 1:
3287                for cls in C, C1, C2:
3288                    s = p.dumps(cls, bin)
3289                    cls2 = p.loads(s)
3290                    self.assertTrue(cls2 is cls)
3291
3292                a = C1(1, 2); a.append(42); a.append(24)
3293                b = C2("hello", "world", 42)
3294                s = p.dumps((a, b), bin)
3295                x, y = p.loads(s)
3296                self.assertEqual(x.__class__, a.__class__)
3297                self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3298                self.assertEqual(y.__class__, b.__class__)
3299                self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3300                self.assertEqual(repr(x), repr(a))
3301                self.assertEqual(repr(y), repr(b))
3302                # Test for __getstate__ and __setstate__ on new style class
3303                u = C3(42)
3304                s = p.dumps(u, bin)
3305                v = p.loads(s)
3306                self.assertEqual(u.__class__, v.__class__)
3307                self.assertEqual(u.foo, v.foo)
3308                # Test for picklability of hybrid class
3309                u = C4()
3310                u.foo = 42
3311                s = p.dumps(u, bin)
3312                v = p.loads(s)
3313                self.assertEqual(u.__class__, v.__class__)
3314                self.assertEqual(u.foo, v.foo)
3315
3316        # Testing copy.deepcopy()
3317        import copy
3318        for cls in C, C1, C2:
3319            cls2 = copy.deepcopy(cls)
3320            self.assertTrue(cls2 is cls)
3321
3322        a = C1(1, 2); a.append(42); a.append(24)
3323        b = C2("hello", "world", 42)
3324        x, y = copy.deepcopy((a, b))
3325        self.assertEqual(x.__class__, a.__class__)
3326        self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3327        self.assertEqual(y.__class__, b.__class__)
3328        self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3329        self.assertEqual(repr(x), repr(a))
3330        self.assertEqual(repr(y), repr(b))
3331
3332    def test_pickle_slots(self):
3333        # Testing pickling of classes with __slots__ ...
3334        import pickle, cPickle
3335        # Pickling of classes with __slots__ but without __getstate__ should fail
3336        global B, C, D, E
3337        class B(object):
3338            pass
3339        for base in [object, B]:
3340            class C(base):
3341                __slots__ = ['a']
3342            class D(C):
3343                pass
3344            try:
3345                pickle.dumps(C())
3346            except TypeError:
3347                pass
3348            else:
3349                self.fail("should fail: pickle C instance - %s" % base)
3350            try:
3351                cPickle.dumps(C())
3352            except TypeError:
3353                pass
3354            else:
3355                self.fail("should fail: cPickle C instance - %s" % base)
3356            try:
3357                pickle.dumps(C())
3358            except TypeError:
3359                pass
3360            else:
3361                self.fail("should fail: pickle D instance - %s" % base)
3362            try:
3363                cPickle.dumps(D())
3364            except TypeError:
3365                pass
3366            else:
3367                self.fail("should fail: cPickle D instance - %s" % base)
3368            # Give C a nice generic __getstate__ and __setstate__
3369            class C(base):
3370                __slots__ = ['a']
3371                def __getstate__(self):
3372                    try:
3373                        d = self.__dict__.copy()
3374                    except AttributeError:
3375                        d = {}
3376                    for cls in self.__class__.__mro__:
3377                        for sn in cls.__dict__.get('__slots__', ()):
3378                            try:
3379                                d[sn] = getattr(self, sn)
3380                            except AttributeError:
3381                                pass
3382                    return d
3383                def __setstate__(self, d):
3384                    for k, v in d.items():
3385                        setattr(self, k, v)
3386            class D(C):
3387                pass
3388            # Now it should work
3389            x = C()
3390            y = pickle.loads(pickle.dumps(x))
3391            self.assertEqual(hasattr(y, 'a'), 0)
3392            y = cPickle.loads(cPickle.dumps(x))
3393            self.assertEqual(hasattr(y, 'a'), 0)
3394            x.a = 42
3395            y = pickle.loads(pickle.dumps(x))
3396            self.assertEqual(y.a, 42)
3397            y = cPickle.loads(cPickle.dumps(x))
3398            self.assertEqual(y.a, 42)
3399            x = D()
3400            x.a = 42
3401            x.b = 100
3402            y = pickle.loads(pickle.dumps(x))
3403            self.assertEqual(y.a + y.b, 142)
3404            y = cPickle.loads(cPickle.dumps(x))
3405            self.assertEqual(y.a + y.b, 142)
3406            # A subclass that adds a slot should also work
3407            class E(C):
3408                __slots__ = ['b']
3409            x = E()
3410            x.a = 42
3411            x.b = "foo"
3412            y = pickle.loads(pickle.dumps(x))
3413            self.assertEqual(y.a, x.a)
3414            self.assertEqual(y.b, x.b)
3415            y = cPickle.loads(cPickle.dumps(x))
3416            self.assertEqual(y.a, x.a)
3417            self.assertEqual(y.b, x.b)
3418
3419    def test_binary_operator_override(self):
3420        # Testing overrides of binary operations...
3421        class I(int):
3422            def __repr__(self):
3423                return "I(%r)" % int(self)
3424            def __add__(self, other):
3425                return I(int(self) + int(other))
3426            __radd__ = __add__
3427            def __pow__(self, other, mod=None):
3428                if mod is None:
3429                    return I(pow(int(self), int(other)))
3430                else:
3431                    return I(pow(int(self), int(other), int(mod)))
3432            def __rpow__(self, other, mod=None):
3433                if mod is None:
3434                    return I(pow(int(other), int(self), mod))
3435                else:
3436                    return I(pow(int(other), int(self), int(mod)))
3437
3438        self.assertEqual(repr(I(1) + I(2)), "I(3)")
3439        self.assertEqual(repr(I(1) + 2), "I(3)")
3440        self.assertEqual(repr(1 + I(2)), "I(3)")
3441        self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3442        self.assertEqual(repr(2 ** I(3)), "I(8)")
3443        self.assertEqual(repr(I(2) ** 3), "I(8)")
3444        self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3445        class S(str):
3446            def __eq__(self, other):
3447                return self.lower() == other.lower()
3448            __hash__ = None # Silence Py3k warning
3449
3450    def test_subclass_propagation(self):
3451        # Testing propagation of slot functions to subclasses...
3452        class A(object):
3453            pass
3454        class B(A):
3455            pass
3456        class C(A):
3457            pass
3458        class D(B, C):
3459            pass
3460        d = D()
3461        orig_hash = hash(d) # related to id(d) in platform-dependent ways
3462        A.__hash__ = lambda self: 42
3463        self.assertEqual(hash(d), 42)
3464        C.__hash__ = lambda self: 314
3465        self.assertEqual(hash(d), 314)
3466        B.__hash__ = lambda self: 144
3467        self.assertEqual(hash(d), 144)
3468        D.__hash__ = lambda self: 100
3469        self.assertEqual(hash(d), 100)
3470        D.__hash__ = None
3471        self.assertRaises(TypeError, hash, d)
3472        del D.__hash__
3473        self.assertEqual(hash(d), 144)
3474        B.__hash__ = None
3475        self.assertRaises(TypeError, hash, d)
3476        del B.__hash__
3477        self.assertEqual(hash(d), 314)
3478        C.__hash__ = None
3479        self.assertRaises(TypeError, hash, d)
3480        del C.__hash__
3481        self.assertEqual(hash(d), 42)
3482        A.__hash__ = None
3483        self.assertRaises(TypeError, hash, d)
3484        del A.__hash__
3485        self.assertEqual(hash(d), orig_hash)
3486        d.foo = 42
3487        d.bar = 42
3488        self.assertEqual(d.foo, 42)
3489        self.assertEqual(d.bar, 42)
3490        def __getattribute__(self, name):
3491            if name == "foo":
3492                return 24
3493            return object.__getattribute__(self, name)
3494        A.__getattribute__ = __getattribute__
3495        self.assertEqual(d.foo, 24)
3496        self.assertEqual(d.bar, 42)
3497        def __getattr__(self, name):
3498            if name in ("spam", "foo", "bar"):
3499                return "hello"
3500            raise AttributeError, name
3501        B.__getattr__ = __getattr__
3502        self.assertEqual(d.spam, "hello")
3503        self.assertEqual(d.foo, 24)
3504        self.assertEqual(d.bar, 42)
3505        del A.__getattribute__
3506        self.assertEqual(d.foo, 42)
3507        del d.foo
3508        self.assertEqual(d.foo, "hello")
3509        self.assertEqual(d.bar, 42)
3510        del B.__getattr__
3511        try:
3512            d.foo
3513        except AttributeError:
3514            pass
3515        else:
3516            self.fail("d.foo should be undefined now")
3517
3518        # Test a nasty bug in recurse_down_subclasses()
3519        class A(object):
3520            pass
3521        class B(A):
3522            pass
3523        del B
3524        test_support.gc_collect()
3525        A.__setitem__ = lambda *a: None # crash
3526
3527    def test_buffer_inheritance(self):
3528        # Testing that buffer interface is inherited ...
3529
3530        import binascii
3531        # SF bug [#470040] ParseTuple t# vs subclasses.
3532
3533        class MyStr(str):
3534            pass
3535        base = 'abc'
3536        m = MyStr(base)
3537        # b2a_hex uses the buffer interface to get its argument's value, via
3538        # PyArg_ParseTuple 't#' code.
3539        self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3540
3541        # It's not clear that unicode will continue to support the character
3542        # buffer interface, and this test will fail if that's taken away.
3543        class MyUni(unicode):
3544            pass
3545        base = u'abc'
3546        m = MyUni(base)
3547        self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3548
3549        class MyInt(int):
3550            pass
3551        m = MyInt(42)
3552        try:
3553            binascii.b2a_hex(m)
3554            self.fail('subclass of int should not have a buffer interface')
3555        except TypeError:
3556            pass
3557
3558    def test_str_of_str_subclass(self):
3559        # Testing __str__ defined in subclass of str ...
3560        import binascii
3561        import cStringIO
3562
3563        class octetstring(str):
3564            def __str__(self):
3565                return binascii.b2a_hex(self)
3566            def __repr__(self):
3567                return self + " repr"
3568
3569        o = octetstring('A')
3570        self.assertEqual(type(o), octetstring)
3571        self.assertEqual(type(str(o)), str)
3572        self.assertEqual(type(repr(o)), str)
3573        self.assertEqual(ord(o), 0x41)
3574        self.assertEqual(str(o), '41')
3575        self.assertEqual(repr(o), 'A repr')
3576        self.assertEqual(o.__str__(), '41')
3577        self.assertEqual(o.__repr__(), 'A repr')
3578
3579        capture = cStringIO.StringIO()
3580        # Calling str() or not exercises different internal paths.
3581        print >> capture, o
3582        print >> capture, str(o)
3583        self.assertEqual(capture.getvalue(), '41\n41\n')
3584        capture.close()
3585
3586    def test_keyword_arguments(self):
3587        # Testing keyword arguments to __init__, __call__...
3588        def f(a): return a
3589        self.assertEqual(f.__call__(a=42), 42)
3590        a = []
3591        list.__init__(a, sequence=[0, 1, 2])
3592        self.assertEqual(a, [0, 1, 2])
3593
3594    def test_recursive_call(self):
3595        # Testing recursive __call__() by setting to instance of class...
3596        class A(object):
3597            pass
3598
3599        A.__call__ = A()
3600        try:
3601            A()()
3602        except RuntimeError:
3603            pass
3604        else:
3605            self.fail("Recursion limit should have been reached for __call__()")
3606
3607    def test_delete_hook(self):
3608        # Testing __del__ hook...
3609        log = []
3610        class C(object):
3611            def __del__(self):
3612                log.append(1)
3613        c = C()
3614        self.assertEqual(log, [])
3615        del c
3616        test_support.gc_collect()
3617        self.assertEqual(log, [1])
3618
3619        class D(object): pass
3620        d = D()
3621        try: del d[0]
3622        except TypeError: pass
3623        else: self.fail("invalid del() didn't raise TypeError")
3624
3625    def test_hash_inheritance(self):
3626        # Testing hash of mutable subclasses...
3627
3628        class mydict(dict):
3629            pass
3630        d = mydict()
3631        try:
3632            hash(d)
3633        except TypeError:
3634            pass
3635        else:
3636            self.fail("hash() of dict subclass should fail")
3637
3638        class mylist(list):
3639            pass
3640        d = mylist()
3641        try:
3642            hash(d)
3643        except TypeError:
3644            pass
3645        else:
3646            self.fail("hash() of list subclass should fail")
3647
3648    def test_str_operations(self):
3649        try: 'a' + 5
3650        except TypeError: pass
3651        else: self.fail("'' + 5 doesn't raise TypeError")
3652
3653        try: ''.split('')
3654        except ValueError: pass
3655        else: self.fail("''.split('') doesn't raise ValueError")
3656
3657        try: ''.join([0])
3658        except TypeError: pass
3659        else: self.fail("''.join([0]) doesn't raise TypeError")
3660
3661        try: ''.rindex('5')
3662        except ValueError: pass
3663        else: self.fail("''.rindex('5') doesn't raise ValueError")
3664
3665        try: '%(n)s' % None
3666        except TypeError: pass
3667        else: self.fail("'%(n)s' % None doesn't raise TypeError")
3668
3669        try: '%(n' % {}
3670        except ValueError: pass
3671        else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3672
3673        try: '%*s' % ('abc')
3674        except TypeError: pass
3675        else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3676
3677        try: '%*.*s' % ('abc', 5)
3678        except TypeError: pass
3679        else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3680
3681        try: '%s' % (1, 2)
3682        except TypeError: pass
3683        else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3684
3685        try: '%' % None
3686        except ValueError: pass
3687        else: self.fail("'%' % None doesn't raise ValueError")
3688
3689        self.assertEqual('534253'.isdigit(), 1)
3690        self.assertEqual('534253x'.isdigit(), 0)
3691        self.assertEqual('%c' % 5, '\x05')
3692        self.assertEqual('%c' % '5', '5')
3693
3694    def test_deepcopy_recursive(self):
3695        # Testing deepcopy of recursive objects...
3696        class Node:
3697            pass
3698        a = Node()
3699        b = Node()
3700        a.b = b
3701        b.a = a
3702        z = deepcopy(a) # This blew up before
3703
3704    def test_unintialized_modules(self):
3705        # Testing uninitialized module objects...
3706        from types import ModuleType as M
3707        m = M.__new__(M)
3708        str(m)
3709        self.assertEqual(hasattr(m, "__name__"), 0)
3710        self.assertEqual(hasattr(m, "__file__"), 0)
3711        self.assertEqual(hasattr(m, "foo"), 0)
3712        self.assertFalse(m.__dict__)   # None or {} are both reasonable answers
3713        m.foo = 1
3714        self.assertEqual(m.__dict__, {"foo": 1})
3715
3716    def test_funny_new(self):
3717        # Testing __new__ returning something unexpected...
3718        class C(object):
3719            def __new__(cls, arg):
3720                if isinstance(arg, str): return [1, 2, 3]
3721                elif isinstance(arg, int): return object.__new__(D)
3722                else: return object.__new__(cls)
3723        class D(C):
3724            def __init__(self, arg):
3725                self.foo = arg
3726        self.assertEqual(C("1"), [1, 2, 3])
3727        self.assertEqual(D("1"), [1, 2, 3])
3728        d = D(None)
3729        self.assertEqual(d.foo, None)
3730        d = C(1)
3731        self.assertEqual(isinstance(d, D), True)
3732        self.assertEqual(d.foo, 1)
3733        d = D(1)
3734        self.assertEqual(isinstance(d, D), True)
3735        self.assertEqual(d.foo, 1)
3736
3737    def test_imul_bug(self):
3738        # Testing for __imul__ problems...
3739        # SF bug 544647
3740        class C(object):
3741            def __imul__(self, other):
3742                return (self, other)
3743        x = C()
3744        y = x
3745        y *= 1.0
3746        self.assertEqual(y, (x, 1.0))
3747        y = x
3748        y *= 2
3749        self.assertEqual(y, (x, 2))
3750        y = x
3751        y *= 3L
3752        self.assertEqual(y, (x, 3L))
3753        y = x
3754        y *= 1L<<100
3755        self.assertEqual(y, (x, 1L<<100))
3756        y = x
3757        y *= None
3758        self.assertEqual(y, (x, None))
3759        y = x
3760        y *= "foo"
3761        self.assertEqual(y, (x, "foo"))
3762
3763    def test_copy_setstate(self):
3764        # Testing that copy.*copy() correctly uses __setstate__...
3765        import copy
3766        class C(object):
3767            def __init__(self, foo=None):
3768                self.foo = foo
3769                self.__foo = foo
3770            def setfoo(self, foo=None):
3771                self.foo = foo
3772            def getfoo(self):
3773                return self.__foo
3774            def __getstate__(self):
3775                return [self.foo]
3776            def __setstate__(self_, lst):
3777                self.assertEqual(len(lst), 1)
3778                self_.__foo = self_.foo = lst[0]
3779        a = C(42)
3780        a.setfoo(24)
3781        self.assertEqual(a.foo, 24)
3782        self.assertEqual(a.getfoo(), 42)
3783        b = copy.copy(a)
3784        self.assertEqual(b.foo, 24)
3785        self.assertEqual(b.getfoo(), 24)
3786        b = copy.deepcopy(a)
3787        self.assertEqual(b.foo, 24)
3788        self.assertEqual(b.getfoo(), 24)
3789
3790    def test_slices(self):
3791        # Testing cases with slices and overridden __getitem__ ...
3792
3793        # Strings
3794        self.assertEqual("hello"[:4], "hell")
3795        self.assertEqual("hello"[slice(4)], "hell")
3796        self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3797        class S(str):
3798            def __getitem__(self, x):
3799                return str.__getitem__(self, x)
3800        self.assertEqual(S("hello")[:4], "hell")
3801        self.assertEqual(S("hello")[slice(4)], "hell")
3802        self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3803        # Tuples
3804        self.assertEqual((1,2,3)[:2], (1,2))
3805        self.assertEqual((1,2,3)[slice(2)], (1,2))
3806        self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3807        class T(tuple):
3808            def __getitem__(self, x):
3809                return tuple.__getitem__(self, x)
3810        self.assertEqual(T((1,2,3))[:2], (1,2))
3811        self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3812        self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3813        # Lists
3814        self.assertEqual([1,2,3][:2], [1,2])
3815        self.assertEqual([1,2,3][slice(2)], [1,2])
3816        self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3817        class L(list):
3818            def __getitem__(self, x):
3819                return list.__getitem__(self, x)
3820        self.assertEqual(L([1,2,3])[:2], [1,2])
3821        self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3822        self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3823        # Now do lists and __setitem__
3824        a = L([1,2,3])
3825        a[slice(1, 3)] = [3,2]
3826        self.assertEqual(a, [1,3,2])
3827        a[slice(0, 2, 1)] = [3,1]
3828        self.assertEqual(a, [3,1,2])
3829        a.__setitem__(slice(1, 3), [2,1])
3830        self.assertEqual(a, [3,2,1])
3831        a.__setitem__(slice(0, 2, 1), [2,3])
3832        self.assertEqual(a, [2,3,1])
3833
3834    def test_subtype_resurrection(self):
3835        # Testing resurrection of new-style instance...
3836
3837        class C(object):
3838            container = []
3839
3840            def __del__(self):
3841                # resurrect the instance
3842                C.container.append(self)
3843
3844        c = C()
3845        c.attr = 42
3846
3847        # The most interesting thing here is whether this blows up, due to
3848        # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3849        # bug).
3850        del c
3851
3852        # If that didn't blow up, it's also interesting to see whether clearing
3853        # the last container slot works: that will attempt to delete c again,
3854        # which will cause c to get appended back to the container again
3855        # "during" the del.  (On non-CPython implementations, however, __del__
3856        # is typically not called again.)
3857        test_support.gc_collect()
3858        self.assertEqual(len(C.container), 1)
3859        del C.container[-1]
3860        if test_support.check_impl_detail():
3861            test_support.gc_collect()
3862            self.assertEqual(len(C.container), 1)
3863            self.assertEqual(C.container[-1].attr, 42)
3864
3865        # Make c mortal again, so that the test framework with -l doesn't report
3866        # it as a leak.
3867        del C.__del__
3868
3869    def test_slots_trash(self):
3870        # Testing slot trash...
3871        # Deallocating deeply nested slotted trash caused stack overflows
3872        class trash(object):
3873            __slots__ = ['x']
3874            def __init__(self, x):
3875                self.x = x
3876        o = None
3877        for i in xrange(50000):
3878            o = trash(o)
3879        del o
3880
3881    def test_slots_multiple_inheritance(self):
3882        # SF bug 575229, multiple inheritance w/ slots dumps core
3883        class A(object):
3884            __slots__=()
3885        class B(object):
3886            pass
3887        class C(A,B) :
3888            __slots__=()
3889        if test_support.check_impl_detail():
3890            self.assertEqual(C.__basicsize__, B.__basicsize__)
3891        self.assertTrue(hasattr(C, '__dict__'))
3892        self.assertTrue(hasattr(C, '__weakref__'))
3893        C().x = 2
3894
3895    def test_rmul(self):
3896        # Testing correct invocation of __rmul__...
3897        # SF patch 592646
3898        class C(object):
3899            def __mul__(self, other):
3900                return "mul"
3901            def __rmul__(self, other):
3902                return "rmul"
3903        a = C()
3904        self.assertEqual(a*2, "mul")
3905        self.assertEqual(a*2.2, "mul")
3906        self.assertEqual(2*a, "rmul")
3907        self.assertEqual(2.2*a, "rmul")
3908
3909    def test_ipow(self):
3910        # Testing correct invocation of __ipow__...
3911        # [SF bug 620179]
3912        class C(object):
3913            def __ipow__(self, other):
3914                pass
3915        a = C()
3916        a **= 2
3917
3918    def test_mutable_bases(self):
3919        # Testing mutable bases...
3920
3921        # stuff that should work:
3922        class C(object):
3923            pass
3924        class C2(object):
3925            def __getattribute__(self, attr):
3926                if attr == 'a':
3927                    return 2
3928                else:
3929                    return super(C2, self).__getattribute__(attr)
3930            def meth(self):
3931                return 1
3932        class D(C):
3933            pass
3934        class E(D):
3935            pass
3936        d = D()
3937        e = E()
3938        D.__bases__ = (C,)
3939        D.__bases__ = (C2,)
3940        self.assertEqual(d.meth(), 1)
3941        self.assertEqual(e.meth(), 1)
3942        self.assertEqual(d.a, 2)
3943        self.assertEqual(e.a, 2)
3944        self.assertEqual(C2.__subclasses__(), [D])
3945
3946        try:
3947            del D.__bases__
3948        except (TypeError, AttributeError):
3949            pass
3950        else:
3951            self.fail("shouldn't be able to delete .__bases__")
3952
3953        try:
3954            D.__bases__ = ()
3955        except TypeError, msg:
3956            if str(msg) == "a new-style class can't have only classic bases":
3957                self.fail("wrong error message for .__bases__ = ()")
3958        else:
3959            self.fail("shouldn't be able to set .__bases__ to ()")
3960
3961        try:
3962            D.__bases__ = (D,)
3963        except TypeError:
3964            pass
3965        else:
3966            # actually, we'll have crashed by here...
3967            self.fail("shouldn't be able to create inheritance cycles")
3968
3969        try:
3970            D.__bases__ = (C, C)
3971        except TypeError:
3972            pass
3973        else:
3974            self.fail("didn't detect repeated base classes")
3975
3976        try:
3977            D.__bases__ = (E,)
3978        except TypeError:
3979            pass
3980        else:
3981            self.fail("shouldn't be able to create inheritance cycles")
3982
3983        # let's throw a classic class into the mix:
3984        class Classic:
3985            def meth2(self):
3986                return 3
3987
3988        D.__bases__ = (C, Classic)
3989
3990        self.assertEqual(d.meth2(), 3)
3991        self.assertEqual(e.meth2(), 3)
3992        try:
3993            d.a
3994        except AttributeError:
3995            pass
3996        else:
3997            self.fail("attribute should have vanished")
3998
3999        try:
4000            D.__bases__ = (Classic,)
4001        except TypeError:
4002            pass
4003        else:
4004            self.fail("new-style class must have a new-style base")
4005
4006    def test_builtin_bases(self):
4007        # Make sure all the builtin types can have their base queried without
4008        # segfaulting. See issue #5787.
4009        builtin_types = [tp for tp in __builtin__.__dict__.itervalues()
4010                         if isinstance(tp, type)]
4011        for tp in builtin_types:
4012            object.__getattribute__(tp, "__bases__")
4013            if tp is not object:
4014                self.assertEqual(len(tp.__bases__), 1, tp)
4015
4016        class L(list):
4017            pass
4018
4019        class C(object):
4020            pass
4021
4022        class D(C):
4023            pass
4024
4025        try:
4026            L.__bases__ = (dict,)
4027        except TypeError:
4028            pass
4029        else:
4030            self.fail("shouldn't turn list subclass into dict subclass")
4031
4032        try:
4033            list.__bases__ = (dict,)
4034        except TypeError:
4035            pass
4036        else:
4037            self.fail("shouldn't be able to assign to list.__bases__")
4038
4039        try:
4040            D.__bases__ = (C, list)
4041        except TypeError:
4042            pass
4043        else:
4044            assert 0, "best_base calculation found wanting"
4045
4046
4047    def test_mutable_bases_with_failing_mro(self):
4048        # Testing mutable bases with failing mro...
4049        class WorkOnce(type):
4050            def __new__(self, name, bases, ns):
4051                self.flag = 0
4052                return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4053            def mro(self):
4054                if self.flag > 0:
4055                    raise RuntimeError, "bozo"
4056                else:
4057                    self.flag += 1
4058                    return type.mro(self)
4059
4060        class WorkAlways(type):
4061            def mro(self):
4062                # this is here to make sure that .mro()s aren't called
4063                # with an exception set (which was possible at one point).
4064                # An error message will be printed in a debug build.
4065                # What's a good way to test for this?
4066                return type.mro(self)
4067
4068        class C(object):
4069            pass
4070
4071        class C2(object):
4072            pass
4073
4074        class D(C):
4075            pass
4076
4077        class E(D):
4078            pass
4079
4080        class F(D):
4081            __metaclass__ = WorkOnce
4082
4083        class G(D):
4084            __metaclass__ = WorkAlways
4085
4086        # Immediate subclasses have their mro's adjusted in alphabetical
4087        # order, so E's will get adjusted before adjusting F's fails.  We
4088        # check here that E's gets restored.
4089
4090        E_mro_before = E.__mro__
4091        D_mro_before = D.__mro__
4092
4093        try:
4094            D.__bases__ = (C2,)
4095        except RuntimeError:
4096            self.assertEqual(E.__mro__, E_mro_before)
4097            self.assertEqual(D.__mro__, D_mro_before)
4098        else:
4099            self.fail("exception not propagated")
4100
4101    def test_mutable_bases_catch_mro_conflict(self):
4102        # Testing mutable bases catch mro conflict...
4103        class A(object):
4104            pass
4105
4106        class B(object):
4107            pass
4108
4109        class C(A, B):
4110            pass
4111
4112        class D(A, B):
4113            pass
4114
4115        class E(C, D):
4116            pass
4117
4118        try:
4119            C.__bases__ = (B, A)
4120        except TypeError:
4121            pass
4122        else:
4123            self.fail("didn't catch MRO conflict")
4124
4125    def test_mutable_names(self):
4126        # Testing mutable names...
4127        class C(object):
4128            pass
4129
4130        # C.__module__ could be 'test_descr' or '__main__'
4131        mod = C.__module__
4132
4133        C.__name__ = 'D'
4134        self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4135
4136        C.__name__ = 'D.E'
4137        self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4138
4139    def test_evil_type_name(self):
4140        # A badly placed Py_DECREF in type_set_name led to arbitrary code
4141        # execution while the type structure was not in a sane state, and a
4142        # possible segmentation fault as a result.  See bug #16447.
4143        class Nasty(str):
4144            def __del__(self):
4145                C.__name__ = "other"
4146
4147        class C(object):
4148            pass
4149
4150        C.__name__ = Nasty("abc")
4151        C.__name__ = "normal"
4152
4153    def test_subclass_right_op(self):
4154        # Testing correct dispatch of subclass overloading __r<op>__...
4155
4156        # This code tests various cases where right-dispatch of a subclass
4157        # should be preferred over left-dispatch of a base class.
4158
4159        # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4160
4161        class B(int):
4162            def __floordiv__(self, other):
4163                return "B.__floordiv__"
4164            def __rfloordiv__(self, other):
4165                return "B.__rfloordiv__"
4166
4167        self.assertEqual(B(1) // 1, "B.__floordiv__")
4168        self.assertEqual(1 // B(1), "B.__rfloordiv__")
4169
4170        # Case 2: subclass of object; this is just the baseline for case 3
4171
4172        class C(object):
4173            def __floordiv__(self, other):
4174                return "C.__floordiv__"
4175            def __rfloordiv__(self, other):
4176                return "C.__rfloordiv__"
4177
4178        self.assertEqual(C() // 1, "C.__floordiv__")
4179        self.assertEqual(1 // C(), "C.__rfloordiv__")
4180
4181        # Case 3: subclass of new-style class; here it gets interesting
4182
4183        class D(C):
4184            def __floordiv__(self, other):
4185                return "D.__floordiv__"
4186            def __rfloordiv__(self, other):
4187                return "D.__rfloordiv__"
4188
4189        self.assertEqual(D() // C(), "D.__floordiv__")
4190        self.assertEqual(C() // D(), "D.__rfloordiv__")
4191
4192        # Case 4: this didn't work right in 2.2.2 and 2.3a1
4193
4194        class E(C):
4195            pass
4196
4197        self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4198
4199        self.assertEqual(E() // 1, "C.__floordiv__")
4200        self.assertEqual(1 // E(), "C.__rfloordiv__")
4201        self.assertEqual(E() // C(), "C.__floordiv__")
4202        self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4203
4204    @test_support.impl_detail("testing an internal kind of method object")
4205    def test_meth_class_get(self):
4206        # Testing __get__ method of METH_CLASS C methods...
4207        # Full coverage of descrobject.c::classmethod_get()
4208
4209        # Baseline
4210        arg = [1, 2, 3]
4211        res = {1: None, 2: None, 3: None}
4212        self.assertEqual(dict.fromkeys(arg), res)
4213        self.assertEqual({}.fromkeys(arg), res)
4214
4215        # Now get the descriptor
4216        descr = dict.__dict__["fromkeys"]
4217
4218        # More baseline using the descriptor directly
4219        self.assertEqual(descr.__get__(None, dict)(arg), res)
4220        self.assertEqual(descr.__get__({})(arg), res)
4221
4222        # Now check various error cases
4223        try:
4224            descr.__get__(None, None)
4225        except TypeError:
4226            pass
4227        else:
4228            self.fail("shouldn't have allowed descr.__get__(None, None)")
4229        try:
4230            descr.__get__(42)
4231        except TypeError:
4232            pass
4233        else:
4234            self.fail("shouldn't have allowed descr.__get__(42)")
4235        try:
4236            descr.__get__(None, 42)
4237        except TypeError:
4238            pass
4239        else:
4240            self.fail("shouldn't have allowed descr.__get__(None, 42)")
4241        try:
4242            descr.__get__(None, int)
4243        except TypeError:
4244            pass
4245        else:
4246            self.fail("shouldn't have allowed descr.__get__(None, int)")
4247
4248    def test_isinst_isclass(self):
4249        # Testing proxy isinstance() and isclass()...
4250        class Proxy(object):
4251            def __init__(self, obj):
4252                self.__obj = obj
4253            def __getattribute__(self, name):
4254                if name.startswith("_Proxy__"):
4255                    return object.__getattribute__(self, name)
4256                else:
4257                    return getattr(self.__obj, name)
4258        # Test with a classic class
4259        class C:
4260            pass
4261        a = C()
4262        pa = Proxy(a)
4263        self.assertIsInstance(a, C)  # Baseline
4264        self.assertIsInstance(pa, C) # Test
4265        # Test with a classic subclass
4266        class D(C):
4267            pass
4268        a = D()
4269        pa = Proxy(a)
4270        self.assertIsInstance(a, C)  # Baseline
4271        self.assertIsInstance(pa, C) # Test
4272        # Test with a new-style class
4273        class C(object):
4274            pass
4275        a = C()
4276        pa = Proxy(a)
4277        self.assertIsInstance(a, C)  # Baseline
4278        self.assertIsInstance(pa, C) # Test
4279        # Test with a new-style subclass
4280        class D(C):
4281            pass
4282        a = D()
4283        pa = Proxy(a)
4284        self.assertIsInstance(a, C)  # Baseline
4285        self.assertIsInstance(pa, C) # Test
4286
4287    def test_proxy_super(self):
4288        # Testing super() for a proxy object...
4289        class Proxy(object):
4290            def __init__(self, obj):
4291                self.__obj = obj
4292            def __getattribute__(self, name):
4293                if name.startswith("_Proxy__"):
4294                    return object.__getattribute__(self, name)
4295                else:
4296                    return getattr(self.__obj, name)
4297
4298        class B(object):
4299            def f(self):
4300                return "B.f"
4301
4302        class C(B):
4303            def f(self):
4304                return super(C, self).f() + "->C.f"
4305
4306        obj = C()
4307        p = Proxy(obj)
4308        self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4309
4310    def test_carloverre(self):
4311        # Testing prohibition of Carlo Verre's hack...
4312        try:
4313            object.__setattr__(str, "foo", 42)
4314        except TypeError:
4315            pass
4316        else:
4317            self.fail("Carlo Verre __setattr__ succeeded!")
4318        try:
4319            object.__delattr__(str, "lower")
4320        except TypeError:
4321            pass
4322        else:
4323            self.fail("Carlo Verre __delattr__ succeeded!")
4324
4325    def test_weakref_segfault(self):
4326        # Testing weakref segfault...
4327        # SF 742911
4328        import weakref
4329
4330        class Provoker:
4331            def __init__(self, referrent):
4332                self.ref = weakref.ref(referrent)
4333
4334            def __del__(self):
4335                x = self.ref()
4336
4337        class Oops(object):
4338            pass
4339
4340        o = Oops()
4341        o.whatever = Provoker(o)
4342        del o
4343
4344    def test_wrapper_segfault(self):
4345        # SF 927248: deeply nested wrappers could cause stack overflow
4346        f = lambda:None
4347        for i in xrange(1000000):
4348            f = f.__call__
4349        f = None
4350
4351    def test_file_fault(self):
4352        # Testing sys.stdout is changed in getattr...
4353        test_stdout = sys.stdout
4354        class StdoutGuard:
4355            def __getattr__(self, attr):
4356                sys.stdout = sys.__stdout__
4357                raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4358        sys.stdout = StdoutGuard()
4359        try:
4360            print "Oops!"
4361        except RuntimeError:
4362            pass
4363        finally:
4364            sys.stdout = test_stdout
4365
4366    def test_vicious_descriptor_nonsense(self):
4367        # Testing vicious_descriptor_nonsense...
4368
4369        # A potential segfault spotted by Thomas Wouters in mail to
4370        # python-dev 2003-04-17, turned into an example & fixed by Michael
4371        # Hudson just less than four months later...
4372
4373        class Evil(object):
4374            def __hash__(self):
4375                return hash('attr')
4376            def __eq__(self, other):
4377                del C.attr
4378                return 0
4379
4380        class Descr(object):
4381            def __get__(self, ob, type=None):
4382                return 1
4383
4384        class C(object):
4385            attr = Descr()
4386
4387        c = C()
4388        c.__dict__[Evil()] = 0
4389
4390        self.assertEqual(c.attr, 1)
4391        # this makes a crash more likely:
4392        test_support.gc_collect()
4393        self.assertEqual(hasattr(c, 'attr'), False)
4394
4395    def test_init(self):
4396        # SF 1155938
4397        class Foo(object):
4398            def __init__(self):
4399                return 10
4400        try:
4401            Foo()
4402        except TypeError:
4403            pass
4404        else:
4405            self.fail("did not test __init__() for None return")
4406
4407    def test_method_wrapper(self):
4408        # Testing method-wrapper objects...
4409        # <type 'method-wrapper'> did not support any reflection before 2.5
4410
4411        l = []
4412        self.assertEqual(l.__add__, l.__add__)
4413        self.assertEqual(l.__add__, [].__add__)
4414        self.assertTrue(l.__add__ != [5].__add__)
4415        self.assertTrue(l.__add__ != l.__mul__)
4416        self.assertTrue(l.__add__.__name__ == '__add__')
4417        if hasattr(l.__add__, '__self__'):
4418            # CPython
4419            self.assertTrue(l.__add__.__self__ is l)
4420            self.assertTrue(l.__add__.__objclass__ is list)
4421        else:
4422            # Python implementations where [].__add__ is a normal bound method
4423            self.assertTrue(l.__add__.im_self is l)
4424            self.assertTrue(l.__add__.im_class is list)
4425        self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4426        try:
4427            hash(l.__add__)
4428        except TypeError:
4429            pass
4430        else:
4431            self.fail("no TypeError from hash([].__add__)")
4432
4433        t = ()
4434        t += (7,)
4435        self.assertEqual(t.__add__, (7,).__add__)
4436        self.assertEqual(hash(t.__add__), hash((7,).__add__))
4437
4438    def test_not_implemented(self):
4439        # Testing NotImplemented...
4440        # all binary methods should be able to return a NotImplemented
4441        import operator
4442
4443        def specialmethod(self, other):
4444            return NotImplemented
4445
4446        def check(expr, x, y):
4447            try:
4448                exec expr in {'x': x, 'y': y, 'operator': operator}
4449            except TypeError:
4450                pass
4451            else:
4452                self.fail("no TypeError from %r" % (expr,))
4453
4454        N1 = sys.maxint + 1L    # might trigger OverflowErrors instead of
4455                                # TypeErrors
4456        N2 = sys.maxint         # if sizeof(int) < sizeof(long), might trigger
4457                                #   ValueErrors instead of TypeErrors
4458        for metaclass in [type, types.ClassType]:
4459            for name, expr, iexpr in [
4460                    ('__add__',      'x + y',                   'x += y'),
4461                    ('__sub__',      'x - y',                   'x -= y'),
4462                    ('__mul__',      'x * y',                   'x *= y'),
4463                    ('__truediv__',  'operator.truediv(x, y)',  None),
4464                    ('__floordiv__', 'operator.floordiv(x, y)', None),
4465                    ('__div__',      'x / y',                   'x /= y'),
4466                    ('__mod__',      'x % y',                   'x %= y'),
4467                    ('__divmod__',   'divmod(x, y)',            None),
4468                    ('__pow__',      'x ** y',                  'x **= y'),
4469                    ('__lshift__',   'x << y',                  'x <<= y'),
4470                    ('__rshift__',   'x >> y',                  'x >>= y'),
4471                    ('__and__',      'x & y',                   'x &= y'),
4472                    ('__or__',       'x | y',                   'x |= y'),
4473                    ('__xor__',      'x ^ y',                   'x ^= y'),
4474                    ('__coerce__',   'coerce(x, y)',            None)]:
4475                if name == '__coerce__':
4476                    rname = name
4477                else:
4478                    rname = '__r' + name[2:]
4479                A = metaclass('A', (), {name: specialmethod})
4480                B = metaclass('B', (), {rname: specialmethod})
4481                a = A()
4482                b = B()
4483                check(expr, a, a)
4484                check(expr, a, b)
4485                check(expr, b, a)
4486                check(expr, b, b)
4487                check(expr, a, N1)
4488                check(expr, a, N2)
4489                check(expr, N1, b)
4490                check(expr, N2, b)
4491                if iexpr:
4492                    check(iexpr, a, a)
4493                    check(iexpr, a, b)
4494                    check(iexpr, b, a)
4495                    check(iexpr, b, b)
4496                    check(iexpr, a, N1)
4497                    check(iexpr, a, N2)
4498                    iname = '__i' + name[2:]
4499                    C = metaclass('C', (), {iname: specialmethod})
4500                    c = C()
4501                    check(iexpr, c, a)
4502                    check(iexpr, c, b)
4503                    check(iexpr, c, N1)
4504                    check(iexpr, c, N2)
4505
4506    def test_assign_slice(self):
4507        # ceval.c's assign_slice used to check for
4508        # tp->tp_as_sequence->sq_slice instead of
4509        # tp->tp_as_sequence->sq_ass_slice
4510
4511        class C(object):
4512            def __setslice__(self, start, stop, value):
4513                self.value = value
4514
4515        c = C()
4516        c[1:2] = 3
4517        self.assertEqual(c.value, 3)
4518
4519    def test_set_and_no_get(self):
4520        # See
4521        # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4522        class Descr(object):
4523
4524            def __init__(self, name):
4525                self.name = name
4526
4527            def __set__(self, obj, value):
4528                obj.__dict__[self.name] = value
4529        descr = Descr("a")
4530
4531        class X(object):
4532            a = descr
4533
4534        x = X()
4535        self.assertIs(x.a, descr)
4536        x.a = 42
4537        self.assertEqual(x.a, 42)
4538
4539        # Also check type_getattro for correctness.
4540        class Meta(type):
4541            pass
4542        class X(object):
4543            __metaclass__ = Meta
4544        X.a = 42
4545        Meta.a = Descr("a")
4546        self.assertEqual(X.a, 42)
4547
4548    def test_getattr_hooks(self):
4549        # issue 4230
4550
4551        class Descriptor(object):
4552            counter = 0
4553            def __get__(self, obj, objtype=None):
4554                def getter(name):
4555                    self.counter += 1
4556                    raise AttributeError(name)
4557                return getter
4558
4559        descr = Descriptor()
4560        class A(object):
4561            __getattribute__ = descr
4562        class B(object):
4563            __getattr__ = descr
4564        class C(object):
4565            __getattribute__ = descr
4566            __getattr__ = descr
4567
4568        self.assertRaises(AttributeError, getattr, A(), "attr")
4569        self.assertEqual(descr.counter, 1)
4570        self.assertRaises(AttributeError, getattr, B(), "attr")
4571        self.assertEqual(descr.counter, 2)
4572        self.assertRaises(AttributeError, getattr, C(), "attr")
4573        self.assertEqual(descr.counter, 4)
4574
4575        class EvilGetattribute(object):
4576            # This used to segfault
4577            def __getattr__(self, name):
4578                raise AttributeError(name)
4579            def __getattribute__(self, name):
4580                del EvilGetattribute.__getattr__
4581                for i in range(5):
4582                    gc.collect()
4583                raise AttributeError(name)
4584
4585        self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4586
4587    def test_type___getattribute__(self):
4588        self.assertRaises(TypeError, type.__getattribute__, list, type)
4589
4590    def test_abstractmethods(self):
4591        # type pretends not to have __abstractmethods__.
4592        self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4593        class meta(type):
4594            pass
4595        self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
4596        class X(object):
4597            pass
4598        with self.assertRaises(AttributeError):
4599            del X.__abstractmethods__
4600
4601    def test_proxy_call(self):
4602        class FakeStr(object):
4603            __class__ = str
4604
4605        fake_str = FakeStr()
4606        # isinstance() reads __class__ on new style classes
4607        self.assertTrue(isinstance(fake_str, str))
4608
4609        # call a method descriptor
4610        with self.assertRaises(TypeError):
4611            str.split(fake_str)
4612
4613        # call a slot wrapper descriptor
4614        with self.assertRaises(TypeError):
4615            str.__add__(fake_str, "abc")
4616
4617    def test_repr_as_str(self):
4618        # Issue #11603: crash or infinite loop when rebinding __str__ as
4619        # __repr__.
4620        class Foo(object):
4621            pass
4622        Foo.__repr__ = Foo.__str__
4623        foo = Foo()
4624        self.assertRaises(RuntimeError, str, foo)
4625        self.assertRaises(RuntimeError, repr, foo)
4626
4627    def test_mixing_slot_wrappers(self):
4628        class X(dict):
4629            __setattr__ = dict.__setitem__
4630        x = X()
4631        x.y = 42
4632        self.assertEqual(x["y"], 42)
4633
4634    def test_cycle_through_dict(self):
4635        # See bug #1469629
4636        class X(dict):
4637            def __init__(self):
4638                dict.__init__(self)
4639                self.__dict__ = self
4640        x = X()
4641        x.attr = 42
4642        wr = weakref.ref(x)
4643        del x
4644        test_support.gc_collect()
4645        self.assertIsNone(wr())
4646        for o in gc.get_objects():
4647            self.assertIsNot(type(o), X)
4648
4649class DictProxyTests(unittest.TestCase):
4650    def setUp(self):
4651        class C(object):
4652            def meth(self):
4653                pass
4654        self.C = C
4655
4656    def test_repr(self):
4657        self.assertIn('dict_proxy({', repr(vars(self.C)))
4658        self.assertIn("'meth':", repr(vars(self.C)))
4659
4660    def test_iter_keys(self):
4661        # Testing dict-proxy iterkeys...
4662        keys = [ key for key in self.C.__dict__.iterkeys() ]
4663        keys.sort()
4664        self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4665            '__weakref__', 'meth'])
4666
4667    def test_iter_values(self):
4668        # Testing dict-proxy itervalues...
4669        values = [ values for values in self.C.__dict__.itervalues() ]
4670        self.assertEqual(len(values), 5)
4671
4672    def test_iter_items(self):
4673        # Testing dict-proxy iteritems...
4674        keys = [ key for (key, value) in self.C.__dict__.iteritems() ]
4675        keys.sort()
4676        self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4677            '__weakref__', 'meth'])
4678
4679    def test_dict_type_with_metaclass(self):
4680        # Testing type of __dict__ when __metaclass__ set...
4681        class B(object):
4682            pass
4683        class M(type):
4684            pass
4685        class C:
4686            # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4687            __metaclass__ = M
4688        self.assertEqual(type(C.__dict__), type(B.__dict__))
4689
4690
4691class PTypesLongInitTest(unittest.TestCase):
4692    # This is in its own TestCase so that it can be run before any other tests.
4693    def test_pytype_long_ready(self):
4694        # Testing SF bug 551412 ...
4695
4696        # This dumps core when SF bug 551412 isn't fixed --
4697        # but only when test_descr.py is run separately.
4698        # (That can't be helped -- as soon as PyType_Ready()
4699        # is called for PyLong_Type, the bug is gone.)
4700        class UserLong(object):
4701            def __pow__(self, *args):
4702                pass
4703        try:
4704            pow(0L, UserLong(), 0L)
4705        except:
4706            pass
4707
4708        # Another segfault only when run early
4709        # (before PyType_Ready(tuple) is called)
4710        type.mro(tuple)
4711
4712
4713def test_main():
4714    deprecations = [(r'complex divmod\(\), // and % are deprecated$',
4715                     DeprecationWarning)]
4716    if sys.py3kwarning:
4717        deprecations += [
4718            ("classic (int|long) division", DeprecationWarning),
4719            ("coerce.. not supported", DeprecationWarning),
4720            (".+__(get|set|del)slice__ has been removed", DeprecationWarning)]
4721    with test_support.check_warnings(*deprecations):
4722        # Run all local test cases, with PTypesLongInitTest first.
4723        test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
4724                                  ClassPropertiesAndMethods, DictProxyTests)
4725
4726if __name__ == "__main__":
4727    test_main()
4728