home *** CD-ROM | disk | FTP | other *** search
/ Freelog 33 / Freelog033.iso / Progr / Python-2.2.1.exe / TEST_DESCR.PY < prev    next >
Encoding:
Python Source  |  2002-04-08  |  82.7 KB  |  2,907 lines

  1. # Test enhancements related to descriptors and new-style classes
  2.  
  3. from test_support import verify, vereq, verbose, TestFailed, TESTFN
  4. from copy import deepcopy
  5.  
  6. def veris(a, b):
  7.     if a is not b:
  8.         raise TestFailed, "%r is %r" % (a, b)
  9.  
  10. def testunop(a, res, expr="len(a)", meth="__len__"):
  11.     if verbose: print "checking", expr
  12.     dict = {'a': a}
  13.     vereq(eval(expr, dict), res)
  14.     t = type(a)
  15.     m = getattr(t, meth)
  16.     while meth not in t.__dict__:
  17.         t = t.__bases__[0]
  18.     vereq(m, t.__dict__[meth])
  19.     vereq(m(a), res)
  20.     bm = getattr(a, meth)
  21.     vereq(bm(), res)
  22.  
  23. def testbinop(a, b, res, expr="a+b", meth="__add__"):
  24.     if verbose: print "checking", expr
  25.     dict = {'a': a, 'b': b}
  26.  
  27.     # XXX Hack so this passes before 2.3 when -Qnew is specified.
  28.     if meth == "__div__" and 1/2 == 0.5:
  29.         meth = "__truediv__"
  30.  
  31.     vereq(eval(expr, dict), res)
  32.     t = type(a)
  33.     m = getattr(t, meth)
  34.     while meth not in t.__dict__:
  35.         t = t.__bases__[0]
  36.     vereq(m, t.__dict__[meth])
  37.     vereq(m(a, b), res)
  38.     bm = getattr(a, meth)
  39.     vereq(bm(b), res)
  40.  
  41. def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
  42.     if verbose: print "checking", expr
  43.     dict = {'a': a, 'b': b, 'c': c}
  44.     vereq(eval(expr, dict), res)
  45.     t = type(a)
  46.     m = getattr(t, meth)
  47.     while meth not in t.__dict__:
  48.         t = t.__bases__[0]
  49.     vereq(m, t.__dict__[meth])
  50.     vereq(m(a, b, c), res)
  51.     bm = getattr(a, meth)
  52.     vereq(bm(b, c), res)
  53.  
  54. def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
  55.     if verbose: print "checking", stmt
  56.     dict = {'a': deepcopy(a), 'b': b}
  57.     exec stmt in dict
  58.     vereq(dict['a'], res)
  59.     t = type(a)
  60.     m = getattr(t, meth)
  61.     while meth not in t.__dict__:
  62.         t = t.__bases__[0]
  63.     vereq(m, t.__dict__[meth])
  64.     dict['a'] = deepcopy(a)
  65.     m(dict['a'], b)
  66.     vereq(dict['a'], res)
  67.     dict['a'] = deepcopy(a)
  68.     bm = getattr(dict['a'], meth)
  69.     bm(b)
  70.     vereq(dict['a'], res)
  71.  
  72. def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
  73.     if verbose: print "checking", stmt
  74.     dict = {'a': deepcopy(a), 'b': b, 'c': c}
  75.     exec stmt in dict
  76.     vereq(dict['a'], res)
  77.     t = type(a)
  78.     m = getattr(t, meth)
  79.     while meth not in t.__dict__:
  80.         t = t.__bases__[0]
  81.     vereq(m, t.__dict__[meth])
  82.     dict['a'] = deepcopy(a)
  83.     m(dict['a'], b, c)
  84.     vereq(dict['a'], res)
  85.     dict['a'] = deepcopy(a)
  86.     bm = getattr(dict['a'], meth)
  87.     bm(b, c)
  88.     vereq(dict['a'], res)
  89.  
  90. def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
  91.     if verbose: print "checking", stmt
  92.     dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
  93.     exec stmt in dict
  94.     vereq(dict['a'], res)
  95.     t = type(a)
  96.     while meth not in t.__dict__:
  97.         t = t.__bases__[0]
  98.     m = getattr(t, meth)
  99.     vereq(m, t.__dict__[meth])
  100.     dict['a'] = deepcopy(a)
  101.     m(dict['a'], b, c, d)
  102.     vereq(dict['a'], res)
  103.     dict['a'] = deepcopy(a)
  104.     bm = getattr(dict['a'], meth)
  105.     bm(b, c, d)
  106.     vereq(dict['a'], res)
  107.  
  108. def class_docstrings():
  109.     class Classic:
  110.         "A classic docstring."
  111.     vereq(Classic.__doc__, "A classic docstring.")
  112.     vereq(Classic.__dict__['__doc__'], "A classic docstring.")
  113.  
  114.     class Classic2:
  115.         pass
  116.     verify(Classic2.__doc__ is None)
  117.  
  118.     class NewStatic(object):
  119.         "Another docstring."
  120.     vereq(NewStatic.__doc__, "Another docstring.")
  121.     vereq(NewStatic.__dict__['__doc__'], "Another docstring.")
  122.  
  123.     class NewStatic2(object):
  124.         pass
  125.     verify(NewStatic2.__doc__ is None)
  126.  
  127.     class NewDynamic(object):
  128.         "Another docstring."
  129.     vereq(NewDynamic.__doc__, "Another docstring.")
  130.     vereq(NewDynamic.__dict__['__doc__'], "Another docstring.")
  131.  
  132.     class NewDynamic2(object):
  133.         pass
  134.     verify(NewDynamic2.__doc__ is None)
  135.  
  136. def lists():
  137.     if verbose: print "Testing list operations..."
  138.     testbinop([1], [2], [1,2], "a+b", "__add__")
  139.     testbinop([1,2,3], 2, 1, "b in a", "__contains__")
  140.     testbinop([1,2,3], 4, 0, "b in a", "__contains__")
  141.     testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
  142.     testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
  143.     testsetop([1], [2], [1,2], "a+=b", "__iadd__")
  144.     testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
  145.     testunop([1,2,3], 3, "len(a)", "__len__")
  146.     testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
  147.     testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
  148.     testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
  149.     testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
  150.  
  151. def dicts():
  152.     if verbose: print "Testing dict operations..."
  153.     testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
  154.     testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
  155.     testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
  156.     testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
  157.     d = {1:2,3:4}
  158.     l1 = []
  159.     for i in d.keys(): l1.append(i)
  160.     l = []
  161.     for i in iter(d): l.append(i)
  162.     vereq(l, l1)
  163.     l = []
  164.     for i in d.__iter__(): l.append(i)
  165.     vereq(l, l1)
  166.     l = []
  167.     for i in dict.__iter__(d): l.append(i)
  168.     vereq(l, l1)
  169.     d = {1:2, 3:4}
  170.     testunop(d, 2, "len(a)", "__len__")
  171.     vereq(eval(repr(d), {}), d)
  172.     vereq(eval(d.__repr__(), {}), d)
  173.     testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
  174.  
  175. def dict_constructor():
  176.     if verbose:
  177.         print "Testing dict constructor ..."
  178.     d = dict()
  179.     vereq(d, {})
  180.     d = dict({})
  181.     vereq(d, {})
  182.     d = dict(items={})
  183.     vereq(d, {})
  184.     d = dict({1: 2, 'a': 'b'})
  185.     vereq(d, {1: 2, 'a': 'b'})
  186.     vereq(d, dict(d.items()))
  187.     vereq(d, dict(items=d.iteritems()))
  188.     for badarg in 0, 0L, 0j, "0", [0], (0,):
  189.         try:
  190.             dict(badarg)
  191.         except TypeError:
  192.             pass
  193.         except ValueError:
  194.             if badarg == "0":
  195.                 # It's a sequence, and its elements are also sequences (gotta
  196.                 # love strings <wink>), but they aren't of length 2, so this
  197.                 # one seemed better as a ValueError than a TypeError.
  198.                 pass
  199.             else:
  200.                 raise TestFailed("no TypeError from dict(%r)" % badarg)
  201.         else:
  202.             raise TestFailed("no TypeError from dict(%r)" % badarg)
  203.     try:
  204.         dict(senseless={})
  205.     except TypeError:
  206.         pass
  207.     else:
  208.         raise TestFailed("no TypeError from dict(senseless={})")
  209.  
  210.     try:
  211.         dict({}, {})
  212.     except TypeError:
  213.         pass
  214.     else:
  215.         raise TestFailed("no TypeError from dict({}, {})")
  216.  
  217.     class Mapping:
  218.         # Lacks a .keys() method; will be added later.
  219.         dict = {1:2, 3:4, 'a':1j}
  220.  
  221.     try:
  222.         dict(Mapping())
  223.     except TypeError:
  224.         pass
  225.     else:
  226.         raise TestFailed("no TypeError from dict(incomplete mapping)")
  227.  
  228.     Mapping.keys = lambda self: self.dict.keys()
  229.     Mapping.__getitem__ = lambda self, i: self.dict[i]
  230.     d = dict(items=Mapping())
  231.     vereq(d, Mapping.dict)
  232.  
  233.     # Init from sequence of iterable objects, each producing a 2-sequence.
  234.     class AddressBookEntry:
  235.         def __init__(self, first, last):
  236.             self.first = first
  237.             self.last = last
  238.         def __iter__(self):
  239.             return iter([self.first, self.last])
  240.  
  241.     d = dict([AddressBookEntry('Tim', 'Warsaw'),
  242.               AddressBookEntry('Barry', 'Peters'),
  243.               AddressBookEntry('Tim', 'Peters'),
  244.               AddressBookEntry('Barry', 'Warsaw')])
  245.     vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
  246.  
  247.     d = dict(zip(range(4), range(1, 5)))
  248.     vereq(d, dict([(i, i+1) for i in range(4)]))
  249.  
  250.     # Bad sequence lengths.
  251.     for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
  252.         try:
  253.             dict(bad)
  254.         except ValueError:
  255.             pass
  256.         else:
  257.             raise TestFailed("no ValueError from dict(%r)" % bad)
  258.  
  259. def test_dir():
  260.     if verbose:
  261.         print "Testing dir() ..."
  262.     junk = 12
  263.     vereq(dir(), ['junk'])
  264.     del junk
  265.  
  266.     # Just make sure these don't blow up!
  267.     for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
  268.         dir(arg)
  269.  
  270.     # Try classic classes.
  271.     class C:
  272.         Cdata = 1
  273.         def Cmethod(self): pass
  274.  
  275.     cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
  276.     vereq(dir(C), cstuff)
  277.     verify('im_self' in dir(C.Cmethod))
  278.  
  279.     c = C()  # c.__doc__ is an odd thing to see here; ditto c.__module__.
  280.     vereq(dir(c), cstuff)
  281.  
  282.     c.cdata = 2
  283.     c.cmethod = lambda self: 0
  284.     vereq(dir(c), cstuff + ['cdata', 'cmethod'])
  285.     verify('im_self' in dir(c.Cmethod))
  286.  
  287.     class A(C):
  288.         Adata = 1
  289.         def Amethod(self): pass
  290.  
  291.     astuff = ['Adata', 'Amethod'] + cstuff
  292.     vereq(dir(A), astuff)
  293.     verify('im_self' in dir(A.Amethod))
  294.     a = A()
  295.     vereq(dir(a), astuff)
  296.     verify('im_self' in dir(a.Amethod))
  297.     a.adata = 42
  298.     a.amethod = lambda self: 3
  299.     vereq(dir(a), astuff + ['adata', 'amethod'])
  300.  
  301.     # The same, but with new-style classes.  Since these have object as a
  302.     # base class, a lot more gets sucked in.
  303.     def interesting(strings):
  304.         return [s for s in strings if not s.startswith('_')]
  305.  
  306.     class C(object):
  307.         Cdata = 1
  308.         def Cmethod(self): pass
  309.  
  310.     cstuff = ['Cdata', 'Cmethod']
  311.     vereq(interesting(dir(C)), cstuff)
  312.  
  313.     c = C()
  314.     vereq(interesting(dir(c)), cstuff)
  315.     verify('im_self' in dir(C.Cmethod))
  316.  
  317.     c.cdata = 2
  318.     c.cmethod = lambda self: 0
  319.     vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
  320.     verify('im_self' in dir(c.Cmethod))
  321.  
  322.     class A(C):
  323.         Adata = 1
  324.         def Amethod(self): pass
  325.  
  326.     astuff = ['Adata', 'Amethod'] + cstuff
  327.     vereq(interesting(dir(A)), astuff)
  328.     verify('im_self' in dir(A.Amethod))
  329.     a = A()
  330.     vereq(interesting(dir(a)), astuff)
  331.     a.adata = 42
  332.     a.amethod = lambda self: 3
  333.     vereq(interesting(dir(a)), astuff + ['adata', 'amethod'])
  334.     verify('im_self' in dir(a.Amethod))
  335.  
  336.     # Try a module subclass.
  337.     import sys
  338.     class M(type(sys)):
  339.         pass
  340.     minstance = M()
  341.     minstance.b = 2
  342.     minstance.a = 1
  343.     vereq(dir(minstance), ['a', 'b'])
  344.  
  345.     class M2(M):
  346.         def getdict(self):
  347.             return "Not a dict!"
  348.         __dict__ = property(getdict)
  349.  
  350.     m2instance = M2()
  351.     m2instance.b = 2
  352.     m2instance.a = 1
  353.     vereq(m2instance.__dict__, "Not a dict!")
  354.     try:
  355.         dir(m2instance)
  356.     except TypeError:
  357.         pass
  358.  
  359.     # Two essentially featureless objects, just inheriting stuff from
  360.     # object.
  361.     vereq(dir(None), dir(Ellipsis))
  362.  
  363. binops = {
  364.     'add': '+',
  365.     'sub': '-',
  366.     'mul': '*',
  367.     'div': '/',
  368.     'mod': '%',
  369.     'divmod': 'divmod',
  370.     'pow': '**',
  371.     'lshift': '<<',
  372.     'rshift': '>>',
  373.     'and': '&',
  374.     'xor': '^',
  375.     'or': '|',
  376.     'cmp': 'cmp',
  377.     'lt': '<',
  378.     'le': '<=',
  379.     'eq': '==',
  380.     'ne': '!=',
  381.     'gt': '>',
  382.     'ge': '>=',
  383.     }
  384.  
  385. for name, expr in binops.items():
  386.     if expr.islower():
  387.         expr = expr + "(a, b)"
  388.     else:
  389.         expr = 'a %s b' % expr
  390.     binops[name] = expr
  391.  
  392. unops = {
  393.     'pos': '+',
  394.     'neg': '-',
  395.     'abs': 'abs',
  396.     'invert': '~',
  397.     'int': 'int',
  398.     'long': 'long',
  399.     'float': 'float',
  400.     'oct': 'oct',
  401.     'hex': 'hex',
  402.     }
  403.  
  404. for name, expr in unops.items():
  405.     if expr.islower():
  406.         expr = expr + "(a)"
  407.     else:
  408.         expr = '%s a' % expr
  409.     unops[name] = expr
  410.  
  411. def numops(a, b, skip=[]):
  412.     dict = {'a': a, 'b': b}
  413.     for name, expr in binops.items():
  414.         if name not in skip:
  415.             name = "__%s__" % name
  416.             if hasattr(a, name):
  417.                 res = eval(expr, dict)
  418.                 testbinop(a, b, res, expr, name)
  419.     for name, expr in unops.items():
  420.         if name not in skip:
  421.             name = "__%s__" % name
  422.             if hasattr(a, name):
  423.                 res = eval(expr, dict)
  424.                 testunop(a, res, expr, name)
  425.  
  426. def ints():
  427.     if verbose: print "Testing int operations..."
  428.     numops(100, 3)
  429.     # The following crashes in Python 2.2
  430.     vereq((1).__nonzero__(), 1)
  431.     vereq((0).__nonzero__(), 0)
  432.     # This returns 'NotImplemented' in Python 2.2
  433.     class C(int):
  434.         def __add__(self, other):
  435.             return NotImplemented
  436.     try:
  437.         C() + ""
  438.     except TypeError:
  439.         pass
  440.     else:
  441.         raise TestFailed, "NotImplemented should have caused TypeError"
  442.  
  443. def longs():
  444.     if verbose: print "Testing long operations..."
  445.     numops(100L, 3L)
  446.  
  447. def floats():
  448.     if verbose: print "Testing float operations..."
  449.     numops(100.0, 3.0)
  450.  
  451. def complexes():
  452.     if verbose: print "Testing complex operations..."
  453.     numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
  454.     class Number(complex):
  455.         __slots__ = ['prec']
  456.         def __new__(cls, *args, **kwds):
  457.             result = complex.__new__(cls, *args)
  458.             result.prec = kwds.get('prec', 12)
  459.             return result
  460.         def __repr__(self):
  461.             prec = self.prec
  462.             if self.imag == 0.0:
  463.                 return "%.*g" % (prec, self.real)
  464.             if self.real == 0.0:
  465.                 return "%.*gj" % (prec, self.imag)
  466.             return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
  467.         __str__ = __repr__
  468.  
  469.     a = Number(3.14, prec=6)
  470.     vereq(`a`, "3.14")
  471.     vereq(a.prec, 6)
  472.  
  473.     a = Number(a, prec=2)
  474.     vereq(`a`, "3.1")
  475.     vereq(a.prec, 2)
  476.  
  477.     a = Number(234.5)
  478.     vereq(`a`, "234.5")
  479.     vereq(a.prec, 12)
  480.  
  481. def spamlists():
  482.     if verbose: print "Testing spamlist operations..."
  483.     import copy, xxsubtype as spam
  484.     def spamlist(l, memo=None):
  485.         import xxsubtype as spam
  486.         return spam.spamlist(l)
  487.     # This is an ugly hack:
  488.     copy._deepcopy_dispatch[spam.spamlist] = spamlist
  489.  
  490.     testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
  491.     testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
  492.     testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
  493.     testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
  494.     testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
  495.                "a[b:c]", "__getslice__")
  496.     testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
  497.               "a+=b", "__iadd__")
  498.     testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
  499.     testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
  500.     testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
  501.     testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
  502.     testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
  503.     testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
  504.                spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
  505.     # Test subclassing
  506.     class C(spam.spamlist):
  507.         def foo(self): return 1
  508.     a = C()
  509.     vereq(a, [])
  510.     vereq(a.foo(), 1)
  511.     a.append(100)
  512.     vereq(a, [100])
  513.     vereq(a.getstate(), 0)
  514.     a.setstate(42)
  515.     vereq(a.getstate(), 42)
  516.  
  517. def spamdicts():
  518.     if verbose: print "Testing spamdict operations..."
  519.     import copy, xxsubtype as spam
  520.     def spamdict(d, memo=None):
  521.         import xxsubtype as spam
  522.         sd = spam.spamdict()
  523.         for k, v in d.items(): sd[k] = v
  524.         return sd
  525.     # This is an ugly hack:
  526.     copy._deepcopy_dispatch[spam.spamdict] = spamdict
  527.  
  528.     testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
  529.     testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
  530.     testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
  531.     testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
  532.     d = spamdict({1:2,3:4})
  533.     l1 = []
  534.     for i in d.keys(): l1.append(i)
  535.     l = []
  536.     for i in iter(d): l.append(i)
  537.     vereq(l, l1)
  538.     l = []
  539.     for i in d.__iter__(): l.append(i)
  540.     vereq(l, l1)
  541.     l = []
  542.     for i in type(spamdict({})).__iter__(d): l.append(i)
  543.     vereq(l, l1)
  544.     straightd = {1:2, 3:4}
  545.     spamd = spamdict(straightd)
  546.     testunop(spamd, 2, "len(a)", "__len__")
  547.     testunop(spamd, repr(straightd), "repr(a)", "__repr__")
  548.     testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
  549.                "a[b]=c", "__setitem__")
  550.     # Test subclassing
  551.     class C(spam.spamdict):
  552.         def foo(self): return 1
  553.     a = C()
  554.     vereq(a.items(), [])
  555.     vereq(a.foo(), 1)
  556.     a['foo'] = 'bar'
  557.     vereq(a.items(), [('foo', 'bar')])
  558.     vereq(a.getstate(), 0)
  559.     a.setstate(100)
  560.     vereq(a.getstate(), 100)
  561.  
  562. def pydicts():
  563.     if verbose: print "Testing Python subclass of dict..."
  564.     verify(issubclass(dict, dict))
  565.     verify(isinstance({}, dict))
  566.     d = dict()
  567.     vereq(d, {})
  568.     verify(d.__class__ is dict)
  569.     verify(isinstance(d, dict))
  570.     class C(dict):
  571.         state = -1
  572.         def __init__(self, *a, **kw):
  573.             if a:
  574.                 vereq(len(a), 1)
  575.                 self.state = a[0]
  576.             if kw:
  577.                 for k, v in kw.items(): self[v] = k
  578.         def __getitem__(self, key):
  579.             return self.get(key, 0)
  580.         def __setitem__(self, key, value):
  581.             verify(isinstance(key, type(0)))
  582.             dict.__setitem__(self, key, value)
  583.         def setstate(self, state):
  584.             self.state = state
  585.         def getstate(self):
  586.             return self.state
  587.     verify(issubclass(C, dict))
  588.     a1 = C(12)
  589.     vereq(a1.state, 12)
  590.     a2 = C(foo=1, bar=2)
  591.     vereq(a2[1] == 'foo' and a2[2], 'bar')
  592.     a = C()
  593.     vereq(a.state, -1)
  594.     vereq(a.getstate(), -1)
  595.     a.setstate(0)
  596.     vereq(a.state, 0)
  597.     vereq(a.getstate(), 0)
  598.     a.setstate(10)
  599.     vereq(a.state, 10)
  600.     vereq(a.getstate(), 10)
  601.     vereq(a[42], 0)
  602.     a[42] = 24
  603.     vereq(a[42], 24)
  604.     if verbose: print "pydict stress test ..."
  605.     N = 50
  606.     for i in range(N):
  607.         a[i] = C()
  608.         for j in range(N):
  609.             a[i][j] = i*j
  610.     for i in range(N):
  611.         for j in range(N):
  612.             vereq(a[i][j], i*j)
  613.  
  614. def pylists():
  615.     if verbose: print "Testing Python subclass of list..."
  616.     class C(list):
  617.         def __getitem__(self, i):
  618.             return list.__getitem__(self, i) + 100
  619.         def __getslice__(self, i, j):
  620.             return (i, j)
  621.     a = C()
  622.     a.extend([0,1,2])
  623.     vereq(a[0], 100)
  624.     vereq(a[1], 101)
  625.     vereq(a[2], 102)
  626.     vereq(a[100:200], (100,200))
  627.  
  628. def metaclass():
  629.     if verbose: print "Testing __metaclass__..."
  630.     class C:
  631.         __metaclass__ = type
  632.         def __init__(self):
  633.             self.__state = 0
  634.         def getstate(self):
  635.             return self.__state
  636.         def setstate(self, state):
  637.             self.__state = state
  638.     a = C()
  639.     vereq(a.getstate(), 0)
  640.     a.setstate(10)
  641.     vereq(a.getstate(), 10)
  642.     class D:
  643.         class __metaclass__(type):
  644.             def myself(cls): return cls
  645.     vereq(D.myself(), D)
  646.     d = D()
  647.     verify(d.__class__ is D)
  648.     class M1(type):
  649.         def __new__(cls, name, bases, dict):
  650.             dict['__spam__'] = 1
  651.             return type.__new__(cls, name, bases, dict)
  652.     class C:
  653.         __metaclass__ = M1
  654.     vereq(C.__spam__, 1)
  655.     c = C()
  656.     vereq(c.__spam__, 1)
  657.  
  658.     class _instance(object):
  659.         pass
  660.     class M2(object):
  661.         def __new__(cls, name, bases, dict):
  662.             self = object.__new__(cls)
  663.             self.name = name
  664.             self.bases = bases
  665.             self.dict = dict
  666.             return self
  667.         __new__ = staticmethod(__new__)
  668.         def __call__(self):
  669.             it = _instance()
  670.             # Early binding of methods
  671.             for key in self.dict:
  672.                 if key.startswith("__"):
  673.                     continue
  674.                 setattr(it, key, self.dict[key].__get__(it, self))
  675.             return it
  676.     class C:
  677.         __metaclass__ = M2
  678.         def spam(self):
  679.             return 42
  680.     vereq(C.name, 'C')
  681.     vereq(C.bases, ())
  682.     verify('spam' in C.dict)
  683.     c = C()
  684.     vereq(c.spam(), 42)
  685.  
  686.     # More metaclass examples
  687.  
  688.     class autosuper(type):
  689.         # Automatically add __super to the class
  690.         # This trick only works for dynamic classes
  691.         def __new__(metaclass, name, bases, dict):
  692.             cls = super(autosuper, metaclass).__new__(metaclass,
  693.                                                       name, bases, dict)
  694.             # Name mangling for __super removes leading underscores
  695.             while name[:1] == "_":
  696.                 name = name[1:]
  697.             if name:
  698.                 name = "_%s__super" % name
  699.             else:
  700.                 name = "__super"
  701.             setattr(cls, name, super(cls))
  702.             return cls
  703.     class A:
  704.         __metaclass__ = autosuper
  705.         def meth(self):
  706.             return "A"
  707.     class B(A):
  708.         def meth(self):
  709.             return "B" + self.__super.meth()
  710.     class C(A):
  711.         def meth(self):
  712.             return "C" + self.__super.meth()
  713.     class D(C, B):
  714.         def meth(self):
  715.             return "D" + self.__super.meth()
  716.     vereq(D().meth(), "DCBA")
  717.     class E(B, C):
  718.         def meth(self):
  719.             return "E" + self.__super.meth()
  720.     vereq(E().meth(), "EBCA")
  721.  
  722.     class autoproperty(type):
  723.         # Automatically create property attributes when methods
  724.         # named _get_x and/or _set_x are found
  725.         def __new__(metaclass, name, bases, dict):
  726.             hits = {}
  727.             for key, val in dict.iteritems():
  728.                 if key.startswith("_get_"):
  729.                     key = key[5:]
  730.                     get, set = hits.get(key, (None, None))
  731.                     get = val
  732.                     hits[key] = get, set
  733.                 elif key.startswith("_set_"):
  734.                     key = key[5:]
  735.                     get, set = hits.get(key, (None, None))
  736.                     set = val
  737.                     hits[key] = get, set
  738.             for key, (get, set) in hits.iteritems():
  739.                 dict[key] = property(get, set)
  740.             return super(autoproperty, metaclass).__new__(metaclass,
  741.                                                         name, bases, dict)
  742.     class A:
  743.         __metaclass__ = autoproperty
  744.         def _get_x(self):
  745.             return -self.__x
  746.         def _set_x(self, x):
  747.             self.__x = -x
  748.     a = A()
  749.     verify(not hasattr(a, "x"))
  750.     a.x = 12
  751.     vereq(a.x, 12)
  752.     vereq(a._A__x, -12)
  753.  
  754.     class multimetaclass(autoproperty, autosuper):
  755.         # Merge of multiple cooperating metaclasses
  756.         pass
  757.     class A:
  758.         __metaclass__ = multimetaclass
  759.         def _get_x(self):
  760.             return "A"
  761.     class B(A):
  762.         def _get_x(self):
  763.             return "B" + self.__super._get_x()
  764.     class C(A):
  765.         def _get_x(self):
  766.             return "C" + self.__super._get_x()
  767.     class D(C, B):
  768.         def _get_x(self):
  769.             return "D" + self.__super._get_x()
  770.     vereq(D().x, "DCBA")
  771.  
  772.     # Make sure type(x) doesn't call x.__class__.__init__
  773.     class T(type):
  774.         counter = 0
  775.         def __init__(self, *args):
  776.             T.counter += 1
  777.     class C:
  778.         __metaclass__ = T
  779.     vereq(T.counter, 1)
  780.     a = C()
  781.     vereq(type(a), C)
  782.     vereq(T.counter, 1)
  783.  
  784.     class C(object): pass
  785.     c = C()
  786.     try: c()
  787.     except TypeError: pass
  788.     else: raise TestError, "calling object w/o call method should raise TypeError"
  789.  
  790. def pymods():
  791.     if verbose: print "Testing Python subclass of module..."
  792.     log = []
  793.     import sys
  794.     MT = type(sys)
  795.     class MM(MT):
  796.         def __init__(self):
  797.             MT.__init__(self)
  798.         def __getattribute__(self, name):
  799.             log.append(("getattr", name))
  800.             return MT.__getattribute__(self, name)
  801.         def __setattr__(self, name, value):
  802.             log.append(("setattr", name, value))
  803.             MT.__setattr__(self, name, value)
  804.         def __delattr__(self, name):
  805.             log.append(("delattr", name))
  806.             MT.__delattr__(self, name)
  807.     a = MM()
  808.     a.foo = 12
  809.     x = a.foo
  810.     del a.foo
  811.     vereq(log, [("setattr", "foo", 12),
  812.                 ("getattr", "foo"),
  813.                 ("delattr", "foo")])
  814.  
  815. def multi():
  816.     if verbose: print "Testing multiple inheritance..."
  817.     class C(object):
  818.         def __init__(self):
  819.             self.__state = 0
  820.         def getstate(self):
  821.             return self.__state
  822.         def setstate(self, state):
  823.             self.__state = state
  824.     a = C()
  825.     vereq(a.getstate(), 0)
  826.     a.setstate(10)
  827.     vereq(a.getstate(), 10)
  828.     class D(dict, C):
  829.         def __init__(self):
  830.             type({}).__init__(self)
  831.             C.__init__(self)
  832.     d = D()
  833.     vereq(d.keys(), [])
  834.     d["hello"] = "world"
  835.     vereq(d.items(), [("hello", "world")])
  836.     vereq(d["hello"], "world")
  837.     vereq(d.getstate(), 0)
  838.     d.setstate(10)
  839.     vereq(d.getstate(), 10)
  840.     vereq(D.__mro__, (D, dict, C, object))
  841.  
  842.     # SF bug #442833
  843.     class Node(object):
  844.         def __int__(self):
  845.             return int(self.foo())
  846.         def foo(self):
  847.             return "23"
  848.     class Frag(Node, list):
  849.         def foo(self):
  850.             return "42"
  851.     vereq(Node().__int__(), 23)
  852.     vereq(int(Node()), 23)
  853.     vereq(Frag().__int__(), 42)
  854.     vereq(int(Frag()), 42)
  855.  
  856.     # MI mixing classic and new-style classes.
  857.  
  858.     class A:
  859.         x = 1
  860.  
  861.     class B(A):
  862.         pass
  863.  
  864.     class C(A):
  865.         x = 2
  866.  
  867.     class D(B, C):
  868.         pass
  869.     vereq(D.x, 1)
  870.  
  871.     # Classic MRO is preserved for a classic base class.
  872.     class E(D, object):
  873.         pass
  874.     vereq(E.__mro__, (E, D, B, A, C, object))
  875.     vereq(E.x, 1)
  876.  
  877.     # But with a mix of classic bases, their MROs are combined using
  878.     # new-style MRO.
  879.     class F(B, C, object):
  880.         pass
  881.     vereq(F.__mro__, (F, B, C, A, object))
  882.     vereq(F.x, 2)
  883.  
  884.     # Try something else.
  885.     class C:
  886.         def cmethod(self):
  887.             return "C a"
  888.         def all_method(self):
  889.             return "C b"
  890.  
  891.     class M1(C, object):
  892.         def m1method(self):
  893.             return "M1 a"
  894.         def all_method(self):
  895.             return "M1 b"
  896.  
  897.     vereq(M1.__mro__, (M1, C, object))
  898.     m = M1()
  899.     vereq(m.cmethod(), "C a")
  900.     vereq(m.m1method(), "M1 a")
  901.     vereq(m.all_method(), "M1 b")
  902.  
  903.     class D(C):
  904.         def dmethod(self):
  905.             return "D a"
  906.         def all_method(self):
  907.             return "D b"
  908.  
  909.     class M2(object, D):
  910.         def m2method(self):
  911.             return "M2 a"
  912.         def all_method(self):
  913.             return "M2 b"
  914.  
  915.     vereq(M2.__mro__, (M2, object, D, C))
  916.     m = M2()
  917.     vereq(m.cmethod(), "C a")
  918.     vereq(m.dmethod(), "D a")
  919.     vereq(m.m2method(), "M2 a")
  920.     vereq(m.all_method(), "M2 b")
  921.  
  922.     class M3(M1, object, M2):
  923.         def m3method(self):
  924.             return "M3 a"
  925.         def all_method(self):
  926.             return "M3 b"
  927.     # XXX Expected this (the commented-out result):
  928.     # vereq(M3.__mro__, (M3, M1, M2, object, D, C))
  929.     vereq(M3.__mro__, (M3, M1, M2, D, C, object))  # XXX ?
  930.     m = M3()
  931.     vereq(m.cmethod(), "C a")
  932.     vereq(m.dmethod(), "D a")
  933.     vereq(m.m1method(), "M1 a")
  934.     vereq(m.m2method(), "M2 a")
  935.     vereq(m.m3method(), "M3 a")
  936.     vereq(m.all_method(), "M3 b")
  937.  
  938.     class Classic:
  939.         pass
  940.     try:
  941.         class New(Classic):
  942.             __metaclass__ = type
  943.     except TypeError:
  944.         pass
  945.     else:
  946.         raise TestFailed, "new class with only classic bases - shouldn't be"
  947.  
  948. def diamond():
  949.     if verbose: print "Testing multiple inheritance special cases..."
  950.     class A(object):
  951.         def spam(self): return "A"
  952.     vereq(A().spam(), "A")
  953.     class B(A):
  954.         def boo(self): return "B"
  955.         def spam(self): return "B"
  956.     vereq(B().spam(), "B")
  957.     vereq(B().boo(), "B")
  958.     class C(A):
  959.         def boo(self): return "C"
  960.     vereq(C().spam(), "A")
  961.     vereq(C().boo(), "C")
  962.     class D(B, C): pass
  963.     vereq(D().spam(), "B")
  964.     vereq(D().boo(), "B")
  965.     vereq(D.__mro__, (D, B, C, A, object))
  966.     class E(C, B): pass
  967.     vereq(E().spam(), "B")
  968.     vereq(E().boo(), "C")
  969.     vereq(E.__mro__, (E, C, B, A, object))
  970.     class F(D, E): pass
  971.     vereq(F().spam(), "B")
  972.     vereq(F().boo(), "B")
  973.     vereq(F.__mro__, (F, D, E, B, C, A, object))
  974.     class G(E, D): pass
  975.     vereq(G().spam(), "B")
  976.     vereq(G().boo(), "C")
  977.     vereq(G.__mro__, (G, E, D, C, B, A, object))
  978.  
  979. def objects():
  980.     if verbose: print "Testing object class..."
  981.     a = object()
  982.     vereq(a.__class__, object)
  983.     vereq(type(a), object)
  984.     b = object()
  985.     verify(a is not b)
  986.     verify(not hasattr(a, "foo"))
  987.     try:
  988.         a.foo = 12
  989.     except (AttributeError, TypeError):
  990.         pass
  991.     else:
  992.         verify(0, "object() should not allow setting a foo attribute")
  993.     verify(not hasattr(object(), "__dict__"))
  994.  
  995.     class Cdict(object):
  996.         pass
  997.     x = Cdict()
  998.     vereq(x.__dict__, {})
  999.     x.foo = 1
  1000.     vereq(x.foo, 1)
  1001.     vereq(x.__dict__, {'foo': 1})
  1002.  
  1003. def slots():
  1004.     if verbose: print "Testing __slots__..."
  1005.     class C0(object):
  1006.         __slots__ = []
  1007.     x = C0()
  1008.     verify(not hasattr(x, "__dict__"))
  1009.     verify(not hasattr(x, "foo"))
  1010.  
  1011.     class C1(object):
  1012.         __slots__ = ['a']
  1013.     x = C1()
  1014.     verify(not hasattr(x, "__dict__"))
  1015.     verify(not hasattr(x, "a"))
  1016.     x.a = 1
  1017.     vereq(x.a, 1)
  1018.     x.a = None
  1019.     veris(x.a, None)
  1020.     del x.a
  1021.     verify(not hasattr(x, "a"))
  1022.  
  1023.     class C3(object):
  1024.         __slots__ = ['a', 'b', 'c']
  1025.     x = C3()
  1026.     verify(not hasattr(x, "__dict__"))
  1027.     verify(not hasattr(x, 'a'))
  1028.     verify(not hasattr(x, 'b'))
  1029.     verify(not hasattr(x, 'c'))
  1030.     x.a = 1
  1031.     x.b = 2
  1032.     x.c = 3
  1033.     vereq(x.a, 1)
  1034.     vereq(x.b, 2)
  1035.     vereq(x.c, 3)
  1036.  
  1037.     # Test leaks
  1038.     class Counted(object):
  1039.         counter = 0    # counts the number of instances alive
  1040.         def __init__(self):
  1041.             Counted.counter += 1
  1042.         def __del__(self):
  1043.             Counted.counter -= 1
  1044.     class C(object):
  1045.         __slots__ = ['a', 'b', 'c']
  1046.     x = C()
  1047.     x.a = Counted()
  1048.     x.b = Counted()
  1049.     x.c = Counted()
  1050.     vereq(Counted.counter, 3)
  1051.     del x
  1052.     vereq(Counted.counter, 0)
  1053.     class D(C):
  1054.         pass
  1055.     x = D()
  1056.     x.a = Counted()
  1057.     x.z = Counted()
  1058.     vereq(Counted.counter, 2)
  1059.     del x
  1060.     vereq(Counted.counter, 0)
  1061.     class E(D):
  1062.         __slots__ = ['e']
  1063.     x = E()
  1064.     x.a = Counted()
  1065.     x.z = Counted()
  1066.     x.e = Counted()
  1067.     vereq(Counted.counter, 3)
  1068.     del x
  1069.     vereq(Counted.counter, 0)
  1070.  
  1071. def dynamics():
  1072.     if verbose: print "Testing class attribute propagation..."
  1073.     class D(object):
  1074.         pass
  1075.     class E(D):
  1076.         pass
  1077.     class F(D):
  1078.         pass
  1079.     D.foo = 1
  1080.     vereq(D.foo, 1)
  1081.     # Test that dynamic attributes are inherited
  1082.     vereq(E.foo, 1)
  1083.     vereq(F.foo, 1)
  1084.     # Test dynamic instances
  1085.     class C(object):
  1086.         pass
  1087.     a = C()
  1088.     verify(not hasattr(a, "foobar"))
  1089.     C.foobar = 2
  1090.     vereq(a.foobar, 2)
  1091.     C.method = lambda self: 42
  1092.     vereq(a.method(), 42)
  1093.     C.__repr__ = lambda self: "C()"
  1094.     vereq(repr(a), "C()")
  1095.     C.__int__ = lambda self: 100
  1096.     vereq(int(a), 100)
  1097.     vereq(a.foobar, 2)
  1098.     verify(not hasattr(a, "spam"))
  1099.     def mygetattr(self, name):
  1100.         if name == "spam":
  1101.             return "spam"
  1102.         raise AttributeError
  1103.     C.__getattr__ = mygetattr
  1104.     vereq(a.spam, "spam")
  1105.     a.new = 12
  1106.     vereq(a.new, 12)
  1107.     def mysetattr(self, name, value):
  1108.         if name == "spam":
  1109.             raise AttributeError
  1110.         return object.__setattr__(self, name, value)
  1111.     C.__setattr__ = mysetattr
  1112.     try:
  1113.         a.spam = "not spam"
  1114.     except AttributeError:
  1115.         pass
  1116.     else:
  1117.         verify(0, "expected AttributeError")
  1118.     vereq(a.spam, "spam")
  1119.     class D(C):
  1120.         pass
  1121.     d = D()
  1122.     d.foo = 1
  1123.     vereq(d.foo, 1)
  1124.  
  1125.     # Test handling of int*seq and seq*int
  1126.     class I(int):
  1127.         pass
  1128.     vereq("a"*I(2), "aa")
  1129.     vereq(I(2)*"a", "aa")
  1130.     vereq(2*I(3), 6)
  1131.     vereq(I(3)*2, 6)
  1132.     vereq(I(3)*I(2), 6)
  1133.  
  1134.     # Test handling of long*seq and seq*long
  1135.     class L(long):
  1136.         pass
  1137.     vereq("a"*L(2L), "aa")
  1138.     vereq(L(2L)*"a", "aa")
  1139.     vereq(2*L(3), 6)
  1140.     vereq(L(3)*2, 6)
  1141.     vereq(L(3)*L(2), 6)
  1142.  
  1143.     # Test comparison of classes with dynamic metaclasses
  1144.     class dynamicmetaclass(type):
  1145.         pass
  1146.     class someclass:
  1147.         __metaclass__ = dynamicmetaclass
  1148.     verify(someclass != object)
  1149.  
  1150. def errors():
  1151.     if verbose: print "Testing errors..."
  1152.  
  1153.     try:
  1154.         class C(list, dict):
  1155.             pass
  1156.     except TypeError:
  1157.         pass
  1158.     else:
  1159.         verify(0, "inheritance from both list and dict should be illegal")
  1160.  
  1161.     try:
  1162.         class C(object, None):
  1163.             pass
  1164.     except TypeError:
  1165.         pass
  1166.     else:
  1167.         verify(0, "inheritance from non-type should be illegal")
  1168.     class Classic:
  1169.         pass
  1170.  
  1171.     try:
  1172.         class C(type(len)):
  1173.             pass
  1174.     except TypeError:
  1175.         pass
  1176.     else:
  1177.         verify(0, "inheritance from CFunction should be illegal")
  1178.  
  1179.     try:
  1180.         class C(object):
  1181.             __slots__ = 1
  1182.     except TypeError:
  1183.         pass
  1184.     else:
  1185.         verify(0, "__slots__ = 1 should be illegal")
  1186.  
  1187.     try:
  1188.         class C(object):
  1189.             __slots__ = [1]
  1190.     except TypeError:
  1191.         pass
  1192.     else:
  1193.         verify(0, "__slots__ = [1] should be illegal")
  1194.  
  1195. def classmethods():
  1196.     if verbose: print "Testing class methods..."
  1197.     class C(object):
  1198.         def foo(*a): return a
  1199.         goo = classmethod(foo)
  1200.     c = C()
  1201.     vereq(C.goo(1), (C, 1))
  1202.     vereq(c.goo(1), (C, 1))
  1203.     vereq(c.foo(1), (c, 1))
  1204.     class D(C):
  1205.         pass
  1206.     d = D()
  1207.     vereq(D.goo(1), (D, 1))
  1208.     vereq(d.goo(1), (D, 1))
  1209.     vereq(d.foo(1), (d, 1))
  1210.     vereq(D.foo(d, 1), (d, 1))
  1211.     # Test for a specific crash (SF bug 528132)
  1212.     def f(cls, arg): return (cls, arg)
  1213.     ff = classmethod(f)
  1214.     vereq(ff.__get__(0, int)(42), (int, 42))
  1215.     vereq(ff.__get__(0)(42), (int, 42))
  1216.  
  1217.     # Test super() with classmethods (SF bug 535444)
  1218.     veris(C.goo.im_self, C)
  1219.     veris(D.goo.im_self, D)
  1220.     veris(super(D,D).goo.im_self, D)
  1221.     veris(super(D,d).goo.im_self, D)
  1222.     vereq(super(D,D).goo(), (D,))
  1223.     vereq(super(D,d).goo(), (D,))
  1224.  
  1225. def staticmethods():
  1226.     if verbose: print "Testing static methods..."
  1227.     class C(object):
  1228.         def foo(*a): return a
  1229.         goo = staticmethod(foo)
  1230.     c = C()
  1231.     vereq(C.goo(1), (1,))
  1232.     vereq(c.goo(1), (1,))
  1233.     vereq(c.foo(1), (c, 1,))
  1234.     class D(C):
  1235.         pass
  1236.     d = D()
  1237.     vereq(D.goo(1), (1,))
  1238.     vereq(d.goo(1), (1,))
  1239.     vereq(d.foo(1), (d, 1))
  1240.     vereq(D.foo(d, 1), (d, 1))
  1241.  
  1242. def classic():
  1243.     if verbose: print "Testing classic classes..."
  1244.     class C:
  1245.         def foo(*a): return a
  1246.         goo = classmethod(foo)
  1247.     c = C()
  1248.     vereq(C.goo(1), (C, 1))
  1249.     vereq(c.goo(1), (C, 1))
  1250.     vereq(c.foo(1), (c, 1))
  1251.     class D(C):
  1252.         pass
  1253.     d = D()
  1254.     vereq(D.goo(1), (D, 1))
  1255.     vereq(d.goo(1), (D, 1))
  1256.     vereq(d.foo(1), (d, 1))
  1257.     vereq(D.foo(d, 1), (d, 1))
  1258.     class E: # *not* subclassing from C
  1259.         foo = C.foo
  1260.     vereq(E().foo, C.foo) # i.e., unbound
  1261.     verify(repr(C.foo.__get__(C())).startswith("<bound method "))
  1262.  
  1263. def compattr():
  1264.     if verbose: print "Testing computed attributes..."
  1265.     class C(object):
  1266.         class computed_attribute(object):
  1267.             def __init__(self, get, set=None):
  1268.                 self.__get = get
  1269.                 self.__set = set
  1270.             def __get__(self, obj, type=None):
  1271.                 return self.__get(obj)
  1272.             def __set__(self, obj, value):
  1273.                 return self.__set(obj, value)
  1274.         def __init__(self):
  1275.             self.__x = 0
  1276.         def __get_x(self):
  1277.             x = self.__x
  1278.             self.__x = x+1
  1279.             return x
  1280.         def __set_x(self, x):
  1281.             self.__x = x
  1282.         x = computed_attribute(__get_x, __set_x)
  1283.     a = C()
  1284.     vereq(a.x, 0)
  1285.     vereq(a.x, 1)
  1286.     a.x = 10
  1287.     vereq(a.x, 10)
  1288.     vereq(a.x, 11)
  1289.  
  1290. def newslot():
  1291.     if verbose: print "Testing __new__ slot override..."
  1292.     class C(list):
  1293.         def __new__(cls):
  1294.             self = list.__new__(cls)
  1295.             self.foo = 1
  1296.             return self
  1297.         def __init__(self):
  1298.             self.foo = self.foo + 2
  1299.     a = C()
  1300.     vereq(a.foo, 3)
  1301.     verify(a.__class__ is C)
  1302.     class D(C):
  1303.         pass
  1304.     b = D()
  1305.     vereq(b.foo, 3)
  1306.     verify(b.__class__ is D)
  1307.  
  1308. def altmro():
  1309.     if verbose: print "Testing mro() and overriding it..."
  1310.     class A(object):
  1311.         def f(self): return "A"
  1312.     class B(A):
  1313.         pass
  1314.     class C(A):
  1315.         def f(self): return "C"
  1316.     class D(B, C):
  1317.         pass
  1318.     vereq(D.mro(), [D, B, C, A, object])
  1319.     vereq(D.__mro__, (D, B, C, A, object))
  1320.     vereq(D().f(), "C")
  1321.     class PerverseMetaType(type):
  1322.         def mro(cls):
  1323.             L = type.mro(cls)
  1324.             L.reverse()
  1325.             return L
  1326.     class X(A,B,C,D):
  1327.         __metaclass__ = PerverseMetaType
  1328.     vereq(X.__mro__, (object, A, C, B, D, X))
  1329.     vereq(X().f(), "A")
  1330.  
  1331. def overloading():
  1332.     if verbose: print "Testing operator overloading..."
  1333.  
  1334.     class B(object):
  1335.         "Intermediate class because object doesn't have a __setattr__"
  1336.  
  1337.     class C(B):
  1338.  
  1339.         def __getattr__(self, name):
  1340.             if name == "foo":
  1341.                 return ("getattr", name)
  1342.             else:
  1343.                 raise AttributeError
  1344.         def __setattr__(self, name, value):
  1345.             if name == "foo":
  1346.                 self.setattr = (name, value)
  1347.             else:
  1348.                 return B.__setattr__(self, name, value)
  1349.         def __delattr__(self, name):
  1350.             if name == "foo":
  1351.                 self.delattr = name
  1352.             else:
  1353.                 return B.__delattr__(self, name)
  1354.  
  1355.         def __getitem__(self, key):
  1356.             return ("getitem", key)
  1357.         def __setitem__(self, key, value):
  1358.             self.setitem = (key, value)
  1359.         def __delitem__(self, key):
  1360.             self.delitem = key
  1361.  
  1362.         def __getslice__(self, i, j):
  1363.             return ("getslice", i, j)
  1364.         def __setslice__(self, i, j, value):
  1365.             self.setslice = (i, j, value)
  1366.         def __delslice__(self, i, j):
  1367.             self.delslice = (i, j)
  1368.  
  1369.     a = C()
  1370.     vereq(a.foo, ("getattr", "foo"))
  1371.     a.foo = 12
  1372.     vereq(a.setattr, ("foo", 12))
  1373.     del a.foo
  1374.     vereq(a.delattr, "foo")
  1375.  
  1376.     vereq(a[12], ("getitem", 12))
  1377.     a[12] = 21
  1378.     vereq(a.setitem, (12, 21))
  1379.     del a[12]
  1380.     vereq(a.delitem, 12)
  1381.  
  1382.     vereq(a[0:10], ("getslice", 0, 10))
  1383.     a[0:10] = "foo"
  1384.     vereq(a.setslice, (0, 10, "foo"))
  1385.     del a[0:10]
  1386.     vereq(a.delslice, (0, 10))
  1387.  
  1388. def methods():
  1389.     if verbose: print "Testing methods..."
  1390.     class C(object):
  1391.         def __init__(self, x):
  1392.             self.x = x
  1393.         def foo(self):
  1394.             return self.x
  1395.     c1 = C(1)
  1396.     vereq(c1.foo(), 1)
  1397.     class D(C):
  1398.         boo = C.foo
  1399.         goo = c1.foo
  1400.     d2 = D(2)
  1401.     vereq(d2.foo(), 2)
  1402.     vereq(d2.boo(), 2)
  1403.     vereq(d2.goo(), 1)
  1404.     class E(object):
  1405.         foo = C.foo
  1406.     vereq(E().foo, C.foo) # i.e., unbound
  1407.     verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
  1408.  
  1409. def specials():
  1410.     # Test operators like __hash__ for which a built-in default exists
  1411.     if verbose: print "Testing special operators..."
  1412.     # Test the default behavior for static classes
  1413.     class C(object):
  1414.         def __getitem__(self, i):
  1415.             if 0 <= i < 10: return i
  1416.             raise IndexError
  1417.     c1 = C()
  1418.     c2 = C()
  1419.     verify(not not c1)
  1420.     vereq(hash(c1), id(c1))
  1421.     vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
  1422.     vereq(c1, c1)
  1423.     verify(c1 != c2)
  1424.     verify(not c1 != c1)
  1425.     verify(not c1 == c2)
  1426.     # Note that the module name appears in str/repr, and that varies
  1427.     # depending on whether this test is run standalone or from a framework.
  1428.     verify(str(c1).find('C object at ') >= 0)
  1429.     vereq(str(c1), repr(c1))
  1430.     verify(-1 not in c1)
  1431.     for i in range(10):
  1432.         verify(i in c1)
  1433.     verify(10 not in c1)
  1434.     # Test the default behavior for dynamic classes
  1435.     class D(object):
  1436.         def __getitem__(self, i):
  1437.             if 0 <= i < 10: return i
  1438.             raise IndexError
  1439.     d1 = D()
  1440.     d2 = D()
  1441.     verify(not not d1)
  1442.     vereq(hash(d1), id(d1))
  1443.     vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
  1444.     vereq(d1, d1)
  1445.     verify(d1 != d2)
  1446.     verify(not d1 != d1)
  1447.     verify(not d1 == d2)
  1448.     # Note that the module name appears in str/repr, and that varies
  1449.     # depending on whether this test is run standalone or from a framework.
  1450.     verify(str(d1).find('D object at ') >= 0)
  1451.     vereq(str(d1), repr(d1))
  1452.     verify(-1 not in d1)
  1453.     for i in range(10):
  1454.         verify(i in d1)
  1455.     verify(10 not in d1)
  1456.     # Test overridden behavior for static classes
  1457.     class Proxy(object):
  1458.         def __init__(self, x):
  1459.             self.x = x
  1460.         def __nonzero__(self):
  1461.             return not not self.x
  1462.         def __hash__(self):
  1463.             return hash(self.x)
  1464.         def __eq__(self, other):
  1465.             return self.x == other
  1466.         def __ne__(self, other):
  1467.             return self.x != other
  1468.         def __cmp__(self, other):
  1469.             return cmp(self.x, other.x)
  1470.         def __str__(self):
  1471.             return "Proxy:%s" % self.x
  1472.         def __repr__(self):
  1473.             return "Proxy(%r)" % self.x
  1474.         def __contains__(self, value):
  1475.             return value in self.x
  1476.     p0 = Proxy(0)
  1477.     p1 = Proxy(1)
  1478.     p_1 = Proxy(-1)
  1479.     verify(not p0)
  1480.     verify(not not p1)
  1481.     vereq(hash(p0), hash(0))
  1482.     vereq(p0, p0)
  1483.     verify(p0 != p1)
  1484.     verify(not p0 != p0)
  1485.     vereq(not p0, p1)
  1486.     vereq(cmp(p0, p1), -1)
  1487.     vereq(cmp(p0, p0), 0)
  1488.     vereq(cmp(p0, p_1), 1)
  1489.     vereq(str(p0), "Proxy:0")
  1490.     vereq(repr(p0), "Proxy(0)")
  1491.     p10 = Proxy(range(10))
  1492.     verify(-1 not in p10)
  1493.     for i in range(10):
  1494.         verify(i in p10)
  1495.     verify(10 not in p10)
  1496.     # Test overridden behavior for dynamic classes
  1497.     class DProxy(object):
  1498.         def __init__(self, x):
  1499.             self.x = x
  1500.         def __nonzero__(self):
  1501.             return not not self.x
  1502.         def __hash__(self):
  1503.             return hash(self.x)
  1504.         def __eq__(self, other):
  1505.             return self.x == other
  1506.         def __ne__(self, other):
  1507.             return self.x != other
  1508.         def __cmp__(self, other):
  1509.             return cmp(self.x, other.x)
  1510.         def __str__(self):
  1511.             return "DProxy:%s" % self.x
  1512.         def __repr__(self):
  1513.             return "DProxy(%r)" % self.x
  1514.         def __contains__(self, value):
  1515.             return value in self.x
  1516.     p0 = DProxy(0)
  1517.     p1 = DProxy(1)
  1518.     p_1 = DProxy(-1)
  1519.     verify(not p0)
  1520.     verify(not not p1)
  1521.     vereq(hash(p0), hash(0))
  1522.     vereq(p0, p0)
  1523.     verify(p0 != p1)
  1524.     verify(not p0 != p0)
  1525.     vereq(not p0, p1)
  1526.     vereq(cmp(p0, p1), -1)
  1527.     vereq(cmp(p0, p0), 0)
  1528.     vereq(cmp(p0, p_1), 1)
  1529.     vereq(str(p0), "DProxy:0")
  1530.     vereq(repr(p0), "DProxy(0)")
  1531.     p10 = DProxy(range(10))
  1532.     verify(-1 not in p10)
  1533.     for i in range(10):
  1534.         verify(i in p10)
  1535.     verify(10 not in p10)
  1536.     # Safety test for __cmp__
  1537.     def unsafecmp(a, b):
  1538.         try:
  1539.             a.__class__.__cmp__(a, b)
  1540.         except TypeError:
  1541.             pass
  1542.         else:
  1543.             raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
  1544.                 a.__class__, a, b)
  1545.     unsafecmp(u"123", "123")
  1546.     unsafecmp("123", u"123")
  1547.     unsafecmp(1, 1.0)
  1548.     unsafecmp(1.0, 1)
  1549.     unsafecmp(1, 1L)
  1550.     unsafecmp(1L, 1)
  1551.  
  1552. def weakrefs():
  1553.     if verbose: print "Testing weak references..."
  1554.     import weakref
  1555.     class C(object):
  1556.         pass
  1557.     c = C()
  1558.     r = weakref.ref(c)
  1559.     verify(r() is c)
  1560.     del c
  1561.     verify(r() is None)
  1562.     del r
  1563.     class NoWeak(object):
  1564.         __slots__ = ['foo']
  1565.     no = NoWeak()
  1566.     try:
  1567.         weakref.ref(no)
  1568.     except TypeError, msg:
  1569.         verify(str(msg).find("weak reference") >= 0)
  1570.     else:
  1571.         verify(0, "weakref.ref(no) should be illegal")
  1572.     class Weak(object):
  1573.         __slots__ = ['foo', '__weakref__']
  1574.     yes = Weak()
  1575.     r = weakref.ref(yes)
  1576.     verify(r() is yes)
  1577.     del yes
  1578.     verify(r() is None)
  1579.     del r
  1580.  
  1581. def properties():
  1582.     if verbose: print "Testing property..."
  1583.     class C(object):
  1584.         def getx(self):
  1585.             return self.__x
  1586.         def setx(self, value):
  1587.             self.__x = value
  1588.         def delx(self):
  1589.             del self.__x
  1590.         x = property(getx, setx, delx, doc="I'm the x property.")
  1591.     a = C()
  1592.     verify(not hasattr(a, "x"))
  1593.     a.x = 42
  1594.     vereq(a._C__x, 42)
  1595.     vereq(a.x, 42)
  1596.     del a.x
  1597.     verify(not hasattr(a, "x"))
  1598.     verify(not hasattr(a, "_C__x"))
  1599.     C.x.__set__(a, 100)
  1600.     vereq(C.x.__get__(a), 100)
  1601. ##    C.x.__set__(a)
  1602. ##    verify(not hasattr(a, "x"))
  1603.  
  1604.     raw = C.__dict__['x']
  1605.     verify(isinstance(raw, property))
  1606.  
  1607.     attrs = dir(raw)
  1608.     verify("__doc__" in attrs)
  1609.     verify("fget" in attrs)
  1610.     verify("fset" in attrs)
  1611.     verify("fdel" in attrs)
  1612.  
  1613.     vereq(raw.__doc__, "I'm the x property.")
  1614.     verify(raw.fget is C.__dict__['getx'])
  1615.     verify(raw.fset is C.__dict__['setx'])
  1616.     verify(raw.fdel is C.__dict__['delx'])
  1617.  
  1618.     for attr in "__doc__", "fget", "fset", "fdel":
  1619.         try:
  1620.             setattr(raw, attr, 42)
  1621.         except TypeError, msg:
  1622.             if str(msg).find('readonly') < 0:
  1623.                 raise TestFailed("when setting readonly attr %r on a "
  1624.                                  "property, got unexpected TypeError "
  1625.                                  "msg %r" % (attr, str(msg)))
  1626.         else:
  1627.             raise TestFailed("expected TypeError from trying to set "
  1628.                              "readonly %r attr on a property" % attr)
  1629.  
  1630. def supers():
  1631.     if verbose: print "Testing super..."
  1632.  
  1633.     class A(object):
  1634.         def meth(self, a):
  1635.             return "A(%r)" % a
  1636.  
  1637.     vereq(A().meth(1), "A(1)")
  1638.  
  1639.     class B(A):
  1640.         def __init__(self):
  1641.             self.__super = super(B, self)
  1642.         def meth(self, a):
  1643.             return "B(%r)" % a + self.__super.meth(a)
  1644.  
  1645.     vereq(B().meth(2), "B(2)A(2)")
  1646.  
  1647.     class C(A):
  1648.         def meth(self, a):
  1649.             return "C(%r)" % a + self.__super.meth(a)
  1650.     C._C__super = super(C)
  1651.  
  1652.     vereq(C().meth(3), "C(3)A(3)")
  1653.  
  1654.     class D(C, B):
  1655.         def meth(self, a):
  1656.             return "D(%r)" % a + super(D, self).meth(a)
  1657.  
  1658.     vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
  1659.  
  1660.     # Test for subclassing super
  1661.  
  1662.     class mysuper(super):
  1663.         def __init__(self, *args):
  1664.             return super(mysuper, self).__init__(*args)
  1665.  
  1666.     class E(D):
  1667.         def meth(self, a):
  1668.             return "E(%r)" % a + mysuper(E, self).meth(a)
  1669.  
  1670.     vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
  1671.  
  1672.     class F(E):
  1673.         def meth(self, a):
  1674.             s = self.__super
  1675.             return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
  1676.     F._F__super = mysuper(F)
  1677.  
  1678.     vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
  1679.  
  1680.     # Make sure certain errors are raised
  1681.  
  1682.     try:
  1683.         super(D, 42)
  1684.     except TypeError:
  1685.         pass
  1686.     else:
  1687.         raise TestFailed, "shouldn't allow super(D, 42)"
  1688.  
  1689.     try:
  1690.         super(D, C())
  1691.     except TypeError:
  1692.         pass
  1693.     else:
  1694.         raise TestFailed, "shouldn't allow super(D, C())"
  1695.  
  1696.     try:
  1697.         super(D).__get__(12)
  1698.     except TypeError:
  1699.         pass
  1700.     else:
  1701.         raise TestFailed, "shouldn't allow super(D).__get__(12)"
  1702.  
  1703.     try:
  1704.         super(D).__get__(C())
  1705.     except TypeError:
  1706.         pass
  1707.     else:
  1708.         raise TestFailed, "shouldn't allow super(D).__get__(C())"
  1709.  
  1710. def inherits():
  1711.     if verbose: print "Testing inheritance from basic types..."
  1712.  
  1713.     class hexint(int):
  1714.         def __repr__(self):
  1715.             return hex(self)
  1716.         def __add__(self, other):
  1717.             return hexint(int.__add__(self, other))
  1718.         # (Note that overriding __radd__ doesn't work,
  1719.         # because the int type gets first dibs.)
  1720.     vereq(repr(hexint(7) + 9), "0x10")
  1721.     vereq(repr(hexint(1000) + 7), "0x3ef")
  1722.     a = hexint(12345)
  1723.     vereq(a, 12345)
  1724.     vereq(int(a), 12345)
  1725.     verify(int(a).__class__ is int)
  1726.     vereq(hash(a), hash(12345))
  1727.     verify((+a).__class__ is int)
  1728.     verify((a >> 0).__class__ is int)
  1729.     verify((a << 0).__class__ is int)
  1730.     verify((hexint(0) << 12).__class__ is int)
  1731.     verify((hexint(0) >> 12).__class__ is int)
  1732.  
  1733.     class octlong(long):
  1734.         __slots__ = []
  1735.         def __str__(self):
  1736.             s = oct(self)
  1737.             if s[-1] == 'L':
  1738.                 s = s[:-1]
  1739.             return s
  1740.         def __add__(self, other):
  1741.             return self.__class__(super(octlong, self).__add__(other))
  1742.         __radd__ = __add__
  1743.     vereq(str(octlong(3) + 5), "010")
  1744.     # (Note that overriding __radd__ here only seems to work
  1745.     # because the example uses a short int left argument.)
  1746.     vereq(str(5 + octlong(3000)), "05675")
  1747.     a = octlong(12345)
  1748.     vereq(a, 12345L)
  1749.     vereq(long(a), 12345L)
  1750.     vereq(hash(a), hash(12345L))
  1751.     verify(long(a).__class__ is long)
  1752.     verify((+a).__class__ is long)
  1753.     verify((-a).__class__ is long)
  1754.     verify((-octlong(0)).__class__ is long)
  1755.     verify((a >> 0).__class__ is long)
  1756.     verify((a << 0).__class__ is long)
  1757.     verify((a - 0).__class__ is long)
  1758.     verify((a * 1).__class__ is long)
  1759.     verify((a ** 1).__class__ is long)
  1760.     verify((a // 1).__class__ is long)
  1761.     verify((1 * a).__class__ is long)
  1762.     verify((a | 0).__class__ is long)
  1763.     verify((a ^ 0).__class__ is long)
  1764.     verify((a & -1L).__class__ is long)
  1765.     verify((octlong(0) << 12).__class__ is long)
  1766.     verify((octlong(0) >> 12).__class__ is long)
  1767.     verify(abs(octlong(0)).__class__ is long)
  1768.  
  1769.     # Because octlong overrides __add__, we can't check the absence of +0
  1770.     # optimizations using octlong.
  1771.     class longclone(long):
  1772.         pass
  1773.     a = longclone(1)
  1774.     verify((a + 0).__class__ is long)
  1775.     verify((0 + a).__class__ is long)
  1776.  
  1777.     # Check that negative clones don't segfault
  1778.     a = longclone(-1)
  1779.     vereq(a.__dict__, {})
  1780.     vereq(long(a), -1)  # verify PyNumber_Long() copies the sign bit
  1781.  
  1782.     class precfloat(float):
  1783.         __slots__ = ['prec']
  1784.         def __init__(self, value=0.0, prec=12):
  1785.             self.prec = int(prec)
  1786.             float.__init__(value)
  1787.         def __repr__(self):
  1788.             return "%.*g" % (self.prec, self)
  1789.     vereq(repr(precfloat(1.1)), "1.1")
  1790.     a = precfloat(12345)
  1791.     vereq(a, 12345.0)
  1792.     vereq(float(a), 12345.0)
  1793.     verify(float(a).__class__ is float)
  1794.     vereq(hash(a), hash(12345.0))
  1795.     verify((+a).__class__ is float)
  1796.  
  1797.     class madcomplex(complex):
  1798.         def __repr__(self):
  1799.             return "%.17gj%+.17g" % (self.imag, self.real)
  1800.     a = madcomplex(-3, 4)
  1801.     vereq(repr(a), "4j-3")
  1802.     base = complex(-3, 4)
  1803.     veris(base.__class__, complex)
  1804.     vereq(a, base)
  1805.     vereq(complex(a), base)
  1806.     veris(complex(a).__class__, complex)
  1807.     a = madcomplex(a)  # just trying another form of the constructor
  1808.     vereq(repr(a), "4j-3")
  1809.     vereq(a, base)
  1810.     vereq(complex(a), base)
  1811.     veris(complex(a).__class__, complex)
  1812.     vereq(hash(a), hash(base))
  1813.     veris((+a).__class__, complex)
  1814.     veris((a + 0).__class__, complex)
  1815.     vereq(a + 0, base)
  1816.     veris((a - 0).__class__, complex)
  1817.     vereq(a - 0, base)
  1818.     veris((a * 1).__class__, complex)
  1819.     vereq(a * 1, base)
  1820.     veris((a / 1).__class__, complex)
  1821.     vereq(a / 1, base)
  1822.  
  1823.     class madtuple(tuple):
  1824.         _rev = None
  1825.         def rev(self):
  1826.             if self._rev is not None:
  1827.                 return self._rev
  1828.             L = list(self)
  1829.             L.reverse()
  1830.             self._rev = self.__class__(L)
  1831.             return self._rev
  1832.     a = madtuple((1,2,3,4,5,6,7,8,9,0))
  1833.     vereq(a, (1,2,3,4,5,6,7,8,9,0))
  1834.     vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
  1835.     vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
  1836.     for i in range(512):
  1837.         t = madtuple(range(i))
  1838.         u = t.rev()
  1839.         v = u.rev()
  1840.         vereq(v, t)
  1841.     a = madtuple((1,2,3,4,5))
  1842.     vereq(tuple(a), (1,2,3,4,5))
  1843.     verify(tuple(a).__class__ is tuple)
  1844.     vereq(hash(a), hash((1,2,3,4,5)))
  1845.     verify(a[:].__class__ is tuple)
  1846.     verify((a * 1).__class__ is tuple)
  1847.     verify((a * 0).__class__ is tuple)
  1848.     verify((a + ()).__class__ is tuple)
  1849.     a = madtuple(())
  1850.     vereq(tuple(a), ())
  1851.     verify(tuple(a).__class__ is tuple)
  1852.     verify((a + a).__class__ is tuple)
  1853.     verify((a * 0).__class__ is tuple)
  1854.     verify((a * 1).__class__ is tuple)
  1855.     verify((a * 2).__class__ is tuple)
  1856.     verify(a[:].__class__ is tuple)
  1857.  
  1858.     class madstring(str):
  1859.         _rev = None
  1860.         def rev(self):
  1861.             if self._rev is not None:
  1862.                 return self._rev
  1863.             L = list(self)
  1864.             L.reverse()
  1865.             self._rev = self.__class__("".join(L))
  1866.             return self._rev
  1867.     s = madstring("abcdefghijklmnopqrstuvwxyz")
  1868.     vereq(s, "abcdefghijklmnopqrstuvwxyz")
  1869.     vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
  1870.     vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
  1871.     for i in range(256):
  1872.         s = madstring("".join(map(chr, range(i))))
  1873.         t = s.rev()
  1874.         u = t.rev()
  1875.         vereq(u, s)
  1876.     s = madstring("12345")
  1877.     vereq(str(s), "12345")
  1878.     verify(str(s).__class__ is str)
  1879.  
  1880.     base = "\x00" * 5
  1881.     s = madstring(base)
  1882.     vereq(s, base)
  1883.     vereq(str(s), base)
  1884.     verify(str(s).__class__ is str)
  1885.     vereq(hash(s), hash(base))
  1886.     vereq({s: 1}[base], 1)
  1887.     vereq({base: 1}[s], 1)
  1888.     verify((s + "").__class__ is str)
  1889.     vereq(s + "", base)
  1890.     verify(("" + s).__class__ is str)
  1891.     vereq("" + s, base)
  1892.     verify((s * 0).__class__ is str)
  1893.     vereq(s * 0, "")
  1894.     verify((s * 1).__class__ is str)
  1895.     vereq(s * 1, base)
  1896.     verify((s * 2).__class__ is str)
  1897.     vereq(s * 2, base + base)
  1898.     verify(s[:].__class__ is str)
  1899.     vereq(s[:], base)
  1900.     verify(s[0:0].__class__ is str)
  1901.     vereq(s[0:0], "")
  1902.     verify(s.strip().__class__ is str)
  1903.     vereq(s.strip(), base)
  1904.     verify(s.lstrip().__class__ is str)
  1905.     vereq(s.lstrip(), base)
  1906.     verify(s.rstrip().__class__ is str)
  1907.     vereq(s.rstrip(), base)
  1908.     identitytab = ''.join([chr(i) for i in range(256)])
  1909.     verify(s.translate(identitytab).__class__ is str)
  1910.     vereq(s.translate(identitytab), base)
  1911.     verify(s.translate(identitytab, "x").__class__ is str)
  1912.     vereq(s.translate(identitytab, "x"), base)
  1913.     vereq(s.translate(identitytab, "\x00"), "")
  1914.     verify(s.replace("x", "x").__class__ is str)
  1915.     vereq(s.replace("x", "x"), base)
  1916.     verify(s.ljust(len(s)).__class__ is str)
  1917.     vereq(s.ljust(len(s)), base)
  1918.     verify(s.rjust(len(s)).__class__ is str)
  1919.     vereq(s.rjust(len(s)), base)
  1920.     verify(s.center(len(s)).__class__ is str)
  1921.     vereq(s.center(len(s)), base)
  1922.     verify(s.lower().__class__ is str)
  1923.     vereq(s.lower(), base)
  1924.  
  1925.     s = madstring("x y")
  1926.     vereq(s, "x y")
  1927.     verify(intern(s).__class__ is str)
  1928.     verify(intern(s) is intern("x y"))
  1929.     vereq(intern(s), "x y")
  1930.  
  1931.     i = intern("y x")
  1932.     s = madstring("y x")
  1933.     vereq(s, i)
  1934.     verify(intern(s).__class__ is str)
  1935.     verify(intern(s) is i)
  1936.  
  1937.     s = madstring(i)
  1938.     verify(intern(s).__class__ is str)
  1939.     verify(intern(s) is i)
  1940.  
  1941.     class madunicode(unicode):
  1942.         _rev = None
  1943.         def rev(self):
  1944.             if self._rev is not None:
  1945.                 return self._rev
  1946.             L = list(self)
  1947.             L.reverse()
  1948.             self._rev = self.__class__(u"".join(L))
  1949.             return self._rev
  1950.     u = madunicode("ABCDEF")
  1951.     vereq(u, u"ABCDEF")
  1952.     vereq(u.rev(), madunicode(u"FEDCBA"))
  1953.     vereq(u.rev().rev(), madunicode(u"ABCDEF"))
  1954.     base = u"12345"
  1955.     u = madunicode(base)
  1956.     vereq(unicode(u), base)
  1957.     verify(unicode(u).__class__ is unicode)
  1958.     vereq(hash(u), hash(base))
  1959.     vereq({u: 1}[base], 1)
  1960.     vereq({base: 1}[u], 1)
  1961.     verify(u.strip().__class__ is unicode)
  1962.     vereq(u.strip(), base)
  1963.     verify(u.lstrip().__class__ is unicode)
  1964.     vereq(u.lstrip(), base)
  1965.     verify(u.rstrip().__class__ is unicode)
  1966.     vereq(u.rstrip(), base)
  1967.     verify(u.replace(u"x", u"x").__class__ is unicode)
  1968.     vereq(u.replace(u"x", u"x"), base)
  1969.     verify(u.replace(u"xy", u"xy").__class__ is unicode)
  1970.     vereq(u.replace(u"xy", u"xy"), base)
  1971.     verify(u.center(len(u)).__class__ is unicode)
  1972.     vereq(u.center(len(u)), base)
  1973.     verify(u.ljust(len(u)).__class__ is unicode)
  1974.     vereq(u.ljust(len(u)), base)
  1975.     verify(u.rjust(len(u)).__class__ is unicode)
  1976.     vereq(u.rjust(len(u)), base)
  1977.     verify(u.lower().__class__ is unicode)
  1978.     vereq(u.lower(), base)
  1979.     verify(u.upper().__class__ is unicode)
  1980.     vereq(u.upper(), base)
  1981.     verify(u.capitalize().__class__ is unicode)
  1982.     vereq(u.capitalize(), base)
  1983.     verify(u.title().__class__ is unicode)
  1984.     vereq(u.title(), base)
  1985.     verify((u + u"").__class__ is unicode)
  1986.     vereq(u + u"", base)
  1987.     verify((u"" + u).__class__ is unicode)
  1988.     vereq(u"" + u, base)
  1989.     verify((u * 0).__class__ is unicode)
  1990.     vereq(u * 0, u"")
  1991.     verify((u * 1).__class__ is unicode)
  1992.     vereq(u * 1, base)
  1993.     verify((u * 2).__class__ is unicode)
  1994.     vereq(u * 2, base + base)
  1995.     verify(u[:].__class__ is unicode)
  1996.     vereq(u[:], base)
  1997.     verify(u[0:0].__class__ is unicode)
  1998.     vereq(u[0:0], u"")
  1999.  
  2000.     class sublist(list):
  2001.         pass
  2002.     a = sublist(range(5))
  2003.     vereq(a, range(5))
  2004.     a.append("hello")
  2005.     vereq(a, range(5) + ["hello"])
  2006.     a[5] = 5
  2007.     vereq(a, range(6))
  2008.     a.extend(range(6, 20))
  2009.     vereq(a, range(20))
  2010.     a[-5:] = []
  2011.     vereq(a, range(15))
  2012.     del a[10:15]
  2013.     vereq(len(a), 10)
  2014.     vereq(a, range(10))
  2015.     vereq(list(a), range(10))
  2016.     vereq(a[0], 0)
  2017.     vereq(a[9], 9)
  2018.     vereq(a[-10], 0)
  2019.     vereq(a[-1], 9)
  2020.     vereq(a[:5], range(5))
  2021.  
  2022.     class CountedInput(file):
  2023.         """Counts lines read by self.readline().
  2024.  
  2025.         self.lineno is the 0-based ordinal of the last line read, up to
  2026.         a maximum of one greater than the number of lines in the file.
  2027.  
  2028.         self.ateof is true if and only if the final "" line has been read,
  2029.         at which point self.lineno stops incrementing, and further calls
  2030.         to readline() continue to return "".
  2031.         """
  2032.  
  2033.         lineno = 0
  2034.         ateof = 0
  2035.         def readline(self):
  2036.             if self.ateof:
  2037.                 return ""
  2038.             s = file.readline(self)
  2039.             # Next line works too.
  2040.             # s = super(CountedInput, self).readline()
  2041.             self.lineno += 1
  2042.             if s == "":
  2043.                 self.ateof = 1
  2044.             return s
  2045.  
  2046.     f = file(name=TESTFN, mode='w')
  2047.     lines = ['a\n', 'b\n', 'c\n']
  2048.     try:
  2049.         f.writelines(lines)
  2050.         f.close()
  2051.         f = CountedInput(TESTFN)
  2052.         for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
  2053.             got = f.readline()
  2054.             vereq(expected, got)
  2055.             vereq(f.lineno, i)
  2056.             vereq(f.ateof, (i > len(lines)))
  2057.         f.close()
  2058.     finally:
  2059.         try:
  2060.             f.close()
  2061.         except:
  2062.             pass
  2063.         try:
  2064.             import os
  2065.             os.unlink(TESTFN)
  2066.         except:
  2067.             pass
  2068.  
  2069. def keywords():
  2070.     if verbose:
  2071.         print "Testing keyword args to basic type constructors ..."
  2072.     vereq(int(x=1), 1)
  2073.     vereq(float(x=2), 2.0)
  2074.     vereq(long(x=3), 3L)
  2075.     vereq(complex(imag=42, real=666), complex(666, 42))
  2076.     vereq(str(object=500), '500')
  2077.     vereq(unicode(string='abc', errors='strict'), u'abc')
  2078.     vereq(tuple(sequence=range(3)), (0, 1, 2))
  2079.     vereq(list(sequence=(0, 1, 2)), range(3))
  2080.     vereq(dict(items={1: 2}), {1: 2})
  2081.  
  2082.     for constructor in (int, float, long, complex, str, unicode,
  2083.                         tuple, list, dict, file):
  2084.         try:
  2085.             constructor(bogus_keyword_arg=1)
  2086.         except TypeError:
  2087.             pass
  2088.         else:
  2089.             raise TestFailed("expected TypeError from bogus keyword "
  2090.                              "argument to %r" % constructor)
  2091.  
  2092. def restricted():
  2093.     import rexec
  2094.     if verbose:
  2095.         print "Testing interaction with restricted execution ..."
  2096.  
  2097.     sandbox = rexec.RExec()
  2098.  
  2099.     code1 = """f = open(%r, 'w')""" % TESTFN
  2100.     code2 = """f = file(%r, 'w')""" % TESTFN
  2101.     code3 = """\
  2102. f = open(%r)
  2103. t = type(f)  # a sneaky way to get the file() constructor
  2104. f.close()
  2105. f = t(%r, 'w')  # rexec can't catch this by itself
  2106. """ % (TESTFN, TESTFN)
  2107.  
  2108.     f = open(TESTFN, 'w')  # Create the file so code3 can find it.
  2109.     f.close()
  2110.  
  2111.     try:
  2112.         for code in code1, code2, code3:
  2113.             try:
  2114.                 sandbox.r_exec(code)
  2115.             except IOError, msg:
  2116.                 if str(msg).find("restricted") >= 0:
  2117.                     outcome = "OK"
  2118.                 else:
  2119.                     outcome = "got an exception, but not an expected one"
  2120.             else:
  2121.                 outcome = "expected a restricted-execution exception"
  2122.  
  2123.             if outcome != "OK":
  2124.                 raise TestFailed("%s, in %r" % (outcome, code))
  2125.  
  2126.     finally:
  2127.         try:
  2128.             import os
  2129.             os.unlink(TESTFN)
  2130.         except:
  2131.             pass
  2132.  
  2133. def str_subclass_as_dict_key():
  2134.     if verbose:
  2135.         print "Testing a str subclass used as dict key .."
  2136.  
  2137.     class cistr(str):
  2138.         """Sublcass of str that computes __eq__ case-insensitively.
  2139.  
  2140.         Also computes a hash code of the string in canonical form.
  2141.         """
  2142.  
  2143.         def __init__(self, value):
  2144.             self.canonical = value.lower()
  2145.             self.hashcode = hash(self.canonical)
  2146.  
  2147.         def __eq__(self, other):
  2148.             if not isinstance(other, cistr):
  2149.                 other = cistr(other)
  2150.             return self.canonical == other.canonical
  2151.  
  2152.         def __hash__(self):
  2153.             return self.hashcode
  2154.  
  2155.     vereq(cistr('ABC'), 'abc')
  2156.     vereq('aBc', cistr('ABC'))
  2157.     vereq(str(cistr('ABC')), 'ABC')
  2158.  
  2159.     d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
  2160.     vereq(d[cistr('one')], 1)
  2161.     vereq(d[cistr('tWo')], 2)
  2162.     vereq(d[cistr('THrEE')], 3)
  2163.     verify(cistr('ONe') in d)
  2164.     vereq(d.get(cistr('thrEE')), 3)
  2165.  
  2166. def classic_comparisons():
  2167.     if verbose: print "Testing classic comparisons..."
  2168.     class classic:
  2169.         pass
  2170.     for base in (classic, int, object):
  2171.         if verbose: print "        (base = %s)" % base
  2172.         class C(base):
  2173.             def __init__(self, value):
  2174.                 self.value = int(value)
  2175.             def __cmp__(self, other):
  2176.                 if isinstance(other, C):
  2177.                     return cmp(self.value, other.value)
  2178.                 if isinstance(other, int) or isinstance(other, long):
  2179.                     return cmp(self.value, other)
  2180.                 return NotImplemented
  2181.         c1 = C(1)
  2182.         c2 = C(2)
  2183.         c3 = C(3)
  2184.         vereq(c1, 1)
  2185.         c = {1: c1, 2: c2, 3: c3}
  2186.         for x in 1, 2, 3:
  2187.             for y in 1, 2, 3:
  2188.                 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
  2189.                 for op in "<", "<=", "==", "!=", ">", ">=":
  2190.                     verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
  2191.                            "x=%d, y=%d" % (x, y))
  2192.                 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
  2193.                 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
  2194.  
  2195. def rich_comparisons():
  2196.     if verbose:
  2197.         print "Testing rich comparisons..."
  2198.     class Z(complex):
  2199.         pass
  2200.     z = Z(1)
  2201.     vereq(z, 1+0j)
  2202.     vereq(1+0j, z)
  2203.     class ZZ(complex):
  2204.         def __eq__(self, other):
  2205.             try:
  2206.                 return abs(self - other) <= 1e-6
  2207.             except:
  2208.                 return NotImplemented
  2209.     zz = ZZ(1.0000003)
  2210.     vereq(zz, 1+0j)
  2211.     vereq(1+0j, zz)
  2212.  
  2213.     class classic:
  2214.         pass
  2215.     for base in (classic, int, object, list):
  2216.         if verbose: print "        (base = %s)" % base
  2217.         class C(base):
  2218.             def __init__(self, value):
  2219.                 self.value = int(value)
  2220.             def __cmp__(self, other):
  2221.                 raise TestFailed, "shouldn't call __cmp__"
  2222.             def __eq__(self, other):
  2223.                 if isinstance(other, C):
  2224.                     return self.value == other.value
  2225.                 if isinstance(other, int) or isinstance(other, long):
  2226.                     return self.value == other
  2227.                 return NotImplemented
  2228.             def __ne__(self, other):
  2229.                 if isinstance(other, C):
  2230.                     return self.value != other.value
  2231.                 if isinstance(other, int) or isinstance(other, long):
  2232.                     return self.value != other
  2233.                 return NotImplemented
  2234.             def __lt__(self, other):
  2235.                 if isinstance(other, C):
  2236.                     return self.value < other.value
  2237.                 if isinstance(other, int) or isinstance(other, long):
  2238.                     return self.value < other
  2239.                 return NotImplemented
  2240.             def __le__(self, other):
  2241.                 if isinstance(other, C):
  2242.                     return self.value <= other.value
  2243.                 if isinstance(other, int) or isinstance(other, long):
  2244.                     return self.value <= other
  2245.                 return NotImplemented
  2246.             def __gt__(self, other):
  2247.                 if isinstance(other, C):
  2248.                     return self.value > other.value
  2249.                 if isinstance(other, int) or isinstance(other, long):
  2250.                     return self.value > other
  2251.                 return NotImplemented
  2252.             def __ge__(self, other):
  2253.                 if isinstance(other, C):
  2254.                     return self.value >= other.value
  2255.                 if isinstance(other, int) or isinstance(other, long):
  2256.                     return self.value >= other
  2257.                 return NotImplemented
  2258.         c1 = C(1)
  2259.         c2 = C(2)
  2260.         c3 = C(3)
  2261.         vereq(c1, 1)
  2262.         c = {1: c1, 2: c2, 3: c3}
  2263.         for x in 1, 2, 3:
  2264.             for y in 1, 2, 3:
  2265.                 for op in "<", "<=", "==", "!=", ">", ">=":
  2266.                     verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
  2267.                            "x=%d, y=%d" % (x, y))
  2268.                     verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
  2269.                            "x=%d, y=%d" % (x, y))
  2270.                     verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
  2271.                            "x=%d, y=%d" % (x, y))
  2272.  
  2273. def coercions():
  2274.     if verbose: print "Testing coercions..."
  2275.     class I(int): pass
  2276.     coerce(I(0), 0)
  2277.     coerce(0, I(0))
  2278.     class L(long): pass
  2279.     coerce(L(0), 0)
  2280.     coerce(L(0), 0L)
  2281.     coerce(0, L(0))
  2282.     coerce(0L, L(0))
  2283.     class F(float): pass
  2284.     coerce(F(0), 0)
  2285.     coerce(F(0), 0L)
  2286.     coerce(F(0), 0.)
  2287.     coerce(0, F(0))
  2288.     coerce(0L, F(0))
  2289.     coerce(0., F(0))
  2290.     class C(complex): pass
  2291.     coerce(C(0), 0)
  2292.     coerce(C(0), 0L)
  2293.     coerce(C(0), 0.)
  2294.     coerce(C(0), 0j)
  2295.     coerce(0, C(0))
  2296.     coerce(0L, C(0))
  2297.     coerce(0., C(0))
  2298.     coerce(0j, C(0))
  2299.  
  2300. def descrdoc():
  2301.     if verbose: print "Testing descriptor doc strings..."
  2302.     def check(descr, what):
  2303.         vereq(descr.__doc__, what)
  2304.     check(file.closed, "flag set if the file is closed") # getset descriptor
  2305.     check(file.name, "file name") # member descriptor
  2306.  
  2307. def setclass():
  2308.     if verbose: print "Testing __class__ assignment..."
  2309.     class C(object): pass
  2310.     class D(object): pass
  2311.     class E(object): pass
  2312.     class F(D, E): pass
  2313.     for cls in C, D, E, F:
  2314.         for cls2 in C, D, E, F:
  2315.             x = cls()
  2316.             x.__class__ = cls2
  2317.             verify(x.__class__ is cls2)
  2318.             x.__class__ = cls
  2319.             verify(x.__class__ is cls)
  2320.     def cant(x, C):
  2321.         try:
  2322.             x.__class__ = C
  2323.         except TypeError:
  2324.             pass
  2325.         else:
  2326.             raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
  2327.     cant(C(), list)
  2328.     cant(list(), C)
  2329.     cant(C(), 1)
  2330.     cant(C(), object)
  2331.     cant(object(), list)
  2332.     cant(list(), object)
  2333.  
  2334. def setdict():
  2335.     if verbose: print "Testing __dict__ assignment..."
  2336.     class C(object): pass
  2337.     a = C()
  2338.     a.__dict__ = {'b': 1}
  2339.     vereq(a.b, 1)
  2340.     def cant(x, dict):
  2341.         try:
  2342.             x.__dict__ = dict
  2343.         except TypeError:
  2344.             pass
  2345.         else:
  2346.             raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
  2347.     cant(a, None)
  2348.     cant(a, [])
  2349.     cant(a, 1)
  2350.     del a.__dict__ # Deleting __dict__ is allowed
  2351.     # Classes don't allow __dict__ assignment
  2352.     cant(C, {})
  2353.  
  2354. def pickles():
  2355.     if verbose:
  2356.         print "Testing pickling and copying new-style classes and objects..."
  2357.     import pickle, cPickle
  2358.  
  2359.     def sorteditems(d):
  2360.         L = d.items()
  2361.         L.sort()
  2362.         return L
  2363.  
  2364.     global C
  2365.     class C(object):
  2366.         def __init__(self, a, b):
  2367.             super(C, self).__init__()
  2368.             self.a = a
  2369.             self.b = b
  2370.         def __repr__(self):
  2371.             return "C(%r, %r)" % (self.a, self.b)
  2372.  
  2373.     global C1
  2374.     class C1(list):
  2375.         def __new__(cls, a, b):
  2376.             return super(C1, cls).__new__(cls)
  2377.         def __init__(self, a, b):
  2378.             self.a = a
  2379.             self.b = b
  2380.         def __repr__(self):
  2381.             return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
  2382.  
  2383.     global C2
  2384.     class C2(int):
  2385.         def __new__(cls, a, b, val=0):
  2386.             return super(C2, cls).__new__(cls, val)
  2387.         def __init__(self, a, b, val=0):
  2388.             self.a = a
  2389.             self.b = b
  2390.         def __repr__(self):
  2391.             return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
  2392.  
  2393.     global C3
  2394.     class C3(object):
  2395.         def __init__(self, foo):
  2396.             self.foo = foo
  2397.         def __getstate__(self):
  2398.             return self.foo
  2399.         def __setstate__(self, foo):
  2400.             self.foo = foo
  2401.  
  2402.     global C4classic, C4
  2403.     class C4classic: # classic
  2404.         pass
  2405.     class C4(C4classic, object): # mixed inheritance
  2406.         pass
  2407.  
  2408.     for p in pickle, cPickle:
  2409.         for bin in 0, 1:
  2410.             if verbose:
  2411.                 print p.__name__, ["text", "binary"][bin]
  2412.  
  2413.             for cls in C, C1, C2:
  2414.                 s = p.dumps(cls, bin)
  2415.                 cls2 = p.loads(s)
  2416.                 verify(cls2 is cls)
  2417.  
  2418.             a = C1(1, 2); a.append(42); a.append(24)
  2419.             b = C2("hello", "world", 42)
  2420.             s = p.dumps((a, b), bin)
  2421.             x, y = p.loads(s)
  2422.             vereq(x.__class__, a.__class__)
  2423.             vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
  2424.             vereq(y.__class__, b.__class__)
  2425.             vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
  2426.             vereq(`x`, `a`)
  2427.             vereq(`y`, `b`)
  2428.             if verbose:
  2429.                 print "a = x =", a
  2430.                 print "b = y =", b
  2431.             # Test for __getstate__ and __setstate__ on new style class
  2432.             u = C3(42)
  2433.             s = p.dumps(u, bin)
  2434.             v = p.loads(s)
  2435.             veris(u.__class__, v.__class__)
  2436.             vereq(u.foo, v.foo)
  2437.             # Test for picklability of hybrid class
  2438.             u = C4()
  2439.             u.foo = 42
  2440.             s = p.dumps(u, bin)
  2441.             v = p.loads(s)
  2442.             veris(u.__class__, v.__class__)
  2443.             vereq(u.foo, v.foo)
  2444.  
  2445.     # Testing copy.deepcopy()
  2446.     if verbose:
  2447.         print "deepcopy"
  2448.     import copy
  2449.     for cls in C, C1, C2:
  2450.         cls2 = copy.deepcopy(cls)
  2451.         verify(cls2 is cls)
  2452.  
  2453.     a = C1(1, 2); a.append(42); a.append(24)
  2454.     b = C2("hello", "world", 42)
  2455.     x, y = copy.deepcopy((a, b))
  2456.     vereq(x.__class__, a.__class__)
  2457.     vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
  2458.     vereq(y.__class__, b.__class__)
  2459.     vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
  2460.     vereq(`x`, `a`)
  2461.     vereq(`y`, `b`)
  2462.     if verbose:
  2463.         print "a = x =", a
  2464.         print "b = y =", b
  2465.  
  2466. def pickleslots():
  2467.     if verbose: print "Testing pickling of classes with __slots__ ..."
  2468.     import pickle, cPickle
  2469.     # Pickling of classes with __slots__ but without __getstate__ should fail
  2470.     global B, C, D, E
  2471.     class B(object):
  2472.         pass
  2473.     for base in [object, B]:
  2474.         class C(base):
  2475.             __slots__ = ['a']
  2476.         class D(C):
  2477.             pass
  2478.         try:
  2479.             pickle.dumps(C())
  2480.         except TypeError:
  2481.             pass
  2482.         else:
  2483.             raise TestFailed, "should fail: pickle C instance - %s" % base
  2484.         try:
  2485.             cPickle.dumps(C())
  2486.         except TypeError:
  2487.             pass
  2488.         else:
  2489.             raise TestFailed, "should fail: cPickle C instance - %s" % base
  2490.         try:
  2491.             pickle.dumps(C())
  2492.         except TypeError:
  2493.             pass
  2494.         else:
  2495.             raise TestFailed, "should fail: pickle D instance - %s" % base
  2496.         try:
  2497.             cPickle.dumps(D())
  2498.         except TypeError:
  2499.             pass
  2500.         else:
  2501.             raise TestFailed, "should fail: cPickle D instance - %s" % base
  2502.         # Give C a __getstate__ and __setstate__
  2503.         class C(base):
  2504.             __slots__ = ['a']
  2505.             def __getstate__(self):
  2506.                 try:
  2507.                     d = self.__dict__.copy()
  2508.                 except AttributeError:
  2509.                     d = {}
  2510.                 try:
  2511.                     d['a'] = self.a
  2512.                 except AttributeError:
  2513.                     pass
  2514.                 return d
  2515.             def __setstate__(self, d):
  2516.                 for k, v in d.items():
  2517.                     setattr(self, k, v)
  2518.         class D(C):
  2519.             pass
  2520.         # Now it should work
  2521.         x = C()
  2522.         y = pickle.loads(pickle.dumps(x))
  2523.         vereq(hasattr(y, 'a'), 0)
  2524.         y = cPickle.loads(cPickle.dumps(x))
  2525.         vereq(hasattr(y, 'a'), 0)
  2526.         x.a = 42
  2527.         y = pickle.loads(pickle.dumps(x))
  2528.         vereq(y.a, 42)
  2529.         y = cPickle.loads(cPickle.dumps(x))
  2530.         vereq(y.a, 42)
  2531.         x = D()
  2532.         x.a = 42
  2533.         x.b = 100
  2534.         y = pickle.loads(pickle.dumps(x))
  2535.         vereq(y.a + y.b, 142)
  2536.         y = cPickle.loads(cPickle.dumps(x))
  2537.         vereq(y.a + y.b, 142)
  2538.         # But a subclass that adds a slot should not work
  2539.         class E(C):
  2540.             __slots__ = ['b']
  2541.         try:
  2542.             pickle.dumps(E())
  2543.         except TypeError:
  2544.             pass
  2545.         else:
  2546.             raise TestFailed, "should fail: pickle E instance - %s" % base
  2547.         try:
  2548.             cPickle.dumps(E())
  2549.         except TypeError:
  2550.             pass
  2551.         else:
  2552.             raise TestFailed, "should fail: cPickle E instance - %s" % base
  2553.  
  2554. def copies():
  2555.     if verbose: print "Testing copy.copy() and copy.deepcopy()..."
  2556.     import copy
  2557.     class C(object):
  2558.         pass
  2559.  
  2560.     a = C()
  2561.     a.foo = 12
  2562.     b = copy.copy(a)
  2563.     vereq(b.__dict__, a.__dict__)
  2564.  
  2565.     a.bar = [1,2,3]
  2566.     c = copy.copy(a)
  2567.     vereq(c.bar, a.bar)
  2568.     verify(c.bar is a.bar)
  2569.  
  2570.     d = copy.deepcopy(a)
  2571.     vereq(d.__dict__, a.__dict__)
  2572.     a.bar.append(4)
  2573.     vereq(d.bar, [1,2,3])
  2574.  
  2575. def binopoverride():
  2576.     if verbose: print "Testing overrides of binary operations..."
  2577.     class I(int):
  2578.         def __repr__(self):
  2579.             return "I(%r)" % int(self)
  2580.         def __add__(self, other):
  2581.             return I(int(self) + int(other))
  2582.         __radd__ = __add__
  2583.         def __pow__(self, other, mod=None):
  2584.             if mod is None:
  2585.                 return I(pow(int(self), int(other)))
  2586.             else:
  2587.                 return I(pow(int(self), int(other), int(mod)))
  2588.         def __rpow__(self, other, mod=None):
  2589.             if mod is None:
  2590.                 return I(pow(int(other), int(self), mod))
  2591.             else:
  2592.                 return I(pow(int(other), int(self), int(mod)))
  2593.  
  2594.     vereq(`I(1) + I(2)`, "I(3)")
  2595.     vereq(`I(1) + 2`, "I(3)")
  2596.     vereq(`1 + I(2)`, "I(3)")
  2597.     vereq(`I(2) ** I(3)`, "I(8)")
  2598.     vereq(`2 ** I(3)`, "I(8)")
  2599.     vereq(`I(2) ** 3`, "I(8)")
  2600.     vereq(`pow(I(2), I(3), I(5))`, "I(3)")
  2601.     class S(str):
  2602.         def __eq__(self, other):
  2603.             return self.lower() == other.lower()
  2604.  
  2605. def subclasspropagation():
  2606.     if verbose: print "Testing propagation of slot functions to subclasses..."
  2607.     class A(object):
  2608.         pass
  2609.     class B(A):
  2610.         pass
  2611.     class C(A):
  2612.         pass
  2613.     class D(B, C):
  2614.         pass
  2615.     d = D()
  2616.     vereq(hash(d), id(d))
  2617.     A.__hash__ = lambda self: 42
  2618.     vereq(hash(d), 42)
  2619.     C.__hash__ = lambda self: 314
  2620.     vereq(hash(d), 314)
  2621.     B.__hash__ = lambda self: 144
  2622.     vereq(hash(d), 144)
  2623.     D.__hash__ = lambda self: 100
  2624.     vereq(hash(d), 100)
  2625.     del D.__hash__
  2626.     vereq(hash(d), 144)
  2627.     del B.__hash__
  2628.     vereq(hash(d), 314)
  2629.     del C.__hash__
  2630.     vereq(hash(d), 42)
  2631.     del A.__hash__
  2632.     vereq(hash(d), id(d))
  2633.     d.foo = 42
  2634.     d.bar = 42
  2635.     vereq(d.foo, 42)
  2636.     vereq(d.bar, 42)
  2637.     def __getattribute__(self, name):
  2638.         if name == "foo":
  2639.             return 24
  2640.         return object.__getattribute__(self, name)
  2641.     A.__getattribute__ = __getattribute__
  2642.     vereq(d.foo, 24)
  2643.     vereq(d.bar, 42)
  2644.     def __getattr__(self, name):
  2645.         if name in ("spam", "foo", "bar"):
  2646.             return "hello"
  2647.         raise AttributeError, name
  2648.     B.__getattr__ = __getattr__
  2649.     vereq(d.spam, "hello")
  2650.     vereq(d.foo, 24)
  2651.     vereq(d.bar, 42)
  2652.     del A.__getattribute__
  2653.     vereq(d.foo, 42)
  2654.     del d.foo
  2655.     vereq(d.foo, "hello")
  2656.     vereq(d.bar, 42)
  2657.     del B.__getattr__
  2658.     try:
  2659.         d.foo
  2660.     except AttributeError:
  2661.         pass
  2662.     else:
  2663.         raise TestFailed, "d.foo should be undefined now"
  2664.  
  2665. def buffer_inherit():
  2666.     import binascii
  2667.     # SF bug [#470040] ParseTuple t# vs subclasses.
  2668.     if verbose:
  2669.         print "Testing that buffer interface is inherited ..."
  2670.  
  2671.     class MyStr(str):
  2672.         pass
  2673.     base = 'abc'
  2674.     m = MyStr(base)
  2675.     # b2a_hex uses the buffer interface to get its argument's value, via
  2676.     # PyArg_ParseTuple 't#' code.
  2677.     vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
  2678.  
  2679.     # It's not clear that unicode will continue to support the character
  2680.     # buffer interface, and this test will fail if that's taken away.
  2681.     class MyUni(unicode):
  2682.         pass
  2683.     base = u'abc'
  2684.     m = MyUni(base)
  2685.     vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
  2686.  
  2687.     class MyInt(int):
  2688.         pass
  2689.     m = MyInt(42)
  2690.     try:
  2691.         binascii.b2a_hex(m)
  2692.         raise TestFailed('subclass of int should not have a buffer interface')
  2693.     except TypeError:
  2694.         pass
  2695.  
  2696. def str_of_str_subclass():
  2697.     import binascii
  2698.     import cStringIO
  2699.  
  2700.     if verbose:
  2701.         print "Testing __str__ defined in subclass of str ..."
  2702.  
  2703.     class octetstring(str):
  2704.         def __str__(self):
  2705.             return binascii.b2a_hex(self)
  2706.         def __repr__(self):
  2707.             return self + " repr"
  2708.  
  2709.     o = octetstring('A')
  2710.     vereq(type(o), octetstring)
  2711.     vereq(type(str(o)), str)
  2712.     vereq(type(repr(o)), str)
  2713.     vereq(ord(o), 0x41)
  2714.     vereq(str(o), '41')
  2715.     vereq(repr(o), 'A repr')
  2716.     vereq(o.__str__(), '41')
  2717.     vereq(o.__repr__(), 'A repr')
  2718.  
  2719.     capture = cStringIO.StringIO()
  2720.     # Calling str() or not exercises different internal paths.
  2721.     print >> capture, o
  2722.     print >> capture, str(o)
  2723.     vereq(capture.getvalue(), '41\n41\n')
  2724.     capture.close()
  2725.  
  2726. def kwdargs():
  2727.     if verbose: print "Testing keyword arguments to __init__, __call__..."
  2728.     def f(a): return a
  2729.     vereq(f.__call__(a=42), 42)
  2730.     a = []
  2731.     list.__init__(a, sequence=[0, 1, 2])
  2732.     vereq(a, [0, 1, 2])
  2733.  
  2734. def delhook():
  2735.     if verbose: print "Testing __del__ hook..."
  2736.     log = []
  2737.     class C(object):
  2738.         def __del__(self):
  2739.             log.append(1)
  2740.     c = C()
  2741.     vereq(log, [])
  2742.     del c
  2743.     vereq(log, [1])
  2744.  
  2745.     class D(object): pass
  2746.     d = D()
  2747.     try: del d[0]
  2748.     except TypeError: pass
  2749.     else: raise TestFailed, "invalid del() didn't raise TypeError"
  2750.  
  2751. def hashinherit():
  2752.     if verbose: print "Testing hash of mutable subclasses..."
  2753.  
  2754.     class mydict(dict):
  2755.         pass
  2756.     d = mydict()
  2757.     try:
  2758.         hash(d)
  2759.     except TypeError:
  2760.         pass
  2761.     else:
  2762.         raise TestFailed, "hash() of dict subclass should fail"
  2763.  
  2764.     class mylist(list):
  2765.         pass
  2766.     d = mylist()
  2767.     try:
  2768.         hash(d)
  2769.     except TypeError:
  2770.         pass
  2771.     else:
  2772.         raise TestFailed, "hash() of list subclass should fail"
  2773.  
  2774. def strops():
  2775.     try: 'a' + 5
  2776.     except TypeError: pass
  2777.     else: raise TestFailed, "'' + 5 doesn't raise TypeError"
  2778.  
  2779.     try: ''.split('')
  2780.     except ValueError: pass
  2781.     else: raise TestFailed, "''.split('') doesn't raise ValueError"
  2782.  
  2783.     try: ''.join([0])
  2784.     except TypeError: pass
  2785.     else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
  2786.  
  2787.     try: ''.rindex('5')
  2788.     except ValueError: pass
  2789.     else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
  2790.  
  2791.     try: ''.replace('', '')
  2792.     except ValueError: pass
  2793.     else: raise TestFailed, "''.replace('', '') doesn't raise ValueError"
  2794.  
  2795.     try: '%(n)s' % None
  2796.     except TypeError: pass
  2797.     else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
  2798.  
  2799.     try: '%(n' % {}
  2800.     except ValueError: pass
  2801.     else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
  2802.  
  2803.     try: '%*s' % ('abc')
  2804.     except TypeError: pass
  2805.     else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
  2806.  
  2807.     try: '%*.*s' % ('abc', 5)
  2808.     except TypeError: pass
  2809.     else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
  2810.  
  2811.     try: '%s' % (1, 2)
  2812.     except TypeError: pass
  2813.     else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
  2814.  
  2815.     try: '%' % None
  2816.     except ValueError: pass
  2817.     else: raise TestFailed, "'%' % None doesn't raise ValueError"
  2818.  
  2819.     vereq('534253'.isdigit(), 1)
  2820.     vereq('534253x'.isdigit(), 0)
  2821.     vereq('%c' % 5, '\x05')
  2822.     vereq('%c' % '5', '5')
  2823.  
  2824. def deepcopyrecursive():
  2825.     if verbose: print "Testing deepcopy of recursive objects..."
  2826.     class Node:
  2827.         pass
  2828.     a = Node()
  2829.     b = Node()
  2830.     a.b = b
  2831.     b.a = a
  2832.     z = deepcopy(a) # This blew up before
  2833.  
  2834. def modules():
  2835.     if verbose: print "Testing uninitialized module objects..."
  2836.     from types import ModuleType as M
  2837.     m = M.__new__(M)
  2838.     str(m)
  2839.     vereq(hasattr(m, "__name__"), 0)
  2840.     vereq(hasattr(m, "__file__"), 0)
  2841.     vereq(hasattr(m, "foo"), 0)
  2842.     vereq(m.__dict__, None)
  2843.     m.foo = 1
  2844.     vereq(m.__dict__, {"foo": 1})
  2845.  
  2846. def test_main():
  2847.     class_docstrings()
  2848.     lists()
  2849.     dicts()
  2850.     dict_constructor()
  2851.     test_dir()
  2852.     ints()
  2853.     longs()
  2854.     floats()
  2855.     complexes()
  2856.     spamlists()
  2857.     spamdicts()
  2858.     pydicts()
  2859.     pylists()
  2860.     metaclass()
  2861.     pymods()
  2862.     multi()
  2863.     diamond()
  2864.     objects()
  2865.     slots()
  2866.     dynamics()
  2867.     errors()
  2868.     classmethods()
  2869.     staticmethods()
  2870.     classic()
  2871.     compattr()
  2872.     newslot()
  2873.     altmro()
  2874.     overloading()
  2875.     methods()
  2876.     specials()
  2877.     weakrefs()
  2878.     properties()
  2879.     supers()
  2880.     inherits()
  2881.     keywords()
  2882.     restricted()
  2883.     str_subclass_as_dict_key()
  2884.     classic_comparisons()
  2885.     rich_comparisons()
  2886.     coercions()
  2887.     descrdoc()
  2888.     setclass()
  2889.     setdict()
  2890.     pickles()
  2891.     copies()
  2892.     binopoverride()
  2893.     subclasspropagation()
  2894.     buffer_inherit()
  2895.     str_of_str_subclass()
  2896.     kwdargs()
  2897.     delhook()
  2898.     hashinherit()
  2899.     strops()
  2900.     deepcopyrecursive()
  2901.     modules()
  2902.     pickleslots()
  2903.     if verbose: print "All OK"
  2904.  
  2905. if __name__ == "__main__":
  2906.     test_main()
  2907.