[pypy-svn] r57380 - in pypy/branch/2.5-features/lib-python/modified-2.5.1/test: . output

bgola at codespeak.net bgola at codespeak.net
Sun Aug 17 23:48:17 CEST 2008


Author: bgola
Date: Sun Aug 17 23:48:15 2008
New Revision: 57380

Added:
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/__init__.py   (contents, props changed)
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/list_tests.py   (contents, props changed)
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/mapping_tests.py   (contents, props changed)
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/output/
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/pickletester.py   (contents, props changed)
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/seq_tests.py   (contents, props changed)
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/string_tests.py   (contents, props changed)
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test___all__.py   (contents, props changed)
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_array.py   (contents, props changed)
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_base64.py   (contents, props changed)
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_bufio.py   (contents, props changed)
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_builtin.py   (contents, props changed)
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_bz2.py   (contents, props changed)
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_class.py   (contents, props changed)
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_codeop.py   (contents, props changed)
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_compile.py   (contents, props changed)
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_complex.py   (contents, props changed)
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_copy.py   (contents, props changed)
   pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_cpickle.py   (contents, props changed)
Log:
some changes applied to tests (stdlib) to work properly in pypy

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/__init__.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/__init__.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,11 @@
+"""
+This package only contains the tests that we have modified for PyPy.
+It uses the 'official' hack to include the rest of the standard
+'test' package from CPython.
+
+This assumes that sys.path is configured to contain 
+'lib-python/modified-2.5.1' before 'lib-python/2.5.1'.
+"""
+
+from pkgutil import extend_path
+__path__ = extend_path(__path__, __name__)

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/list_tests.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/list_tests.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,523 @@
+"""
+Tests common to list and UserList.UserList
+"""
+
+import sys
+import os
+
+import unittest
+from test import test_support, seq_tests
+
+class CommonTest(seq_tests.CommonTest):
+
+    def test_init(self):
+        # Iterable arg is optional
+        self.assertEqual(self.type2test([]), self.type2test())
+
+        # Init clears previous values
+        a = self.type2test([1, 2, 3])
+        a.__init__()
+        self.assertEqual(a, self.type2test([]))
+
+        # Init overwrites previous values
+        a = self.type2test([1, 2, 3])
+        a.__init__([4, 5, 6])
+        self.assertEqual(a, self.type2test([4, 5, 6]))
+
+        # Mutables always return a new object
+        b = self.type2test(a)
+        self.assertNotEqual(id(a), id(b))
+        self.assertEqual(a, b)
+
+    def test_repr(self):
+        l0 = []
+        l2 = [0, 1, 2]
+        a0 = self.type2test(l0)
+        a2 = self.type2test(l2)
+
+        self.assertEqual(str(a0), str(l0))
+        self.assertEqual(repr(a0), repr(l0))
+        self.assertEqual(`a2`, `l2`)
+        self.assertEqual(str(a2), "[0, 1, 2]")
+        self.assertEqual(repr(a2), "[0, 1, 2]")
+
+        a2.append(a2)
+        a2.append(3)
+        self.assertEqual(str(a2), "[0, 1, 2, [...], 3]")
+        self.assertEqual(repr(a2), "[0, 1, 2, [...], 3]")
+
+    def test_print(self):
+        d = self.type2test(xrange(200))
+        d.append(d)
+        d.extend(xrange(200,400))
+        d.append(d)
+        d.append(400)
+        try:
+            fo = open(test_support.TESTFN, "wb")
+            print >> fo, d,
+            fo.close()
+            fo = open(test_support.TESTFN, "rb")
+            self.assertEqual(fo.read(), repr(d))
+        finally:
+            fo.close()
+            os.remove(test_support.TESTFN)
+
+    def test_set_subscript(self):
+        a = self.type2test(range(20))
+        self.assertRaises(ValueError, a.__setitem__, slice(0, 10, 0), [1,2,3])
+        self.assertRaises(TypeError, a.__setitem__, slice(0, 10), 1)
+        self.assertRaises(ValueError, a.__setitem__, slice(0, 10, 2), [1,2])
+        self.assertRaises(TypeError, a.__getitem__, 'x', 1)
+        a[slice(2,10,3)] = [1,2,3]
+        self.assertEqual(a, self.type2test([0, 1, 1, 3, 4, 2, 6, 7, 3,
+                                            9, 10, 11, 12, 13, 14, 15,
+                                            16, 17, 18, 19]))
+
+    def test_reversed(self):
+        a = self.type2test(range(20))
+        r = reversed(a)
+        self.assertEqual(list(r), self.type2test(range(19, -1, -1)))
+        self.assertRaises(StopIteration, r.next)
+        self.assertEqual(list(reversed(self.type2test())),
+                         self.type2test())
+
+    def test_setitem(self):
+        a = self.type2test([0, 1])
+        a[0] = 0
+        a[1] = 100
+        self.assertEqual(a, self.type2test([0, 100]))
+        a[-1] = 200
+        self.assertEqual(a, self.type2test([0, 200]))
+        a[-2] = 100
+        self.assertEqual(a, self.type2test([100, 200]))
+        self.assertRaises(IndexError, a.__setitem__, -3, 200)
+        self.assertRaises(IndexError, a.__setitem__, 2, 200)
+
+        a = self.type2test([])
+        self.assertRaises(IndexError, a.__setitem__, 0, 200)
+        self.assertRaises(IndexError, a.__setitem__, -1, 200)
+        self.assertRaises(TypeError, a.__setitem__)
+
+        a = self.type2test([0,1,2,3,4])
+        a[0L] = 1
+        a[1L] = 2
+        a[2L] = 3
+        self.assertEqual(a, self.type2test([1,2,3,3,4]))
+        a[0] = 5
+        a[1] = 6
+        a[2] = 7
+        self.assertEqual(a, self.type2test([5,6,7,3,4]))
+        a[-2L] = 88
+        a[-1L] = 99
+        self.assertEqual(a, self.type2test([5,6,7,88,99]))
+        a[-2] = 8
+        a[-1] = 9
+        self.assertEqual(a, self.type2test([5,6,7,8,9]))
+
+    def test_delitem(self):
+        a = self.type2test([0, 1])
+        del a[1]
+        self.assertEqual(a, [0])
+        del a[0]
+        self.assertEqual(a, [])
+
+        a = self.type2test([0, 1])
+        del a[-2]
+        self.assertEqual(a, [1])
+        del a[-1]
+        self.assertEqual(a, [])
+
+        a = self.type2test([0, 1])
+        self.assertRaises(IndexError, a.__delitem__, -3)
+        self.assertRaises(IndexError, a.__delitem__, 2)
+
+        a = self.type2test([])
+        self.assertRaises(IndexError, a.__delitem__, 0)
+
+        self.assertRaises(TypeError, a.__delitem__)
+
+    def test_setslice(self):
+        l = [0, 1]
+        a = self.type2test(l)
+
+        for i in range(-3, 4):
+            a[:i] = l[:i]
+            self.assertEqual(a, l)
+            a2 = a[:]
+            a2[:i] = a[:i]
+            self.assertEqual(a2, a)
+            a[i:] = l[i:]
+            self.assertEqual(a, l)
+            a2 = a[:]
+            a2[i:] = a[i:]
+            self.assertEqual(a2, a)
+            for j in range(-3, 4):
+                a[i:j] = l[i:j]
+                self.assertEqual(a, l)
+                a2 = a[:]
+                a2[i:j] = a[i:j]
+                self.assertEqual(a2, a)
+
+        aa2 = a2[:]
+        aa2[:0] = [-2, -1]
+        self.assertEqual(aa2, [-2, -1, 0, 1])
+        aa2[0:] = []
+        self.assertEqual(aa2, [])
+
+        a = self.type2test([1, 2, 3, 4, 5])
+        a[:-1] = a
+        self.assertEqual(a, self.type2test([1, 2, 3, 4, 5, 5]))
+        a = self.type2test([1, 2, 3, 4, 5])
+        a[1:] = a
+        self.assertEqual(a, self.type2test([1, 1, 2, 3, 4, 5]))
+        a = self.type2test([1, 2, 3, 4, 5])
+        a[1:-1] = a
+        self.assertEqual(a, self.type2test([1, 1, 2, 3, 4, 5, 5]))
+
+        a = self.type2test([])
+        a[:] = tuple(range(10))
+        self.assertEqual(a, self.type2test(range(10)))
+
+        if hasattr(a, '__setslice__'):
+            self.assertRaises(TypeError, a.__setslice__, 0, 1, 5)
+
+            self.assertRaises(TypeError, a.__setslice__)
+
+    def test_delslice(self):
+        a = self.type2test([0, 1])
+        del a[1:2]
+        del a[0:1]
+        self.assertEqual(a, self.type2test([]))
+
+        a = self.type2test([0, 1])
+        del a[1L:2L]
+        del a[0L:1L]
+        self.assertEqual(a, self.type2test([]))
+
+        a = self.type2test([0, 1])
+        del a[-2:-1]
+        self.assertEqual(a, self.type2test([1]))
+
+        a = self.type2test([0, 1])
+        del a[-2L:-1L]
+        self.assertEqual(a, self.type2test([1]))
+
+        a = self.type2test([0, 1])
+        del a[1:]
+        del a[:1]
+        self.assertEqual(a, self.type2test([]))
+
+        a = self.type2test([0, 1])
+        del a[1L:]
+        del a[:1L]
+        self.assertEqual(a, self.type2test([]))
+
+        a = self.type2test([0, 1])
+        del a[-1:]
+        self.assertEqual(a, self.type2test([0]))
+
+        a = self.type2test([0, 1])
+        del a[-1L:]
+        self.assertEqual(a, self.type2test([0]))
+
+        a = self.type2test([0, 1])
+        del a[:]
+        self.assertEqual(a, self.type2test([]))
+
+    def test_append(self):
+        a = self.type2test([])
+        a.append(0)
+        a.append(1)
+        a.append(2)
+        self.assertEqual(a, self.type2test([0, 1, 2]))
+
+        self.assertRaises(TypeError, a.append)
+
+    def test_extend(self):
+        a1 = self.type2test([0])
+        a2 = self.type2test((0, 1))
+        a = a1[:]
+        a.extend(a2)
+        self.assertEqual(a, a1 + a2)
+
+        a.extend(self.type2test([]))
+        self.assertEqual(a, a1 + a2)
+
+        a.extend(a)
+        self.assertEqual(a, self.type2test([0, 0, 1, 0, 0, 1]))
+
+        a = self.type2test("spam")
+        a.extend("eggs")
+        self.assertEqual(a, list("spameggs"))
+
+        self.assertRaises(TypeError, a.extend, None)
+
+        self.assertRaises(TypeError, a.extend)
+
+    def test_insert(self):
+        a = self.type2test([0, 1, 2])
+        a.insert(0, -2)
+        a.insert(1, -1)
+        a.insert(2, 0)
+        self.assertEqual(a, [-2, -1, 0, 0, 1, 2])
+
+        b = a[:]
+        b.insert(-2, "foo")
+        b.insert(-200, "left")
+        b.insert(200, "right")
+        self.assertEqual(b, self.type2test(["left",-2,-1,0,0,"foo",1,2,"right"]))
+
+        self.assertRaises(TypeError, a.insert)
+
+    def test_pop(self):
+        a = self.type2test([-1, 0, 1])
+        a.pop()
+        self.assertEqual(a, [-1, 0])
+        a.pop(0)
+        self.assertEqual(a, [0])
+        self.assertRaises(IndexError, a.pop, 5)
+        a.pop(0)
+        self.assertEqual(a, [])
+        self.assertRaises(IndexError, a.pop)
+        self.assertRaises(TypeError, a.pop, 42, 42)
+        a = self.type2test([0, 10, 20, 30, 40])
+
+    def test_remove(self):
+        a = self.type2test([0, 0, 1])
+        a.remove(1)
+        self.assertEqual(a, [0, 0])
+        a.remove(0)
+        self.assertEqual(a, [0])
+        a.remove(0)
+        self.assertEqual(a, [])
+
+        self.assertRaises(ValueError, a.remove, 0)
+
+        self.assertRaises(TypeError, a.remove)
+
+        class BadExc(Exception):
+            pass
+
+        class BadCmp:
+            def __eq__(self, other):
+                if other == 2:
+                    raise BadExc()
+                return False
+
+        a = self.type2test([0, 1, 2, 3])
+        self.assertRaises(BadExc, a.remove, BadCmp())
+
+        class BadCmp2:
+            def __cmp__(self, other):
+                raise BadExc()
+
+        d = self.type2test('abcdefghcij')
+        d.remove('c')
+        self.assertEqual(d, self.type2test('abdefghcij'))
+        d.remove('c')
+        self.assertEqual(d, self.type2test('abdefghij'))
+        self.assertRaises(ValueError, d.remove, 'c')
+        self.assertEqual(d, self.type2test('abdefghij'))
+
+        # Handle comparison errors
+        d = self.type2test(['a', 'b', BadCmp2(), 'c'])
+        e = self.type2test(d)
+        self.assertRaises(BadExc, d.remove, 'c')
+        for x, y in zip(d, e):
+            # verify that original order and values are retained.
+            self.assert_(x is y)
+
+    def test_count(self):
+        a = self.type2test([0, 1, 2])*3
+        self.assertEqual(a.count(0), 3)
+        self.assertEqual(a.count(1), 3)
+        self.assertEqual(a.count(3), 0)
+
+        self.assertRaises(TypeError, a.count)
+
+        class BadExc(Exception):
+            pass
+
+        class BadCmp:
+            def __eq__(self, other):
+                if other == 2:
+                    raise BadExc()
+                return False
+
+        self.assertRaises(BadExc, a.count, BadCmp())
+
+    def test_index(self):
+        u = self.type2test([0, 1])
+        self.assertEqual(u.index(0), 0)
+        self.assertEqual(u.index(1), 1)
+        self.assertRaises(ValueError, u.index, 2)
+
+        u = self.type2test([-2, -1, 0, 0, 1, 2])
+        self.assertEqual(u.count(0), 2)
+        self.assertEqual(u.index(0), 2)
+        self.assertEqual(u.index(0, 2), 2)
+        self.assertEqual(u.index(-2, -10), 0)
+        self.assertEqual(u.index(0, 3), 3)
+        self.assertEqual(u.index(0, 3, 4), 3)
+        self.assertRaises(ValueError, u.index, 2, 0, -10)
+
+        self.assertRaises(TypeError, u.index)
+
+        class BadExc(Exception):
+            pass
+
+        class BadCmp:
+            def __eq__(self, other):
+                if other == 2:
+                    raise BadExc()
+                return False
+
+        a = self.type2test([0, 1, 2, 3])
+        self.assertRaises(BadExc, a.index, BadCmp())
+
+        a = self.type2test([-2, -1, 0, 0, 1, 2])
+        self.assertEqual(a.index(0), 2)
+        self.assertEqual(a.index(0, 2), 2)
+        self.assertEqual(a.index(0, -4), 2)
+        self.assertEqual(a.index(-2, -10), 0)
+        self.assertEqual(a.index(0, 3), 3)
+        self.assertEqual(a.index(0, -3), 3)
+        self.assertEqual(a.index(0, 3, 4), 3)
+        self.assertEqual(a.index(0, -3, -2), 3)
+        self.assertEqual(a.index(0, -4*sys.maxint, 4*sys.maxint), 2)
+        self.assertRaises(ValueError, a.index, 0, 4*sys.maxint,-4*sys.maxint)
+        self.assertRaises(ValueError, a.index, 2, 0, -10)
+        a.remove(0)
+        self.assertRaises(ValueError, a.index, 2, 0, 4)
+        self.assertEqual(a, self.type2test([-2, -1, 0, 1, 2]))
+
+        # Test modifying the list during index's iteration
+        class EvilCmp:
+            def __init__(self, victim):
+                self.victim = victim
+            def __eq__(self, other):
+                del self.victim[:]
+                return False
+        a = self.type2test()
+        a[:] = [EvilCmp(a) for _ in xrange(100)]
+        # This used to seg fault before patch #1005778
+        self.assertRaises(ValueError, a.index, None)
+
+    def test_reverse(self):
+        u = self.type2test([-2, -1, 0, 1, 2])
+        u2 = u[:]
+        u.reverse()
+        self.assertEqual(u, [2, 1, 0, -1, -2])
+        u.reverse()
+        self.assertEqual(u, u2)
+
+        self.assertRaises(TypeError, u.reverse, 42)
+
+    def test_sort(self):
+        u = self.type2test([1, 0])
+        u.sort()
+        self.assertEqual(u, [0, 1])
+
+        u = self.type2test([2,1,0,-1,-2])
+        u.sort()
+        self.assertEqual(u, self.type2test([-2,-1,0,1,2]))
+
+        self.assertRaises(TypeError, u.sort, 42, 42)
+
+        def revcmp(a, b):
+            return cmp(b, a)
+        u.sort(revcmp)
+        self.assertEqual(u, self.type2test([2,1,0,-1,-2]))
+
+        # The following dumps core in unpatched Python 1.5:
+        def myComparison(x,y):
+            return cmp(x%3, y%7)
+        z = self.type2test(range(12))
+        z.sort(myComparison)
+
+        self.assertRaises(TypeError, z.sort, 2)
+
+        def selfmodifyingComparison(x,y):
+            z.append(1)
+            return cmp(x, y)
+        self.assertRaises(ValueError, z.sort, selfmodifyingComparison)
+
+        self.assertRaises(TypeError, z.sort, lambda x, y: 's')
+
+        self.assertRaises(TypeError, z.sort, 42, 42, 42, 42)
+
+    def test_slice(self):
+        u = self.type2test("spam")
+        u[:2] = "h"
+        self.assertEqual(u, list("ham"))
+
+    def test_iadd(self):
+        super(CommonTest, self).test_iadd()
+        u = self.type2test([0, 1])
+        u2 = u
+        u += [2, 3]
+        self.assert_(u is u2)
+
+        u = self.type2test("spam")
+        u += "eggs"
+        self.assertEqual(u, self.type2test("spameggs"))
+
+        self.assertRaises(TypeError, u.__iadd__, None)
+
+    def test_imul(self):
+        u = self.type2test([0, 1])
+        u *= 3
+        self.assertEqual(u, self.type2test([0, 1, 0, 1, 0, 1]))
+        u *= 0
+        self.assertEqual(u, self.type2test([]))
+        s = self.type2test([])
+        oldid = id(s)
+        s *= 10
+        self.assertEqual(id(s), oldid)
+
+    def test_extendedslicing(self):
+        #  subscript
+        a = self.type2test([0,1,2,3,4])
+
+        #  deletion
+        del a[::2]
+        self.assertEqual(a, self.type2test([1,3]))
+        a = self.type2test(range(5))
+        del a[1::2]
+        self.assertEqual(a, self.type2test([0,2,4]))
+        a = self.type2test(range(5))
+        del a[1::-2]
+        self.assertEqual(a, self.type2test([0,2,3,4]))
+        a = self.type2test(range(10))
+        del a[::1000]
+        self.assertEqual(a, self.type2test([1, 2, 3, 4, 5, 6, 7, 8, 9]))
+        #  assignment
+        a = self.type2test(range(10))
+        a[::2] = [-1]*5
+        self.assertEqual(a, self.type2test([-1, 1, -1, 3, -1, 5, -1, 7, -1, 9]))
+        a = self.type2test(range(10))
+        a[::-4] = [10]*3
+        self.assertEqual(a, self.type2test([0, 10, 2, 3, 4, 10, 6, 7, 8 ,10]))
+        a = self.type2test(range(4))
+        a[::-1] = a
+        self.assertEqual(a, self.type2test([3, 2, 1, 0]))
+        a = self.type2test(range(10))
+        b = a[:]
+        c = a[:]
+        a[2:3] = self.type2test(["two", "elements"])
+        b[slice(2,3)] = self.type2test(["two", "elements"])
+        c[2:3:] = self.type2test(["two", "elements"])
+        self.assertEqual(a, b)
+        self.assertEqual(a, c)
+        a = self.type2test(range(10))
+        a[::2] = tuple(range(5))
+        self.assertEqual(a, self.type2test([0, 1, 1, 3, 2, 5, 3, 7, 4, 9]))
+
+    def test_constructor_exception_handling(self):
+        # Bug #1242657
+        class F(object):
+            def __iter__(self):
+                yield 23
+            def __len__(self):
+                raise KeyboardInterrupt
+        self.assertRaises(KeyboardInterrupt, list, F())

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/mapping_tests.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/mapping_tests.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,672 @@
+# tests common to dict and UserDict
+import unittest
+import UserDict
+
+
+class BasicTestMappingProtocol(unittest.TestCase):
+    # This base class can be used to check that an object conforms to the
+    # mapping protocol
+
+    # Functions that can be useful to override to adapt to dictionary
+    # semantics
+    type2test = None # which class is being tested (overwrite in subclasses)
+
+    def _reference(self):
+        """Return a dictionary of values which are invariant by storage
+        in the object under test."""
+        return {1:2, "key1":"value1", "key2":(1,2,3)}
+    def _empty_mapping(self):
+        """Return an empty mapping object"""
+        return self.type2test()
+    def _full_mapping(self, data):
+        """Return a mapping object with the value contained in data
+        dictionary"""
+        x = self._empty_mapping()
+        for key, value in data.items():
+            x[key] = value
+        return x
+
+    def __init__(self, *args, **kw):
+        unittest.TestCase.__init__(self, *args, **kw)
+        self.reference = self._reference().copy()
+
+        # A (key, value) pair not in the mapping
+        key, value = self.reference.popitem()
+        self.other = {key:value}
+
+        # A (key, value) pair in the mapping
+        key, value = self.reference.popitem()
+        self.inmapping = {key:value}
+        self.reference[key] = value
+
+    def test_read(self):
+        # Test for read only operations on mapping
+        p = self._empty_mapping()
+        p1 = dict(p) #workaround for singleton objects
+        d = self._full_mapping(self.reference)
+        if d is p:
+            p = p1
+        #Indexing
+        for key, value in self.reference.items():
+            self.assertEqual(d[key], value)
+        knownkey = self.other.keys()[0]
+        self.failUnlessRaises(KeyError, lambda:d[knownkey])
+        #len
+        self.assertEqual(len(p), 0)
+        self.assertEqual(len(d), len(self.reference))
+        #has_key
+        for k in self.reference:
+            self.assert_(d.has_key(k))
+            self.assert_(k in d)
+        for k in self.other:
+            self.failIf(d.has_key(k))
+            self.failIf(k in d)
+        #cmp
+        self.assertEqual(cmp(p,p), 0)
+        self.assertEqual(cmp(d,d), 0)
+        self.assertEqual(cmp(p,d), -1)
+        self.assertEqual(cmp(d,p), 1)
+        #__non__zero__
+        if p: self.fail("Empty mapping must compare to False")
+        if not d: self.fail("Full mapping must compare to True")
+        # keys(), items(), iterkeys() ...
+        def check_iterandlist(iter, lst, ref):
+            self.assert_(hasattr(iter, 'next'))
+            self.assert_(hasattr(iter, '__iter__'))
+            x = list(iter)
+            self.assert_(set(x)==set(lst)==set(ref))
+        check_iterandlist(d.iterkeys(), d.keys(), self.reference.keys())
+        check_iterandlist(iter(d), d.keys(), self.reference.keys())
+        check_iterandlist(d.itervalues(), d.values(), self.reference.values())
+        check_iterandlist(d.iteritems(), d.items(), self.reference.items())
+        #get
+        key, value = d.iteritems().next()
+        knownkey, knownvalue = self.other.iteritems().next()
+        self.assertEqual(d.get(key, knownvalue), value)
+        self.assertEqual(d.get(knownkey, knownvalue), knownvalue)
+        self.failIf(knownkey in d)
+
+    def test_write(self):
+        # Test for write operations on mapping
+        p = self._empty_mapping()
+        #Indexing
+        for key, value in self.reference.items():
+            p[key] = value
+            self.assertEqual(p[key], value)
+        for key in self.reference.keys():
+            del p[key]
+            self.failUnlessRaises(KeyError, lambda:p[key])
+        p = self._empty_mapping()
+        #update
+        p.update(self.reference)
+        self.assertEqual(dict(p), self.reference)
+        items = p.items()
+        p = self._empty_mapping()
+        p.update(items)
+        self.assertEqual(dict(p), self.reference)
+        d = self._full_mapping(self.reference)
+        #setdefault
+        key, value = d.iteritems().next()
+        knownkey, knownvalue = self.other.iteritems().next()
+        self.assertEqual(d.setdefault(key, knownvalue), value)
+        self.assertEqual(d[key], value)
+        self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue)
+        self.assertEqual(d[knownkey], knownvalue)
+        #pop
+        self.assertEqual(d.pop(knownkey), knownvalue)
+        self.failIf(knownkey in d)
+        self.assertRaises(KeyError, d.pop, knownkey)
+        default = 909
+        d[knownkey] = knownvalue
+        self.assertEqual(d.pop(knownkey, default), knownvalue)
+        self.failIf(knownkey in d)
+        self.assertEqual(d.pop(knownkey, default), default)
+        #popitem
+        key, value = d.popitem()
+        self.failIf(key in d)
+        self.assertEqual(value, self.reference[key])
+        p=self._empty_mapping()
+        self.assertRaises(KeyError, p.popitem)
+
+    def test_constructor(self):
+        self.assertEqual(self._empty_mapping(), self._empty_mapping())
+
+    def test_bool(self):
+        self.assert_(not self._empty_mapping())
+        self.assert_(self.reference)
+        self.assert_(bool(self._empty_mapping()) is False)
+        self.assert_(bool(self.reference) is True)
+
+    def test_keys(self):
+        d = self._empty_mapping()
+        self.assertEqual(d.keys(), [])
+        d = self.reference
+        self.assert_(self.inmapping.keys()[0] in d.keys())
+        self.assert_(self.other.keys()[0] not in d.keys())
+        self.assertRaises(TypeError, d.keys, None)
+
+    def test_values(self):
+        d = self._empty_mapping()
+        self.assertEqual(d.values(), [])
+
+        self.assertRaises(TypeError, d.values, None)
+
+    def test_items(self):
+        d = self._empty_mapping()
+        self.assertEqual(d.items(), [])
+
+        self.assertRaises(TypeError, d.items, None)
+
+    def test_len(self):
+        d = self._empty_mapping()
+        self.assertEqual(len(d), 0)
+
+    def test_getitem(self):
+        d = self.reference
+        self.assertEqual(d[self.inmapping.keys()[0]], self.inmapping.values()[0])
+
+        self.assertRaises(TypeError, d.__getitem__)
+
+    def test_update(self):
+        # mapping argument
+        d = self._empty_mapping()
+        d.update(self.other)
+        self.assertEqual(d.items(), self.other.items())
+
+        # No argument
+        d = self._empty_mapping()
+        d.update()
+        self.assertEqual(d, self._empty_mapping())
+
+        # item sequence
+        d = self._empty_mapping()
+        d.update(self.other.items())
+        self.assertEqual(d.items(), self.other.items())
+
+        # Iterator
+        d = self._empty_mapping()
+        d.update(self.other.iteritems())
+        self.assertEqual(d.items(), self.other.items())
+
+        # FIXME: Doesn't work with UserDict
+        # self.assertRaises((TypeError, AttributeError), d.update, None)
+        self.assertRaises((TypeError, AttributeError), d.update, 42)
+
+        outerself = self
+        class SimpleUserDict:
+            def __init__(self):
+                self.d = outerself.reference
+            def keys(self):
+                return self.d.keys()
+            def __getitem__(self, i):
+                return self.d[i]
+        d.clear()
+        d.update(SimpleUserDict())
+        i1 = d.items()
+        i2 = self.reference.items()
+        i1.sort()
+        i2.sort()
+        self.assertEqual(i1, i2)
+
+        class Exc(Exception): pass
+
+        d = self._empty_mapping()
+        class FailingUserDict:
+            def keys(self):
+                raise Exc
+        self.assertRaises(Exc, d.update, FailingUserDict())
+
+        d.clear()
+
+        class FailingUserDict:
+            def keys(self):
+                class BogonIter:
+                    def __init__(self):
+                        self.i = 1
+                    def __iter__(self):
+                        return self
+                    def next(self):
+                        if self.i:
+                            self.i = 0
+                            return 'a'
+                        raise Exc
+                return BogonIter()
+            def __getitem__(self, key):
+                return key
+        self.assertRaises(Exc, d.update, FailingUserDict())
+
+        class FailingUserDict:
+            def keys(self):
+                class BogonIter:
+                    def __init__(self):
+                        self.i = ord('a')
+                    def __iter__(self):
+                        return self
+                    def next(self):
+                        if self.i <= ord('z'):
+                            rtn = chr(self.i)
+                            self.i += 1
+                            return rtn
+                        raise StopIteration
+                return BogonIter()
+            def __getitem__(self, key):
+                raise Exc
+        self.assertRaises(Exc, d.update, FailingUserDict())
+
+        d = self._empty_mapping()
+        class badseq(object):
+            def __iter__(self):
+                return self
+            def next(self):
+                raise Exc()
+
+        self.assertRaises(Exc, d.update, badseq())
+
+        self.assertRaises(ValueError, d.update, [(1, 2, 3)])
+
+    # no test_fromkeys or test_copy as both os.environ and selves don't support it
+
+    def test_get(self):
+        d = self._empty_mapping()
+        self.assert_(d.get(self.other.keys()[0]) is None)
+        self.assertEqual(d.get(self.other.keys()[0], 3), 3)
+        d = self.reference
+        self.assert_(d.get(self.other.keys()[0]) is None)
+        self.assertEqual(d.get(self.other.keys()[0], 3), 3)
+        self.assertEqual(d.get(self.inmapping.keys()[0]), self.inmapping.values()[0])
+        self.assertEqual(d.get(self.inmapping.keys()[0], 3), self.inmapping.values()[0])
+        self.assertRaises(TypeError, d.get)
+        self.assertRaises(TypeError, d.get, None, None, None)
+
+    def test_setdefault(self):
+        d = self._empty_mapping()
+        self.assertRaises(TypeError, d.setdefault)
+
+    def test_popitem(self):
+        d = self._empty_mapping()
+        self.assertRaises(KeyError, d.popitem)
+        self.assertRaises(TypeError, d.popitem, 42)
+
+    def test_pop(self):
+        d = self._empty_mapping()
+        k, v = self.inmapping.items()[0]
+        d[k] = v
+        self.assertRaises(KeyError, d.pop, self.other.keys()[0])
+
+        self.assertEqual(d.pop(k), v)
+        self.assertEqual(len(d), 0)
+
+        self.assertRaises(KeyError, d.pop, k)
+
+
+class TestMappingProtocol(BasicTestMappingProtocol):
+    def test_constructor(self):
+        BasicTestMappingProtocol.test_constructor(self)
+        self.assert_(self._empty_mapping() is not self._empty_mapping())
+        self.assertEqual(self.type2test(x=1, y=2), {"x": 1, "y": 2})
+
+    def test_bool(self):
+        BasicTestMappingProtocol.test_bool(self)
+        self.assert_(not self._empty_mapping())
+        self.assert_(self._full_mapping({"x": "y"}))
+        self.assert_(bool(self._empty_mapping()) is False)
+        self.assert_(bool(self._full_mapping({"x": "y"})) is True)
+
+    def test_keys(self):
+        BasicTestMappingProtocol.test_keys(self)
+        d = self._empty_mapping()
+        self.assertEqual(d.keys(), [])
+        d = self._full_mapping({'a': 1, 'b': 2})
+        k = d.keys()
+        self.assert_('a' in k)
+        self.assert_('b' in k)
+        self.assert_('c' not in k)
+
+    def test_values(self):
+        BasicTestMappingProtocol.test_values(self)
+        d = self._full_mapping({1:2})
+        self.assertEqual(d.values(), [2])
+
+    def test_items(self):
+        BasicTestMappingProtocol.test_items(self)
+
+        d = self._full_mapping({1:2})
+        self.assertEqual(d.items(), [(1, 2)])
+
+    def test_has_key(self):
+        d = self._empty_mapping()
+        self.assert_(not d.has_key('a'))
+        d = self._full_mapping({'a': 1, 'b': 2})
+        k = d.keys()
+        k.sort()
+        self.assertEqual(k, ['a', 'b'])
+
+        self.assertRaises(TypeError, d.has_key)
+
+    def test_contains(self):
+        d = self._empty_mapping()
+        self.assert_(not ('a' in d))
+        self.assert_('a' not in d)
+        d = self._full_mapping({'a': 1, 'b': 2})
+        self.assert_('a' in d)
+        self.assert_('b' in d)
+        self.assert_('c' not in d)
+
+        self.assertRaises(TypeError, d.__contains__)
+
+    def test_len(self):
+        BasicTestMappingProtocol.test_len(self)
+        d = self._full_mapping({'a': 1, 'b': 2})
+        self.assertEqual(len(d), 2)
+
+    def test_getitem(self):
+        BasicTestMappingProtocol.test_getitem(self)
+        d = self._full_mapping({'a': 1, 'b': 2})
+        self.assertEqual(d['a'], 1)
+        self.assertEqual(d['b'], 2)
+        d['c'] = 3
+        d['a'] = 4
+        self.assertEqual(d['c'], 3)
+        self.assertEqual(d['a'], 4)
+        del d['b']
+        self.assertEqual(d, {'a': 4, 'c': 3})
+
+        self.assertRaises(TypeError, d.__getitem__)
+
+    def test_clear(self):
+        d = self._full_mapping({1:1, 2:2, 3:3})
+        d.clear()
+        self.assertEqual(d, {})
+
+        self.assertRaises(TypeError, d.clear, None)
+
+    def test_update(self):
+        BasicTestMappingProtocol.test_update(self)
+        # mapping argument
+        d = self._empty_mapping()
+        d.update({1:100})
+        d.update({2:20})
+        d.update({1:1, 2:2, 3:3})
+        self.assertEqual(d, {1:1, 2:2, 3:3})
+
+        # no argument
+        d.update()
+        self.assertEqual(d, {1:1, 2:2, 3:3})
+
+        # keyword arguments
+        d = self._empty_mapping()
+        d.update(x=100)
+        d.update(y=20)
+        d.update(x=1, y=2, z=3)
+        self.assertEqual(d, {"x":1, "y":2, "z":3})
+
+        # item sequence
+        d = self._empty_mapping()
+        d.update([("x", 100), ("y", 20)])
+        self.assertEqual(d, {"x":100, "y":20})
+
+        # Both item sequence and keyword arguments
+        d = self._empty_mapping()
+        d.update([("x", 100), ("y", 20)], x=1, y=2)
+        self.assertEqual(d, {"x":1, "y":2})
+
+        # iterator
+        d = self._full_mapping({1:3, 2:4})
+        d.update(self._full_mapping({1:2, 3:4, 5:6}).iteritems())
+        self.assertEqual(d, {1:2, 2:4, 3:4, 5:6})
+
+        class SimpleUserDict:
+            def __init__(self):
+                self.d = {1:1, 2:2, 3:3}
+            def keys(self):
+                return self.d.keys()
+            def __getitem__(self, i):
+                return self.d[i]
+        d.clear()
+        d.update(SimpleUserDict())
+        self.assertEqual(d, {1:1, 2:2, 3:3})
+
+    def test_fromkeys(self):
+        self.assertEqual(self.type2test.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
+        d = self._empty_mapping()
+        self.assert_(not(d.fromkeys('abc') is d))
+        self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
+        self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0})
+        self.assertEqual(d.fromkeys([]), {})
+        def g():
+            yield 1
+        self.assertEqual(d.fromkeys(g()), {1:None})
+        self.assertRaises(TypeError, {}.fromkeys, 3)
+        class dictlike(self.type2test): pass
+        self.assertEqual(dictlike.fromkeys('a'), {'a':None})
+        self.assertEqual(dictlike().fromkeys('a'), {'a':None})
+        self.assert_(dictlike.fromkeys('a').__class__ is dictlike)
+        self.assert_(dictlike().fromkeys('a').__class__ is dictlike)
+        # FIXME: the following won't work with UserDict, because it's an old style class
+        # self.assert_(type(dictlike.fromkeys('a')) is dictlike)
+        class mydict(self.type2test):
+            def __new__(cls):
+                return UserDict.UserDict()
+        ud = mydict.fromkeys('ab')
+        self.assertEqual(ud, {'a':None, 'b':None})
+        # FIXME: the following won't work with UserDict, because it's an old style class
+        # self.assert_(isinstance(ud, UserDict.UserDict))
+        self.assertRaises(TypeError, dict.fromkeys)
+
+        class Exc(Exception): pass
+
+        class baddict1(self.type2test):
+            def __init__(self):
+                raise Exc()
+
+        self.assertRaises(Exc, baddict1.fromkeys, [1])
+
+        class BadSeq(object):
+            def __iter__(self):
+                return self
+            def next(self):
+                raise Exc()
+
+        self.assertRaises(Exc, self.type2test.fromkeys, BadSeq())
+
+        class baddict2(self.type2test):
+            def __setitem__(self, key, value):
+                raise Exc()
+
+        self.assertRaises(Exc, baddict2.fromkeys, [1])
+
+    def test_copy(self):
+        d = self._full_mapping({1:1, 2:2, 3:3})
+        self.assertEqual(d.copy(), {1:1, 2:2, 3:3})
+        d = self._empty_mapping()
+        self.assertEqual(d.copy(), d)
+        self.assert_(isinstance(d.copy(), d.__class__))
+        self.assertRaises(TypeError, d.copy, None)
+
+    def test_get(self):
+        BasicTestMappingProtocol.test_get(self)
+        d = self._empty_mapping()
+        self.assert_(d.get('c') is None)
+        self.assertEqual(d.get('c', 3), 3)
+        d = self._full_mapping({'a' : 1, 'b' : 2})
+        self.assert_(d.get('c') is None)
+        self.assertEqual(d.get('c', 3), 3)
+        self.assertEqual(d.get('a'), 1)
+        self.assertEqual(d.get('a', 3), 1)
+
+    def test_setdefault(self):
+        BasicTestMappingProtocol.test_setdefault(self)
+        d = self._empty_mapping()
+        self.assert_(d.setdefault('key0') is None)
+        d.setdefault('key0', [])
+        self.assert_(d.setdefault('key0') is None)
+        d.setdefault('key', []).append(3)
+        self.assertEqual(d['key'][0], 3)
+        d.setdefault('key', []).append(4)
+        self.assertEqual(len(d['key']), 2)
+
+    def test_popitem(self):
+        BasicTestMappingProtocol.test_popitem(self)
+        for copymode in -1, +1:
+            # -1: b has same structure as a
+            # +1: b is a.copy()
+            for log2size in range(4): # XXX 12 too large for PyPy
+                size = 2**log2size
+                a = self._empty_mapping()
+                b = self._empty_mapping()
+                for i in range(size):
+                    a[repr(i)] = i
+                    if copymode < 0:
+                        b[repr(i)] = i
+                if copymode > 0:
+                    b = a.copy()
+                for i in range(size):
+                    ka, va = ta = a.popitem()
+                    self.assertEqual(va, int(ka))
+                    kb, vb = tb = b.popitem()
+                    self.assertEqual(vb, int(kb))
+                    self.assert_(not(copymode < 0 and ta != tb))
+                self.assert_(not a)
+                self.assert_(not b)
+
+    def test_pop(self):
+        BasicTestMappingProtocol.test_pop(self)
+
+        # Tests for pop with specified key
+        d = self._empty_mapping()
+        k, v = 'abc', 'def'
+
+        # verify longs/ints get same value when key > 32 bits (for 64-bit archs)
+        # see SF bug #689659
+        x = 4503599627370496L
+        y = 4503599627370496
+        h = self._full_mapping({x: 'anything', y: 'something else'})
+        self.assertEqual(h[x], h[y])
+
+        self.assertEqual(d.pop(k, v), v)
+        d[k] = v
+        self.assertEqual(d.pop(k, 1), v)
+
+
+class TestHashMappingProtocol(TestMappingProtocol):
+
+    def test_getitem(self):
+        TestMappingProtocol.test_getitem(self)
+        class Exc(Exception): pass
+
+        class BadEq(object):
+            def __eq__(self, other):
+                raise Exc()
+
+        d = self._empty_mapping()
+        d[BadEq()] = 42
+        self.assertRaises(KeyError, d.__getitem__, 23)
+
+        class BadHash(object):
+            fail = False
+            def __hash__(self):
+                if self.fail:
+                    raise Exc()
+                else:
+                    return 42
+
+        d = self._empty_mapping()
+        x = BadHash()
+        d[x] = 42
+        x.fail = True
+        self.assertRaises(Exc, d.__getitem__, x)
+
+    def test_fromkeys(self):
+        TestMappingProtocol.test_fromkeys(self)
+        class mydict(self.type2test):
+            def __new__(cls):
+                return UserDict.UserDict()
+        ud = mydict.fromkeys('ab')
+        self.assertEqual(ud, {'a':None, 'b':None})
+        self.assert_(isinstance(ud, UserDict.UserDict))
+
+    def test_pop(self):
+        TestMappingProtocol.test_pop(self)
+
+        class Exc(Exception): pass
+
+        class BadHash(object):
+            fail = False
+            def __hash__(self):
+                if self.fail:
+                    raise Exc()
+                else:
+                    return 42
+
+        d = self._empty_mapping()
+        x = BadHash()
+        d[x] = 42
+        x.fail = True
+        self.assertRaises(Exc, d.pop, x)
+
+    def test_mutatingiteration(self):
+        d = self._empty_mapping()
+        d[1] = 1
+        try:
+            for i in d:
+                d[i+1] = 1
+        except RuntimeError:
+            pass
+        else:
+            self.fail("changing dict size during iteration doesn't raise Error")
+
+    def test_repr(self):
+        d = self._empty_mapping()
+        self.assertEqual(repr(d), '{}')
+        d[1] = 2
+        self.assertEqual(repr(d), '{1: 2}')
+        d = self._empty_mapping()
+        d[1] = d
+        self.assertEqual(repr(d), '{1: {...}}')
+
+        class Exc(Exception): pass
+
+        class BadRepr(object):
+            def __repr__(self):
+                raise Exc()
+
+        d = self._full_mapping({1: BadRepr()})
+        self.assertRaises(Exc, repr, d)
+
+    def test_le(self):
+        self.assert_(not (self._empty_mapping() < self._empty_mapping()))
+        self.assert_(not (self._full_mapping({1: 2}) < self._full_mapping({1L: 2L})))
+
+        class Exc(Exception): pass
+
+        class BadCmp(object):
+            def __cmp__(self, other):
+                raise Exc()
+
+        d1 = self._full_mapping({BadCmp(): 1})
+        d2 = self._full_mapping({1: 1})
+        try:
+            d1 < d2
+        except Exc:
+            pass
+        else:
+            self.fail("< didn't raise Exc")
+
+    def test_setdefault(self):
+        TestMappingProtocol.test_setdefault(self)
+
+        class Exc(Exception): pass
+
+        class BadHash(object):
+            fail = False
+            def __hash__(self):
+                if self.fail:
+                    raise Exc()
+                else:
+                    return 42
+
+        d = self._empty_mapping()
+        x = BadHash()
+        d[x] = 42
+        x.fail = True
+        self.assertRaises(Exc, d.setdefault, x, [])

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/pickletester.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/pickletester.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,1007 @@
+# Notes about changes in this file:
+# a prefix of "dont_" means the test makes no sense,
+# because we don't use cPickle at all.
+# "xxx_" means it works and can be done, but takes ages.
+# When PyPy gets really fast, we should remove "xxx_".
+
+import unittest
+import pickle
+import cPickle
+import pickletools
+import copy_reg
+
+from test.test_support import TestFailed, have_unicode, TESTFN, \
+                              run_with_locale
+
+# Tests that try a number of pickle protocols should have a
+#     for proto in protocols:
+# kind of outer loop.
+assert pickle.HIGHEST_PROTOCOL == cPickle.HIGHEST_PROTOCOL == 2
+protocols = range(pickle.HIGHEST_PROTOCOL + 1)
+
+
+# Return True if opcode code appears in the pickle, else False.
+def opcode_in_pickle(code, pickle):
+    for op, dummy, dummy in pickletools.genops(pickle):
+        if op.code == code:
+            return True
+    return False
+
+# Return the number of times opcode code appears in pickle.
+def count_opcode(code, pickle):
+    n = 0
+    for op, dummy, dummy in pickletools.genops(pickle):
+        if op.code == code:
+            n += 1
+    return n
+
+# We can't very well test the extension registry without putting known stuff
+# in it, but we have to be careful to restore its original state.  Code
+# should do this:
+#
+#     e = ExtensionSaver(extension_code)
+#     try:
+#         fiddle w/ the extension registry's stuff for extension_code
+#     finally:
+#         e.restore()
+
+class ExtensionSaver:
+    # Remember current registration for code (if any), and remove it (if
+    # there is one).
+    def __init__(self, code):
+        self.code = code
+        if code in copy_reg._inverted_registry:
+            self.pair = copy_reg._inverted_registry[code]
+            copy_reg.remove_extension(self.pair[0], self.pair[1], code)
+        else:
+            self.pair = None
+
+    # Restore previous registration for code.
+    def restore(self):
+        code = self.code
+        curpair = copy_reg._inverted_registry.get(code)
+        if curpair is not None:
+            copy_reg.remove_extension(curpair[0], curpair[1], code)
+        pair = self.pair
+        if pair is not None:
+            copy_reg.add_extension(pair[0], pair[1], code)
+
+class C:
+    def __cmp__(self, other):
+        return cmp(self.__dict__, other.__dict__)
+
+import __main__
+__main__.C = C
+C.__module__ = "__main__"
+
+class myint(int):
+    def __init__(self, x):
+        self.str = str(x)
+
+class initarg(C):
+
+    def __init__(self, a, b):
+        self.a = a
+        self.b = b
+
+    def __getinitargs__(self):
+        return self.a, self.b
+
+class metaclass(type):
+    pass
+
+class use_metaclass(object):
+    __metaclass__ = metaclass
+
+# DATA0 .. DATA2 are the pickles we expect under the various protocols, for
+# the object returned by create_data().
+
+# break into multiple strings to avoid confusing font-lock-mode
+DATA0 = """(lp1
+I0
+aL1L
+aF2
+ac__builtin__
+complex
+p2
+""" + \
+"""(F3
+F0
+tRp3
+aI1
+aI-1
+aI255
+aI-255
+aI-256
+aI65535
+aI-65535
+aI-65536
+aI2147483647
+aI-2147483647
+aI-2147483648
+a""" + \
+"""(S'abc'
+p4
+g4
+""" + \
+"""(i__main__
+C
+p5
+""" + \
+"""(dp6
+S'foo'
+p7
+I1
+sS'bar'
+p8
+I2
+sbg5
+tp9
+ag9
+aI5
+a.
+"""
+
+# Disassembly of DATA0.
+DATA0_DIS = """\
+    0: (    MARK
+    1: l        LIST       (MARK at 0)
+    2: p    PUT        1
+    5: I    INT        0
+    8: a    APPEND
+    9: L    LONG       1L
+   13: a    APPEND
+   14: F    FLOAT      2.0
+   17: a    APPEND
+   18: c    GLOBAL     '__builtin__ complex'
+   39: p    PUT        2
+   42: (    MARK
+   43: F        FLOAT      3.0
+   46: F        FLOAT      0.0
+   49: t        TUPLE      (MARK at 42)
+   50: R    REDUCE
+   51: p    PUT        3
+   54: a    APPEND
+   55: I    INT        1
+   58: a    APPEND
+   59: I    INT        -1
+   63: a    APPEND
+   64: I    INT        255
+   69: a    APPEND
+   70: I    INT        -255
+   76: a    APPEND
+   77: I    INT        -256
+   83: a    APPEND
+   84: I    INT        65535
+   91: a    APPEND
+   92: I    INT        -65535
+  100: a    APPEND
+  101: I    INT        -65536
+  109: a    APPEND
+  110: I    INT        2147483647
+  122: a    APPEND
+  123: I    INT        -2147483647
+  136: a    APPEND
+  137: I    INT        -2147483648
+  150: a    APPEND
+  151: (    MARK
+  152: S        STRING     'abc'
+  159: p        PUT        4
+  162: g        GET        4
+  165: (        MARK
+  166: i            INST       '__main__ C' (MARK at 165)
+  178: p        PUT        5
+  181: (        MARK
+  182: d            DICT       (MARK at 181)
+  183: p        PUT        6
+  186: S        STRING     'foo'
+  193: p        PUT        7
+  196: I        INT        1
+  199: s        SETITEM
+  200: S        STRING     'bar'
+  207: p        PUT        8
+  210: I        INT        2
+  213: s        SETITEM
+  214: b        BUILD
+  215: g        GET        5
+  218: t        TUPLE      (MARK at 151)
+  219: p    PUT        9
+  222: a    APPEND
+  223: g    GET        9
+  226: a    APPEND
+  227: I    INT        5
+  230: a    APPEND
+  231: .    STOP
+highest protocol among opcodes = 0
+"""
+
+DATA1 = (']q\x01(K\x00L1L\nG@\x00\x00\x00\x00\x00\x00\x00'
+         'c__builtin__\ncomplex\nq\x02(G@\x08\x00\x00\x00\x00\x00'
+         '\x00G\x00\x00\x00\x00\x00\x00\x00\x00tRq\x03K\x01J\xff\xff'
+         '\xff\xffK\xffJ\x01\xff\xff\xffJ\x00\xff\xff\xffM\xff\xff'
+         'J\x01\x00\xff\xffJ\x00\x00\xff\xffJ\xff\xff\xff\x7fJ\x01\x00'
+         '\x00\x80J\x00\x00\x00\x80(U\x03abcq\x04h\x04(c__main__\n'
+         'C\nq\x05oq\x06}q\x07(U\x03fooq\x08K\x01U\x03barq\tK\x02ubh'
+         '\x06tq\nh\nK\x05e.'
+        )
+
+# Disassembly of DATA1.
+DATA1_DIS = """\
+    0: ]    EMPTY_LIST
+    1: q    BINPUT     1
+    3: (    MARK
+    4: K        BININT1    0
+    6: L        LONG       1L
+   10: G        BINFLOAT   2.0
+   19: c        GLOBAL     '__builtin__ complex'
+   40: q        BINPUT     2
+   42: (        MARK
+   43: G            BINFLOAT   3.0
+   52: G            BINFLOAT   0.0
+   61: t            TUPLE      (MARK at 42)
+   62: R        REDUCE
+   63: q        BINPUT     3
+   65: K        BININT1    1
+   67: J        BININT     -1
+   72: K        BININT1    255
+   74: J        BININT     -255
+   79: J        BININT     -256
+   84: M        BININT2    65535
+   87: J        BININT     -65535
+   92: J        BININT     -65536
+   97: J        BININT     2147483647
+  102: J        BININT     -2147483647
+  107: J        BININT     -2147483648
+  112: (        MARK
+  113: U            SHORT_BINSTRING 'abc'
+  118: q            BINPUT     4
+  120: h            BINGET     4
+  122: (            MARK
+  123: c                GLOBAL     '__main__ C'
+  135: q                BINPUT     5
+  137: o                OBJ        (MARK at 122)
+  138: q            BINPUT     6
+  140: }            EMPTY_DICT
+  141: q            BINPUT     7
+  143: (            MARK
+  144: U                SHORT_BINSTRING 'foo'
+  149: q                BINPUT     8
+  151: K                BININT1    1
+  153: U                SHORT_BINSTRING 'bar'
+  158: q                BINPUT     9
+  160: K                BININT1    2
+  162: u                SETITEMS   (MARK at 143)
+  163: b            BUILD
+  164: h            BINGET     6
+  166: t            TUPLE      (MARK at 112)
+  167: q        BINPUT     10
+  169: h        BINGET     10
+  171: K        BININT1    5
+  173: e        APPENDS    (MARK at 3)
+  174: .    STOP
+highest protocol among opcodes = 1
+"""
+
+DATA2 = ('\x80\x02]q\x01(K\x00\x8a\x01\x01G@\x00\x00\x00\x00\x00\x00\x00'
+         'c__builtin__\ncomplex\nq\x02G@\x08\x00\x00\x00\x00\x00\x00G\x00'
+         '\x00\x00\x00\x00\x00\x00\x00\x86Rq\x03K\x01J\xff\xff\xff\xffK'
+         '\xffJ\x01\xff\xff\xffJ\x00\xff\xff\xffM\xff\xffJ\x01\x00\xff\xff'
+         'J\x00\x00\xff\xffJ\xff\xff\xff\x7fJ\x01\x00\x00\x80J\x00\x00\x00'
+         '\x80(U\x03abcq\x04h\x04(c__main__\nC\nq\x05oq\x06}q\x07(U\x03foo'
+         'q\x08K\x01U\x03barq\tK\x02ubh\x06tq\nh\nK\x05e.')
+
+# Disassembly of DATA2.
+DATA2_DIS = """\
+    0: \x80 PROTO      2
+    2: ]    EMPTY_LIST
+    3: q    BINPUT     1
+    5: (    MARK
+    6: K        BININT1    0
+    8: \x8a     LONG1      1L
+   11: G        BINFLOAT   2.0
+   20: c        GLOBAL     '__builtin__ complex'
+   41: q        BINPUT     2
+   43: G        BINFLOAT   3.0
+   52: G        BINFLOAT   0.0
+   61: \x86     TUPLE2
+   62: R        REDUCE
+   63: q        BINPUT     3
+   65: K        BININT1    1
+   67: J        BININT     -1
+   72: K        BININT1    255
+   74: J        BININT     -255
+   79: J        BININT     -256
+   84: M        BININT2    65535
+   87: J        BININT     -65535
+   92: J        BININT     -65536
+   97: J        BININT     2147483647
+  102: J        BININT     -2147483647
+  107: J        BININT     -2147483648
+  112: (        MARK
+  113: U            SHORT_BINSTRING 'abc'
+  118: q            BINPUT     4
+  120: h            BINGET     4
+  122: (            MARK
+  123: c                GLOBAL     '__main__ C'
+  135: q                BINPUT     5
+  137: o                OBJ        (MARK at 122)
+  138: q            BINPUT     6
+  140: }            EMPTY_DICT
+  141: q            BINPUT     7
+  143: (            MARK
+  144: U                SHORT_BINSTRING 'foo'
+  149: q                BINPUT     8
+  151: K                BININT1    1
+  153: U                SHORT_BINSTRING 'bar'
+  158: q                BINPUT     9
+  160: K                BININT1    2
+  162: u                SETITEMS   (MARK at 143)
+  163: b            BUILD
+  164: h            BINGET     6
+  166: t            TUPLE      (MARK at 112)
+  167: q        BINPUT     10
+  169: h        BINGET     10
+  171: K        BININT1    5
+  173: e        APPENDS    (MARK at 5)
+  174: .    STOP
+highest protocol among opcodes = 2
+"""
+
+def create_data():
+    c = C()
+    c.foo = 1
+    c.bar = 2
+    x = [0, 1L, 2.0, 3.0+0j]
+    # Append some integer test cases at cPickle.c's internal size
+    # cutoffs.
+    uint1max = 0xff
+    uint2max = 0xffff
+    int4max = 0x7fffffff
+    x.extend([1, -1,
+              uint1max, -uint1max, -uint1max-1,
+              uint2max, -uint2max, -uint2max-1,
+               int4max,  -int4max,  -int4max-1])
+    y = ('abc', 'abc', c, c)
+    x.append(y)
+    x.append(y)
+    x.append(5)
+    return x
+
+class AbstractPickleTests(unittest.TestCase):
+    # Subclass must define self.dumps, self.loads, self.error.
+
+    _testdata = create_data()
+
+    def setUp(self):
+        pass
+
+    def test_misc(self):
+        # test various datatypes not tested by testdata
+        for proto in protocols:
+            x = myint(4)
+            s = self.dumps(x, proto)
+            y = self.loads(s)
+            self.assertEqual(x, y)
+
+            x = (1, ())
+            s = self.dumps(x, proto)
+            y = self.loads(s)
+            self.assertEqual(x, y)
+
+            x = initarg(1, x)
+            s = self.dumps(x, proto)
+            y = self.loads(s)
+            self.assertEqual(x, y)
+
+        # XXX test __reduce__ protocol?
+
+    def test_roundtrip_equality(self):
+        expected = self._testdata
+        for proto in protocols:
+            s = self.dumps(expected, proto)
+            got = self.loads(s)
+            self.assertEqual(expected, got)
+
+    def test_load_from_canned_string(self):
+        expected = self._testdata
+        for canned in DATA0, DATA1, DATA2:
+            got = self.loads(canned)
+            self.assertEqual(expected, got)
+
+    # There are gratuitous differences between pickles produced by
+    # pickle and cPickle, largely because cPickle starts PUT indices at
+    # 1 and pickle starts them at 0.  See XXX comment in cPickle's put2() --
+    # there's a comment with an exclamation point there whose meaning
+    # is a mystery.  cPickle also suppresses PUT for objects with a refcount
+    # of 1.
+    def dont_test_disassembly(self):
+        from cStringIO import StringIO
+        from pickletools import dis
+
+        for proto, expected in (0, DATA0_DIS), (1, DATA1_DIS):
+            s = self.dumps(self._testdata, proto)
+            filelike = StringIO()
+            dis(s, out=filelike)
+            got = filelike.getvalue()
+            self.assertEqual(expected, got)
+
+    def test_recursive_list(self):
+        l = []
+        l.append(l)
+        for proto in protocols:
+            s = self.dumps(l, proto)
+            x = self.loads(s)
+            self.assertEqual(len(x), 1)
+            self.assert_(x is x[0])
+
+    def test_recursive_dict(self):
+        d = {}
+        d[1] = d
+        for proto in protocols:
+            s = self.dumps(d, proto)
+            x = self.loads(s)
+            self.assertEqual(x.keys(), [1])
+            self.assert_(x[1] is x)
+
+    def test_recursive_inst(self):
+        i = C()
+        i.attr = i
+        for proto in protocols:
+            s = self.dumps(i, 2)
+            x = self.loads(s)
+            self.assertEqual(dir(x), dir(i))
+            self.assert_(x.attr is x)
+
+    def test_recursive_multi(self):
+        l = []
+        d = {1:l}
+        i = C()
+        i.attr = d
+        l.append(i)
+        for proto in protocols:
+            s = self.dumps(l, proto)
+            x = self.loads(s)
+            self.assertEqual(len(x), 1)
+            self.assertEqual(dir(x[0]), dir(i))
+            self.assertEqual(x[0].attr.keys(), [1])
+            self.assert_(x[0].attr[1] is x)
+
+    def test_garyp(self):
+        self.assertRaises(self.error, self.loads, 'garyp')
+
+    def test_insecure_strings(self):
+        insecure = ["abc", "2 + 2", # not quoted
+                    #"'abc' + 'def'", # not a single quoted string
+                    "'abc", # quote is not closed
+                    "'abc\"", # open quote and close quote don't match
+                    "'abc'   ?", # junk after close quote
+                    "'\\'", # trailing backslash
+                    # some tests of the quoting rules
+                    #"'abc\"\''",
+                    #"'\\\\a\'\'\'\\\'\\\\\''",
+                    ]
+        for s in insecure:
+            buf = "S" + s + "\012p0\012."
+            self.assertRaises(ValueError, self.loads, buf)
+
+    if have_unicode:
+        def test_unicode(self):
+            endcases = [unicode(''), unicode('<\\u>'), unicode('<\\\u1234>'),
+                        unicode('<\n>'),  unicode('<\\>')]
+            for proto in protocols:
+                for u in endcases:
+                    p = self.dumps(u, proto)
+                    u2 = self.loads(p)
+                    self.assertEqual(u2, u)
+
+    def test_ints(self):
+        import sys
+        for proto in protocols:
+            n = sys.maxint
+            while n:
+                for expected in (-n, n):
+                    s = self.dumps(expected, proto)
+                    n2 = self.loads(s)
+                    self.assertEqual(expected, n2)
+                n = n >> 1
+
+    def test_maxint64(self):
+        maxint64 = (1L << 63) - 1
+        data = 'I' + str(maxint64) + '\n.'
+        got = self.loads(data)
+        self.assertEqual(got, maxint64)
+
+        # Try too with a bogus literal.
+        data = 'I' + str(maxint64) + 'JUNK\n.'
+        self.assertRaises(ValueError, self.loads, data)
+
+    def xxx_test_long(self):
+        for proto in protocols:
+            # 256 bytes is where LONG4 begins.
+            for nbits in 1, 8, 8*254, 8*255, 8*256, 8*257:
+                nbase = 1L << nbits
+                for npos in nbase-1, nbase, nbase+1:
+                    for n in npos, -npos:
+                        pickle = self.dumps(n, proto)
+                        got = self.loads(pickle)
+                        self.assertEqual(n, got)
+        # Try a monster.  This is quadratic-time in protos 0 & 1, so don't
+        # bother with those.
+        nbase = long("deadbeeffeedface", 16)
+        nbase += nbase << 1000000
+        for n in nbase, -nbase:
+            p = self.dumps(n, 2)
+            got = self.loads(p)
+            self.assertEqual(n, got)
+
+    @run_with_locale('LC_ALL', 'de_DE', 'fr_FR')
+    def test_float_format(self):
+        # make sure that floats are formatted locale independent
+        self.assertEqual(self.dumps(1.2)[0:3], 'F1.')
+
+    def test_reduce(self):
+        pass
+
+    def test_getinitargs(self):
+        pass
+
+    def test_metaclass(self):
+        a = use_metaclass()
+        for proto in protocols:
+            s = self.dumps(a, proto)
+            b = self.loads(s)
+            self.assertEqual(a.__class__, b.__class__)
+
+    def test_structseq(self):
+        import time
+        import os
+
+        t = time.localtime()
+        for proto in protocols:
+            s = self.dumps(t, proto)
+            u = self.loads(s)
+            self.assertEqual(t, u)
+            if hasattr(os, "stat"):
+                t = os.stat(os.curdir)
+                s = self.dumps(t, proto)
+                u = self.loads(s)
+                self.assertEqual(t, u)
+            if hasattr(os, "statvfs"):
+                t = os.statvfs(os.curdir)
+                s = self.dumps(t, proto)
+                u = self.loads(s)
+                self.assertEqual(t, u)
+
+    # Tests for protocol 2
+
+    def test_proto(self):
+        build_none = pickle.NONE + pickle.STOP
+        for proto in protocols:
+            expected = build_none
+            if proto >= 2:
+                expected = pickle.PROTO + chr(proto) + expected
+            p = self.dumps(None, proto)
+            self.assertEqual(p, expected)
+
+        oob = protocols[-1] + 1     # a future protocol
+        badpickle = pickle.PROTO + chr(oob) + build_none
+        try:
+            self.loads(badpickle)
+        except ValueError, detail:
+            self.failUnless(str(detail).startswith(
+                                            "unsupported pickle protocol"))
+        else:
+            self.fail("expected bad protocol number to raise ValueError")
+
+    def test_long1(self):
+        x = 12345678910111213141516178920L
+        for proto in protocols:
+            s = self.dumps(x, proto)
+            y = self.loads(s)
+            self.assertEqual(x, y)
+            self.assertEqual(opcode_in_pickle(pickle.LONG1, s), proto >= 2)
+
+    def test_long4(self):
+        x = 12345678910111213141516178920L << (256*8)
+        for proto in protocols:
+            s = self.dumps(x, proto)
+            y = self.loads(s)
+            self.assertEqual(x, y)
+            self.assertEqual(opcode_in_pickle(pickle.LONG4, s), proto >= 2)
+
+    def test_short_tuples(self):
+        # Map (proto, len(tuple)) to expected opcode.
+        expected_opcode = {(0, 0): pickle.TUPLE,
+                           (0, 1): pickle.TUPLE,
+                           (0, 2): pickle.TUPLE,
+                           (0, 3): pickle.TUPLE,
+                           (0, 4): pickle.TUPLE,
+
+                           (1, 0): pickle.EMPTY_TUPLE,
+                           (1, 1): pickle.TUPLE,
+                           (1, 2): pickle.TUPLE,
+                           (1, 3): pickle.TUPLE,
+                           (1, 4): pickle.TUPLE,
+
+                           (2, 0): pickle.EMPTY_TUPLE,
+                           (2, 1): pickle.TUPLE1,
+                           (2, 2): pickle.TUPLE2,
+                           (2, 3): pickle.TUPLE3,
+                           (2, 4): pickle.TUPLE,
+                          }
+        a = ()
+        b = (1,)
+        c = (1, 2)
+        d = (1, 2, 3)
+        e = (1, 2, 3, 4)
+        for proto in protocols:
+            for x in a, b, c, d, e:
+                s = self.dumps(x, proto)
+                y = self.loads(s)
+                self.assertEqual(x, y, (proto, x, s, y))
+                expected = expected_opcode[proto, len(x)]
+                self.assertEqual(opcode_in_pickle(expected, s), True)
+
+    def test_singletons(self):
+        # Map (proto, singleton) to expected opcode.
+        expected_opcode = {(0, None): pickle.NONE,
+                           (1, None): pickle.NONE,
+                           (2, None): pickle.NONE,
+
+                           (0, True): pickle.INT,
+                           (1, True): pickle.INT,
+                           (2, True): pickle.NEWTRUE,
+
+                           (0, False): pickle.INT,
+                           (1, False): pickle.INT,
+                           (2, False): pickle.NEWFALSE,
+                          }
+        for proto in protocols:
+            for x in None, False, True:
+                s = self.dumps(x, proto)
+                y = self.loads(s)
+                self.assert_(x is y, (proto, x, s, y))
+                expected = expected_opcode[proto, x]
+                self.assertEqual(opcode_in_pickle(expected, s), True)
+
+    def test_newobj_tuple(self):
+        x = MyTuple([1, 2, 3])
+        x.foo = 42
+        x.bar = "hello"
+        for proto in protocols:
+            s = self.dumps(x, proto)
+            y = self.loads(s)
+            self.assertEqual(tuple(x), tuple(y))
+            self.assertEqual(x.__dict__, y.__dict__)
+
+    def test_newobj_list(self):
+        x = MyList([1, 2, 3])
+        x.foo = 42
+        x.bar = "hello"
+        for proto in protocols:
+            s = self.dumps(x, proto)
+            y = self.loads(s)
+            self.assertEqual(list(x), list(y))
+            self.assertEqual(x.__dict__, y.__dict__)
+
+    def test_newobj_generic(self):
+        for proto in protocols:
+            for C in myclasses:
+                B = C.__base__
+                x = C(C.sample)
+                x.foo = 42
+                s = self.dumps(x, proto)
+                y = self.loads(s)
+                detail = (proto, C, B, x, y, type(y))
+                self.assertEqual(B(x), B(y), detail)
+                self.assertEqual(x.__dict__, y.__dict__, detail)
+
+    # Register a type with copy_reg, with extension code extcode.  Pickle
+    # an object of that type.  Check that the resulting pickle uses opcode
+    # (EXT[124]) under proto 2, and not in proto 1.
+
+    def produce_global_ext(self, extcode, opcode):
+        e = ExtensionSaver(extcode)
+        try:
+            copy_reg.add_extension(__name__, "MyList", extcode)
+            x = MyList([1, 2, 3])
+            x.foo = 42
+            x.bar = "hello"
+
+            # Dump using protocol 1 for comparison.
+            s1 = self.dumps(x, 1)
+            self.assert_(__name__ in s1)
+            self.assert_("MyList" in s1)
+            self.assertEqual(opcode_in_pickle(opcode, s1), False)
+
+            y = self.loads(s1)
+            self.assertEqual(list(x), list(y))
+            self.assertEqual(x.__dict__, y.__dict__)
+
+            # Dump using protocol 2 for test.
+            s2 = self.dumps(x, 2)
+            self.assert_(__name__ not in s2)
+            self.assert_("MyList" not in s2)
+            self.assertEqual(opcode_in_pickle(opcode, s2), True)
+
+            y = self.loads(s2)
+            self.assertEqual(list(x), list(y))
+            self.assertEqual(x.__dict__, y.__dict__)
+
+        finally:
+            e.restore()
+
+    def test_global_ext1(self):
+        self.produce_global_ext(0x00000001, pickle.EXT1)  # smallest EXT1 code
+        self.produce_global_ext(0x000000ff, pickle.EXT1)  # largest EXT1 code
+
+    def test_global_ext2(self):
+        self.produce_global_ext(0x00000100, pickle.EXT2)  # smallest EXT2 code
+        self.produce_global_ext(0x0000ffff, pickle.EXT2)  # largest EXT2 code
+        self.produce_global_ext(0x0000abcd, pickle.EXT2)  # check endianness
+
+    def test_global_ext4(self):
+        self.produce_global_ext(0x00010000, pickle.EXT4)  # smallest EXT4 code
+        self.produce_global_ext(0x7fffffff, pickle.EXT4)  # largest EXT4 code
+        self.produce_global_ext(0x12abcdef, pickle.EXT4)  # check endianness
+
+    def xxx_test_list_chunking(self):
+        n = 10  # too small to chunk
+        x = range(n)
+        for proto in protocols:
+            s = self.dumps(x, proto)
+            y = self.loads(s)
+            self.assertEqual(x, y)
+            num_appends = count_opcode(pickle.APPENDS, s)
+            self.assertEqual(num_appends, proto > 0)
+
+        n = 2500  # expect at least two chunks when proto > 0
+        x = range(n)
+        for proto in protocols:
+            s = self.dumps(x, proto)
+            y = self.loads(s)
+            self.assertEqual(x, y)
+            num_appends = count_opcode(pickle.APPENDS, s)
+            if proto == 0:
+                self.assertEqual(num_appends, 0)
+            else:
+                self.failUnless(num_appends >= 2)
+
+    def xxx_test_dict_chunking(self):
+        n = 10  # too small to chunk
+        x = dict.fromkeys(range(n))
+        for proto in protocols:
+            s = self.dumps(x, proto)
+            y = self.loads(s)
+            self.assertEqual(x, y)
+            num_setitems = count_opcode(pickle.SETITEMS, s)
+            self.assertEqual(num_setitems, proto > 0)
+
+        n = 2500  # expect at least two chunks when proto > 0
+        x = dict.fromkeys(range(n))
+        for proto in protocols:
+            s = self.dumps(x, proto)
+            y = self.loads(s)
+            self.assertEqual(x, y)
+            num_setitems = count_opcode(pickle.SETITEMS, s)
+            if proto == 0:
+                self.assertEqual(num_setitems, 0)
+            else:
+                self.failUnless(num_setitems >= 2)
+
+    def test_simple_newobj(self):
+        x = object.__new__(SimpleNewObj)  # avoid __init__
+        x.abc = 666
+        for proto in protocols:
+            s = self.dumps(x, proto)
+            self.assertEqual(opcode_in_pickle(pickle.NEWOBJ, s), proto >= 2)
+            y = self.loads(s)   # will raise TypeError if __init__ called
+            self.assertEqual(y.abc, 666)
+            self.assertEqual(x.__dict__, y.__dict__)
+
+    def test_newobj_list_slots(self):
+        x = SlotList([1, 2, 3])
+        x.foo = 42
+        x.bar = "hello"
+        s = self.dumps(x, 2)
+        y = self.loads(s)
+        self.assertEqual(list(x), list(y))
+        self.assertEqual(x.__dict__, y.__dict__)
+        self.assertEqual(x.foo, y.foo)
+        self.assertEqual(x.bar, y.bar)
+
+    def test_reduce_overrides_default_reduce_ex(self):
+        for proto in 0, 1, 2:
+            x = REX_one()
+            self.assertEqual(x._reduce_called, 0)
+            s = self.dumps(x, proto)
+            self.assertEqual(x._reduce_called, 1)
+            y = self.loads(s)
+            self.assertEqual(y._reduce_called, 0)
+
+    def test_reduce_ex_called(self):
+        for proto in 0, 1, 2:
+            x = REX_two()
+            self.assertEqual(x._proto, None)
+            s = self.dumps(x, proto)
+            self.assertEqual(x._proto, proto)
+            y = self.loads(s)
+            self.assertEqual(y._proto, None)
+
+    def test_reduce_ex_overrides_reduce(self):
+        for proto in 0, 1, 2:
+            x = REX_three()
+            self.assertEqual(x._proto, None)
+            s = self.dumps(x, proto)
+            self.assertEqual(x._proto, proto)
+            y = self.loads(s)
+            self.assertEqual(y._proto, None)
+
+    def test_reduce_ex_calls_base(self):
+        for proto in 0, 1, 2:
+            x = REX_four()
+            self.assertEqual(x._proto, None)
+            s = self.dumps(x, proto)
+            self.assertEqual(x._proto, proto)
+            y = self.loads(s)
+            self.assertEqual(y._proto, proto)
+
+    def test_reduce_calls_base(self):
+        for proto in 0, 1, 2:
+            x = REX_five()
+            self.assertEqual(x._reduce_called, 0)
+            s = self.dumps(x, proto)
+            self.assertEqual(x._reduce_called, 1)
+            y = self.loads(s)
+            self.assertEqual(y._reduce_called, 1)
+
+# Test classes for reduce_ex
+
+class REX_one(object):
+    _reduce_called = 0
+    def __reduce__(self):
+        self._reduce_called = 1
+        return REX_one, ()
+    # No __reduce_ex__ here, but inheriting it from object
+
+class REX_two(object):
+    _proto = None
+    def __reduce_ex__(self, proto):
+        self._proto = proto
+        return REX_two, ()
+    # No __reduce__ here, but inheriting it from object
+
+class REX_three(object):
+    _proto = None
+    def __reduce_ex__(self, proto):
+        self._proto = proto
+        return REX_two, ()
+    def __reduce__(self):
+        raise TestFailed, "This __reduce__ shouldn't be called"
+
+class REX_four(object):
+    _proto = None
+    def __reduce_ex__(self, proto):
+        self._proto = proto
+        return object.__reduce_ex__(self, proto)
+    # Calling base class method should succeed
+
+class REX_five(object):
+    _reduce_called = 0
+    def __reduce__(self):
+        self._reduce_called = 1
+        return object.__reduce__(self)
+    # This one used to fail with infinite recursion
+
+# Test classes for newobj
+
+class MyInt(int):
+    sample = 1
+
+class MyLong(long):
+    sample = 1L
+
+class MyFloat(float):
+    sample = 1.0
+
+class MyComplex(complex):
+    sample = 1.0 + 0.0j
+
+class MyStr(str):
+    sample = "hello"
+
+class MyUnicode(unicode):
+    sample = u"hello \u1234"
+
+class MyTuple(tuple):
+    sample = (1, 2, 3)
+
+class MyList(list):
+    sample = [1, 2, 3]
+
+class MyDict(dict):
+    sample = {"a": 1, "b": 2}
+
+myclasses = [MyInt, MyLong, MyFloat,
+             MyComplex,
+             MyStr, MyUnicode,
+             MyTuple, MyList, MyDict]
+
+
+class SlotList(MyList):
+    __slots__ = ["foo"]
+
+class SimpleNewObj(object):
+    def __init__(self, a, b, c):
+        # raise an error, to make sure this isn't called
+        raise TypeError("SimpleNewObj.__init__() didn't expect to get called")
+
+class AbstractPickleModuleTests(unittest.TestCase):
+
+    def test_dump_closed_file(self):
+        import os
+        f = open(TESTFN, "w")
+        try:
+            f.close()
+            self.assertRaises(ValueError, self.module.dump, 123, f)
+        finally:
+            os.remove(TESTFN)
+
+    def test_load_closed_file(self):
+        import os
+        f = open(TESTFN, "w")
+        try:
+            f.close()
+            self.assertRaises(ValueError, self.module.dump, 123, f)
+        finally:
+            os.remove(TESTFN)
+
+    def test_highest_protocol(self):
+        # Of course this needs to be changed when HIGHEST_PROTOCOL changes.
+        self.assertEqual(self.module.HIGHEST_PROTOCOL, 2)
+
+    def test_callapi(self):
+        from cStringIO import StringIO
+        f = StringIO()
+        # With and without keyword arguments
+        self.module.dump(123, f, -1)
+        self.module.dump(123, file=f, protocol=-1)
+        self.module.dumps(123, -1)
+        self.module.dumps(123, protocol=-1)
+        self.module.Pickler(f, -1)
+        self.module.Pickler(f, protocol=-1)
+
+class AbstractPersistentPicklerTests(unittest.TestCase):
+
+    # This class defines persistent_id() and persistent_load()
+    # functions that should be used by the pickler.  All even integers
+    # are pickled using persistent ids.
+
+    def persistent_id(self, object):
+        if isinstance(object, int) and object % 2 == 0:
+            self.id_count += 1
+            return str(object)
+        else:
+            return None
+
+    def persistent_load(self, oid):
+        self.load_count += 1
+        object = int(oid)
+        assert object % 2 == 0
+        return object
+
+    def test_persistence(self):
+        self.id_count = 0
+        self.load_count = 0
+        L = range(10)
+        self.assertEqual(self.loads(self.dumps(L)), L)
+        self.assertEqual(self.id_count, 5)
+        self.assertEqual(self.load_count, 5)
+
+    def test_bin_persistence(self):
+        self.id_count = 0
+        self.load_count = 0
+        L = range(10)
+        self.assertEqual(self.loads(self.dumps(L, 1)), L)
+        self.assertEqual(self.id_count, 5)
+        self.assertEqual(self.load_count, 5)

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/seq_tests.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/seq_tests.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,325 @@
+"""
+Tests common to tuple, list and UserList.UserList
+"""
+
+import unittest
+from test import test_support
+
+# Various iterables
+# This is used for checking the constructor (here and in test_deque.py)
+def iterfunc(seqn):
+    'Regular generator'
+    for i in seqn:
+        yield i
+
+class Sequence:
+    'Sequence using __getitem__'
+    def __init__(self, seqn):
+        self.seqn = seqn
+    def __getitem__(self, i):
+        return self.seqn[i]
+
+class IterFunc:
+    'Sequence using iterator protocol'
+    def __init__(self, seqn):
+        self.seqn = seqn
+        self.i = 0
+    def __iter__(self):
+        return self
+    def next(self):
+        if self.i >= len(self.seqn): raise StopIteration
+        v = self.seqn[self.i]
+        self.i += 1
+        return v
+
+class IterGen:
+    'Sequence using iterator protocol defined with a generator'
+    def __init__(self, seqn):
+        self.seqn = seqn
+        self.i = 0
+    def __iter__(self):
+        for val in self.seqn:
+            yield val
+
+class IterNextOnly:
+    'Missing __getitem__ and __iter__'
+    def __init__(self, seqn):
+        self.seqn = seqn
+        self.i = 0
+    def next(self):
+        if self.i >= len(self.seqn): raise StopIteration
+        v = self.seqn[self.i]
+        self.i += 1
+        return v
+
+class IterNoNext:
+    'Iterator missing next()'
+    def __init__(self, seqn):
+        self.seqn = seqn
+        self.i = 0
+    def __iter__(self):
+        return self
+
+class IterGenExc:
+    'Test propagation of exceptions'
+    def __init__(self, seqn):
+        self.seqn = seqn
+        self.i = 0
+    def __iter__(self):
+        return self
+    def next(self):
+        3 // 0
+
+class IterFuncStop:
+    'Test immediate stop'
+    def __init__(self, seqn):
+        pass
+    def __iter__(self):
+        return self
+    def next(self):
+        raise StopIteration
+
+from itertools import chain, imap
+def itermulti(seqn):
+    'Test multiple tiers of iterators'
+    return chain(imap(lambda x:x, iterfunc(IterGen(Sequence(seqn)))))
+
+class CommonTest(unittest.TestCase):
+    # The type to be tested
+    type2test = None
+
+    def test_constructors(self):
+        l0 = []
+        l1 = [0]
+        l2 = [0, 1]
+
+        u = self.type2test()
+        u0 = self.type2test(l0)
+        u1 = self.type2test(l1)
+        u2 = self.type2test(l2)
+
+        uu = self.type2test(u)
+        uu0 = self.type2test(u0)
+        uu1 = self.type2test(u1)
+        uu2 = self.type2test(u2)
+
+        v = self.type2test(tuple(u))
+        class OtherSeq:
+            def __init__(self, initseq):
+                self.__data = initseq
+            def __len__(self):
+                return len(self.__data)
+            def __getitem__(self, i):
+                return self.__data[i]
+        s = OtherSeq(u0)
+        v0 = self.type2test(s)
+        self.assertEqual(len(v0), len(s))
+
+        s = "this is also a sequence"
+        vv = self.type2test(s)
+        self.assertEqual(len(vv), len(s))
+
+        # Create from various iteratables
+        for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
+            for g in (Sequence, IterFunc, IterGen,
+                      itermulti, iterfunc):
+                self.assertEqual(self.type2test(g(s)), self.type2test(s))
+            self.assertEqual(self.type2test(IterFuncStop(s)), self.type2test())
+            self.assertEqual(self.type2test(c for c in "123"), self.type2test("123"))
+            self.assertRaises(TypeError, self.type2test, IterNextOnly(s))
+            self.assertRaises(TypeError, self.type2test, IterNoNext(s))
+            self.assertRaises(ZeroDivisionError, self.type2test, IterGenExc(s))
+
+    def test_truth(self):
+        self.assert_(not self.type2test())
+        self.assert_(self.type2test([42]))
+
+    def test_getitem(self):
+        u = self.type2test([0, 1, 2, 3, 4])
+        for i in xrange(len(u)):
+            self.assertEqual(u[i], i)
+            self.assertEqual(u[long(i)], i)
+        for i in xrange(-len(u), -1):
+            self.assertEqual(u[i], len(u)+i)
+            self.assertEqual(u[long(i)], len(u)+i)
+        self.assertRaises(IndexError, u.__getitem__, -len(u)-1)
+        self.assertRaises(IndexError, u.__getitem__, len(u))
+        self.assertRaises(ValueError, u.__getitem__, slice(0,10,0))
+
+        u = self.type2test()
+        self.assertRaises(IndexError, u.__getitem__, 0)
+        self.assertRaises(IndexError, u.__getitem__, -1)
+
+        self.assertRaises(TypeError, u.__getitem__)
+
+        a = self.type2test([10, 11])
+        self.assertEqual(a[0], 10)
+        self.assertEqual(a[1], 11)
+        self.assertEqual(a[-2], 10)
+        self.assertEqual(a[-1], 11)
+        self.assertRaises(IndexError, a.__getitem__, -3)
+        self.assertRaises(IndexError, a.__getitem__, 3)
+
+    def test_getslice(self):
+        l = [0, 1, 2, 3, 4]
+        u = self.type2test(l)
+
+        self.assertEqual(u[0:0], self.type2test())
+        self.assertEqual(u[1:2], self.type2test([1]))
+        self.assertEqual(u[-2:-1], self.type2test([3]))
+        self.assertEqual(u[-1000:1000], u)
+        self.assertEqual(u[1000:-1000], self.type2test([]))
+        self.assertEqual(u[:], u)
+        self.assertEqual(u[1:None], self.type2test([1, 2, 3, 4]))
+        self.assertEqual(u[None:3], self.type2test([0, 1, 2]))
+
+        # Extended slices
+        self.assertEqual(u[::], u)
+        self.assertEqual(u[::2], self.type2test([0, 2, 4]))
+        self.assertEqual(u[1::2], self.type2test([1, 3]))
+        self.assertEqual(u[::-1], self.type2test([4, 3, 2, 1, 0]))
+        self.assertEqual(u[::-2], self.type2test([4, 2, 0]))
+        self.assertEqual(u[3::-2], self.type2test([3, 1]))
+        self.assertEqual(u[3:3:-2], self.type2test([]))
+        self.assertEqual(u[3:2:-2], self.type2test([3]))
+        self.assertEqual(u[3:1:-2], self.type2test([3]))
+        self.assertEqual(u[3:0:-2], self.type2test([3, 1]))
+        self.assertEqual(u[::-100], self.type2test([4]))
+        self.assertEqual(u[100:-100:], self.type2test([]))
+        self.assertEqual(u[-100:100:], u)
+        self.assertEqual(u[100:-100:-1], u[::-1])
+        self.assertEqual(u[-100:100:-1], self.type2test([]))
+        self.assertEqual(u[-100L:100L:2L], self.type2test([0, 2, 4]))
+
+        # Test extreme cases with long ints
+        a = self.type2test([0,1,2,3,4])
+        self.assertEqual(a[ -pow(2,128L): 3 ], self.type2test([0,1,2]))
+        self.assertEqual(a[ 3: pow(2,145L) ], self.type2test([3,4]))
+
+        if hasattr(u, '__getslice__'):
+            self.assertRaises(TypeError, u.__getslice__)
+
+    def test_contains(self):
+        u = self.type2test([0, 1, 2])
+        for i in u:
+            self.assert_(i in u)
+        for i in min(u)-1, max(u)+1:
+            self.assert_(i not in u)
+
+        self.assertRaises(TypeError, u.__contains__)
+
+    def test_contains_fake(self):
+        class AllEq:
+            # Sequences must use rich comparison against each item
+            # (unless "is" is true, or an earlier item answered)
+            # So instances of AllEq must be found in all non-empty sequences.
+            def __eq__(self, other):
+                return True
+            def __hash__(self):
+                raise NotImplemented
+        self.assert_(AllEq() not in self.type2test([]))
+        self.assert_(AllEq() in self.type2test([1]))
+
+    def test_contains_order(self):
+        # Sequences must test in-order.  If a rich comparison has side
+        # effects, these will be visible to tests against later members.
+        # In this test, the "side effect" is a short-circuiting raise.
+        class DoNotTestEq(Exception):
+            pass
+        class StopCompares:
+            def __eq__(self, other):
+                raise DoNotTestEq
+
+        checkfirst = self.type2test([1, StopCompares()])
+        self.assert_(1 in checkfirst)
+        checklast = self.type2test([StopCompares(), 1])
+        self.assertRaises(DoNotTestEq, checklast.__contains__, 1)
+
+    def test_len(self):
+        self.assertEqual(len(self.type2test()), 0)
+        self.assertEqual(len(self.type2test([])), 0)
+        self.assertEqual(len(self.type2test([0])), 1)
+        self.assertEqual(len(self.type2test([0, 1, 2])), 3)
+
+    def test_minmax(self):
+        u = self.type2test([0, 1, 2])
+        self.assertEqual(min(u), 0)
+        self.assertEqual(max(u), 2)
+
+    def test_addmul(self):
+        u1 = self.type2test([0])
+        u2 = self.type2test([0, 1])
+        self.assertEqual(u1, u1 + self.type2test())
+        self.assertEqual(u1, self.type2test() + u1)
+        self.assertEqual(u1 + self.type2test([1]), u2)
+        self.assertEqual(self.type2test([-1]) + u1, self.type2test([-1, 0]))
+        self.assertEqual(self.type2test(), u2*0)
+        self.assertEqual(self.type2test(), 0*u2)
+        self.assertEqual(self.type2test(), u2*0L)
+        self.assertEqual(self.type2test(), 0L*u2)
+        self.assertEqual(u2, u2*1)
+        self.assertEqual(u2, 1*u2)
+        self.assertEqual(u2, u2*1L)
+        self.assertEqual(u2, 1L*u2)
+        self.assertEqual(u2+u2, u2*2)
+        self.assertEqual(u2+u2, 2*u2)
+        self.assertEqual(u2+u2, u2*2L)
+        self.assertEqual(u2+u2, 2L*u2)
+        self.assertEqual(u2+u2+u2, u2*3)
+        self.assertEqual(u2+u2+u2, 3*u2)
+
+        class subclass(self.type2test):
+            pass
+        u3 = subclass([0, 1])
+        self.assertEqual(u3, u3*1)
+        self.assert_(u3 is not u3*1)
+
+    def test_iadd(self):
+        u = self.type2test([0, 1])
+        u += self.type2test()
+        self.assertEqual(u, self.type2test([0, 1]))
+        u += self.type2test([2, 3])
+        self.assertEqual(u, self.type2test([0, 1, 2, 3]))
+        u += self.type2test([4, 5])
+        self.assertEqual(u, self.type2test([0, 1, 2, 3, 4, 5]))
+
+        u = self.type2test("spam")
+        u += self.type2test("eggs")
+        self.assertEqual(u, self.type2test("spameggs"))
+
+    def test_imul(self):
+        u = self.type2test([0, 1])
+        u *= 3
+        self.assertEqual(u, self.type2test([0, 1, 0, 1, 0, 1]))
+
+    #def test_getitemoverwriteiter(self):
+    #    # Verify that __getitem__ overrides are not recognized by __iter__
+    #      XXX PyPy behaves differently on this detail
+    #    class T(self.type2test):
+    #        def __getitem__(self, key):
+    #            return str(key) + '!!!'
+    #    self.assertEqual(iter(T((1,2))).next(), 1)
+
+    def test_repeat(self):
+        for m in xrange(4):
+            s = tuple(range(m))
+            for n in xrange(-3, 5):
+                self.assertEqual(self.type2test(s*n), self.type2test(s)*n)
+            self.assertEqual(self.type2test(s)*(-4), self.type2test([]))
+            #self.assertEqual(id(s), id(s*1))
+
+    def test_subscript(self):
+        a = self.type2test([10, 11])
+        self.assertEqual(a.__getitem__(0L), 10)
+        self.assertEqual(a.__getitem__(1L), 11)
+        self.assertEqual(a.__getitem__(-2L), 10)
+        self.assertEqual(a.__getitem__(-1L), 11)
+        self.assertRaises(IndexError, a.__getitem__, -3)
+        self.assertRaises(IndexError, a.__getitem__, 3)
+        self.assertEqual(a.__getitem__(slice(0,1)), self.type2test([10]))
+        self.assertEqual(a.__getitem__(slice(1,2)), self.type2test([11]))
+        self.assertEqual(a.__getitem__(slice(0,2)), self.type2test([10, 11]))
+        self.assertEqual(a.__getitem__(slice(0,3)), self.type2test([10, 11]))
+        self.assertEqual(a.__getitem__(slice(3,5)), self.type2test([]))
+        self.assertRaises(ValueError, a.__getitem__, slice(0, 10, 0))
+        self.assertRaises(TypeError, a.__getitem__, 'x')

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/string_tests.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/string_tests.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,1219 @@
+"""
+Common tests shared by test_str, test_unicode, test_userstring and test_string.
+"""
+
+import unittest, string, sys, operator
+from test import test_support
+from UserList import UserList
+
+class Sequence:
+    def __init__(self, seq='wxyz'): self.seq = seq
+    def __len__(self): return len(self.seq)
+    def __getitem__(self, i): return self.seq[i]
+
+class BadSeq1(Sequence):
+    def __init__(self): self.seq = [7, 'hello', 123L]
+
+class BadSeq2(Sequence):
+    def __init__(self): self.seq = ['a', 'b', 'c']
+    def __len__(self): return 8
+
+class CommonTest(unittest.TestCase):
+    # This testcase contains test that can be used in all
+    # stringlike classes. Currently this is str, unicode
+    # UserString and the string module.
+
+    # The type to be tested
+    # Change in subclasses to change the behaviour of fixtesttype()
+    type2test = None
+
+    # All tests pass their arguments to the testing methods
+    # as str objects. fixtesttype() can be used to propagate
+    # these arguments to the appropriate type
+    def fixtype(self, obj):
+        if isinstance(obj, str):
+            return self.__class__.type2test(obj)
+        elif isinstance(obj, list):
+            return [self.fixtype(x) for x in obj]
+        elif isinstance(obj, tuple):
+            return tuple([self.fixtype(x) for x in obj])
+        elif isinstance(obj, dict):
+            return dict([
+               (self.fixtype(key), self.fixtype(value))
+               for (key, value) in obj.iteritems()
+            ])
+        else:
+            return obj
+
+    # single this out, because UserString cannot cope with fixed args
+    fixargs = fixtype
+    subclasscheck = True
+
+    # check that object.method(*args) returns result
+    def checkequal(self, result, object, methodname, *args):
+        result = self.fixtype(result)
+        object = self.fixtype(object)
+        args = self.fixargs(args)
+        realresult = getattr(object, methodname)(*args)
+        self.assertEqual(
+            result,
+            realresult
+        )
+        # if the original is returned make sure that
+        # this doesn't happen with subclasses
+        if object == realresult and self.subclasscheck:
+            class subtype(self.__class__.type2test):
+                pass
+            object = subtype(object)
+            realresult = getattr(object, methodname)(*args)
+            self.assert_(object is not realresult)
+
+    # check that op(*args) returns result
+    def checkop(self, result, op, *args):
+        result = self.fixtype(result)
+        object = self.fixtype(args[0])
+        args = self.fixargs(args[1:])
+        realresult = op(object, *args)
+        self.assertEqual(
+            result,
+            realresult
+        )
+        # if the original is returned make sure that
+        # this doesn't happen with subclasses
+        if object == realresult and self.subclasscheck:
+            class subtype(self.__class__.type2test):
+                pass
+            object = subtype(object)
+            realresult = op(object, *args)
+            self.assert_(object is not realresult)
+
+    # check that object.method(*args) raises exc
+    def checkraises(self, exc, object, methodname, *args):
+        object = self.fixtype(object)
+        args = self.fixargs(args)
+        self.assertRaises(
+            exc,
+            getattr(object, methodname),
+            *args
+        )
+
+    # check that op(*args) raises exc
+    def checkopraises(self, exc, op, *args):
+        object = self.fixtype(args[0])
+        args = self.fixargs(args[1:])
+        self.assertRaises(
+            exc,
+            op,
+            object,
+            *args
+        )
+
+    # call object.method(*args) without any checks
+    def checkcall(self, object, methodname, *args):
+        object = self.fixtype(object)
+        args = self.fixargs(args)
+        getattr(object, methodname)(*args)
+
+    # call op(*args) without any checks
+    def checkopcall(self, op, *args):
+        object = self.fixtype(args[0])
+        args = self.fixargs(args[1:])
+        op(object, *args)
+
+    def test_hash(self):
+        # SF bug 1054139:  += optimization was not invalidating cached hash value
+        a = self.type2test('DNSSEC')
+        b = self.type2test('')
+        for c in a:
+            b += c
+            hash(b)
+        self.assertEqual(hash(a), hash(b))
+
+    def test_capitalize(self):
+        self.checkequal(' hello ', ' hello ', 'capitalize')
+        self.checkequal('Hello ', 'Hello ','capitalize')
+        self.checkequal('Hello ', 'hello ','capitalize')
+        self.checkequal('Aaaa', 'aaaa', 'capitalize')
+        self.checkequal('Aaaa', 'AaAa', 'capitalize')
+
+        self.checkraises(TypeError, 'hello', 'capitalize', 42)
+
+    def test_count(self):
+        self.checkequal(3, 'aaa', 'count', 'a')
+        self.checkequal(0, 'aaa', 'count', 'b')
+        self.checkequal(3, 'aaa', 'count', 'a')
+        self.checkequal(0, 'aaa', 'count', 'b')
+        self.checkequal(3, 'aaa', 'count', 'a')
+        self.checkequal(0, 'aaa', 'count', 'b')
+        self.checkequal(0, 'aaa', 'count', 'b')
+        self.checkequal(2, 'aaa', 'count', 'a', 1)
+        self.checkequal(0, 'aaa', 'count', 'a', 10)
+        self.checkequal(1, 'aaa', 'count', 'a', -1)
+        self.checkequal(3, 'aaa', 'count', 'a', -10)
+        self.checkequal(1, 'aaa', 'count', 'a', 0, 1)
+        self.checkequal(3, 'aaa', 'count', 'a', 0, 10)
+        self.checkequal(2, 'aaa', 'count', 'a', 0, -1)
+        self.checkequal(0, 'aaa', 'count', 'a', 0, -10)
+        self.checkequal(3, 'aaa', 'count', '', 1)
+        self.checkequal(1, 'aaa', 'count', '', 3)
+        self.checkequal(0, 'aaa', 'count', '', 10)
+        self.checkequal(2, 'aaa', 'count', '', -1)
+        self.checkequal(4, 'aaa', 'count', '', -10)
+
+        self.checkraises(TypeError, 'hello', 'count')
+        self.checkraises(TypeError, 'hello', 'count', 42)
+
+        # For a variety of combinations,
+        #    verify that str.count() matches an equivalent function
+        #    replacing all occurrences and then differencing the string lengths
+        charset = ['', 'a', 'b']
+        digits = 7
+        base = len(charset)
+        teststrings = set()
+        for i in xrange(base ** digits):
+            entry = []
+            for j in xrange(digits):
+                i, m = divmod(i, base)
+                entry.append(charset[m])
+            teststrings.add(''.join(entry))
+        teststrings = list(teststrings)
+        for i in teststrings:
+            i = self.fixtype(i)
+            n = len(i)
+            for j in teststrings:
+                r1 = i.count(j)
+                if j:
+                    r2, rem = divmod(n - len(i.replace(j, '')), len(j))
+                else:
+                    r2, rem = len(i)+1, 0
+                if rem or r1 != r2:
+                    self.assertEqual(rem, 0, '%s != 0 for %s' % (rem, i))
+                    self.assertEqual(r1, r2, '%s != %s for %s' % (r1, r2, i))
+
+    def test_find(self):
+        self.checkequal(0, 'abcdefghiabc', 'find', 'abc')
+        self.checkequal(9, 'abcdefghiabc', 'find', 'abc', 1)
+        self.checkequal(-1, 'abcdefghiabc', 'find', 'def', 4)
+
+        self.checkequal(0, 'abc', 'find', '', 0)
+        self.checkequal(3, 'abc', 'find', '', 3)
+        self.checkequal(-1, 'abc', 'find', '', 4)
+
+        self.checkraises(TypeError, 'hello', 'find')
+        self.checkraises(TypeError, 'hello', 'find', 42)
+
+        # For a variety of combinations,
+        #    verify that str.find() matches __contains__
+        #    and that the found substring is really at that location
+        charset = ['', 'a', 'b', 'c']
+        digits = 5
+        base = len(charset)
+        teststrings = set()
+        for i in xrange(base ** digits):
+            entry = []
+            for j in xrange(digits):
+                i, m = divmod(i, base)
+                entry.append(charset[m])
+            teststrings.add(''.join(entry))
+        teststrings = list(teststrings)
+        for i in teststrings:
+            i = self.fixtype(i)
+            for j in teststrings:
+                loc = i.find(j)
+                r1 = (loc != -1)
+                r2 = j in i
+                if r1 != r2:
+                    self.assertEqual(r1, r2)
+                if loc != -1:
+                    self.assertEqual(i[loc:loc+len(j)], j)
+
+    def test_rfind(self):
+        self.checkequal(9,  'abcdefghiabc', 'rfind', 'abc')
+        self.checkequal(12, 'abcdefghiabc', 'rfind', '')
+        self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd')
+        self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz')
+
+        self.checkequal(3, 'abc', 'rfind', '', 0)
+        self.checkequal(3, 'abc', 'rfind', '', 3)
+        self.checkequal(-1, 'abc', 'rfind', '', 4)
+
+        self.checkraises(TypeError, 'hello', 'rfind')
+        self.checkraises(TypeError, 'hello', 'rfind', 42)
+
+    def test_index(self):
+        self.checkequal(0, 'abcdefghiabc', 'index', '')
+        self.checkequal(3, 'abcdefghiabc', 'index', 'def')
+        self.checkequal(0, 'abcdefghiabc', 'index', 'abc')
+        self.checkequal(9, 'abcdefghiabc', 'index', 'abc', 1)
+
+        self.checkraises(ValueError, 'abcdefghiabc', 'index', 'hib')
+        self.checkraises(ValueError, 'abcdefghiab', 'index', 'abc', 1)
+        self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', 8)
+        self.checkraises(ValueError, 'abcdefghi', 'index', 'ghi', -1)
+
+        self.checkraises(TypeError, 'hello', 'index')
+        self.checkraises(TypeError, 'hello', 'index', 42)
+
+    def test_rindex(self):
+        self.checkequal(12, 'abcdefghiabc', 'rindex', '')
+        self.checkequal(3,  'abcdefghiabc', 'rindex', 'def')
+        self.checkequal(9,  'abcdefghiabc', 'rindex', 'abc')
+        self.checkequal(0,  'abcdefghiabc', 'rindex', 'abc', 0, -1)
+
+        self.checkraises(ValueError, 'abcdefghiabc', 'rindex', 'hib')
+        self.checkraises(ValueError, 'defghiabc', 'rindex', 'def', 1)
+        self.checkraises(ValueError, 'defghiabc', 'rindex', 'abc', 0, -1)
+        self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, 8)
+        self.checkraises(ValueError, 'abcdefghi', 'rindex', 'ghi', 0, -1)
+
+        self.checkraises(TypeError, 'hello', 'rindex')
+        self.checkraises(TypeError, 'hello', 'rindex', 42)
+
+    def test_lower(self):
+        self.checkequal('hello', 'HeLLo', 'lower')
+        self.checkequal('hello', 'hello', 'lower')
+        self.checkraises(TypeError, 'hello', 'lower', 42)
+
+    def test_upper(self):
+        self.checkequal('HELLO', 'HeLLo', 'upper')
+        self.checkequal('HELLO', 'HELLO', 'upper')
+        self.checkraises(TypeError, 'hello', 'upper', 42)
+
+    def test_expandtabs(self):
+        self.checkequal('abc\rab      def\ng       hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
+        self.checkequal('abc\rab      def\ng       hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
+        self.checkequal('abc\rab  def\ng   hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 4)
+        self.checkequal('abc\r\nab  def\ng   hi', 'abc\r\nab\tdef\ng\thi', 'expandtabs', 4)
+        self.checkequal('abc\rab      def\ng       hi', 'abc\rab\tdef\ng\thi', 'expandtabs')
+        self.checkequal('abc\rab      def\ng       hi', 'abc\rab\tdef\ng\thi', 'expandtabs', 8)
+        self.checkequal('abc\r\nab\r\ndef\ng\r\nhi', 'abc\r\nab\r\ndef\ng\r\nhi', 'expandtabs', 4)
+
+        self.checkraises(TypeError, 'hello', 'expandtabs', 42, 42)
+
+    def test_split(self):
+        self.checkequal(['this', 'is', 'the', 'split', 'function'],
+            'this is the split function', 'split')
+
+        # by whitespace
+        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'split')
+        self.checkequal(['a', 'b c d'], 'a b c d', 'split', None, 1)
+        self.checkequal(['a', 'b', 'c d'], 'a b c d', 'split', None, 2)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 3)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None, 4)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'split', None,
+                        sys.maxint-1)
+        self.checkequal(['a b c d'], 'a b c d', 'split', None, 0)
+        self.checkequal(['a b c d'], '  a b c d', 'split', None, 0)
+        self.checkequal(['a', 'b', 'c  d'], 'a  b  c  d', 'split', None, 2)
+
+        self.checkequal([], '         ', 'split')
+        self.checkequal(['a'], '  a    ', 'split')
+        self.checkequal(['a', 'b'], '  a    b   ', 'split')
+        self.checkequal(['a', 'b   '], '  a    b   ', 'split', None, 1)
+        self.checkequal(['a', 'b   c   '], '  a    b   c   ', 'split', None, 1)
+        self.checkequal(['a', 'b', 'c   '], '  a    b   c   ', 'split', None, 2)
+        self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'split')
+        aaa = ' a '*20
+        self.checkequal(['a']*20, aaa, 'split')
+        self.checkequal(['a'] + [aaa[4:]], aaa, 'split', None, 1)
+        self.checkequal(['a']*19 + ['a '], aaa, 'split', None, 19)
+
+        # by a char
+        self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|')
+        self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
+        self.checkequal(['a', 'b|c|d'], 'a|b|c|d', 'split', '|', 1)
+        self.checkequal(['a', 'b', 'c|d'], 'a|b|c|d', 'split', '|', 2)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 3)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|', 4)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'split', '|',
+                        sys.maxint-2)
+        self.checkequal(['a|b|c|d'], 'a|b|c|d', 'split', '|', 0)
+        self.checkequal(['a', '', 'b||c||d'], 'a||b||c||d', 'split', '|', 2)
+        self.checkequal(['endcase ', ''], 'endcase |', 'split', '|')
+        self.checkequal(['', ' startcase'], '| startcase', 'split', '|')
+        self.checkequal(['', 'bothcase', ''], '|bothcase|', 'split', '|')
+        self.checkequal(['a', '', 'b\x00c\x00d'], 'a\x00\x00b\x00c\x00d', 'split', '\x00', 2)
+
+        self.checkequal(['a']*20, ('a|'*20)[:-1], 'split', '|')
+        self.checkequal(['a']*15 +['a|a|a|a|a'],
+                                   ('a|'*20)[:-1], 'split', '|', 15)
+
+        # by string
+        self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
+        self.checkequal(['a', 'b//c//d'], 'a//b//c//d', 'split', '//', 1)
+        self.checkequal(['a', 'b', 'c//d'], 'a//b//c//d', 'split', '//', 2)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 3)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//', 4)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//',
+                        sys.maxint-10)
+        self.checkequal(['a//b//c//d'], 'a//b//c//d', 'split', '//', 0)
+        self.checkequal(['a', '', 'b////c////d'], 'a////b////c////d', 'split', '//', 2)
+        self.checkequal(['endcase ', ''], 'endcase test', 'split', 'test')
+        self.checkequal(['', ' begincase'], 'test begincase', 'split', 'test')
+        self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
+                        'split', 'test')
+        self.checkequal(['a', 'bc'], 'abbbc', 'split', 'bb')
+        self.checkequal(['', ''], 'aaa', 'split', 'aaa')
+        self.checkequal(['aaa'], 'aaa', 'split', 'aaa', 0)
+        self.checkequal(['ab', 'ab'], 'abbaab', 'split', 'ba')
+        self.checkequal(['aaaa'], 'aaaa', 'split', 'aab')
+        self.checkequal([''], '', 'split', 'aaa')
+        self.checkequal(['aa'], 'aa', 'split', 'aaa')
+        self.checkequal(['A', 'bobb'], 'Abbobbbobb', 'split', 'bbobb')
+        self.checkequal(['A', 'B', ''], 'AbbobbBbbobb', 'split', 'bbobb')
+
+        self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH')
+        self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'split', 'BLAH', 19)
+        self.checkequal(['a']*18 + ['aBLAHa'], ('aBLAH'*20)[:-4],
+                        'split', 'BLAH', 18)
+
+        # mixed use of str and unicode
+        self.checkequal([u'a', u'b', u'c d'], 'a b c d', 'split', u' ', 2)
+
+        # argument type
+        self.checkraises(TypeError, 'hello', 'split', 42, 42, 42)
+
+        # null case
+        self.checkraises(ValueError, 'hello', 'split', '')
+        self.checkraises(ValueError, 'hello', 'split', '', 0)
+
+    def test_rsplit(self):
+        self.checkequal(['this', 'is', 'the', 'rsplit', 'function'],
+                         'this is the rsplit function', 'rsplit')
+
+        # by whitespace
+        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d ', 'rsplit')
+        self.checkequal(['a b c', 'd'], 'a b c d', 'rsplit', None, 1)
+        self.checkequal(['a b', 'c', 'd'], 'a b c d', 'rsplit', None, 2)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 3)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None, 4)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a b c d', 'rsplit', None,
+                        sys.maxint-20)
+        self.checkequal(['a b c d'], 'a b c d', 'rsplit', None, 0)
+        self.checkequal(['a b c d'], 'a b c d  ', 'rsplit', None, 0)
+        self.checkequal(['a  b', 'c', 'd'], 'a  b  c  d', 'rsplit', None, 2)
+
+        self.checkequal([], '         ', 'rsplit')
+        self.checkequal(['a'], '  a    ', 'rsplit')
+        self.checkequal(['a', 'b'], '  a    b   ', 'rsplit')
+        self.checkequal(['  a', 'b'], '  a    b   ', 'rsplit', None, 1)
+        self.checkequal(['  a    b','c'], '  a    b   c   ', 'rsplit',
+                        None, 1)
+        self.checkequal(['  a', 'b', 'c'], '  a    b   c   ', 'rsplit',
+                        None, 2)
+        self.checkequal(['a', 'b'], '\n\ta \t\r b \v ', 'rsplit', None, 88)
+        aaa = ' a '*20
+        self.checkequal(['a']*20, aaa, 'rsplit')
+        self.checkequal([aaa[:-4]] + ['a'], aaa, 'rsplit', None, 1)
+        self.checkequal([' a  a'] + ['a']*18, aaa, 'rsplit', None, 18)
+
+
+        # by a char
+        self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|')
+        self.checkequal(['a|b|c', 'd'], 'a|b|c|d', 'rsplit', '|', 1)
+        self.checkequal(['a|b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 2)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 3)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|', 4)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a|b|c|d', 'rsplit', '|',
+                        sys.maxint-100)
+        self.checkequal(['a|b|c|d'], 'a|b|c|d', 'rsplit', '|', 0)
+        self.checkequal(['a||b||c', '', 'd'], 'a||b||c||d', 'rsplit', '|', 2)
+        self.checkequal(['', ' begincase'], '| begincase', 'rsplit', '|')
+        self.checkequal(['endcase ', ''], 'endcase |', 'rsplit', '|')
+        self.checkequal(['', 'bothcase', ''], '|bothcase|', 'rsplit', '|')
+
+        self.checkequal(['a\x00\x00b', 'c', 'd'], 'a\x00\x00b\x00c\x00d', 'rsplit', '\x00', 2)
+
+        self.checkequal(['a']*20, ('a|'*20)[:-1], 'rsplit', '|')
+        self.checkequal(['a|a|a|a|a']+['a']*15,
+                        ('a|'*20)[:-1], 'rsplit', '|', 15)
+
+        # by string
+        self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//')
+        self.checkequal(['a//b//c', 'd'], 'a//b//c//d', 'rsplit', '//', 1)
+        self.checkequal(['a//b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 2)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 3)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//', 4)
+        self.checkequal(['a', 'b', 'c', 'd'], 'a//b//c//d', 'rsplit', '//',
+                        sys.maxint-5)
+        self.checkequal(['a//b//c//d'], 'a//b//c//d', 'rsplit', '//', 0)
+        self.checkequal(['a////b////c', '', 'd'], 'a////b////c////d', 'rsplit', '//', 2)
+        self.checkequal(['', ' begincase'], 'test begincase', 'rsplit', 'test')
+        self.checkequal(['endcase ', ''], 'endcase test', 'rsplit', 'test')
+        self.checkequal(['', ' bothcase ', ''], 'test bothcase test',
+                        'rsplit', 'test')
+        self.checkequal(['ab', 'c'], 'abbbc', 'rsplit', 'bb')
+        self.checkequal(['', ''], 'aaa', 'rsplit', 'aaa')
+        self.checkequal(['aaa'], 'aaa', 'rsplit', 'aaa', 0)
+        self.checkequal(['ab', 'ab'], 'abbaab', 'rsplit', 'ba')
+        self.checkequal(['aaaa'], 'aaaa', 'rsplit', 'aab')
+        self.checkequal([''], '', 'rsplit', 'aaa')
+        self.checkequal(['aa'], 'aa', 'rsplit', 'aaa')
+        self.checkequal(['bbob', 'A'], 'bbobbbobbA', 'rsplit', 'bbobb')
+        self.checkequal(['', 'B', 'A'], 'bbobbBbbobbA', 'rsplit', 'bbobb')
+
+        self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH')
+        self.checkequal(['a']*20, ('aBLAH'*20)[:-4], 'rsplit', 'BLAH', 19)
+        self.checkequal(['aBLAHa'] + ['a']*18, ('aBLAH'*20)[:-4],
+                        'rsplit', 'BLAH', 18)
+
+        # mixed use of str and unicode
+        self.checkequal([u'a b', u'c', u'd'], 'a b c d', 'rsplit', u' ', 2)
+
+        # argument type
+        self.checkraises(TypeError, 'hello', 'rsplit', 42, 42, 42)
+
+        # null case
+        self.checkraises(ValueError, 'hello', 'rsplit', '')
+        self.checkraises(ValueError, 'hello', 'rsplit', '', 0)
+
+    def test_strip(self):
+        self.checkequal('hello', '   hello   ', 'strip')
+        self.checkequal('hello   ', '   hello   ', 'lstrip')
+        self.checkequal('   hello', '   hello   ', 'rstrip')
+        self.checkequal('hello', 'hello', 'strip')
+
+        # strip/lstrip/rstrip with None arg
+        self.checkequal('hello', '   hello   ', 'strip', None)
+        self.checkequal('hello   ', '   hello   ', 'lstrip', None)
+        self.checkequal('   hello', '   hello   ', 'rstrip', None)
+        self.checkequal('hello', 'hello', 'strip', None)
+
+        # strip/lstrip/rstrip with str arg
+        self.checkequal('hello', 'xyzzyhelloxyzzy', 'strip', 'xyz')
+        self.checkequal('helloxyzzy', 'xyzzyhelloxyzzy', 'lstrip', 'xyz')
+        self.checkequal('xyzzyhello', 'xyzzyhelloxyzzy', 'rstrip', 'xyz')
+        self.checkequal('hello', 'hello', 'strip', 'xyz')
+
+        # strip/lstrip/rstrip with unicode arg
+        if test_support.have_unicode:
+            self.checkequal(unicode('hello', 'ascii'), 'xyzzyhelloxyzzy',
+                 'strip', unicode('xyz', 'ascii'))
+            self.checkequal(unicode('helloxyzzy', 'ascii'), 'xyzzyhelloxyzzy',
+                 'lstrip', unicode('xyz', 'ascii'))
+            self.checkequal(unicode('xyzzyhello', 'ascii'), 'xyzzyhelloxyzzy',
+                 'rstrip', unicode('xyz', 'ascii'))
+            self.checkequal(unicode('hello', 'ascii'), 'hello',
+                 'strip', unicode('xyz', 'ascii'))
+
+        self.checkraises(TypeError, 'hello', 'strip', 42, 42)
+        self.checkraises(TypeError, 'hello', 'lstrip', 42, 42)
+        self.checkraises(TypeError, 'hello', 'rstrip', 42, 42)
+
+    def test_ljust(self):
+        self.checkequal('abc       ', 'abc', 'ljust', 10)
+        self.checkequal('abc   ', 'abc', 'ljust', 6)
+        self.checkequal('abc', 'abc', 'ljust', 3)
+        self.checkequal('abc', 'abc', 'ljust', 2)
+        self.checkequal('abc*******', 'abc', 'ljust', 10, '*')
+        self.checkraises(TypeError, 'abc', 'ljust')
+
+    def test_rjust(self):
+        self.checkequal('       abc', 'abc', 'rjust', 10)
+        self.checkequal('   abc', 'abc', 'rjust', 6)
+        self.checkequal('abc', 'abc', 'rjust', 3)
+        self.checkequal('abc', 'abc', 'rjust', 2)
+        self.checkequal('*******abc', 'abc', 'rjust', 10, '*')
+        self.checkraises(TypeError, 'abc', 'rjust')
+
+    def test_center(self):
+        self.checkequal('   abc    ', 'abc', 'center', 10)
+        self.checkequal(' abc  ', 'abc', 'center', 6)
+        self.checkequal('abc', 'abc', 'center', 3)
+        self.checkequal('abc', 'abc', 'center', 2)
+        self.checkequal('***abc****', 'abc', 'center', 10, '*')
+        self.checkraises(TypeError, 'abc', 'center')
+
+    def test_swapcase(self):
+        self.checkequal('hEllO CoMPuTErS', 'HeLLo cOmpUteRs', 'swapcase')
+
+        self.checkraises(TypeError, 'hello', 'swapcase', 42)
+
+    def test_replace(self):
+        EQ = self.checkequal
+
+        # Operations on the empty string
+        EQ("", "", "replace", "", "")
+        EQ("A", "", "replace", "", "A")
+        EQ("", "", "replace", "A", "")
+        EQ("", "", "replace", "A", "A")
+        EQ("", "", "replace", "", "", 100)
+        EQ("", "", "replace", "", "", sys.maxint)
+
+        # interleave (from=="", 'to' gets inserted everywhere)
+        EQ("A", "A", "replace", "", "")
+        EQ("*A*", "A", "replace", "", "*")
+        EQ("*1A*1", "A", "replace", "", "*1")
+        EQ("*-#A*-#", "A", "replace", "", "*-#")
+        EQ("*-A*-A*-", "AA", "replace", "", "*-")
+        EQ("*-A*-A*-", "AA", "replace", "", "*-", -1)
+        EQ("*-A*-A*-", "AA", "replace", "", "*-", sys.maxint)
+        EQ("*-A*-A*-", "AA", "replace", "", "*-", 4)
+        EQ("*-A*-A*-", "AA", "replace", "", "*-", 3)
+        EQ("*-A*-A", "AA", "replace", "", "*-", 2)
+        EQ("*-AA", "AA", "replace", "", "*-", 1)
+        EQ("AA", "AA", "replace", "", "*-", 0)
+
+        # single character deletion (from=="A", to=="")
+        EQ("", "A", "replace", "A", "")
+        EQ("", "AAA", "replace", "A", "")
+        EQ("", "AAA", "replace", "A", "", -1)
+        EQ("", "AAA", "replace", "A", "", sys.maxint)
+        EQ("", "AAA", "replace", "A", "", 4)
+        EQ("", "AAA", "replace", "A", "", 3)
+        EQ("A", "AAA", "replace", "A", "", 2)
+        EQ("AA", "AAA", "replace", "A", "", 1)
+        EQ("AAA", "AAA", "replace", "A", "", 0)
+        EQ("", "AAAAAAAAAA", "replace", "A", "")
+        EQ("BCD", "ABACADA", "replace", "A", "")
+        EQ("BCD", "ABACADA", "replace", "A", "", -1)
+        EQ("BCD", "ABACADA", "replace", "A", "", sys.maxint)
+        EQ("BCD", "ABACADA", "replace", "A", "", 5)
+        EQ("BCD", "ABACADA", "replace", "A", "", 4)
+        EQ("BCDA", "ABACADA", "replace", "A", "", 3)
+        EQ("BCADA", "ABACADA", "replace", "A", "", 2)
+        EQ("BACADA", "ABACADA", "replace", "A", "", 1)
+        EQ("ABACADA", "ABACADA", "replace", "A", "", 0)
+        EQ("BCD", "ABCAD", "replace", "A", "")
+        EQ("BCD", "ABCADAA", "replace", "A", "")
+        EQ("BCD", "BCD", "replace", "A", "")
+        EQ("*************", "*************", "replace", "A", "")
+        EQ("^A^", "^"+"A"*1000+"^", "replace", "A", "", 999)
+
+        # substring deletion (from=="the", to=="")
+        EQ("", "the", "replace", "the", "")
+        EQ("ater", "theater", "replace", "the", "")
+        EQ("", "thethe", "replace", "the", "")
+        EQ("", "thethethethe", "replace", "the", "")
+        EQ("aaaa", "theatheatheathea", "replace", "the", "")
+        EQ("that", "that", "replace", "the", "")
+        EQ("thaet", "thaet", "replace", "the", "")
+        EQ("here and re", "here and there", "replace", "the", "")
+        EQ("here and re and re", "here and there and there",
+           "replace", "the", "", sys.maxint)
+        EQ("here and re and re", "here and there and there",
+           "replace", "the", "", -1)
+        EQ("here and re and re", "here and there and there",
+           "replace", "the", "", 3)
+        EQ("here and re and re", "here and there and there",
+           "replace", "the", "", 2)
+        EQ("here and re and there", "here and there and there",
+           "replace", "the", "", 1)
+        EQ("here and there and there", "here and there and there",
+           "replace", "the", "", 0)
+        EQ("here and re and re", "here and there and there", "replace", "the", "")
+
+        EQ("abc", "abc", "replace", "the", "")
+        EQ("abcdefg", "abcdefg", "replace", "the", "")
+
+        # substring deletion (from=="bob", to=="")
+        EQ("bob", "bbobob", "replace", "bob", "")
+        EQ("bobXbob", "bbobobXbbobob", "replace", "bob", "")
+        EQ("aaaaaaa", "aaaaaaabob", "replace", "bob", "")
+        EQ("aaaaaaa", "aaaaaaa", "replace", "bob", "")
+
+        # single character replace in place (len(from)==len(to)==1)
+        EQ("Who goes there?", "Who goes there?", "replace", "o", "o")
+        EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O")
+        EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", sys.maxint)
+        EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", -1)
+        EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 3)
+        EQ("WhO gOes there?", "Who goes there?", "replace", "o", "O", 2)
+        EQ("WhO goes there?", "Who goes there?", "replace", "o", "O", 1)
+        EQ("Who goes there?", "Who goes there?", "replace", "o", "O", 0)
+
+        EQ("Who goes there?", "Who goes there?", "replace", "a", "q")
+        EQ("who goes there?", "Who goes there?", "replace", "W", "w")
+        EQ("wwho goes there?ww", "WWho goes there?WW", "replace", "W", "w")
+        EQ("Who goes there!", "Who goes there?", "replace", "?", "!")
+        EQ("Who goes there!!", "Who goes there??", "replace", "?", "!")
+
+        EQ("Who goes there?", "Who goes there?", "replace", ".", "!")
+
+        # substring replace in place (len(from)==len(to) > 1)
+        EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**")
+        EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", sys.maxint)
+        EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", -1)
+        EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 4)
+        EQ("Th** ** a t**sue", "This is a tissue", "replace", "is", "**", 3)
+        EQ("Th** ** a tissue", "This is a tissue", "replace", "is", "**", 2)
+        EQ("Th** is a tissue", "This is a tissue", "replace", "is", "**", 1)
+        EQ("This is a tissue", "This is a tissue", "replace", "is", "**", 0)
+        EQ("cobob", "bobob", "replace", "bob", "cob")
+        EQ("cobobXcobocob", "bobobXbobobob", "replace", "bob", "cob")
+        EQ("bobob", "bobob", "replace", "bot", "bot")
+
+        # replace single character (len(from)==1, len(to)>1)
+        EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK")
+        EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", -1)
+        EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", sys.maxint)
+        EQ("ReyKKjaviKK", "Reykjavik", "replace", "k", "KK", 2)
+        EQ("ReyKKjavik", "Reykjavik", "replace", "k", "KK", 1)
+        EQ("Reykjavik", "Reykjavik", "replace", "k", "KK", 0)
+        EQ("A----B----C----", "A.B.C.", "replace", ".", "----")
+
+        EQ("Reykjavik", "Reykjavik", "replace", "q", "KK")
+
+        # replace substring (len(from)>1, len(to)!=len(from))
+        EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
+           "replace", "spam", "ham")
+        EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
+           "replace", "spam", "ham", sys.maxint)
+        EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
+           "replace", "spam", "ham", -1)
+        EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
+           "replace", "spam", "ham", 4)
+        EQ("ham, ham, eggs and ham", "spam, spam, eggs and spam",
+           "replace", "spam", "ham", 3)
+        EQ("ham, ham, eggs and spam", "spam, spam, eggs and spam",
+           "replace", "spam", "ham", 2)
+        EQ("ham, spam, eggs and spam", "spam, spam, eggs and spam",
+           "replace", "spam", "ham", 1)
+        EQ("spam, spam, eggs and spam", "spam, spam, eggs and spam",
+           "replace", "spam", "ham", 0)
+
+        EQ("bobob", "bobobob", "replace", "bobob", "bob")
+        EQ("bobobXbobob", "bobobobXbobobob", "replace", "bobob", "bob")
+        EQ("BOBOBOB", "BOBOBOB", "replace", "bob", "bobby")
+
+        ba = buffer('a')
+        bb = buffer('b')
+        EQ("bbc", "abc", "replace", ba, bb)
+        EQ("aac", "abc", "replace", bb, ba)
+
+        #
+        self.checkequal('one at two!three!', 'one!two!three!', 'replace', '!', '@', 1)
+        self.checkequal('onetwothree', 'one!two!three!', 'replace', '!', '')
+        self.checkequal('one at two@three!', 'one!two!three!', 'replace', '!', '@', 2)
+        self.checkequal('one at two@three@', 'one!two!three!', 'replace', '!', '@', 3)
+        self.checkequal('one at two@three@', 'one!two!three!', 'replace', '!', '@', 4)
+        self.checkequal('one!two!three!', 'one!two!three!', 'replace', '!', '@', 0)
+        self.checkequal('one at two@three@', 'one!two!three!', 'replace', '!', '@')
+        self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@')
+        self.checkequal('one!two!three!', 'one!two!three!', 'replace', 'x', '@', 2)
+        self.checkequal('-a-b-c-', 'abc', 'replace', '', '-')
+        self.checkequal('-a-b-c', 'abc', 'replace', '', '-', 3)
+        self.checkequal('abc', 'abc', 'replace', '', '-', 0)
+        self.checkequal('', '', 'replace', '', '')
+        self.checkequal('abc', 'abc', 'replace', 'ab', '--', 0)
+        self.checkequal('abc', 'abc', 'replace', 'xy', '--')
+        # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with
+        # MemoryError due to empty result (platform malloc issue when requesting
+        # 0 bytes).
+        self.checkequal('', '123', 'replace', '123', '')
+        self.checkequal('', '123123', 'replace', '123', '')
+        self.checkequal('x', '123x123', 'replace', '123', '')
+
+        self.checkraises(TypeError, 'hello', 'replace')
+        self.checkraises(TypeError, 'hello', 'replace', 42)
+        self.checkraises(TypeError, 'hello', 'replace', 42, 'h')
+        self.checkraises(TypeError, 'hello', 'replace', 'h', 42)
+
+    def test_replace_overflow(self):
+        # Check for overflow checking on 32 bit machines
+        if sys.maxint != 2147483647:
+            return
+        A2_16 = "A" * (2**16)
+        self.checkraises(OverflowError, A2_16, "replace", "", A2_16)
+        self.checkraises(OverflowError, A2_16, "replace", "A", A2_16)
+        self.checkraises(OverflowError, A2_16, "replace", "AA", A2_16+A2_16)
+
+    def test_zfill(self):
+        self.checkequal('123', '123', 'zfill', 2)
+        self.checkequal('123', '123', 'zfill', 3)
+        self.checkequal('0123', '123', 'zfill', 4)
+        self.checkequal('+123', '+123', 'zfill', 3)
+        self.checkequal('+123', '+123', 'zfill', 4)
+        self.checkequal('+0123', '+123', 'zfill', 5)
+        self.checkequal('-123', '-123', 'zfill', 3)
+        self.checkequal('-123', '-123', 'zfill', 4)
+        self.checkequal('-0123', '-123', 'zfill', 5)
+        self.checkequal('000', '', 'zfill', 3)
+        self.checkequal('34', '34', 'zfill', 1)
+        self.checkequal('0034', '34', 'zfill', 4)
+
+        self.checkraises(TypeError, '123', 'zfill')
+
+class MixinStrUnicodeUserStringTest:
+    # additional tests that only work for
+    # stringlike objects, i.e. str, unicode, UserString
+    # (but not the string module)
+
+    def test_islower(self):
+        self.checkequal(False, '', 'islower')
+        self.checkequal(True, 'a', 'islower')
+        self.checkequal(False, 'A', 'islower')
+        self.checkequal(False, '\n', 'islower')
+        self.checkequal(True, 'abc', 'islower')
+        self.checkequal(False, 'aBc', 'islower')
+        self.checkequal(True, 'abc\n', 'islower')
+        self.checkraises(TypeError, 'abc', 'islower', 42)
+
+    def test_isupper(self):
+        self.checkequal(False, '', 'isupper')
+        self.checkequal(False, 'a', 'isupper')
+        self.checkequal(True, 'A', 'isupper')
+        self.checkequal(False, '\n', 'isupper')
+        self.checkequal(True, 'ABC', 'isupper')
+        self.checkequal(False, 'AbC', 'isupper')
+        self.checkequal(True, 'ABC\n', 'isupper')
+        self.checkraises(TypeError, 'abc', 'isupper', 42)
+
+    def test_istitle(self):
+        self.checkequal(False, '', 'istitle')
+        self.checkequal(False, 'a', 'istitle')
+        self.checkequal(True, 'A', 'istitle')
+        self.checkequal(False, '\n', 'istitle')
+        self.checkequal(True, 'A Titlecased Line', 'istitle')
+        self.checkequal(True, 'A\nTitlecased Line', 'istitle')
+        self.checkequal(True, 'A Titlecased, Line', 'istitle')
+        self.checkequal(False, 'Not a capitalized String', 'istitle')
+        self.checkequal(False, 'Not\ta Titlecase String', 'istitle')
+        self.checkequal(False, 'Not--a Titlecase String', 'istitle')
+        self.checkequal(False, 'NOT', 'istitle')
+        self.checkraises(TypeError, 'abc', 'istitle', 42)
+
+    def test_isspace(self):
+        self.checkequal(False, '', 'isspace')
+        self.checkequal(False, 'a', 'isspace')
+        self.checkequal(True, ' ', 'isspace')
+        self.checkequal(True, '\t', 'isspace')
+        self.checkequal(True, '\r', 'isspace')
+        self.checkequal(True, '\n', 'isspace')
+        self.checkequal(True, ' \t\r\n', 'isspace')
+        self.checkequal(False, ' \t\r\na', 'isspace')
+        self.checkraises(TypeError, 'abc', 'isspace', 42)
+
+    def test_isalpha(self):
+        self.checkequal(False, '', 'isalpha')
+        self.checkequal(True, 'a', 'isalpha')
+        self.checkequal(True, 'A', 'isalpha')
+        self.checkequal(False, '\n', 'isalpha')
+        self.checkequal(True, 'abc', 'isalpha')
+        self.checkequal(False, 'aBc123', 'isalpha')
+        self.checkequal(False, 'abc\n', 'isalpha')
+        self.checkraises(TypeError, 'abc', 'isalpha', 42)
+
+    def test_isalnum(self):
+        self.checkequal(False, '', 'isalnum')
+        self.checkequal(True, 'a', 'isalnum')
+        self.checkequal(True, 'A', 'isalnum')
+        self.checkequal(False, '\n', 'isalnum')
+        self.checkequal(True, '123abc456', 'isalnum')
+        self.checkequal(True, 'a1b3c', 'isalnum')
+        self.checkequal(False, 'aBc000 ', 'isalnum')
+        self.checkequal(False, 'abc\n', 'isalnum')
+        self.checkraises(TypeError, 'abc', 'isalnum', 42)
+
+    def test_isdigit(self):
+        self.checkequal(False, '', 'isdigit')
+        self.checkequal(False, 'a', 'isdigit')
+        self.checkequal(True, '0', 'isdigit')
+        self.checkequal(True, '0123456789', 'isdigit')
+        self.checkequal(False, '0123456789a', 'isdigit')
+
+        self.checkraises(TypeError, 'abc', 'isdigit', 42)
+
+    def test_title(self):
+        self.checkequal(' Hello ', ' hello ', 'title')
+        self.checkequal('Hello ', 'hello ', 'title')
+        self.checkequal('Hello ', 'Hello ', 'title')
+        self.checkequal('Format This As Title String', "fOrMaT thIs aS titLe String", 'title')
+        self.checkequal('Format,This-As*Title;String', "fOrMaT,thIs-aS*titLe;String", 'title', )
+        self.checkequal('Getint', "getInt", 'title')
+        self.checkraises(TypeError, 'hello', 'title', 42)
+
+    def test_splitlines(self):
+        self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines')
+        self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines')
+        self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi", 'splitlines')
+        self.checkequal(['abc', 'def', 'ghi'], "abc\ndef\r\nghi\n", 'splitlines')
+        self.checkequal(['abc', 'def', 'ghi', ''], "abc\ndef\r\nghi\n\r", 'splitlines')
+        self.checkequal(['', 'abc', 'def', 'ghi', ''], "\nabc\ndef\r\nghi\n\r", 'splitlines')
+        self.checkequal(['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'], "\nabc\ndef\r\nghi\n\r", 'splitlines', 1)
+
+        self.checkraises(TypeError, 'abc', 'splitlines', 42, 42)
+
+    def test_startswith(self):
+        self.checkequal(True, 'hello', 'startswith', 'he')
+        self.checkequal(True, 'hello', 'startswith', 'hello')
+        self.checkequal(False, 'hello', 'startswith', 'hello world')
+        self.checkequal(True, 'hello', 'startswith', '')
+        self.checkequal(False, 'hello', 'startswith', 'ello')
+        self.checkequal(True, 'hello', 'startswith', 'ello', 1)
+        self.checkequal(True, 'hello', 'startswith', 'o', 4)
+        self.checkequal(False, 'hello', 'startswith', 'o', 5)
+        self.checkequal(True, 'hello', 'startswith', '', 5)
+        self.checkequal(False, 'hello', 'startswith', 'lo', 6)
+        self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3)
+        self.checkequal(True, 'helloworld', 'startswith', 'lowo', 3, 7)
+        self.checkequal(False, 'helloworld', 'startswith', 'lowo', 3, 6)
+
+        # test negative indices
+        self.checkequal(True, 'hello', 'startswith', 'he', 0, -1)
+        self.checkequal(True, 'hello', 'startswith', 'he', -53, -1)
+        self.checkequal(False, 'hello', 'startswith', 'hello', 0, -1)
+        self.checkequal(False, 'hello', 'startswith', 'hello world', -1, -10)
+        self.checkequal(False, 'hello', 'startswith', 'ello', -5)
+        self.checkequal(True, 'hello', 'startswith', 'ello', -4)
+        self.checkequal(False, 'hello', 'startswith', 'o', -2)
+        self.checkequal(True, 'hello', 'startswith', 'o', -1)
+        self.checkequal(True, 'hello', 'startswith', '', -3, -3)
+        self.checkequal(False, 'hello', 'startswith', 'lo', -9)
+
+        self.checkraises(TypeError, 'hello', 'startswith')
+        self.checkraises(TypeError, 'hello', 'startswith', 42)
+
+        # test tuple arguments
+        self.checkequal(True, 'hello', 'startswith', ('he', 'ha'))
+        self.checkequal(False, 'hello', 'startswith', ('lo', 'llo'))
+        self.checkequal(True, 'hello', 'startswith', ('hellox', 'hello'))
+        self.checkequal(False, 'hello', 'startswith', ())
+        self.checkequal(True, 'helloworld', 'startswith', ('hellowo',
+                                                           'rld', 'lowo'), 3)
+        self.checkequal(False, 'helloworld', 'startswith', ('hellowo', 'ello',
+                                                            'rld'), 3)
+        self.checkequal(True, 'hello', 'startswith', ('lo', 'he'), 0, -1)
+        self.checkequal(False, 'hello', 'startswith', ('he', 'hel'), 0, 1)
+        self.checkequal(True, 'hello', 'startswith', ('he', 'hel'), 0, 2)
+
+        self.checkraises(TypeError, 'hello', 'startswith', (42,))
+
+    def test_endswith(self):
+        self.checkequal(True, 'hello', 'endswith', 'lo')
+        self.checkequal(False, 'hello', 'endswith', 'he')
+        self.checkequal(True, 'hello', 'endswith', '')
+        self.checkequal(False, 'hello', 'endswith', 'hello world')
+        self.checkequal(False, 'helloworld', 'endswith', 'worl')
+        self.checkequal(True, 'helloworld', 'endswith', 'worl', 3, 9)
+        self.checkequal(True, 'helloworld', 'endswith', 'world', 3, 12)
+        self.checkequal(True, 'helloworld', 'endswith', 'lowo', 1, 7)
+        self.checkequal(True, 'helloworld', 'endswith', 'lowo', 2, 7)
+        self.checkequal(True, 'helloworld', 'endswith', 'lowo', 3, 7)
+        self.checkequal(False, 'helloworld', 'endswith', 'lowo', 4, 7)
+        self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, 8)
+        self.checkequal(False, 'ab', 'endswith', 'ab', 0, 1)
+        self.checkequal(False, 'ab', 'endswith', 'ab', 0, 0)
+
+        # test negative indices
+        self.checkequal(True, 'hello', 'endswith', 'lo', -2)
+        self.checkequal(False, 'hello', 'endswith', 'he', -2)
+        self.checkequal(True, 'hello', 'endswith', '', -3, -3)
+        self.checkequal(False, 'hello', 'endswith', 'hello world', -10, -2)
+        self.checkequal(False, 'helloworld', 'endswith', 'worl', -6)
+        self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, -1)
+        self.checkequal(True, 'helloworld', 'endswith', 'worl', -5, 9)
+        self.checkequal(True, 'helloworld', 'endswith', 'world', -7, 12)
+        self.checkequal(True, 'helloworld', 'endswith', 'lowo', -99, -3)
+        self.checkequal(True, 'helloworld', 'endswith', 'lowo', -8, -3)
+        self.checkequal(True, 'helloworld', 'endswith', 'lowo', -7, -3)
+        self.checkequal(False, 'helloworld', 'endswith', 'lowo', 3, -4)
+        self.checkequal(False, 'helloworld', 'endswith', 'lowo', -8, -2)
+
+        self.checkraises(TypeError, 'hello', 'endswith')
+        self.checkraises(TypeError, 'hello', 'endswith', 42)
+
+        # test tuple arguments
+        self.checkequal(False, 'hello', 'endswith', ('he', 'ha'))
+        self.checkequal(True, 'hello', 'endswith', ('lo', 'llo'))
+        self.checkequal(True, 'hello', 'endswith', ('hellox', 'hello'))
+        self.checkequal(False, 'hello', 'endswith', ())
+        self.checkequal(True, 'helloworld', 'endswith', ('hellowo',
+                                                           'rld', 'lowo'), 3)
+        self.checkequal(False, 'helloworld', 'endswith', ('hellowo', 'ello',
+                                                            'rld'), 3, -1)
+        self.checkequal(True, 'hello', 'endswith', ('hell', 'ell'), 0, -1)
+        self.checkequal(False, 'hello', 'endswith', ('he', 'hel'), 0, 1)
+        self.checkequal(True, 'hello', 'endswith', ('he', 'hell'), 0, 4)
+
+        self.checkraises(TypeError, 'hello', 'endswith', (42,))
+
+    def test___contains__(self):
+        self.checkop(True, operator.contains, '', '')         # vereq('' in '', True)
+        self.checkop(True, operator.contains, 'abc', '')      # vereq('' in 'abc', True)
+        self.checkop(False, operator.contains, 'abc', '\0')   # vereq('\0' in 'abc', False)
+        self.checkop(True, operator.contains, '\0abc', '\0')  # vereq('\0' in '\0abc', True)
+        self.checkop(True, operator.contains, 'abc\0', '\0')  # vereq('\0' in 'abc\0', True)
+        self.checkop(True, operator.contains, '\0abc', 'a')   # vereq('a' in '\0abc', True)
+        self.checkop(True, operator.contains, 'asdf', 'asdf') # vereq('asdf' in 'asdf', True)
+        self.checkop(False, operator.contains, 'asd', 'asdf') # vereq('asdf' in 'asd', False)
+        self.checkop(False, operator.contains, '', 'asdf')    # vereq('asdf' in '', False)
+
+    def test_subscript(self):
+        self.checkop(u'a', operator.getitem, 'abc', 0)
+        self.checkop(u'c', operator.getitem, 'abc', -1)
+        self.checkop(u'a', operator.getitem, 'abc', 0L)
+        self.checkop(u'abc', operator.getitem, 'abc', slice(0, 3))
+        self.checkop(u'abc', operator.getitem, 'abc', slice(0, 1000))
+        self.checkop(u'a', operator.getitem, 'abc', slice(0, 1))
+        self.checkop(u'', operator.getitem, 'abc', slice(0, 0))
+        # FIXME What about negative indizes? This is handled differently by [] and __getitem__(slice)
+
+        self.checkopraises(TypeError, operator.getitem, 'abc', 'def')
+
+    def test_slice(self):
+        self.checkop('abc', operator.getslice, 'abc', 0, 1000)
+        self.checkop('abc', operator.getslice, 'abc', 0, 3)
+        self.checkop('ab', operator.getslice, 'abc', 0, 2)
+        self.checkop('bc', operator.getslice, 'abc', 1, 3)
+        self.checkop('b', operator.getslice, 'abc', 1, 2)
+        self.checkop('', operator.getslice, 'abc', 2, 2)
+        self.checkop('', operator.getslice, 'abc', 1000, 1000)
+        self.checkop('', operator.getslice, 'abc', 2000, 1000)
+        self.checkop('', operator.getslice, 'abc', 2, 1)
+        # FIXME What about negative indizes? This is handled differently by [] and __getslice__
+
+        self.checkopraises(TypeError, operator.getslice, 'abc', 'def')
+
+    def test_mul(self):
+        self.checkop('', operator.mul, 'abc', -1)
+        self.checkop('', operator.mul, 'abc', 0)
+        self.checkop('abc', operator.mul, 'abc', 1)
+        self.checkop('abcabcabc', operator.mul, 'abc', 3)
+        self.checkopraises(TypeError, operator.mul, 'abc')
+        self.checkopraises(TypeError, operator.mul, 'abc', '')
+        self.checkopraises(OverflowError, operator.mul, 10000*'abc', 2000000000)
+        # XXX: on a 64-bit system, this doesn't raise an overflow error,
+        # but either raises a MemoryError, or succeeds (if you have 54TiB)
+        #self.checkraises(OverflowError, 10000*'abc', '__mul__', 2000000000)
+
+    def test_join(self):
+        # join now works with any sequence type
+        # moved here, because the argument order is
+        # different in string.join (see the test in
+        # test.test_string.StringTest.test_join)
+        self.checkequal('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
+        self.checkequal('abcd', '', 'join', ('a', 'b', 'c', 'd'))
+        self.checkequal('bd', '', 'join', ('', 'b', '', 'd'))
+        self.checkequal('ac', '', 'join', ('a', '', 'c', ''))
+        self.checkequal('w x y z', ' ', 'join', Sequence())
+        self.checkequal('abc', 'a', 'join', ('abc',))
+        self.checkequal('z', 'a', 'join', UserList(['z']))
+        if test_support.have_unicode:
+            self.checkequal(unicode('a.b.c'), unicode('.'), 'join', ['a', 'b', 'c'])
+            self.checkequal(unicode('a.b.c'), '.', 'join', [unicode('a'), 'b', 'c'])
+            self.checkequal(unicode('a.b.c'), '.', 'join', ['a', unicode('b'), 'c'])
+            self.checkequal(unicode('a.b.c'), '.', 'join', ['a', 'b', unicode('c')])
+            self.checkraises(TypeError, '.', 'join', ['a', unicode('b'), 3])
+        for i in [5, 25, 125]:
+            self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
+                 ['a' * i] * i)
+            self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join',
+                 ('a' * i,) * i)
+
+        self.checkraises(TypeError, ' ', 'join', BadSeq1())
+        self.checkequal('a b c', ' ', 'join', BadSeq2())
+
+        self.checkraises(TypeError, ' ', 'join')
+        self.checkraises(TypeError, ' ', 'join', 7)
+        self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123L]))
+        try:
+            def f():
+                yield 4 + ""
+            self.fixtype(' ').join(f())
+        except TypeError, e:
+            if '+' not in str(e):
+                self.fail('join() ate exception message')
+        else:
+            self.fail('exception not raised')
+
+    def test_formatting(self):
+        self.checkop('+hello+', operator.mod, '+%s+', 'hello')
+        self.checkop('+10+', operator.mod, '+%d+', 10)
+        self.checkop('a', operator.mod, "%c", "a")
+        self.checkop('a', operator.mod, "%c", "a")
+        self.checkop('"', operator.mod, "%c", 34)
+        self.checkop('$', operator.mod, "%c", 36)
+        self.checkop('10', operator.mod, "%d", 10)
+        self.checkop('\x7f', operator.mod, "%c", 0x7f)
+
+        for ordinal in (-100, 0x200000):
+            # unicode raises ValueError, str raises OverflowError
+            self.checkopraises((ValueError, OverflowError), operator.mod, '%c', ordinal)
+
+        self.checkop(' 42', operator.mod, '%3ld', 42)
+        self.checkop('0042.00', operator.mod, '%07.2f', 42)
+        self.checkop('0042.00', operator.mod, '%07.2F', 42)
+
+        self.checkopraises(TypeError, operator.mod, 'abc')
+        self.checkopraises(TypeError, operator.mod, '%(foo)s', 42)
+        self.checkopraises(TypeError, operator.mod, '%s%s', (42,))
+        self.checkopraises(TypeError, operator.mod, '%c', (None,))
+        self.checkopraises(ValueError, operator.mod, '%(foo', {})
+        self.checkopraises(TypeError, operator.mod, '%(foo)s %(bar)s', ('foo', 42))
+
+        # argument names with properly nested brackets are supported
+        self.checkop('bar', operator.mod, '%((foo))s', {'(foo)': 'bar'})
+
+        # 100 is a magic number in PyUnicode_Format, this forces a resize
+        self.checkop(103*'a'+'x', operator.mod, '%sx', 103*'a')
+
+        self.checkopraises(TypeError, operator.mod, '%*s', ('foo', 'bar'))
+        self.checkopraises(TypeError, operator.mod, '%10.*f', ('foo', 42.))
+        self.checkopraises(ValueError, operator.mod, '%10', (42,))
+
+    def test_floatformatting(self):
+        # float formatting
+        # XXX changed for PyPy to be faster
+        for prec, value in [(0, 3.141592655),
+                            (1, 0.01),
+                            (2, 120394),
+                            (5, 23.01958),
+                            (20, 141414.51321098),
+                            (49, 0.01),
+                            (50, 1e50),
+                            (99, 123)]:
+            format = '%%.%if' % prec
+            try:
+                self.checkopcall(operator.mod, format, value)
+            except OverflowError:
+                self.failUnless(abs(value) < 1e25 and prec >= 67,
+                                "OverflowError on small examples")
+                
+    def test_inplace_rewrites(self):
+        # Check that strings don't copy and modify cached single-character strings
+        self.checkequal('a', 'A', 'lower')
+        self.checkequal(True, 'A', 'isupper')
+        self.checkequal('A', 'a', 'upper')
+        self.checkequal(True, 'a', 'islower')
+
+        self.checkequal('a', 'A', 'replace', 'A', 'a')
+        self.checkequal(True, 'A', 'isupper')
+
+        self.checkequal('A', 'a', 'capitalize')
+        self.checkequal(True, 'a', 'islower')
+
+        self.checkequal('A', 'a', 'swapcase')
+        self.checkequal(True, 'a', 'islower')
+
+        self.checkequal('A', 'a', 'title')
+        self.checkequal(True, 'a', 'islower')
+
+    def test_partition(self):
+
+        self.checkequal(('this is the par', 'ti', 'tion method'),
+            'this is the partition method', 'partition', 'ti')
+
+        # from raymond's original specification
+        S = 'http://www.python.org'
+        self.checkequal(('http', '://', 'www.python.org'), S, 'partition', '://')
+        self.checkequal(('http://www.python.org', '', ''), S, 'partition', '?')
+        self.checkequal(('', 'http://', 'www.python.org'), S, 'partition', 'http://')
+        self.checkequal(('http://www.python.', 'org', ''), S, 'partition', 'org')
+
+        self.checkraises(ValueError, S, 'partition', '')
+        self.checkraises(TypeError, S, 'partition', None)
+
+    def test_rpartition(self):
+
+        self.checkequal(('this is the rparti', 'ti', 'on method'),
+            'this is the rpartition method', 'rpartition', 'ti')
+
+        # from raymond's original specification
+        S = 'http://www.python.org'
+        self.checkequal(('http', '://', 'www.python.org'), S, 'rpartition', '://')
+        self.checkequal(('', '', 'http://www.python.org'), S, 'rpartition', '?')
+        self.checkequal(('', 'http://', 'www.python.org'), S, 'rpartition', 'http://')
+        self.checkequal(('http://www.python.', 'org', ''), S, 'rpartition', 'org')
+
+        self.checkraises(ValueError, S, 'rpartition', '')
+        self.checkraises(TypeError, S, 'rpartition', None)
+
+
+class MixinStrStringUserStringTest:
+    # Additional tests for 8bit strings, i.e. str, UserString and
+    # the string module
+
+    def test_maketrans(self):
+        self.assertEqual(
+           ''.join(map(chr, xrange(256))).replace('abc', 'xyz'),
+           string.maketrans('abc', 'xyz')
+        )
+        self.assertRaises(ValueError, string.maketrans, 'abc', 'xyzw')
+
+    def test_translate(self):
+        table = string.maketrans('abc', 'xyz')
+        self.checkequal('xyzxyz', 'xyzabcdef', 'translate', table, 'def')
+
+        table = string.maketrans('a', 'A')
+        self.checkequal('Abc', 'abc', 'translate', table)
+        self.checkequal('xyz', 'xyz', 'translate', table)
+        self.checkequal('yz', 'xyz', 'translate', table, 'x')
+        self.checkraises(ValueError, 'xyz', 'translate', 'too short', 'strip')
+        self.checkraises(ValueError, 'xyz', 'translate', 'too short')
+
+
+class MixinStrUserStringTest:
+    # Additional tests that only work with
+    # 8bit compatible object, i.e. str and UserString
+
+    if test_support.have_unicode:
+        def test_encoding_decoding(self):
+            codecs = [('rot13', 'uryyb jbeyq'),
+                      ('base64', 'aGVsbG8gd29ybGQ=\n'),
+                      ('hex', '68656c6c6f20776f726c64'),
+                      ('uu', 'begin 666 <data>\n+:&5L;&\\@=V]R;&0 \n \nend\n')]
+            for encoding, data in codecs:
+                self.checkequal(data, 'hello world', 'encode', encoding)
+                self.checkequal('hello world', data, 'decode', encoding)
+            # zlib is optional, so we make the test optional too...
+            try:
+                import zlib
+            except ImportError:
+                pass
+            else:
+                data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]'
+                self.checkequal(data, 'hello world', 'encode', 'zlib')
+                self.checkequal('hello world', data, 'decode', 'zlib')
+
+            self.checkraises(TypeError, 'xyz', 'decode', 42)
+            self.checkraises(TypeError, 'xyz', 'encode', 42)
+
+
+class MixinStrUnicodeTest:
+    # Additional tests that only work with str and unicode.
+
+    def test_bug1001011(self):
+        # Make sure join returns a NEW object for single item sequences
+        # involving a subclass.
+        # Make sure that it is of the appropriate type.
+        # Check the optimisation still occurs for standard objects.
+        t = self.type2test
+        class subclass(t):
+            pass
+        s1 = subclass("abcd")
+        s2 = t().join([s1])
+        self.assert_(s1 is not s2)
+        self.assert_(type(s2) is t)
+
+
+        # XXX impl. specific optimisation
+        #s1 = t("abcd")
+        #s2 = t().join([s1])
+        #self.assert_(s1 is s2)
+
+        # Should also test mixed-type join.
+        if t is unicode:
+            s1 = subclass("abcd")
+            s2 = "".join([s1])
+            self.assert_(s1 is not s2)
+            self.assert_(type(s2) is t)
+
+            # XXX impl. specific opt.
+            #s1 = t("abcd")
+            #s2 = "".join([s1])
+            #self.assert_(s1 is s2)
+
+        elif t is str:
+            s1 = subclass("abcd")
+            s2 = u"".join([s1])
+            self.assert_(s1 is not s2)
+            self.assert_(type(s2) is unicode) # promotes!
+
+            s1 = t("abcd")
+            s2 = u"".join([s1])
+            self.assert_(s1 is not s2)
+            self.assert_(type(s2) is unicode) # promotes!
+
+        else:
+            self.fail("unexpected type for MixinStrUnicodeTest %r" % t)

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test___all__.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test___all__.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,200 @@
+import unittest
+from test import test_support
+
+from test.test_support import verify, verbose
+import sys
+import warnings
+
+warnings.filterwarnings("ignore",
+                        "the gopherlib module is deprecated",
+                        DeprecationWarning,
+                        "<string>")
+
+class AllTest(unittest.TestCase):
+
+    def check_all(self, modname):
+        names = {}
+        original_sys_modules = sys.modules.copy()
+        try:
+            exec "import %s" % modname in names
+        except ImportError:
+            # Silent fail here seems the best route since some modules
+            # may not be available in all environments.
+            # We restore sys.modules to avoid leaving broken modules behind,
+            # but we must not remove built-in modules from sys.modules
+            # (because they can't be re-imported, typically)
+            for name in sys.modules.keys():
+                if name in original_sys_modules:
+                    continue
+                # XXX hackish
+                mod = sys.modules[name]
+                if not hasattr(mod, '__file__'):
+                    continue
+                if (mod.__file__.lower().endswith('.py') or
+                    mod.__file__.lower().endswith('.pyc') or
+                    mod.__file__.lower().endswith('.pyo')):
+                    del sys.modules[name]
+            return
+        verify(hasattr(sys.modules[modname], "__all__"),
+               "%s has no __all__ attribute" % modname)
+        names = {}
+        exec "from %s import *" % modname in names
+        if names.has_key("__builtins__"):
+            del names["__builtins__"]
+        keys = set(names)
+        all = set(sys.modules[modname].__all__)
+        verify(keys==all, "%s != %s" % (keys, all))
+
+    def test_all(self):
+        if not sys.platform.startswith('java'):
+            # In case _socket fails to build, make this test fail more gracefully
+            # than an AttributeError somewhere deep in CGIHTTPServer.
+            import _socket
+
+        self.check_all("BaseHTTPServer")
+        self.check_all("Bastion")
+        self.check_all("CGIHTTPServer")
+        self.check_all("ConfigParser")
+        self.check_all("Cookie")
+        self.check_all("MimeWriter")
+        self.check_all("Queue")
+        self.check_all("SimpleHTTPServer")
+        self.check_all("SocketServer")
+        self.check_all("StringIO")
+        self.check_all("UserString")
+        self.check_all("aifc")
+        self.check_all("atexit")
+        self.check_all("audiodev")
+        self.check_all("base64")
+        self.check_all("bdb")
+        self.check_all("binhex")
+        self.check_all("calendar")
+        self.check_all("cgi")
+        self.check_all("cmd")
+        self.check_all("code")
+        self.check_all("codecs")
+        self.check_all("codeop")
+        self.check_all("colorsys")
+        self.check_all("commands")
+        self.check_all("compileall")
+        self.check_all("copy")
+        self.check_all("copy_reg")
+        self.check_all("csv")
+        self.check_all("dbhash")
+        self.check_all("decimal")
+        self.check_all("difflib")
+        self.check_all("dircache")
+        self.check_all("dis")
+        self.check_all("doctest")
+        self.check_all("dummy_thread")
+        self.check_all("dummy_threading")
+        self.check_all("filecmp")
+        self.check_all("fileinput")
+        self.check_all("fnmatch")
+        self.check_all("fpformat")
+        self.check_all("ftplib")
+        self.check_all("getopt")
+        self.check_all("getpass")
+        self.check_all("gettext")
+        self.check_all("glob")
+        self.check_all("gopherlib")
+        self.check_all("gzip")
+        self.check_all("heapq")
+        self.check_all("htmllib")
+        self.check_all("httplib")
+        self.check_all("ihooks")
+        self.check_all("imaplib")
+        self.check_all("imghdr")
+        self.check_all("imputil")
+        self.check_all("keyword")
+        self.check_all("linecache")
+        self.check_all("locale")
+        self.check_all("macpath")
+        self.check_all("macurl2path")
+        self.check_all("mailbox")
+        self.check_all("mailcap")
+        self.check_all("mhlib")
+        self.check_all("mimetools")
+        self.check_all("mimetypes")
+        self.check_all("mimify")
+        self.check_all("multifile")
+        self.check_all("netrc")
+        self.check_all("nntplib")
+        self.check_all("ntpath")
+        self.check_all("opcode")
+        self.check_all("optparse")
+        self.check_all("os")
+        self.check_all("os2emxpath")
+        self.check_all("pdb")
+        self.check_all("pickle")
+        self.check_all("pickletools")
+        self.check_all("pipes")
+        self.check_all("popen2")
+        self.check_all("poplib")
+        self.check_all("posixpath")
+        self.check_all("pprint")
+        self.check_all("profile")
+        self.check_all("pstats")
+        self.check_all("pty")
+        self.check_all("py_compile")
+        self.check_all("pyclbr")
+        self.check_all("quopri")
+        self.check_all("random")
+        self.check_all("re")
+        self.check_all("repr")
+        self.check_all("rexec")
+        self.check_all("rfc822")
+        self.check_all("rlcompleter")
+        self.check_all("robotparser")
+        self.check_all("sched")
+        self.check_all("sets")
+        self.check_all("sgmllib")
+        self.check_all("shelve")
+        self.check_all("shlex")
+        self.check_all("shutil")
+        self.check_all("smtpd")
+        self.check_all("smtplib")
+        self.check_all("sndhdr")
+        self.check_all("socket")
+        self.check_all("_strptime")
+        self.check_all("symtable")
+        self.check_all("tabnanny")
+        self.check_all("tarfile")
+        self.check_all("telnetlib")
+        self.check_all("tempfile")
+        self.check_all("textwrap")
+        self.check_all("threading")
+        self.check_all("timeit")
+        self.check_all("toaiff")
+        self.check_all("tokenize")
+        self.check_all("traceback")
+        self.check_all("tty")
+        self.check_all("unittest")
+        self.check_all("urllib")
+        self.check_all("urlparse")
+        self.check_all("uu")
+        self.check_all("warnings")
+        self.check_all("wave")
+        self.check_all("weakref")
+        self.check_all("webbrowser")
+        self.check_all("xdrlib")
+        self.check_all("zipfile")
+
+        # rlcompleter needs special consideration; it import readline which
+        # initializes GNU readline which calls setlocale(LC_CTYPE, "")... :-(
+        try:
+            self.check_all("rlcompleter")
+        finally:
+            try:
+                import locale
+            except ImportError:
+                pass
+            else:
+                locale.setlocale(locale.LC_CTYPE, 'C')
+
+
+def test_main():
+    test_support.run_unittest(AllTest)
+
+if __name__ == "__main__":
+    test_main()

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_array.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_array.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,1002 @@
+#! /usr/bin/env python
+"""Test the arraymodule.
+   Roger E. Masse
+"""
+
+import unittest
+from test import test_support
+#from weakref import proxy
+import array, cStringIO, math
+from cPickle import loads, dumps
+
+# XXX as we use the struct module we get struct.error when trying to push
+# objects of invalid types or out of range into an array.  If this issue
+# is fixed, remove all mentions of struct.error in the sequel.
+import struct
+
+class ArraySubclass(array.array):
+    pass
+
+class ArraySubclassWithKwargs(array.array):
+    def __init__(self, typecode, newarg=None):
+        array.array.__init__(typecode)
+
+tests = [] # list to accumulate all tests
+typecodes = "cubBhHiIlLfd"
+
+class BadConstructorTest(unittest.TestCase):
+
+    def test_constructor(self):
+        self.assertRaises(TypeError, array.array)
+        self.assertRaises(TypeError, array.array, spam=42)
+        self.assertRaises(TypeError, array.array, 'xx')
+        self.assertRaises(ValueError, array.array, 'x')
+
+tests.append(BadConstructorTest)
+
+class BaseTest(unittest.TestCase):
+    # Required class attributes (provided by subclasses
+    # typecode: the typecode to test
+    # example: an initializer usable in the constructor for this type
+    # smallerexample: the same length as example, but smaller
+    # biggerexample: the same length as example, but bigger
+    # outside: An entry that is not in example
+    # minitemsize: the minimum guaranteed itemsize
+
+    def assertEntryEqual(self, entry1, entry2):
+        self.assertEqual(entry1, entry2)
+
+    def badtypecode(self):
+        # Return a typecode that is different from our own
+        return typecodes[(typecodes.index(self.typecode)+1) % len(typecodes)]
+
+    def test_constructor(self):
+        a = array.array(self.typecode)
+        self.assertEqual(a.typecode, self.typecode)
+        self.assert_(a.itemsize>=self.minitemsize)
+        self.assertRaises(TypeError, array.array, self.typecode, None)
+
+    def test_len(self):
+        a = array.array(self.typecode)
+        a.append(self.example[0])
+        self.assertEqual(len(a), 1)
+
+        a = array.array(self.typecode, self.example)
+        self.assertEqual(len(a), len(self.example))
+
+    def test_buffer_info(self):
+        a = array.array(self.typecode, self.example)
+        self.assertRaises(TypeError, a.buffer_info, 42)
+        bi = a.buffer_info()
+        self.assert_(isinstance(bi, tuple))
+        self.assertEqual(len(bi), 2)
+        self.assert_(isinstance(bi[0], (int, long)))
+        self.assert_(isinstance(bi[1], int))
+        self.assertEqual(bi[1], len(a))
+
+    def test_byteswap(self):
+        a = array.array(self.typecode, self.example)
+        self.assertRaises(TypeError, a.byteswap, 42)
+        if a.itemsize in (1, 2, 4, 8):
+            b = array.array(self.typecode, self.example)
+            b.byteswap()
+            if a.itemsize==1:
+                self.assertEqual(a, b)
+            else:
+                self.assertNotEqual(a, b)
+            b.byteswap()
+            self.assertEqual(a, b)
+
+    def test_copy(self):
+        import copy
+        a = array.array(self.typecode, self.example)
+        b = copy.copy(a)
+        self.assertNotEqual(id(a), id(b))
+        self.assertEqual(a, b)
+
+    def test_deepcopy(self):
+        import copy
+        a = array.array(self.typecode, self.example)
+        b = copy.deepcopy(a)
+        self.assertNotEqual(id(a), id(b))
+        self.assertEqual(a, b)
+
+    def test_pickle(self):
+        for protocol in (0, 1, 2):
+            a = array.array(self.typecode, self.example)
+            b = loads(dumps(a, protocol))
+            self.assertNotEqual(id(a), id(b))
+            self.assertEqual(a, b)
+
+            a = ArraySubclass(self.typecode, self.example)
+            a.x = 10
+            b = loads(dumps(a, protocol))
+            self.assertNotEqual(id(a), id(b))
+            self.assertEqual(a, b)
+            self.assertEqual(a.x, b.x)
+            self.assertEqual(type(a), type(b))
+
+    def test_pickle_for_empty_array(self):
+        for protocol in (0, 1, 2):
+            a = array.array(self.typecode)
+            b = loads(dumps(a, protocol))
+            self.assertNotEqual(id(a), id(b))
+            self.assertEqual(a, b)
+
+            a = ArraySubclass(self.typecode)
+            a.x = 10
+            b = loads(dumps(a, protocol))
+            self.assertNotEqual(id(a), id(b))
+            self.assertEqual(a, b)
+            self.assertEqual(a.x, b.x)
+            self.assertEqual(type(a), type(b))
+
+    def test_insert(self):
+        a = array.array(self.typecode, self.example)
+        a.insert(0, self.example[0])
+        self.assertEqual(len(a), 1+len(self.example))
+        self.assertEqual(a[0], a[1])
+        self.assertRaises(TypeError, a.insert)
+        self.assertRaises(TypeError, a.insert, None)
+        self.assertRaises((TypeError, struct.error), a.insert, 0, None)
+
+        a = array.array(self.typecode, self.example)
+        a.insert(-1, self.example[0])
+        self.assertEqual(
+            a,
+            array.array(
+                self.typecode,
+                self.example[:-1] + self.example[:1] + self.example[-1:]
+            )
+        )
+
+        a = array.array(self.typecode, self.example)
+        a.insert(-1000, self.example[0])
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example[:1] + self.example)
+        )
+
+        a = array.array(self.typecode, self.example)
+        a.insert(1000, self.example[0])
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example + self.example[:1])
+        )
+
+    def test_tofromfile(self):
+        a = array.array(self.typecode, 2*self.example)
+        self.assertRaises(TypeError, a.tofile)
+        self.assertRaises(TypeError, a.tofile, cStringIO.StringIO())
+        f = open(test_support.TESTFN, 'wb')
+        try:
+            a.tofile(f)
+            f.close()
+            b = array.array(self.typecode)
+            f = open(test_support.TESTFN, 'rb')
+            self.assertRaises(TypeError, b.fromfile)
+            self.assertRaises(
+                TypeError,
+                b.fromfile,
+                cStringIO.StringIO(), len(self.example)
+            )
+            b.fromfile(f, len(self.example))
+            self.assertEqual(b, array.array(self.typecode, self.example))
+            self.assertNotEqual(a, b)
+            b.fromfile(f, len(self.example))
+            self.assertEqual(a, b)
+            self.assertRaises(EOFError, b.fromfile, f, 1)
+            f.close()
+        finally:
+            if not f.closed:
+                f.close()
+            test_support.unlink(test_support.TESTFN)
+
+    def test_tofromlist(self):
+        a = array.array(self.typecode, 2*self.example)
+        b = array.array(self.typecode)
+        self.assertRaises(TypeError, a.tolist, 42)
+        self.assertRaises(TypeError, b.fromlist)
+        self.assertRaises(TypeError, b.fromlist, 42)
+        self.assertRaises((TypeError, struct.error), b.fromlist, [None])
+        b.fromlist(a.tolist())
+        self.assertEqual(a, b)
+
+    def test_tofromstring(self):
+        a = array.array(self.typecode, 2*self.example)
+        b = array.array(self.typecode)
+        self.assertRaises(TypeError, a.tostring, 42)
+        self.assertRaises(TypeError, b.fromstring)
+        self.assertRaises(TypeError, b.fromstring, 42)
+        b.fromstring(a.tostring())
+        self.assertEqual(a, b)
+        if a.itemsize>1:
+            self.assertRaises(ValueError, b.fromstring, "x")
+
+    def test_repr(self):
+        a = array.array(self.typecode, 2*self.example)
+        self.assertEqual(a, eval(repr(a), {"array": array.array}))
+
+        a = array.array(self.typecode)
+        self.assertEqual(repr(a), "array('%s')" % self.typecode)
+
+    def test_str(self):
+        a = array.array(self.typecode, 2*self.example)
+        str(a)
+
+    def test_cmp(self):
+        a = array.array(self.typecode, self.example)
+        self.assert_((a == 42) is False)
+        self.assert_((a != 42) is True)
+
+        self.assert_((a == a) is True)
+        self.assert_((a != a) is False)
+        self.assert_((a < a) is False)
+        self.assert_((a <= a) is True)
+        self.assert_((a > a) is False)
+        self.assert_((a >= a) is True)
+
+        al = array.array(self.typecode, self.smallerexample)
+        ab = array.array(self.typecode, self.biggerexample)
+
+        self.assert_((a == 2*a) is False)
+        self.assert_((a != 2*a) is True)
+        self.assert_((a < 2*a) is True)
+        self.assert_((a <= 2*a) is True)
+        self.assert_((a > 2*a) is False)
+        self.assert_((a >= 2*a) is False)
+
+        self.assert_((a == al) is False)
+        self.assert_((a != al) is True)
+        self.assert_((a < al) is False)
+        self.assert_((a <= al) is False)
+        self.assert_((a > al) is True)
+        self.assert_((a >= al) is True)
+
+        self.assert_((a == ab) is False)
+        self.assert_((a != ab) is True)
+        self.assert_((a < ab) is True)
+        self.assert_((a <= ab) is True)
+        self.assert_((a > ab) is False)
+        self.assert_((a >= ab) is False)
+
+    def test_add(self):
+        a = array.array(self.typecode, self.example) \
+            + array.array(self.typecode, self.example[::-1])
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example + self.example[::-1])
+        )
+
+        b = array.array(self.badtypecode())
+        self.assertRaises(TypeError, a.__add__, b)
+
+        self.assertRaises(TypeError, a.__add__, "bad")
+
+    def test_iadd(self):
+        a = array.array(self.typecode, self.example[::-1])
+        b = a
+        a += array.array(self.typecode, 2*self.example)
+        self.assert_(a is b)
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example[::-1]+2*self.example)
+        )
+
+        b = array.array(self.badtypecode())
+        self.assertRaises(TypeError, a.__add__, b)
+
+        self.assertRaises(TypeError, a.__iadd__, "bad")
+
+    def test_mul(self):
+        a = 5*array.array(self.typecode, self.example)
+        self.assertEqual(
+            a,
+            array.array(self.typecode, 5*self.example)
+        )
+
+        a = array.array(self.typecode, self.example)*5
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example*5)
+        )
+
+        a = 0*array.array(self.typecode, self.example)
+        self.assertEqual(
+            a,
+            array.array(self.typecode)
+        )
+
+        a = (-1)*array.array(self.typecode, self.example)
+        self.assertEqual(
+            a,
+            array.array(self.typecode)
+        )
+
+        self.assertRaises(TypeError, a.__mul__, "bad")
+
+    def test_imul(self):
+        a = array.array(self.typecode, self.example)
+        b = a
+
+        a *= 5
+        self.assert_(a is b)
+        self.assertEqual(
+            a,
+            array.array(self.typecode, 5*self.example)
+        )
+
+        a *= 0
+        self.assert_(a is b)
+        self.assertEqual(a, array.array(self.typecode))
+
+        a *= 1000
+        self.assert_(a is b)
+        self.assertEqual(a, array.array(self.typecode))
+
+        a *= -1
+        self.assert_(a is b)
+        self.assertEqual(a, array.array(self.typecode))
+
+        a = array.array(self.typecode, self.example)
+        a *= -1
+        self.assertEqual(a, array.array(self.typecode))
+
+        self.assertRaises(TypeError, a.__imul__, "bad")
+
+    def test_getitem(self):
+        a = array.array(self.typecode, self.example)
+        self.assertEntryEqual(a[0], self.example[0])
+        self.assertEntryEqual(a[0L], self.example[0])
+        self.assertEntryEqual(a[-1], self.example[-1])
+        self.assertEntryEqual(a[-1L], self.example[-1])
+        self.assertEntryEqual(a[len(self.example)-1], self.example[-1])
+        self.assertEntryEqual(a[-len(self.example)], self.example[0])
+        self.assertRaises(TypeError, a.__getitem__)
+        self.assertRaises(IndexError, a.__getitem__, len(self.example))
+        self.assertRaises(IndexError, a.__getitem__, -len(self.example)-1)
+
+    def test_setitem(self):
+        a = array.array(self.typecode, self.example)
+        a[0] = a[-1]
+        self.assertEntryEqual(a[0], a[-1])
+
+        a = array.array(self.typecode, self.example)
+        a[0L] = a[-1]
+        self.assertEntryEqual(a[0], a[-1])
+
+        a = array.array(self.typecode, self.example)
+        a[-1] = a[0]
+        self.assertEntryEqual(a[0], a[-1])
+
+        a = array.array(self.typecode, self.example)
+        a[-1L] = a[0]
+        self.assertEntryEqual(a[0], a[-1])
+
+        a = array.array(self.typecode, self.example)
+        a[len(self.example)-1] = a[0]
+        self.assertEntryEqual(a[0], a[-1])
+
+        a = array.array(self.typecode, self.example)
+        a[-len(self.example)] = a[-1]
+        self.assertEntryEqual(a[0], a[-1])
+
+        self.assertRaises(TypeError, a.__setitem__)
+        self.assertRaises(TypeError, a.__setitem__, None)
+        self.assertRaises((TypeError, struct.error), a.__setitem__, 0, None)
+        self.assertRaises(
+            IndexError,
+            a.__setitem__,
+            len(self.example), self.example[0]
+        )
+        self.assertRaises(
+            IndexError,
+            a.__setitem__,
+            -len(self.example)-1, self.example[0]
+        )
+
+    def test_delitem(self):
+        a = array.array(self.typecode, self.example)
+        del a[0]
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example[1:])
+        )
+
+        a = array.array(self.typecode, self.example)
+        del a[-1]
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example[:-1])
+        )
+
+        a = array.array(self.typecode, self.example)
+        del a[len(self.example)-1]
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example[:-1])
+        )
+
+        a = array.array(self.typecode, self.example)
+        del a[-len(self.example)]
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example[1:])
+        )
+
+        self.assertRaises(TypeError, a.__delitem__)
+        self.assertRaises(TypeError, a.__delitem__, None)
+        self.assertRaises(IndexError, a.__delitem__, len(self.example))
+        self.assertRaises(IndexError, a.__delitem__, -len(self.example)-1)
+
+    def test_getslice(self):
+        a = array.array(self.typecode, self.example)
+        self.assertEqual(a[:], a)
+
+        self.assertEqual(
+            a[1:],
+            array.array(self.typecode, self.example[1:])
+        )
+
+        self.assertEqual(
+            a[:1],
+            array.array(self.typecode, self.example[:1])
+        )
+
+        self.assertEqual(
+            a[:-1],
+            array.array(self.typecode, self.example[:-1])
+        )
+
+        self.assertEqual(
+            a[-1:],
+            array.array(self.typecode, self.example[-1:])
+        )
+
+        self.assertEqual(
+            a[-1:-1],
+            array.array(self.typecode)
+        )
+
+        self.assertEqual(
+            a[2:1],
+            array.array(self.typecode)
+        )
+
+        self.assertEqual(
+            a[1000:],
+            array.array(self.typecode)
+        )
+        self.assertEqual(a[-1000:], a)
+        self.assertEqual(a[:1000], a)
+        self.assertEqual(
+            a[:-1000],
+            array.array(self.typecode)
+        )
+        self.assertEqual(a[-1000:1000], a)
+        self.assertEqual(
+            a[2000:1000],
+            array.array(self.typecode)
+        )
+
+    def test_setslice(self):
+        a = array.array(self.typecode, self.example)
+        a[:1] = a
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example + self.example[1:])
+        )
+
+        a = array.array(self.typecode, self.example)
+        a[:-1] = a
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example + self.example[-1:])
+        )
+
+        a = array.array(self.typecode, self.example)
+        a[-1:] = a
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example[:-1] + self.example)
+        )
+
+        a = array.array(self.typecode, self.example)
+        a[1:] = a
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example[:1] + self.example)
+        )
+
+        a = array.array(self.typecode, self.example)
+        a[1:-1] = a
+        self.assertEqual(
+            a,
+            array.array(
+                self.typecode,
+                self.example[:1] + self.example + self.example[-1:]
+            )
+        )
+
+        a = array.array(self.typecode, self.example)
+        a[1000:] = a
+        self.assertEqual(
+            a,
+            array.array(self.typecode, 2*self.example)
+        )
+
+        a = array.array(self.typecode, self.example)
+        a[-1000:] = a
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example)
+        )
+
+        a = array.array(self.typecode, self.example)
+        a[:1000] = a
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example)
+        )
+
+        a = array.array(self.typecode, self.example)
+        a[:-1000] = a
+        self.assertEqual(
+            a,
+            array.array(self.typecode, 2*self.example)
+        )
+
+        a = array.array(self.typecode, self.example)
+        a[1:0] = a
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example[:1] + self.example + self.example[1:])
+        )
+
+        a = array.array(self.typecode, self.example)
+        a[2000:1000] = a
+        self.assertEqual(
+            a,
+            array.array(self.typecode, 2*self.example)
+        )
+
+        a = array.array(self.typecode, self.example)
+        self.assertRaises(TypeError, a.__setslice__, 0, 0, None)
+        self.assertRaises(TypeError, a.__setitem__, slice(0, 1), None)
+
+        b = array.array(self.badtypecode())
+        self.assertRaises(TypeError, a.__setslice__, 0, 0, b)
+        self.assertRaises(TypeError, a.__setitem__, slice(0, 1), b)
+
+    def test_index(self):
+        example = 2*self.example
+        a = array.array(self.typecode, example)
+        self.assertRaises(TypeError, a.index)
+        for x in example:
+            self.assertEqual(a.index(x), example.index(x))
+        self.assertRaises(ValueError, a.index, None)
+        self.assertRaises(ValueError, a.index, self.outside)
+
+    def test_count(self):
+        example = 2*self.example
+        a = array.array(self.typecode, example)
+        self.assertRaises(TypeError, a.count)
+        for x in example:
+            self.assertEqual(a.count(x), example.count(x))
+        self.assertEqual(a.count(self.outside), 0)
+        self.assertEqual(a.count(None), 0)
+
+    def test_remove(self):
+        for x in self.example:
+            example = 2*self.example
+            a = array.array(self.typecode, example)
+            pos = example.index(x)
+            example2 = example[:pos] + example[pos+1:]
+            a.remove(x)
+            self.assertEqual(a, array.array(self.typecode, example2))
+
+        a = array.array(self.typecode, self.example)
+        self.assertRaises(ValueError, a.remove, self.outside)
+
+        self.assertRaises(ValueError, a.remove, None)
+
+    def test_pop(self):
+        a = array.array(self.typecode)
+        self.assertRaises(IndexError, a.pop)
+
+        a = array.array(self.typecode, 2*self.example)
+        self.assertRaises(TypeError, a.pop, 42, 42)
+        self.assertRaises(TypeError, a.pop, None)
+        self.assertRaises(IndexError, a.pop, len(a))
+        self.assertRaises(IndexError, a.pop, -len(a)-1)
+
+        self.assertEntryEqual(a.pop(0), self.example[0])
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example[1:]+self.example)
+        )
+        self.assertEntryEqual(a.pop(1), self.example[2])
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example[1:2]+self.example[3:]+self.example)
+        )
+        self.assertEntryEqual(a.pop(0), self.example[1])
+        self.assertEntryEqual(a.pop(), self.example[-1])
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example[3:]+self.example[:-1])
+        )
+
+    def test_reverse(self):
+        a = array.array(self.typecode, self.example)
+        self.assertRaises(TypeError, a.reverse, 42)
+        a.reverse()
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example[::-1])
+        )
+
+    def test_extend(self):
+        a = array.array(self.typecode, self.example)
+        self.assertRaises(TypeError, a.extend)
+        a.extend(array.array(self.typecode, self.example[::-1]))
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example+self.example[::-1])
+        )
+
+        b = array.array(self.badtypecode())
+        self.assertRaises(TypeError, a.extend, b)
+
+        a = array.array(self.typecode, self.example)
+        a.extend(self.example[::-1])
+        self.assertEqual(
+            a,
+            array.array(self.typecode, self.example+self.example[::-1])
+        )
+
+    def test_constructor_with_iterable_argument(self):
+        a = array.array(self.typecode, iter(self.example))
+        b = array.array(self.typecode, self.example)
+        self.assertEqual(a, b)
+
+        # non-iterable argument
+        self.assertRaises(TypeError, array.array, self.typecode, 10)
+
+        # pass through errors raised in __iter__
+        class A:
+            def __iter__(self):
+                raise UnicodeError
+        self.assertRaises(UnicodeError, array.array, self.typecode, A())
+
+        # pass through errors raised in next()
+        def B():
+            raise UnicodeError
+            yield None
+        self.assertRaises(UnicodeError, array.array, self.typecode, B())
+
+    def test_coveritertraverse(self):
+        try:
+            import gc
+        except ImportError:
+            return
+        a = array.array(self.typecode)
+        l = [iter(a)]
+        l.append(l)
+        gc.collect()
+
+    def test_buffer(self):
+        a = array.array(self.typecode, self.example)
+        b = buffer(a)
+        self.assertEqual(b[0], a.tostring()[0])
+
+    def DONOTtest_weakref(self):
+        # XXX disabled until PyPy grows weakref support
+        s = array.array(self.typecode, self.example)
+        p = proxy(s)
+        self.assertEqual(p.tostring(), s.tostring())
+        s = None
+        self.assertRaises(ReferenceError, len, p)
+
+    def test_bug_782369(self):
+        import sys
+        if hasattr(sys, "getrefcount"):
+            for i in range(10):
+                b = array.array('B', range(64))
+            rc = sys.getrefcount(10)
+            for i in range(10):
+                b = array.array('B', range(64))
+            self.assertEqual(rc, sys.getrefcount(10))
+
+    def test_subclass_with_kwargs(self):
+        # SF bug #1486663 -- this used to erroneously raise a TypeError
+        ArraySubclassWithKwargs('b', newarg=1)
+
+
+class StringTest(BaseTest):
+
+    def test_setitem(self):
+        super(StringTest, self).test_setitem()
+        a = array.array(self.typecode, self.example)
+        self.assertRaises((TypeError, struct.error), a.__setitem__, 0, self.example[:2])
+
+class CharacterTest(StringTest):
+    typecode = 'c'
+    example = '\x01azAZ\x00\xfe'
+    smallerexample = '\x01azAY\x00\xfe'
+    biggerexample = '\x01azAZ\x00\xff'
+    outside = '\x33'
+    minitemsize = 1
+
+    def test_subbclassing(self):
+        class EditableString(array.array):
+            def __new__(cls, s, *args, **kwargs):
+                return array.array.__new__(cls, 'c', s)
+
+            def __init__(self, s, color='blue'):
+                array.array.__init__(self, 'c', s)
+                self.color = color
+
+            def strip(self):
+                self[:] = array.array('c', self.tostring().strip())
+
+            def __repr__(self):
+                return 'EditableString(%r)' % self.tostring()
+
+        s = EditableString("\ttest\r\n")
+        s.strip()
+        self.assertEqual(s.tostring(), "test")
+
+        self.assertEqual(s.color, "blue")
+        s.color = "red"
+        self.assertEqual(s.color, "red")
+        self.assertEqual(s.__dict__.keys(), ["color"])
+
+    def test_nounicode(self):
+        a = array.array(self.typecode, self.example)
+        self.assertRaises(ValueError, a.fromunicode, unicode(''))
+        self.assertRaises(ValueError, a.tounicode)
+
+tests.append(CharacterTest)
+
+if test_support.have_unicode:
+    class UnicodeTest(StringTest):
+        typecode = 'u'
+        example = unicode(r'\x01\u263a\x00\ufeff', 'unicode-escape')
+        smallerexample = unicode(r'\x01\u263a\x00\ufefe', 'unicode-escape')
+        biggerexample = unicode(r'\x01\u263a\x01\ufeff', 'unicode-escape')
+        outside = unicode('\x33')
+        minitemsize = 2
+
+        def test_unicode(self):
+            self.assertRaises((TypeError, struct.error), array.array, 'b', unicode('foo', 'ascii'))
+
+            a = array.array('u', unicode(r'\xa0\xc2\u1234', 'unicode-escape'))
+            a.fromunicode(unicode(' ', 'ascii'))
+            a.fromunicode(unicode('', 'ascii'))
+            a.fromunicode(unicode('', 'ascii'))
+            a.fromunicode(unicode(r'\x11abc\xff\u1234', 'unicode-escape'))
+            s = a.tounicode()
+            self.assertEqual(
+                s,
+                unicode(r'\xa0\xc2\u1234 \x11abc\xff\u1234', 'unicode-escape')
+            )
+
+            s = unicode(r'\x00="\'a\\b\x80\xff\u0000\u0001\u1234', 'unicode-escape')
+            a = array.array('u', s)
+            self.assertEqual(
+                repr(a),
+                r"""array('u', u'\x00="\'a\\b\x80\xff\x00\x01\u1234')"""
+            )
+
+            self.assertRaises(TypeError, a.fromunicode)
+
+    tests.append(UnicodeTest)
+
+class NumberTest(BaseTest):
+
+    def test_extslice(self):
+        a = array.array(self.typecode, range(5))
+        self.assertEqual(a[::], a)
+        self.assertEqual(a[::2], array.array(self.typecode, [0,2,4]))
+        self.assertEqual(a[1::2], array.array(self.typecode, [1,3]))
+        self.assertEqual(a[::-1], array.array(self.typecode, [4,3,2,1,0]))
+        self.assertEqual(a[::-2], array.array(self.typecode, [4,2,0]))
+        self.assertEqual(a[3::-2], array.array(self.typecode, [3,1]))
+        self.assertEqual(a[-100:100:], a)
+        self.assertEqual(a[100:-100:-1], a[::-1])
+        self.assertEqual(a[-100L:100L:2L], array.array(self.typecode, [0,2,4]))
+        self.assertEqual(a[1000:2000:2], array.array(self.typecode, []))
+        self.assertEqual(a[-1000:-2000:-2], array.array(self.typecode, []))
+
+    def test_delslice(self):
+        a = array.array(self.typecode, range(5))
+        del a[::2]
+        self.assertEqual(a, array.array(self.typecode, [1,3]))
+        a = array.array(self.typecode, range(5))
+        del a[1::2]
+        self.assertEqual(a, array.array(self.typecode, [0,2,4]))
+        a = array.array(self.typecode, range(5))
+        del a[1::-2]
+        self.assertEqual(a, array.array(self.typecode, [0,2,3,4]))
+        a = array.array(self.typecode, range(10))
+        del a[::1000]
+        self.assertEqual(a, array.array(self.typecode, [1,2,3,4,5,6,7,8,9]))
+
+    def test_assignment(self):
+        a = array.array(self.typecode, range(10))
+        a[::2] = array.array(self.typecode, [42]*5)
+        self.assertEqual(a, array.array(self.typecode, [42, 1, 42, 3, 42, 5, 42, 7, 42, 9]))
+        a = array.array(self.typecode, range(10))
+        a[::-4] = array.array(self.typecode, [10]*3)
+        self.assertEqual(a, array.array(self.typecode, [0, 10, 2, 3, 4, 10, 6, 7, 8 ,10]))
+        a = array.array(self.typecode, range(4))
+        a[::-1] = a
+        self.assertEqual(a, array.array(self.typecode, [3, 2, 1, 0]))
+        a = array.array(self.typecode, range(10))
+        b = a[:]
+        c = a[:]
+        ins = array.array(self.typecode, range(2))
+        a[2:3] = ins
+        b[slice(2,3)] = ins
+        c[2:3:] = ins
+
+    def test_iterationcontains(self):
+        a = array.array(self.typecode, range(10))
+        self.assertEqual(list(a), range(10))
+        b = array.array(self.typecode, [20])
+        self.assertEqual(a[-1] in a, True)
+        self.assertEqual(b[0] not in a, True)
+
+    def check_overflow(self, lower, upper):
+        # method to be used by subclasses
+
+        # should not overflow assigning lower limit
+        a = array.array(self.typecode, [lower])
+        a[0] = lower
+        # should overflow assigning less than lower limit
+        self.assertRaises((OverflowError, struct.error, ValueError), array.array, self.typecode, [lower-1])
+        self.assertRaises((OverflowError, struct.error, ValueError), a.__setitem__, 0, lower-1)
+        # should not overflow assigning upper limit
+        a = array.array(self.typecode, [upper])
+        a[0] = upper
+        # should overflow assigning more than upper limit
+        self.assertRaises((OverflowError, struct.error), array.array, self.typecode, [upper+1])
+        self.assertRaises((OverflowError, struct.error), a.__setitem__, 0, upper+1)
+
+    def test_subclassing(self):
+        typecode = self.typecode
+        class ExaggeratingArray(array.array):
+            __slots__ = ['offset']
+
+            def __new__(cls, typecode, data, offset):
+                return array.array.__new__(cls, typecode, data)
+
+            def __init__(self, typecode, data, offset):
+                self.offset = offset
+
+            def __getitem__(self, i):
+                return array.array.__getitem__(self, i) + self.offset
+
+        a = ExaggeratingArray(self.typecode, [3, 6, 7, 11], 4)
+        self.assertEntryEqual(a[0], 7)
+
+        self.assertRaises(AttributeError, setattr, a, "color", "blue")
+
+class SignedNumberTest(NumberTest):
+    example = [-1, 0, 1, 42, 0x7f]
+    smallerexample = [-1, 0, 1, 42, 0x7e]
+    biggerexample = [-1, 0, 1, 43, 0x7f]
+    outside = 23
+
+    def test_overflow(self):
+        a = array.array(self.typecode)
+        lower = -1 * long(pow(2, a.itemsize * 8 - 1))
+        upper = long(pow(2, a.itemsize * 8 - 1)) - 1L
+        self.check_overflow(lower, upper)
+
+class UnsignedNumberTest(NumberTest):
+    example = [0, 1, 17, 23, 42, 0xff]
+    smallerexample = [0, 1, 17, 23, 42, 0xfe]
+    biggerexample = [0, 1, 17, 23, 43, 0xff]
+    outside = 0xaa
+
+    def test_overflow(self):
+        a = array.array(self.typecode)
+        lower = 0
+        upper = long(pow(2, a.itemsize * 8)) - 1L
+        self.check_overflow(lower, upper)
+
+
+class ByteTest(SignedNumberTest):
+    typecode = 'b'
+    minitemsize = 1
+tests.append(ByteTest)
+
+class UnsignedByteTest(UnsignedNumberTest):
+    typecode = 'B'
+    minitemsize = 1
+tests.append(UnsignedByteTest)
+
+class ShortTest(SignedNumberTest):
+    typecode = 'h'
+    minitemsize = 2
+tests.append(ShortTest)
+
+class UnsignedShortTest(UnsignedNumberTest):
+    typecode = 'H'
+    minitemsize = 2
+tests.append(UnsignedShortTest)
+
+class IntTest(SignedNumberTest):
+    typecode = 'i'
+    minitemsize = 2
+tests.append(IntTest)
+
+class UnsignedIntTest(UnsignedNumberTest):
+    typecode = 'I'
+    minitemsize = 2
+tests.append(UnsignedIntTest)
+
+class LongTest(SignedNumberTest):
+    typecode = 'l'
+    minitemsize = 4
+tests.append(LongTest)
+
+class UnsignedLongTest(UnsignedNumberTest):
+    typecode = 'L'
+    minitemsize = 4
+tests.append(UnsignedLongTest)
+
+class FPTest(NumberTest):
+    example = [-42.0, 0, 42, 1e5, -1e10]
+    smallerexample = [-42.0, 0, 42, 1e5, -2e10]
+    biggerexample = [-42.0, 0, 42, 1e5, 1e10]
+    outside = 23
+
+    def assertEntryEqual(self, entry1, entry2):
+        self.assertAlmostEqual(entry1, entry2)
+
+    def test_byteswap(self):
+        a = array.array(self.typecode, self.example)
+        self.assertRaises(TypeError, a.byteswap, 42)
+        if a.itemsize in (1, 2, 4, 8):
+            b = array.array(self.typecode, self.example)
+            b.byteswap()
+            if a.itemsize==1:
+                self.assertEqual(a, b)
+            else:
+                # On alphas treating the byte swapped bit patters as
+                # floats/doubles results in floating point exceptions
+                # => compare the 8bit string values instead
+                self.assertNotEqual(a.tostring(), b.tostring())
+            b.byteswap()
+            self.assertEqual(a, b)
+
+class FloatTest(FPTest):
+    typecode = 'f'
+    minitemsize = 4
+tests.append(FloatTest)
+
+class DoubleTest(FPTest):
+    typecode = 'd'
+    minitemsize = 8
+tests.append(DoubleTest)
+
+def test_main(verbose=None):
+    import sys
+
+    test_support.run_unittest(*tests)
+
+    # verify reference counting
+    if verbose and hasattr(sys, "gettotalrefcount"):
+        import gc
+        counts = [None] * 5
+        for i in xrange(len(counts)):
+            test_support.run_unittest(*tests)
+            gc.collect()
+            counts[i] = sys.gettotalrefcount()
+        print counts
+
+if __name__ == "__main__":
+    test_main(verbose=True)

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_base64.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_base64.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,208 @@
+import unittest
+from test import test_support
+import base64
+
+
+
+class LegacyBase64TestCase(unittest.TestCase):
+    def test_encodestring(self):
+        eq = self.assertEqual
+        eq(base64.encodestring("www.python.org"), "d3d3LnB5dGhvbi5vcmc=\n")
+        eq(base64.encodestring("a"), "YQ==\n")
+        eq(base64.encodestring("ab"), "YWI=\n")
+        eq(base64.encodestring("abc"), "YWJj\n")
+        eq(base64.encodestring(""), "")
+        eq(base64.encodestring("abcdefghijklmnopqrstuvwxyz"
+                               "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+                               "0123456789!@#0^&*();:<>,. []{}"),
+           "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
+           "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT"
+           "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n")
+
+    def test_decodestring(self):
+        eq = self.assertEqual
+        eq(base64.decodestring("d3d3LnB5dGhvbi5vcmc=\n"), "www.python.org")
+        eq(base64.decodestring("YQ==\n"), "a")
+        eq(base64.decodestring("YWI=\n"), "ab")
+        eq(base64.decodestring("YWJj\n"), "abc")
+        eq(base64.decodestring("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
+                               "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT"
+                               "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n"),
+           "abcdefghijklmnopqrstuvwxyz"
+           "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+           "0123456789!@#0^&*();:<>,. []{}")
+        eq(base64.decodestring(''), '')
+
+    def test_encode(self):
+        eq = self.assertEqual
+        from cStringIO import StringIO
+        infp = StringIO('abcdefghijklmnopqrstuvwxyz'
+                        'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+                        '0123456789!@#0^&*();:<>,. []{}')
+        outfp = StringIO()
+        base64.encode(infp, outfp)
+        eq(outfp.getvalue(),
+           'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE'
+           'RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT'
+           'Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n')
+
+    def test_decode(self):
+        from cStringIO import StringIO
+        infp = StringIO('d3d3LnB5dGhvbi5vcmc=')
+        outfp = StringIO()
+        base64.decode(infp, outfp)
+        self.assertEqual(outfp.getvalue(), 'www.python.org')
+
+
+
+class BaseXYTestCase(unittest.TestCase):
+    def test_b64encode(self):
+        eq = self.assertEqual
+        # Test default alphabet
+        eq(base64.b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=")
+        eq(base64.b64encode('\x00'), 'AA==')
+        eq(base64.b64encode("a"), "YQ==")
+        eq(base64.b64encode("ab"), "YWI=")
+        eq(base64.b64encode("abc"), "YWJj")
+        eq(base64.b64encode(""), "")
+        eq(base64.b64encode("abcdefghijklmnopqrstuvwxyz"
+                            "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+                            "0123456789!@#0^&*();:<>,. []{}"),
+           "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
+           "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT"
+           "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==")
+        # Test with arbitrary alternative characters
+        eq(base64.b64encode('\xd3V\xbeo\xf7\x1d', altchars='*$'), '01a*b$cd')
+        # Test standard alphabet
+        eq(base64.standard_b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=")
+        eq(base64.standard_b64encode("a"), "YQ==")
+        eq(base64.standard_b64encode("ab"), "YWI=")
+        eq(base64.standard_b64encode("abc"), "YWJj")
+        eq(base64.standard_b64encode(""), "")
+        eq(base64.standard_b64encode("abcdefghijklmnopqrstuvwxyz"
+                                     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+                                     "0123456789!@#0^&*();:<>,. []{}"),
+           "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
+           "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT"
+           "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==")
+        # Test with 'URL safe' alternative characters
+        eq(base64.urlsafe_b64encode('\xd3V\xbeo\xf7\x1d'), '01a-b_cd')
+
+    def test_b64decode(self):
+        eq = self.assertEqual
+        eq(base64.b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org")
+        eq(base64.b64decode('AA=='), '\x00')
+        eq(base64.b64decode("YQ=="), "a")
+        eq(base64.b64decode("YWI="), "ab")
+        eq(base64.b64decode("YWJj"), "abc")
+        eq(base64.b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
+                            "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT"
+                            "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="),
+           "abcdefghijklmnopqrstuvwxyz"
+           "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+           "0123456789!@#0^&*();:<>,. []{}")
+        eq(base64.b64decode(''), '')
+        # Test with arbitrary alternative characters
+        eq(base64.b64decode('01a*b$cd', altchars='*$'), '\xd3V\xbeo\xf7\x1d')
+        # Test standard alphabet
+        eq(base64.standard_b64decode("d3d3LnB5dGhvbi5vcmc="), "www.python.org")
+        eq(base64.standard_b64decode("YQ=="), "a")
+        eq(base64.standard_b64decode("YWI="), "ab")
+        eq(base64.standard_b64decode("YWJj"), "abc")
+        eq(base64.standard_b64decode(""), "")
+        eq(base64.standard_b64decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
+                                     "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT"
+                                     "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ=="),
+           "abcdefghijklmnopqrstuvwxyz"
+           "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+           "0123456789!@#0^&*();:<>,. []{}")
+        # Test with 'URL safe' alternative characters
+        eq(base64.urlsafe_b64decode('01a-b_cd'), '\xd3V\xbeo\xf7\x1d')
+
+
+    # This test is testing an implementation specific detail.
+    # In our implementation, we make a best attempt to translate
+    # strings with broken encoding back to their original form.
+    # Since the user will most likely be interested in what remains
+    # of a message which has been broken in transmission, this seems to
+    # be the most reasonable thing to do.
+    # In pypy we disable this test!
+    '''
+    def test_b64decode_error(self):
+        self.assertRaises(TypeError, base64.b64decode, 'abc')
+    '''
+    
+    def test_b32encode(self):
+        eq = self.assertEqual
+        eq(base64.b32encode(''), '')
+        eq(base64.b32encode('\x00'), 'AA======')
+        eq(base64.b32encode('a'), 'ME======')
+        eq(base64.b32encode('ab'), 'MFRA====')
+        eq(base64.b32encode('abc'), 'MFRGG===')
+        eq(base64.b32encode('abcd'), 'MFRGGZA=')
+        eq(base64.b32encode('abcde'), 'MFRGGZDF')
+
+    def test_b32decode(self):
+        eq = self.assertEqual
+        eq(base64.b32decode(''), '')
+        eq(base64.b32decode('AA======'), '\x00')
+        eq(base64.b32decode('ME======'), 'a')
+        eq(base64.b32decode('MFRA===='), 'ab')
+        eq(base64.b32decode('MFRGG==='), 'abc')
+        eq(base64.b32decode('MFRGGZA='), 'abcd')
+        eq(base64.b32decode('MFRGGZDF'), 'abcde')
+
+    def test_b32decode_casefold(self):
+        eq = self.assertEqual
+        eq(base64.b32decode('', True), '')
+        eq(base64.b32decode('ME======', True), 'a')
+        eq(base64.b32decode('MFRA====', True), 'ab')
+        eq(base64.b32decode('MFRGG===', True), 'abc')
+        eq(base64.b32decode('MFRGGZA=', True), 'abcd')
+        eq(base64.b32decode('MFRGGZDF', True), 'abcde')
+        # Lower cases
+        eq(base64.b32decode('me======', True), 'a')
+        eq(base64.b32decode('mfra====', True), 'ab')
+        eq(base64.b32decode('mfrgg===', True), 'abc')
+        eq(base64.b32decode('mfrggza=', True), 'abcd')
+        eq(base64.b32decode('mfrggzdf', True), 'abcde')
+        # Expected exceptions
+        self.assertRaises(TypeError, base64.b32decode, 'me======')
+        # Mapping zero and one
+        eq(base64.b32decode('MLO23456'), 'b\xdd\xad\xf3\xbe')
+        eq(base64.b32decode('M1023456', map01='L'), 'b\xdd\xad\xf3\xbe')
+        eq(base64.b32decode('M1023456', map01='I'), 'b\x1d\xad\xf3\xbe')
+
+    def test_b32decode_error(self):
+        self.assertRaises(TypeError, base64.b32decode, 'abc')
+        self.assertRaises(TypeError, base64.b32decode, 'ABCDEF==')
+
+    def test_b16encode(self):
+        eq = self.assertEqual
+        eq(base64.b16encode('\x01\x02\xab\xcd\xef'), '0102ABCDEF')
+        eq(base64.b16encode('\x00'), '00')
+
+    def test_b16decode(self):
+        eq = self.assertEqual
+        eq(base64.b16decode('0102ABCDEF'), '\x01\x02\xab\xcd\xef')
+        eq(base64.b16decode('00'), '\x00')
+        # Lower case is not allowed without a flag
+        self.assertRaises(TypeError, base64.b16decode, '0102abcdef')
+        # Case fold
+        eq(base64.b16decode('0102abcdef', True), '\x01\x02\xab\xcd\xef')
+
+
+
+def suite():
+    suite = unittest.TestSuite()
+    suite.addTest(unittest.makeSuite(LegacyBase64TestCase))
+    suite.addTest(unittest.makeSuite(BaseXYTestCase))
+    return suite
+
+
+def test_main():
+    test_support.run_suite(suite())
+
+
+if __name__ == '__main__':
+    test_main()

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_bufio.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_bufio.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,63 @@
+from test.test_support import verify, TestFailed, TESTFN
+
+# Simple test to ensure that optimizations in fileobject.c deliver
+# the expected results.  For best testing, run this under a debug-build
+# Python too (to exercise asserts in the C code).
+
+# Repeat string 'pattern' as often as needed to reach total length
+# 'length'.  Then call try_one with that string, a string one larger
+# than that, and a string one smaller than that.  The main driver
+# feeds this all small sizes and various powers of 2, so we exercise
+# all likely stdio buffer sizes, and "off by one" errors on both
+# sides.
+def drive_one(pattern, length):
+    q, r = divmod(length, len(pattern))
+    teststring = pattern * q + pattern[:r]
+    verify(len(teststring) == length)
+    try_one(teststring)
+    try_one(teststring + "x")
+    try_one(teststring[:-1])
+
+# Write s + "\n" + s to file, then open it and ensure that successive
+# .readline()s deliver what we wrote.
+def try_one(s):
+    # Since C doesn't guarantee we can write/read arbitrary bytes in text
+    # files, use binary mode.
+    f = open(TESTFN, "wb")
+    # write once with \n and once without
+    f.write(s)
+    f.write("\n")
+    f.write(s)
+    f.close()
+    f = open(TESTFN, "rb")
+    line = f.readline()
+    if line != s + "\n":
+        raise TestFailed("Expected %r got %r" % (s + "\n", line))
+    line = f.readline()
+    if line != s:
+        raise TestFailed("Expected %r got %r" % (s, line))
+    line = f.readline()
+    if line:
+        raise TestFailed("Expected EOF but got %r" % line)
+    f.close()
+
+# A pattern with prime length, to avoid simple relationships with
+# stdio buffer sizes.
+primepat = "1234567890\00\01\02\03\04\05\06"
+
+nullpat = "\0" * 1000
+
+try:
+# Too slow for PyPy.
+#    for size in range(1, 257) + [512, 1000, 1024, 2048, 4096, 8192, 10000,
+#                      16384, 32768, 65536, 1000000]:
+    for size in range(1, 9) + [9, 63, 64, 65, 128, 129, 254, 255, 256, 512,
+                               1000, 1024, 2048, 4096, 8192, 10000, 16384]:
+        drive_one(primepat, size)
+        drive_one(nullpat, size)
+finally:
+    try:
+        import os
+        os.unlink(TESTFN)
+    except:
+        pass

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_builtin.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_builtin.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,1785 @@
+# Python test set -- built-in functions
+
+import test.test_support, unittest
+from test.test_support import fcmp, have_unicode, TESTFN, unlink, \
+                              run_unittest, run_with_locale
+from operator import neg
+
+import sys, warnings, cStringIO, random, UserDict
+warnings.filterwarnings("ignore", "hex../oct.. of negative int",
+                        FutureWarning, __name__)
+warnings.filterwarnings("ignore", "integer argument expected",
+                        DeprecationWarning, "unittest")
+
+# count the number of test runs.
+# used to skip running test_execfile() multiple times
+numruns = 0
+
+class Squares:
+
+    def __init__(self, max):
+        self.max = max
+        self.sofar = []
+
+    def __len__(self): return len(self.sofar)
+
+    def __getitem__(self, i):
+        if not 0 <= i < self.max: raise IndexError
+        n = len(self.sofar)
+        while n <= i:
+            self.sofar.append(n*n)
+            n += 1
+        return self.sofar[i]
+
+class StrSquares:
+
+    def __init__(self, max):
+        self.max = max
+        self.sofar = []
+
+    def __len__(self):
+        return len(self.sofar)
+
+    def __getitem__(self, i):
+        if not 0 <= i < self.max:
+            raise IndexError
+        n = len(self.sofar)
+        while n <= i:
+            self.sofar.append(str(n*n))
+            n += 1
+        return self.sofar[i]
+
+class BitBucket:
+    def write(self, line):
+        pass
+
+L = [
+        ('0', 0),
+        ('1', 1),
+        ('9', 9),
+        ('10', 10),
+        ('99', 99),
+        ('100', 100),
+        ('314', 314),
+        (' 314', 314),
+        ('314 ', 314),
+        ('  \t\t  314  \t\t  ', 314),
+        (repr(sys.maxint), sys.maxint),
+        ('  1x', ValueError),
+        ('  1  ', 1),
+        ('  1\02  ', ValueError),
+        ('', ValueError),
+        (' ', ValueError),
+        ('  \t\t  ', ValueError)
+]
+if have_unicode:
+    L += [
+        (unicode('0'), 0),
+        (unicode('1'), 1),
+        (unicode('9'), 9),
+        (unicode('10'), 10),
+        (unicode('99'), 99),
+        (unicode('100'), 100),
+        (unicode('314'), 314),
+        (unicode(' 314'), 314),
+        (unicode('\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
+        (unicode('  \t\t  314  \t\t  '), 314),
+        (unicode('  1x'), ValueError),
+        (unicode('  1  '), 1),
+        (unicode('  1\02  '), ValueError),
+        (unicode(''), ValueError),
+        (unicode(' '), ValueError),
+        (unicode('  \t\t  '), ValueError),
+        (unichr(0x200), ValueError),
+]
+
+class TestFailingBool:
+    def __nonzero__(self):
+        raise RuntimeError
+
+class TestFailingIter:
+    def __iter__(self):
+        raise RuntimeError
+
+class BuiltinTest(unittest.TestCase):
+
+    def test_import(self):
+        __import__('sys')
+        __import__('time')
+        __import__('string')
+        self.assertRaises(ImportError, __import__, 'spamspam')
+        self.assertRaises(TypeError, __import__, 1, 2, 3, 4)
+        self.assertRaises(ValueError, __import__, '')
+
+    def test_abs(self):
+        # int
+        self.assertEqual(abs(0), 0)
+        self.assertEqual(abs(1234), 1234)
+        self.assertEqual(abs(-1234), 1234)
+        self.assertTrue(abs(-sys.maxint-1) > 0)
+        # float
+        self.assertEqual(abs(0.0), 0.0)
+        self.assertEqual(abs(3.14), 3.14)
+        self.assertEqual(abs(-3.14), 3.14)
+        # long
+        self.assertEqual(abs(0L), 0L)
+        self.assertEqual(abs(1234L), 1234L)
+        self.assertEqual(abs(-1234L), 1234L)
+        # str
+        self.assertRaises(TypeError, abs, 'a')
+
+    def test_all(self):
+        self.assertEqual(all([2, 4, 6]), True)
+        self.assertEqual(all([2, None, 6]), False)
+        self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6])
+        self.assertRaises(RuntimeError, all, TestFailingIter())
+        self.assertRaises(TypeError, all, 10)               # Non-iterable
+        self.assertRaises(TypeError, all)                   # No args
+        self.assertRaises(TypeError, all, [2, 4, 6], [])    # Too many args
+        self.assertEqual(all([]), True)                     # Empty iterator
+        S = [50, 60]
+        self.assertEqual(all(x > 42 for x in S), True)
+        S = [50, 40, 60]
+        self.assertEqual(all(x > 42 for x in S), False)
+
+    def test_any(self):
+        self.assertEqual(any([None, None, None]), False)
+        self.assertEqual(any([None, 4, None]), True)
+        self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6])
+        self.assertRaises(RuntimeError, all, TestFailingIter())
+        self.assertRaises(TypeError, any, 10)               # Non-iterable
+        self.assertRaises(TypeError, any)                   # No args
+        self.assertRaises(TypeError, any, [2, 4, 6], [])    # Too many args
+        self.assertEqual(any([]), False)                    # Empty iterator
+        S = [40, 60, 30]
+        self.assertEqual(any(x > 42 for x in S), True)
+        S = [10, 20, 30]
+        self.assertEqual(any(x > 42 for x in S), False)
+
+    def test_neg(self):
+        x = -sys.maxint-1
+        self.assert_(isinstance(x, int))
+        self.assertEqual(-x, sys.maxint+1)
+
+    def test_apply(self):
+        def f0(*args):
+            self.assertEqual(args, ())
+        def f1(a1):
+            self.assertEqual(a1, 1)
+        def f2(a1, a2):
+            self.assertEqual(a1, 1)
+            self.assertEqual(a2, 2)
+        def f3(a1, a2, a3):
+            self.assertEqual(a1, 1)
+            self.assertEqual(a2, 2)
+            self.assertEqual(a3, 3)
+        apply(f0, ())
+        apply(f1, (1,))
+        apply(f2, (1, 2))
+        apply(f3, (1, 2, 3))
+
+        # A PyCFunction that takes only positional parameters should allow an
+        # empty keyword dictionary to pass without a complaint, but raise a
+        # TypeError if the dictionary is non-empty.
+        apply(id, (1,), {})
+        self.assertRaises(TypeError, apply, id, (1,), {"foo": 1})
+        self.assertRaises(TypeError, apply)
+        self.assertRaises(TypeError, apply, id, 42)
+        self.assertRaises(TypeError, apply, id, (42,), 42)
+
+    def test_callable(self):
+        self.assert_(callable(len))
+        def f(): pass
+        self.assert_(callable(f))
+        class C:
+            def meth(self): pass
+        self.assert_(callable(C))
+        x = C()
+        self.assert_(callable(x.meth))
+        self.assert_(not callable(x))
+        class D(C):
+            def __call__(self): pass
+        y = D()
+        self.assert_(callable(y))
+        y()
+
+    def test_chr(self):
+        self.assertEqual(chr(32), ' ')
+        self.assertEqual(chr(65), 'A')
+        self.assertEqual(chr(97), 'a')
+        self.assertEqual(chr(0xff), '\xff')
+        self.assertRaises(ValueError, chr, 256)
+        self.assertRaises(TypeError, chr)
+
+    def test_cmp(self):
+        self.assertEqual(cmp(-1, 1), -1)
+        self.assertEqual(cmp(1, -1), 1)
+        self.assertEqual(cmp(1, 1), 0)
+        # verify that circular objects are not handled
+        a = []; a.append(a)
+        b = []; b.append(b)
+        from UserList import UserList
+        c = UserList(); c.append(c)
+        self.assertRaises(RuntimeError, cmp, a, b)
+        self.assertRaises(RuntimeError, cmp, b, c)
+        self.assertRaises(RuntimeError, cmp, c, a)
+        self.assertRaises(RuntimeError, cmp, a, c)
+       # okay, now break the cycles
+        a.pop(); b.pop(); c.pop()
+        self.assertRaises(TypeError, cmp)
+
+    def test_coerce(self):
+        self.assert_(not fcmp(coerce(1, 1.1), (1.0, 1.1)))
+        self.assertEqual(coerce(1, 1L), (1L, 1L))
+        self.assert_(not fcmp(coerce(1L, 1.1), (1.0, 1.1)))
+        self.assertRaises(TypeError, coerce)
+        class BadNumber:
+            def __coerce__(self, other):
+                raise ValueError
+        self.assertRaises(ValueError, coerce, 42, BadNumber())
+        self.assertRaises(OverflowError, coerce, 0.5, int("12345" * 1000))
+
+    def test_compile(self):
+        compile('print 1\n', '', 'exec')
+        bom = '\xef\xbb\xbf'
+        compile(bom + 'print 1\n', '', 'exec')
+        self.assertRaises(TypeError, compile)
+        self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'badmode')
+        self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'single', 0xff)
+        self.assertRaises(TypeError, compile, chr(0), 'f', 'exec')
+        if have_unicode:
+            compile(unicode('print u"\xc3\xa5"\n', 'utf8'), '', 'exec')
+            self.assertRaises(TypeError, compile, unichr(0), 'f', 'exec')
+            self.assertRaises(ValueError, compile, unicode('a = 1'), 'f', 'bad')
+
+    def test_delattr(self):
+        import sys
+        sys.spam = 1
+        delattr(sys, 'spam')
+        self.assertRaises(TypeError, delattr)
+
+    def test_dir(self):
+        x = 1
+        self.assert_('x' in dir())
+        import sys
+        self.assert_('modules' in dir(sys))
+        self.assertRaises(TypeError, dir, 42, 42)
+
+    def test_divmod(self):
+        self.assertEqual(divmod(12, 7), (1, 5))
+        self.assertEqual(divmod(-12, 7), (-2, 2))
+        self.assertEqual(divmod(12, -7), (-2, -2))
+        self.assertEqual(divmod(-12, -7), (1, -5))
+
+        self.assertEqual(divmod(12L, 7L), (1L, 5L))
+        self.assertEqual(divmod(-12L, 7L), (-2L, 2L))
+        self.assertEqual(divmod(12L, -7L), (-2L, -2L))
+        self.assertEqual(divmod(-12L, -7L), (1L, -5L))
+
+        self.assertEqual(divmod(12, 7L), (1, 5L))
+        self.assertEqual(divmod(-12, 7L), (-2, 2L))
+        self.assertEqual(divmod(12L, -7), (-2L, -2))
+        self.assertEqual(divmod(-12L, -7), (1L, -5))
+
+        self.assertEqual(divmod(-sys.maxint-1, -1),
+                         (sys.maxint+1, 0))
+
+        self.assert_(not fcmp(divmod(3.25, 1.0), (3.0, 0.25)))
+        self.assert_(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75)))
+        self.assert_(not fcmp(divmod(3.25, -1.0), (-4.0, -0.75)))
+        self.assert_(not fcmp(divmod(-3.25, -1.0), (3.0, -0.25)))
+
+        self.assertRaises(TypeError, divmod)
+
+    def test_eval(self):
+        self.assertEqual(eval('1+1'), 2)
+        self.assertEqual(eval(' 1+1\n'), 2)
+        globals = {'a': 1, 'b': 2}
+        locals = {'b': 200, 'c': 300}
+        self.assertEqual(eval('a', globals) , 1)
+        self.assertEqual(eval('a', globals, locals), 1)
+        self.assertEqual(eval('b', globals, locals), 200)
+        self.assertEqual(eval('c', globals, locals), 300)
+        if have_unicode:
+            self.assertEqual(eval(unicode('1+1')), 2)
+            self.assertEqual(eval(unicode(' 1+1\n')), 2)
+        globals = {'a': 1, 'b': 2}
+        locals = {'b': 200, 'c': 300}
+        if have_unicode:
+            self.assertEqual(eval(unicode('a'), globals), 1)
+            self.assertEqual(eval(unicode('a'), globals, locals), 1)
+            self.assertEqual(eval(unicode('b'), globals, locals), 200)
+            self.assertEqual(eval(unicode('c'), globals, locals), 300)
+            bom = '\xef\xbb\xbf'
+            self.assertEqual(eval(bom + 'a', globals, locals), 1)
+            self.assertEqual(eval(unicode('u"\xc3\xa5"', 'utf8'), globals),
+                             unicode('\xc3\xa5', 'utf8'))
+        self.assertRaises(TypeError, eval)
+        self.assertRaises(TypeError, eval, ())
+
+    def test_general_eval(self):
+        # Tests that general mappings can be used for the locals argument
+
+        class M:
+            "Test mapping interface versus possible calls from eval()."
+            def __getitem__(self, key):
+                if key == 'a':
+                    return 12
+                raise KeyError
+            def keys(self):
+                return list('xyz')
+
+        m = M()
+        g = globals()
+        self.assertEqual(eval('a', g, m), 12)
+        self.assertRaises(NameError, eval, 'b', g, m)
+        self.assertEqual(eval('dir()', g, m), list('xyz'))
+        self.assertEqual(eval('globals()', g, m), g)
+        self.assertEqual(eval('locals()', g, m), m)
+        # the following line checks a detail of CPython: the globals() of
+        # any frame must be a real dictionary
+        #self.assertRaises(TypeError, eval, 'a', m)
+        class A:
+            "Non-mapping"
+            pass
+        m = A()
+        self.assertRaises((TypeError, AttributeError) , eval, 'a', g, m)
+
+        # Verify that dict subclasses work as well
+        class D(dict):
+            def __getitem__(self, key):
+                if key == 'a':
+                    return 12
+                return dict.__getitem__(self, key)
+            def keys(self):
+                return list('xyz')
+
+        d = D()
+        self.assertEqual(eval('a', g, d), 12)
+        self.assertRaises(NameError, eval, 'b', g, d)
+        self.assertEqual(eval('dir()', g, d), list('xyz'))
+        self.assertEqual(eval('globals()', g, d), g)
+        self.assertEqual(eval('locals()', g, d), d)
+
+        # Verify locals stores (used by list comps)
+        eval('[locals() for i in (2,3)]', g, d)
+        eval('[locals() for i in (2,3)]', g, UserDict.UserDict())
+
+        class SpreadSheet:
+            "Sample application showing nested, calculated lookups."
+            _cells = {}
+            def __setitem__(self, key, formula):
+                self._cells[key] = formula
+            def __getitem__(self, key):
+                return eval(self._cells[key], globals(), self)
+
+        ss = SpreadSheet()
+        ss['a1'] = '5'
+        ss['a2'] = 'a1*6'
+        ss['a3'] = 'a2*7'
+        self.assertEqual(ss['a3'], 210)
+
+        # Verify that dir() catches a non-list returned by eval
+        # SF bug #1004669
+        class C:
+            def __getitem__(self, item):
+                raise KeyError(item)
+            def keys(self):
+                return 'a'
+        self.assertRaises(TypeError, eval, 'dir()', globals(), C())
+
+    # Done outside of the method test_z to get the correct scope
+    z = 0
+    f = open(TESTFN, 'w')
+    f.write('z = z+1\n')
+    f.write('z = z*2\n')
+    f.close()
+    execfile(TESTFN)
+
+    def test_execfile(self):
+        global numruns
+        if numruns:
+            return
+        numruns += 1
+
+        globals = {'a': 1, 'b': 2}
+        locals = {'b': 200, 'c': 300}
+
+        self.assertEqual(self.__class__.z, 2)
+        globals['z'] = 0
+        execfile(TESTFN, globals)
+        self.assertEqual(globals['z'], 2)
+        locals['z'] = 0
+        execfile(TESTFN, globals, locals)
+        self.assertEqual(locals['z'], 2)
+
+        class M:
+            "Test mapping interface versus possible calls from execfile()."
+            def __init__(self):
+                self.z = 10
+            def __getitem__(self, key):
+                if key == 'z':
+                    return self.z
+                raise KeyError
+            def __setitem__(self, key, value):
+                if key == 'z':
+                    self.z = value
+                    return
+                raise KeyError
+
+        locals = M()
+        locals['z'] = 0
+        execfile(TESTFN, globals, locals)
+        self.assertEqual(locals['z'], 2)
+
+        unlink(TESTFN)
+        self.assertRaises(TypeError, execfile)
+        self.assertRaises(TypeError, execfile, TESTFN, {}, ())
+        import os
+        self.assertRaises(IOError, execfile, os.curdir)
+        self.assertRaises(IOError, execfile, "I_dont_exist")
+
+    def test_filter(self):
+        self.assertEqual(filter(lambda c: 'a' <= c <= 'z', 'Hello World'), 'elloorld')
+        self.assertEqual(filter(None, [1, 'hello', [], [3], '', None, 9, 0]), [1, 'hello', [3], 9])
+        self.assertEqual(filter(lambda x: x > 0, [1, -3, 9, 0, 2]), [1, 9, 2])
+        self.assertEqual(filter(None, Squares(10)), [1, 4, 9, 16, 25, 36, 49, 64, 81])
+        self.assertEqual(filter(lambda x: x%2, Squares(10)), [1, 9, 25, 49, 81])
+        def identity(item):
+            return 1
+        filter(identity, Squares(5))
+        self.assertRaises(TypeError, filter)
+        class BadSeq(object):
+            def __getitem__(self, index):
+                if index<4:
+                    return 42
+                raise ValueError
+        self.assertRaises(ValueError, filter, lambda x: x, BadSeq())
+        def badfunc():
+            pass
+        self.assertRaises(TypeError, filter, badfunc, range(5))
+
+        # test bltinmodule.c::filtertuple()
+        self.assertEqual(filter(None, (1, 2)), (1, 2))
+        self.assertEqual(filter(lambda x: x>=3, (1, 2, 3, 4)), (3, 4))
+        self.assertRaises(TypeError, filter, 42, (1, 2))
+
+        # test bltinmodule.c::filterstring()
+        self.assertEqual(filter(None, "12"), "12")
+        self.assertEqual(filter(lambda x: x>="3", "1234"), "34")
+        self.assertRaises(TypeError, filter, 42, "12")
+        class badstr(str):
+            def __getitem__(self, index):
+                raise ValueError
+        self.assertRaises(ValueError, filter, lambda x: x >="3", badstr("1234"))
+
+        class badstr2(str):
+            def __getitem__(self, index):
+                return 42
+        self.assertRaises(TypeError, filter, lambda x: x >=42, badstr2("1234"))
+
+        class weirdstr(str):
+            def __getitem__(self, index):
+                return weirdstr(2*str.__getitem__(self, index))
+        self.assertEqual(filter(lambda x: x>="33", weirdstr("1234")), "3344")
+
+        class shiftstr(str):
+            def __getitem__(self, index):
+                return chr(ord(str.__getitem__(self, index))+1)
+        self.assertEqual(filter(lambda x: x>="3", shiftstr("1234")), "345")
+
+        if have_unicode:
+            # test bltinmodule.c::filterunicode()
+            self.assertEqual(filter(None, unicode("12")), unicode("12"))
+            self.assertEqual(filter(lambda x: x>="3", unicode("1234")), unicode("34"))
+            self.assertRaises(TypeError, filter, 42, unicode("12"))
+            self.assertRaises(ValueError, filter, lambda x: x >="3", badstr(unicode("1234")))
+
+            class badunicode(unicode):
+                def __getitem__(self, index):
+                    return 42
+            self.assertRaises(TypeError, filter, lambda x: x >=42, badunicode("1234"))
+
+            class weirdunicode(unicode):
+                def __getitem__(self, index):
+                    return weirdunicode(2*unicode.__getitem__(self, index))
+            self.assertEqual(
+                filter(lambda x: x>=unicode("33"), weirdunicode("1234")), unicode("3344"))
+
+            class shiftunicode(unicode):
+                def __getitem__(self, index):
+                    return unichr(ord(unicode.__getitem__(self, index))+1)
+            self.assertEqual(
+                filter(lambda x: x>=unicode("3"), shiftunicode("1234")),
+                unicode("345")
+            )
+
+    def test_filter_subclasses(self):
+        # test that filter() never returns tuple, str or unicode subclasses
+        # and that the result always goes through __getitem__
+        funcs = (None, bool, lambda x: True)
+        class tuple2(tuple):
+            def __getitem__(self, index):
+                return 2*tuple.__getitem__(self, index)
+        class str2(str):
+            def __getitem__(self, index):
+                return 2*str.__getitem__(self, index)
+        inputs = {
+            tuple2: {(): (), (1, 2, 3): (2, 4, 6)},
+            str2:   {"": "", "123": "112233"}
+        }
+        if have_unicode:
+            class unicode2(unicode):
+                def __getitem__(self, index):
+                    return 2*unicode.__getitem__(self, index)
+            inputs[unicode2] = {
+                unicode(): unicode(),
+                unicode("123"): unicode("112233")
+            }
+
+        for (cls, inps) in inputs.iteritems():
+            for (inp, exp) in inps.iteritems():
+                # make sure the output goes through __getitem__
+                # even if func is None
+                self.assertEqual(
+                    filter(funcs[0], cls(inp)),
+                    filter(funcs[1], cls(inp))
+                )
+                for func in funcs:
+                    outp = filter(func, cls(inp))
+                    self.assertEqual(outp, exp)
+                    self.assert_(not isinstance(outp, cls))
+
+    def test_float(self):
+        self.assertEqual(float(3.14), 3.14)
+        self.assertEqual(float(314), 314.0)
+        self.assertEqual(float(314L), 314.0)
+        self.assertEqual(float("  3.14  "), 3.14)
+        self.assertRaises(ValueError, float, "  0x3.1  ")
+        self.assertRaises(ValueError, float, "  -0x3.p-1  ")
+        if have_unicode:
+            self.assertEqual(float(unicode("  3.14  ")), 3.14)
+            self.assertEqual(float(unicode("  \u0663.\u0661\u0664  ",'raw-unicode-escape')), 3.14)
+            # Implementation limitation in PyFloat_FromString()
+            self.assertRaises(ValueError, float, unicode("1"*10000))
+
+    @run_with_locale('LC_NUMERIC', 'fr_FR', 'de_DE')
+    def test_float_with_comma(self):
+        # set locale to something that doesn't use '.' for the decimal point
+        # float must not accept the locale specific decimal point but
+        # it still has to accept the normal python syntac
+        import locale
+        if not locale.localeconv()['decimal_point'] == ',':
+            return
+
+        self.assertEqual(float("  3.14  "), 3.14)
+        self.assertEqual(float("+3.14  "), 3.14)
+        self.assertEqual(float("-3.14  "), -3.14)
+        self.assertEqual(float(".14  "), .14)
+        self.assertEqual(float("3.  "), 3.0)
+        self.assertEqual(float("3.e3  "), 3000.0)
+        self.assertEqual(float("3.2e3  "), 3200.0)
+        self.assertEqual(float("2.5e-1  "), 0.25)
+        self.assertEqual(float("5e-1"), 0.5)
+        self.assertRaises(ValueError, float, "  3,14  ")
+        self.assertRaises(ValueError, float, "  +3,14  ")
+        self.assertRaises(ValueError, float, "  -3,14  ")
+        self.assertRaises(ValueError, float, "  0x3.1  ")
+        self.assertRaises(ValueError, float, "  -0x3.p-1  ")
+        self.assertEqual(float("  25.e-1  "), 2.5)
+        self.assertEqual(fcmp(float("  .25e-1  "), .025), 0)
+
+    def test_floatconversion(self):
+        # Make sure that calls to __float__() work properly
+        class Foo0:
+            def __float__(self):
+                return 42.
+
+        class Foo1(object):
+            def __float__(self):
+                return 42.
+
+        class Foo2(float):
+            def __float__(self):
+                return 42.
+
+        class Foo3(float):
+            def __new__(cls, value=0.):
+                return float.__new__(cls, 2*value)
+
+            def __float__(self):
+                return self
+
+        class Foo4(float):
+            def __float__(self):
+                return 42
+
+        self.assertAlmostEqual(float(Foo0()), 42.)
+        self.assertAlmostEqual(float(Foo1()), 42.)
+        self.assertAlmostEqual(float(Foo2()), 42.)
+        self.assertAlmostEqual(float(Foo3(21)), 42.)
+        self.assertRaises(TypeError, float, Foo4(42))
+
+    def test_getattr(self):
+        import sys
+        self.assert_(getattr(sys, 'stdout') is sys.stdout)
+        self.assertRaises(TypeError, getattr, sys, 1)
+        self.assertRaises(TypeError, getattr, sys, 1, "foo")
+        self.assertRaises(TypeError, getattr)
+        if have_unicode:
+            self.assertRaises(UnicodeError, getattr, sys, unichr(sys.maxunicode))
+
+    def test_hasattr(self):
+        import sys
+        self.assert_(hasattr(sys, 'stdout'))
+        self.assertRaises(TypeError, hasattr, sys, 1)
+        self.assertRaises(TypeError, hasattr)
+        if have_unicode:
+            self.assertRaises(UnicodeError, hasattr, sys, unichr(sys.maxunicode))
+
+    def test_hash(self):
+        hash(None)
+        self.assertEqual(hash(1), hash(1L))
+        self.assertEqual(hash(1), hash(1.0))
+        hash('spam')
+        if have_unicode:
+            self.assertEqual(hash('spam'), hash(unicode('spam')))
+        hash((0,1,2,3))
+        def f(): pass
+        self.assertRaises(TypeError, hash, [])
+        self.assertRaises(TypeError, hash, {})
+        # Bug 1536021: Allow hash to return long objects
+        class X:
+            def __hash__(self):
+                return 2**100
+        self.assertEquals(type(hash(X())), int)
+        class Y(object):
+            def __hash__(self):
+                return 2**100
+        self.assertEquals(type(hash(Y())), int)
+        class Z(long):
+            def __hash__(self):
+                return self
+        self.assertEquals(hash(Z(42)), hash(42L))
+
+    def test_hex(self):
+        self.assertEqual(hex(16), '0x10')
+        self.assertEqual(hex(16L), '0x10L')
+        self.assertEqual(hex(-16), '-0x10')
+        self.assertEqual(hex(-16L), '-0x10L')
+        self.assertRaises(TypeError, hex, {})
+
+    def test_id(self):
+        id(None)
+        id(1)
+        id(1L)
+        id(1.0)
+        id('spam')
+        id((0,1,2,3))
+        id([0,1,2,3])
+        id({'spam': 1, 'eggs': 2, 'ham': 3})
+
+    # Test input() later, together with raw_input
+
+    def test_int(self):
+        self.assertEqual(int(314), 314)
+        self.assertEqual(int(3.14), 3)
+        self.assertEqual(int(314L), 314)
+        # Check that conversion from float truncates towards zero
+        self.assertEqual(int(-3.14), -3)
+        self.assertEqual(int(3.9), 3)
+        self.assertEqual(int(-3.9), -3)
+        self.assertEqual(int(3.5), 3)
+        self.assertEqual(int(-3.5), -3)
+        # Different base:
+        self.assertEqual(int("10",16), 16L)
+        if have_unicode:
+            self.assertEqual(int(unicode("10"),16), 16L)
+        # Test conversion from strings and various anomalies
+        for s, v in L:
+            for sign in "", "+", "-":
+                for prefix in "", " ", "\t", "  \t\t  ":
+                    ss = prefix + sign + s
+                    vv = v
+                    if sign == "-" and v is not ValueError:
+                        vv = -v
+                    try:
+                        self.assertEqual(int(ss), vv)
+                    except v:
+                        pass
+
+        s = repr(-1-sys.maxint)
+        x = int(s)
+        self.assertEqual(x+1, -sys.maxint)
+        self.assert_(isinstance(x, int))
+        # should return long
+        self.assertEqual(int(s[1:]), sys.maxint+1)
+
+        # should return long
+        x = int(1e100)
+        self.assert_(isinstance(x, long))
+        x = int(-1e100)
+        self.assert_(isinstance(x, long))
+
+
+        # SF bug 434186:  0x80000000/2 != 0x80000000>>1.
+        # Worked by accident in Windows release build, but failed in debug build.
+        # Failed in all Linux builds.
+        x = -1-sys.maxint
+        self.assertEqual(x >> 1, x//2)
+
+        self.assertRaises(ValueError, int, '123\0')
+        self.assertRaises(ValueError, int, '53', 40)
+
+        # SF bug 1545497: embedded NULs were not detected with
+        # explicit base
+        self.assertRaises(ValueError, int, '123\0', 10)
+        self.assertRaises(ValueError, int, '123\x00 245', 20)
+
+        x = int('1' * 600)
+        self.assert_(isinstance(x, long))
+
+        if have_unicode:
+            x = int(unichr(0x661) * 600)
+            self.assert_(isinstance(x, long))
+
+        self.assertRaises(TypeError, int, 1, 12)
+
+        self.assertEqual(int('0123', 0), 83)
+        self.assertEqual(int('0x123', 16), 291)
+
+        # SF bug 1334662: int(string, base) wrong answers
+        # Various representations of 2**32 evaluated to 0
+        # rather than 2**32 in previous versions
+
+        self.assertEqual(int('100000000000000000000000000000000', 2), 4294967296L)
+        self.assertEqual(int('102002022201221111211', 3), 4294967296L)
+        self.assertEqual(int('10000000000000000', 4), 4294967296L)
+        self.assertEqual(int('32244002423141', 5), 4294967296L)
+        self.assertEqual(int('1550104015504', 6), 4294967296L)
+        self.assertEqual(int('211301422354', 7), 4294967296L)
+        self.assertEqual(int('40000000000', 8), 4294967296L)
+        self.assertEqual(int('12068657454', 9), 4294967296L)
+        self.assertEqual(int('4294967296', 10), 4294967296L)
+        self.assertEqual(int('1904440554', 11), 4294967296L)
+        self.assertEqual(int('9ba461594', 12), 4294967296L)
+        self.assertEqual(int('535a79889', 13), 4294967296L)
+        self.assertEqual(int('2ca5b7464', 14), 4294967296L)
+        self.assertEqual(int('1a20dcd81', 15), 4294967296L)
+        self.assertEqual(int('100000000', 16), 4294967296L)
+        self.assertEqual(int('a7ffda91', 17), 4294967296L)
+        self.assertEqual(int('704he7g4', 18), 4294967296L)
+        self.assertEqual(int('4f5aff66', 19), 4294967296L)
+        self.assertEqual(int('3723ai4g', 20), 4294967296L)
+        self.assertEqual(int('281d55i4', 21), 4294967296L)
+        self.assertEqual(int('1fj8b184', 22), 4294967296L)
+        self.assertEqual(int('1606k7ic', 23), 4294967296L)
+        self.assertEqual(int('mb994ag', 24), 4294967296L)
+        self.assertEqual(int('hek2mgl', 25), 4294967296L)
+        self.assertEqual(int('dnchbnm', 26), 4294967296L)
+        self.assertEqual(int('b28jpdm', 27), 4294967296L)
+        self.assertEqual(int('8pfgih4', 28), 4294967296L)
+        self.assertEqual(int('76beigg', 29), 4294967296L)
+        self.assertEqual(int('5qmcpqg', 30), 4294967296L)
+        self.assertEqual(int('4q0jto4', 31), 4294967296L)
+        self.assertEqual(int('4000000', 32), 4294967296L)
+        self.assertEqual(int('3aokq94', 33), 4294967296L)
+        self.assertEqual(int('2qhxjli', 34), 4294967296L)
+        self.assertEqual(int('2br45qb', 35), 4294967296L)
+        self.assertEqual(int('1z141z4', 36), 4294967296L)
+
+        # SF bug 1334662: int(string, base) wrong answers
+        # Checks for proper evaluation of 2**32 + 1
+        self.assertEqual(int('100000000000000000000000000000001', 2), 4294967297L)
+        self.assertEqual(int('102002022201221111212', 3), 4294967297L)
+        self.assertEqual(int('10000000000000001', 4), 4294967297L)
+        self.assertEqual(int('32244002423142', 5), 4294967297L)
+        self.assertEqual(int('1550104015505', 6), 4294967297L)
+        self.assertEqual(int('211301422355', 7), 4294967297L)
+        self.assertEqual(int('40000000001', 8), 4294967297L)
+        self.assertEqual(int('12068657455', 9), 4294967297L)
+        self.assertEqual(int('4294967297', 10), 4294967297L)
+        self.assertEqual(int('1904440555', 11), 4294967297L)
+        self.assertEqual(int('9ba461595', 12), 4294967297L)
+        self.assertEqual(int('535a7988a', 13), 4294967297L)
+        self.assertEqual(int('2ca5b7465', 14), 4294967297L)
+        self.assertEqual(int('1a20dcd82', 15), 4294967297L)
+        self.assertEqual(int('100000001', 16), 4294967297L)
+        self.assertEqual(int('a7ffda92', 17), 4294967297L)
+        self.assertEqual(int('704he7g5', 18), 4294967297L)
+        self.assertEqual(int('4f5aff67', 19), 4294967297L)
+        self.assertEqual(int('3723ai4h', 20), 4294967297L)
+        self.assertEqual(int('281d55i5', 21), 4294967297L)
+        self.assertEqual(int('1fj8b185', 22), 4294967297L)
+        self.assertEqual(int('1606k7id', 23), 4294967297L)
+        self.assertEqual(int('mb994ah', 24), 4294967297L)
+        self.assertEqual(int('hek2mgm', 25), 4294967297L)
+        self.assertEqual(int('dnchbnn', 26), 4294967297L)
+        self.assertEqual(int('b28jpdn', 27), 4294967297L)
+        self.assertEqual(int('8pfgih5', 28), 4294967297L)
+        self.assertEqual(int('76beigh', 29), 4294967297L)
+        self.assertEqual(int('5qmcpqh', 30), 4294967297L)
+        self.assertEqual(int('4q0jto5', 31), 4294967297L)
+        self.assertEqual(int('4000001', 32), 4294967297L)
+        self.assertEqual(int('3aokq95', 33), 4294967297L)
+        self.assertEqual(int('2qhxjlj', 34), 4294967297L)
+        self.assertEqual(int('2br45qc', 35), 4294967297L)
+        self.assertEqual(int('1z141z5', 36), 4294967297L)
+
+    def test_intconversion(self):
+        # Test __int__()
+        class Foo0:
+            def __int__(self):
+                return 42
+
+        class Foo1(object):
+            def __int__(self):
+                return 42
+
+        class Foo2(int):
+            def __int__(self):
+                return 42
+
+        class Foo3(int):
+            def __int__(self):
+                return self
+
+        class Foo4(int):
+            def __int__(self):
+                return 42L
+
+        class Foo5(int):
+            def __int__(self):
+                return 42.
+
+        self.assertEqual(int(Foo0()), 42)
+        self.assertEqual(int(Foo1()), 42)
+        self.assertEqual(int(Foo2()), 42)
+        self.assertEqual(int(Foo3()), 0)
+        self.assertEqual(int(Foo4()), 42L)
+        self.assertRaises(TypeError, int, Foo5())
+
+    def test_intern(self):
+        self.assertRaises(TypeError, intern)
+        s = "never interned before"
+        self.assert_(intern(s) is s)
+        s2 = s.swapcase().swapcase()
+        self.assert_(intern(s2) is s)
+
+        # Subclasses of string can't be interned, because they
+        # provide too much opportunity for insane things to happen.
+        # We don't want them in the interned dict and if they aren't
+        # actually interned, we don't want to create the appearance
+        # that they are by allowing intern() to succeeed.
+        class S(str):
+            def __hash__(self):
+                return 123
+
+        self.assertRaises(TypeError, intern, S("abc"))
+
+        # It's still safe to pass these strings to routines that
+        # call intern internally, e.g. PyObject_SetAttr().
+        s = S("abc")
+        setattr(s, s, s)
+        self.assertEqual(getattr(s, s), s)
+
+    def test_iter(self):
+        self.assertRaises(TypeError, iter)
+        self.assertRaises(TypeError, iter, 42, 42)
+        lists = [("1", "2"), ["1", "2"], "12"]
+        if have_unicode:
+            lists.append(unicode("12"))
+        for l in lists:
+            i = iter(l)
+            self.assertEqual(i.next(), '1')
+            self.assertEqual(i.next(), '2')
+            self.assertRaises(StopIteration, i.next)
+
+    def test_isinstance(self):
+        class C:
+            pass
+        class D(C):
+            pass
+        class E:
+            pass
+        c = C()
+        d = D()
+        e = E()
+        self.assert_(isinstance(c, C))
+        self.assert_(isinstance(d, C))
+        self.assert_(not isinstance(e, C))
+        self.assert_(not isinstance(c, D))
+        self.assert_(not isinstance('foo', E))
+        self.assertRaises(TypeError, isinstance, E, 'foo')
+        self.assertRaises(TypeError, isinstance)
+
+    def test_issubclass(self):
+        class C:
+            pass
+        class D(C):
+            pass
+        class E:
+            pass
+        c = C()
+        d = D()
+        e = E()
+        self.assert_(issubclass(D, C))
+        self.assert_(issubclass(C, C))
+        self.assert_(not issubclass(C, D))
+        self.assertRaises(TypeError, issubclass, 'foo', E)
+        self.assertRaises(TypeError, issubclass, E, 'foo')
+        self.assertRaises(TypeError, issubclass)
+
+    def test_len(self):
+        self.assertEqual(len('123'), 3)
+        self.assertEqual(len(()), 0)
+        self.assertEqual(len((1, 2, 3, 4)), 4)
+        self.assertEqual(len([1, 2, 3, 4]), 4)
+        self.assertEqual(len({}), 0)
+        self.assertEqual(len({'a':1, 'b': 2}), 2)
+        class BadSeq:
+            def __len__(self):
+                raise ValueError
+        self.assertRaises(ValueError, len, BadSeq())
+
+    def test_list(self):
+        self.assertEqual(list([]), [])
+        l0_3 = [0, 1, 2, 3]
+        l0_3_bis = list(l0_3)
+        self.assertEqual(l0_3, l0_3_bis)
+        self.assert_(l0_3 is not l0_3_bis)
+        self.assertEqual(list(()), [])
+        self.assertEqual(list((0, 1, 2, 3)), [0, 1, 2, 3])
+        self.assertEqual(list(''), [])
+        self.assertEqual(list('spam'), ['s', 'p', 'a', 'm'])
+
+        if sys.maxint == 0x7fffffff:
+            # This test can currently only work on 32-bit machines.
+            # XXX If/when PySequence_Length() returns a ssize_t, it should be
+            # XXX re-enabled.
+            # Verify clearing of bug #556025.
+            # This assumes that the max data size (sys.maxint) == max
+            # address size this also assumes that the address size is at
+            # least 4 bytes with 8 byte addresses, the bug is not well
+            # tested
+            #
+            # Note: This test is expected to SEGV under Cygwin 1.3.12 or
+            # earlier due to a newlib bug.  See the following mailing list
+            # thread for the details:
+
+            #     http://sources.redhat.com/ml/newlib/2002/msg00369.html
+            self.assertRaises(MemoryError, [None].__mul__, sys.maxint // 2)
+
+        # This code used to segfault in Py2.4a3
+        x = []
+        x.extend(-y for y in x)
+        self.assertEqual(x, [])
+
+    def test_long(self):
+        self.assertEqual(long(314), 314L)
+        self.assertEqual(long(3.14), 3L)
+        self.assertEqual(long(314L), 314L)
+        # Check that conversion from float truncates towards zero
+        self.assertEqual(long(-3.14), -3L)
+        self.assertEqual(long(3.9), 3L)
+        self.assertEqual(long(-3.9), -3L)
+        self.assertEqual(long(3.5), 3L)
+        self.assertEqual(long(-3.5), -3L)
+        self.assertEqual(long("-3"), -3L)
+        if have_unicode:
+            self.assertEqual(long(unicode("-3")), -3L)
+        # Different base:
+        self.assertEqual(long("10",16), 16L)
+        if have_unicode:
+            self.assertEqual(long(unicode("10"),16), 16L)
+        # Check conversions from string (same test set as for int(), and then some)
+        LL = [
+                ('1' + '0'*20, 10L**20),
+                ('1' + '0'*100, 10L**100)
+        ]
+        L2 = L[:]
+        if have_unicode:
+            L2 += [
+                (unicode('1') + unicode('0')*20, 10L**20),
+                (unicode('1') + unicode('0')*100, 10L**100),
+        ]
+        for s, v in L2 + LL:
+            for sign in "", "+", "-":
+                for prefix in "", " ", "\t", "  \t\t  ":
+                    ss = prefix + sign + s
+                    vv = v
+                    if sign == "-" and v is not ValueError:
+                        vv = -v
+                    try:
+                        self.assertEqual(long(ss), long(vv))
+                    except v:
+                        pass
+
+        self.assertRaises(ValueError, long, '123\0')
+        self.assertRaises(ValueError, long, '53', 40)
+        self.assertRaises(TypeError, long, 1, 12)
+
+        # SF patch #1638879: embedded NULs were not detected with
+        # explicit base
+        self.assertRaises(ValueError, long, '123\0', 10)
+        self.assertRaises(ValueError, long, '123\x00 245', 20)
+
+        self.assertEqual(long('100000000000000000000000000000000', 2),
+                         4294967296)
+        self.assertEqual(long('102002022201221111211', 3), 4294967296)
+        self.assertEqual(long('10000000000000000', 4), 4294967296)
+        self.assertEqual(long('32244002423141', 5), 4294967296)
+        self.assertEqual(long('1550104015504', 6), 4294967296)
+        self.assertEqual(long('211301422354', 7), 4294967296)
+        self.assertEqual(long('40000000000', 8), 4294967296)
+        self.assertEqual(long('12068657454', 9), 4294967296)
+        self.assertEqual(long('4294967296', 10), 4294967296)
+        self.assertEqual(long('1904440554', 11), 4294967296)
+        self.assertEqual(long('9ba461594', 12), 4294967296)
+        self.assertEqual(long('535a79889', 13), 4294967296)
+        self.assertEqual(long('2ca5b7464', 14), 4294967296)
+        self.assertEqual(long('1a20dcd81', 15), 4294967296)
+        self.assertEqual(long('100000000', 16), 4294967296)
+        self.assertEqual(long('a7ffda91', 17), 4294967296)
+        self.assertEqual(long('704he7g4', 18), 4294967296)
+        self.assertEqual(long('4f5aff66', 19), 4294967296)
+        self.assertEqual(long('3723ai4g', 20), 4294967296)
+        self.assertEqual(long('281d55i4', 21), 4294967296)
+        self.assertEqual(long('1fj8b184', 22), 4294967296)
+        self.assertEqual(long('1606k7ic', 23), 4294967296)
+        self.assertEqual(long('mb994ag', 24), 4294967296)
+        self.assertEqual(long('hek2mgl', 25), 4294967296)
+        self.assertEqual(long('dnchbnm', 26), 4294967296)
+        self.assertEqual(long('b28jpdm', 27), 4294967296)
+        self.assertEqual(long('8pfgih4', 28), 4294967296)
+        self.assertEqual(long('76beigg', 29), 4294967296)
+        self.assertEqual(long('5qmcpqg', 30), 4294967296)
+        self.assertEqual(long('4q0jto4', 31), 4294967296)
+        self.assertEqual(long('4000000', 32), 4294967296)
+        self.assertEqual(long('3aokq94', 33), 4294967296)
+        self.assertEqual(long('2qhxjli', 34), 4294967296)
+        self.assertEqual(long('2br45qb', 35), 4294967296)
+        self.assertEqual(long('1z141z4', 36), 4294967296)
+
+        self.assertEqual(long('100000000000000000000000000000001', 2),
+                         4294967297)
+        self.assertEqual(long('102002022201221111212', 3), 4294967297)
+        self.assertEqual(long('10000000000000001', 4), 4294967297)
+        self.assertEqual(long('32244002423142', 5), 4294967297)
+        self.assertEqual(long('1550104015505', 6), 4294967297)
+        self.assertEqual(long('211301422355', 7), 4294967297)
+        self.assertEqual(long('40000000001', 8), 4294967297)
+        self.assertEqual(long('12068657455', 9), 4294967297)
+        self.assertEqual(long('4294967297', 10), 4294967297)
+        self.assertEqual(long('1904440555', 11), 4294967297)
+        self.assertEqual(long('9ba461595', 12), 4294967297)
+        self.assertEqual(long('535a7988a', 13), 4294967297)
+        self.assertEqual(long('2ca5b7465', 14), 4294967297)
+        self.assertEqual(long('1a20dcd82', 15), 4294967297)
+        self.assertEqual(long('100000001', 16), 4294967297)
+        self.assertEqual(long('a7ffda92', 17), 4294967297)
+        self.assertEqual(long('704he7g5', 18), 4294967297)
+        self.assertEqual(long('4f5aff67', 19), 4294967297)
+        self.assertEqual(long('3723ai4h', 20), 4294967297)
+        self.assertEqual(long('281d55i5', 21), 4294967297)
+        self.assertEqual(long('1fj8b185', 22), 4294967297)
+        self.assertEqual(long('1606k7id', 23), 4294967297)
+        self.assertEqual(long('mb994ah', 24), 4294967297)
+        self.assertEqual(long('hek2mgm', 25), 4294967297)
+        self.assertEqual(long('dnchbnn', 26), 4294967297)
+        self.assertEqual(long('b28jpdn', 27), 4294967297)
+        self.assertEqual(long('8pfgih5', 28), 4294967297)
+        self.assertEqual(long('76beigh', 29), 4294967297)
+        self.assertEqual(long('5qmcpqh', 30), 4294967297)
+        self.assertEqual(long('4q0jto5', 31), 4294967297)
+        self.assertEqual(long('4000001', 32), 4294967297)
+        self.assertEqual(long('3aokq95', 33), 4294967297)
+        self.assertEqual(long('2qhxjlj', 34), 4294967297)
+        self.assertEqual(long('2br45qc', 35), 4294967297)
+        self.assertEqual(long('1z141z5', 36), 4294967297)
+
+
+    def test_longconversion(self):
+        # Test __long__()
+        class Foo0:
+            def __long__(self):
+                return 42L
+
+        class Foo1(object):
+            def __long__(self):
+                return 42L
+
+        class Foo2(long):
+            def __long__(self):
+                return 42L
+
+        class Foo3(long):
+            def __long__(self):
+                return self
+
+        class Foo4(long):
+            def __long__(self):
+                return 42
+
+        class Foo5(long):
+            def __long__(self):
+                return 42.
+
+        self.assertEqual(long(Foo0()), 42L)
+        self.assertEqual(long(Foo1()), 42L)
+        self.assertEqual(long(Foo2()), 42L)
+        self.assertEqual(long(Foo3()), 0)
+        self.assertEqual(long(Foo4()), 42)
+        self.assertRaises(TypeError, long, Foo5())
+
+    def test_map(self):
+        self.assertEqual(
+            map(None, 'hello world'),
+            ['h','e','l','l','o',' ','w','o','r','l','d']
+        )
+        self.assertEqual(
+            map(None, 'abcd', 'efg'),
+            [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', None)]
+        )
+        self.assertEqual(
+            map(None, range(10)),
+            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+        )
+        self.assertEqual(
+            map(lambda x: x*x, range(1,4)),
+            [1, 4, 9]
+        )
+        try:
+            from math import sqrt
+        except ImportError:
+            def sqrt(x):
+                return pow(x, 0.5)
+        self.assertEqual(
+            map(lambda x: map(sqrt,x), [[16, 4], [81, 9]]),
+            [[4.0, 2.0], [9.0, 3.0]]
+        )
+        self.assertEqual(
+            map(lambda x, y: x+y, [1,3,2], [9,1,4]),
+            [10, 4, 6]
+        )
+
+        def plus(*v):
+            accu = 0
+            for i in v: accu = accu + i
+            return accu
+        self.assertEqual(
+            map(plus, [1, 3, 7]),
+            [1, 3, 7]
+        )
+        self.assertEqual(
+            map(plus, [1, 3, 7], [4, 9, 2]),
+            [1+4, 3+9, 7+2]
+        )
+        self.assertEqual(
+            map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0]),
+            [1+4+1, 3+9+1, 7+2+0]
+        )
+        self.assertEqual(
+            map(None, Squares(10)),
+            [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
+        )
+        self.assertEqual(
+            map(int, Squares(10)),
+            [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
+        )
+        self.assertEqual(
+            map(None, Squares(3), Squares(2)),
+            [(0,0), (1,1), (4,None)]
+        )
+        self.assertEqual(
+            map(max, Squares(3), Squares(2)),
+            [0, 1, 4]
+        )
+        self.assertRaises(TypeError, map)
+        self.assertRaises(TypeError, map, lambda x: x, 42)
+        self.assertEqual(map(None, [42]), [42])
+        class BadSeq:
+            def __getitem__(self, index):
+                raise ValueError
+        self.assertRaises(ValueError, map, lambda x: x, BadSeq())
+        def badfunc(x):
+            raise RuntimeError
+        self.assertRaises(RuntimeError, map, badfunc, range(5))
+
+    def test_max(self):
+        self.assertEqual(max('123123'), '3')
+        self.assertEqual(max(1, 2, 3), 3)
+        self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)
+        self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)
+
+        self.assertEqual(max(1, 2L, 3.0), 3.0)
+        self.assertEqual(max(1L, 2.0, 3), 3)
+        self.assertEqual(max(1.0, 2, 3L), 3L)
+
+        for stmt in (
+            "max(key=int)",                 # no args
+            "max(1, key=int)",              # single arg not iterable
+            "max(1, 2, keystone=int)",      # wrong keyword
+            "max(1, 2, key=int, abc=int)",  # two many keywords
+            "max(1, 2, key=1)",             # keyfunc is not callable
+            ):
+            try:
+                exec(stmt) in globals()
+            except TypeError:
+                pass
+            else:
+                self.fail(stmt)
+
+        self.assertEqual(max((1,), key=neg), 1)     # one elem iterable
+        self.assertEqual(max((1,2), key=neg), 1)    # two elem iterable
+        self.assertEqual(max(1, 2, key=neg), 1)     # two elems
+
+        data = [random.randrange(200) for i in range(100)]
+        keys = dict((elem, random.randrange(50)) for elem in data)
+        f = keys.__getitem__
+        self.assertEqual(max(data, key=f),
+                         sorted(reversed(data), key=f)[-1])
+
+    def test_min(self):
+        self.assertEqual(min('123123'), '1')
+        self.assertEqual(min(1, 2, 3), 1)
+        self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1)
+        self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1)
+
+        self.assertEqual(min(1, 2L, 3.0), 1)
+        self.assertEqual(min(1L, 2.0, 3), 1L)
+        self.assertEqual(min(1.0, 2, 3L), 1.0)
+
+        self.assertRaises(TypeError, min)
+        self.assertRaises(TypeError, min, 42)
+        self.assertRaises(ValueError, min, ())
+        class BadSeq:
+            def __getitem__(self, index):
+                raise ValueError
+        self.assertRaises(ValueError, min, BadSeq())
+        class BadNumber:
+            def __cmp__(self, other):
+                raise ValueError
+        self.assertRaises(ValueError, min, (42, BadNumber()))
+
+        for stmt in (
+            "min(key=int)",                 # no args
+            "min(1, key=int)",              # single arg not iterable
+            "min(1, 2, keystone=int)",      # wrong keyword
+            "min(1, 2, key=int, abc=int)",  # two many keywords
+            "min(1, 2, key=1)",             # keyfunc is not callable
+            ):
+            try:
+                exec(stmt) in globals()
+            except TypeError:
+                pass
+            else:
+                self.fail(stmt)
+
+        self.assertEqual(min((1,), key=neg), 1)     # one elem iterable
+        self.assertEqual(min((1,2), key=neg), 2)    # two elem iterable
+        self.assertEqual(min(1, 2, key=neg), 2)     # two elems
+
+        data = [random.randrange(200) for i in range(100)]
+        keys = dict((elem, random.randrange(50)) for elem in data)
+        f = keys.__getitem__
+        self.assertEqual(min(data, key=f),
+                         sorted(data, key=f)[0])
+
+    def test_oct(self):
+        self.assertEqual(oct(100), '0144')
+        self.assertEqual(oct(100L), '0144L')
+        self.assertEqual(oct(-100), '-0144')
+        self.assertEqual(oct(-100L), '-0144L')
+        self.assertRaises(TypeError, oct, ())
+
+    def write_testfile(self):
+        # NB the first 4 lines are also used to test input and raw_input, below
+        fp = open(TESTFN, 'w')
+        try:
+            fp.write('1+1\n')
+            fp.write('1+1\n')
+            fp.write('The quick brown fox jumps over the lazy dog')
+            fp.write('.\n')
+            fp.write('Dear John\n')
+            fp.write('XXX'*100)
+            fp.write('YYY'*100)
+        finally:
+            fp.close()
+
+    def test_open(self):
+        self.write_testfile()
+        fp = open(TESTFN, 'r')
+        try:
+            self.assertEqual(fp.readline(4), '1+1\n')
+            self.assertEqual(fp.readline(4), '1+1\n')
+            self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n')
+            self.assertEqual(fp.readline(4), 'Dear')
+            self.assertEqual(fp.readline(100), ' John\n')
+            self.assertEqual(fp.read(300), 'XXX'*100)
+            self.assertEqual(fp.read(1000), 'YYY'*100)
+        finally:
+            fp.close()
+        unlink(TESTFN)
+
+    def test_ord(self):
+        self.assertEqual(ord(' '), 32)
+        self.assertEqual(ord('A'), 65)
+        self.assertEqual(ord('a'), 97)
+        if have_unicode:
+            self.assertEqual(ord(unichr(sys.maxunicode)), sys.maxunicode)
+        self.assertRaises(TypeError, ord, 42)
+        if have_unicode:
+            self.assertRaises(TypeError, ord, unicode("12"))
+
+    def test_pow(self):
+        self.assertEqual(pow(0,0), 1)
+        self.assertEqual(pow(0,1), 0)
+        self.assertEqual(pow(1,0), 1)
+        self.assertEqual(pow(1,1), 1)
+
+        self.assertEqual(pow(2,0), 1)
+        self.assertEqual(pow(2,10), 1024)
+        self.assertEqual(pow(2,20), 1024*1024)
+        self.assertEqual(pow(2,30), 1024*1024*1024)
+
+        self.assertEqual(pow(-2,0), 1)
+        self.assertEqual(pow(-2,1), -2)
+        self.assertEqual(pow(-2,2), 4)
+        self.assertEqual(pow(-2,3), -8)
+
+        self.assertEqual(pow(0L,0), 1)
+        self.assertEqual(pow(0L,1), 0)
+        self.assertEqual(pow(1L,0), 1)
+        self.assertEqual(pow(1L,1), 1)
+
+        self.assertEqual(pow(2L,0), 1)
+        self.assertEqual(pow(2L,10), 1024)
+        self.assertEqual(pow(2L,20), 1024*1024)
+        self.assertEqual(pow(2L,30), 1024*1024*1024)
+
+        self.assertEqual(pow(-2L,0), 1)
+        self.assertEqual(pow(-2L,1), -2)
+        self.assertEqual(pow(-2L,2), 4)
+        self.assertEqual(pow(-2L,3), -8)
+
+        self.assertAlmostEqual(pow(0.,0), 1.)
+        self.assertAlmostEqual(pow(0.,1), 0.)
+        self.assertAlmostEqual(pow(1.,0), 1.)
+        self.assertAlmostEqual(pow(1.,1), 1.)
+
+        self.assertAlmostEqual(pow(2.,0), 1.)
+        self.assertAlmostEqual(pow(2.,10), 1024.)
+        self.assertAlmostEqual(pow(2.,20), 1024.*1024.)
+        self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.)
+
+        self.assertAlmostEqual(pow(-2.,0), 1.)
+        self.assertAlmostEqual(pow(-2.,1), -2.)
+        self.assertAlmostEqual(pow(-2.,2), 4.)
+        self.assertAlmostEqual(pow(-2.,3), -8.)
+
+        for x in 2, 2L, 2.0:
+            for y in 10, 10L, 10.0:
+                for z in 1000, 1000L, 1000.0:
+                    if isinstance(x, float) or \
+                       isinstance(y, float) or \
+                       isinstance(z, float):
+                        self.assertRaises(TypeError, pow, x, y, z)
+                    else:
+                        self.assertAlmostEqual(pow(x, y, z), 24.0)
+
+        self.assertRaises(TypeError, pow, -1, -2, 3)
+        self.assertRaises(ValueError, pow, 1, 2, 0)
+        self.assertRaises(TypeError, pow, -1L, -2L, 3L)
+        self.assertRaises(ValueError, pow, 1L, 2L, 0L)
+        self.assertRaises(ValueError, pow, -342.43, 0.234)
+
+        self.assertRaises(TypeError, pow)
+
+    def test_range(self):
+        self.assertEqual(range(3), [0, 1, 2])
+        self.assertEqual(range(1, 5), [1, 2, 3, 4])
+        self.assertEqual(range(0), [])
+        self.assertEqual(range(-3), [])
+        self.assertEqual(range(1, 10, 3), [1, 4, 7])
+        self.assertEqual(range(5, -5, -3), [5, 2, -1, -4])
+
+        # Now test range() with longs
+        self.assertEqual(range(-2**100), [])
+        self.assertEqual(range(0, -2**100), [])
+        self.assertEqual(range(0, 2**100, -1), [])
+        self.assertEqual(range(0, 2**100, -1), [])
+
+        a = long(10 * sys.maxint)
+        b = long(100 * sys.maxint)
+        c = long(50 * sys.maxint)
+
+        self.assertEqual(range(a, a+2), [a, a+1])
+        self.assertEqual(range(a+2, a, -1L), [a+2, a+1])
+        self.assertEqual(range(a+4, a, -2), [a+4, a+2])
+
+        seq = range(a, b, c)
+        self.assert_(a in seq)
+        self.assert_(b not in seq)
+        self.assertEqual(len(seq), 2)
+
+        seq = range(b, a, -c)
+        self.assert_(b in seq)
+        self.assert_(a not in seq)
+        self.assertEqual(len(seq), 2)
+
+        seq = range(-a, -b, -c)
+        self.assert_(-a in seq)
+        self.assert_(-b not in seq)
+        self.assertEqual(len(seq), 2)
+
+        self.assertRaises(TypeError, range)
+        self.assertRaises(TypeError, range, 1, 2, 3, 4)
+        self.assertRaises(ValueError, range, 1, 2, 0)
+        self.assertRaises(ValueError, range, a, a + 1, long(0))
+
+        class badzero(int):
+            def __cmp__(self, other):
+                raise RuntimeError
+        self.assertRaises(RuntimeError, range, a, a + 1, badzero(1))
+
+        # Reject floats when it would require PyLongs to represent.
+        # (smaller floats still accepted, but deprecated)
+        self.assertRaises(TypeError, range, 1e100, 1e101, 1e101)
+
+        self.assertRaises(TypeError, range, 0, "spam")
+        self.assertRaises(TypeError, range, 0, 42, "spam")
+
+        self.assertRaises(OverflowError, range, -sys.maxint, sys.maxint)
+        self.assertRaises(OverflowError, range, 0, 2*sys.maxint)
+
+    def test_input_and_raw_input(self):
+        self.write_testfile()
+        fp = open(TESTFN, 'r')
+        savestdin = sys.stdin
+        savestdout = sys.stdout # Eats the echo
+        try:
+            sys.stdin = fp
+            sys.stdout = BitBucket()
+            self.assertEqual(input(), 2)
+            self.assertEqual(input('testing\n'), 2)
+            self.assertEqual(raw_input(), 'The quick brown fox jumps over the lazy dog.')
+            self.assertEqual(raw_input('testing\n'), 'Dear John')
+
+            # SF 1535165: don't segfault on closed stdin
+            # sys.stdout must be a regular file for triggering
+            sys.stdout = savestdout
+            sys.stdin.close()
+            self.assertRaises(ValueError, input)
+
+            sys.stdout = BitBucket()
+            sys.stdin = cStringIO.StringIO("NULL\0")
+            self.assertRaises(TypeError, input, 42, 42)
+            sys.stdin = cStringIO.StringIO("    'whitespace'")
+            self.assertEqual(input(), 'whitespace')
+            sys.stdin = cStringIO.StringIO()
+            self.assertRaises(EOFError, input)
+
+            # SF 876178: make sure input() respect future options.
+            sys.stdin = cStringIO.StringIO('1/2')
+            sys.stdout = cStringIO.StringIO()
+            exec compile('print input()', 'test_builtin_tmp', 'exec')
+            sys.stdin.seek(0, 0)
+            exec compile('from __future__ import division;print input()',
+                         'test_builtin_tmp', 'exec')
+            sys.stdin.seek(0, 0)
+            exec compile('print input()', 'test_builtin_tmp', 'exec')
+            # The result we expect depends on whether new division semantics
+            # are already in effect.
+            if 1/2 == 0:
+                # This test was compiled with old semantics.
+                expected = ['0', '0.5', '0']
+            else:
+                # This test was compiled with new semantics (e.g., -Qnew
+                # was given on the command line.
+                expected = ['0.5', '0.5', '0.5']
+            self.assertEqual(sys.stdout.getvalue().splitlines(), expected)
+
+            del sys.stdout
+            self.assertRaises(RuntimeError, input, 'prompt')
+            del sys.stdin
+            self.assertRaises(RuntimeError, input, 'prompt')
+        finally:
+            sys.stdin = savestdin
+            sys.stdout = savestdout
+            fp.close()
+            unlink(TESTFN)
+
+    def test_reduce(self):
+        self.assertEqual(reduce(lambda x, y: x+y, ['a', 'b', 'c'], ''), 'abc')
+        self.assertEqual(
+            reduce(lambda x, y: x+y, [['a', 'c'], [], ['d', 'w']], []),
+            ['a','c','d','w']
+        )
+        self.assertEqual(reduce(lambda x, y: x*y, range(2,8), 1), 5040)
+        self.assertEqual(
+            reduce(lambda x, y: x*y, range(2,21), 1L),
+            2432902008176640000L
+        )
+        self.assertEqual(reduce(lambda x, y: x+y, Squares(10)), 285)
+        self.assertEqual(reduce(lambda x, y: x+y, Squares(10), 0), 285)
+        self.assertEqual(reduce(lambda x, y: x+y, Squares(0), 0), 0)
+        self.assertRaises(TypeError, reduce)
+        self.assertRaises(TypeError, reduce, 42, 42)
+        self.assertRaises(TypeError, reduce, 42, 42, 42)
+        self.assertEqual(reduce(42, "1"), "1") # func is never called with one item
+        self.assertEqual(reduce(42, "", "1"), "1") # func is never called with one item
+        self.assertRaises(TypeError, reduce, 42, (42, 42))
+
+        class BadSeq:
+            def __getitem__(self, index):
+                raise ValueError
+        self.assertRaises(ValueError, reduce, 42, BadSeq())
+
+    def test_reload(self):
+        import marshal
+        reload(marshal)
+        import string
+        reload(string)
+        ## import sys
+        ## self.assertRaises(ImportError, reload, sys)
+
+    def test_repr(self):
+        self.assertEqual(repr(''), '\'\'')
+        self.assertEqual(repr(0), '0')
+        self.assertEqual(repr(0L), '0L')
+        self.assertEqual(repr(()), '()')
+        self.assertEqual(repr([]), '[]')
+        self.assertEqual(repr({}), '{}')
+        a = []
+        a.append(a)
+        self.assertEqual(repr(a), '[[...]]')
+        a = {}
+        a[0] = a
+        self.assertEqual(repr(a), '{0: {...}}')
+
+    def test_round(self):
+        self.assertEqual(round(0.0), 0.0)
+        self.assertEqual(round(1.0), 1.0)
+        self.assertEqual(round(10.0), 10.0)
+        self.assertEqual(round(1000000000.0), 1000000000.0)
+        self.assertEqual(round(1e20), 1e20)
+
+        self.assertEqual(round(-1.0), -1.0)
+        self.assertEqual(round(-10.0), -10.0)
+        self.assertEqual(round(-1000000000.0), -1000000000.0)
+        self.assertEqual(round(-1e20), -1e20)
+
+        self.assertEqual(round(0.1), 0.0)
+        self.assertEqual(round(1.1), 1.0)
+        self.assertEqual(round(10.1), 10.0)
+        self.assertEqual(round(1000000000.1), 1000000000.0)
+
+        self.assertEqual(round(-1.1), -1.0)
+        self.assertEqual(round(-10.1), -10.0)
+        self.assertEqual(round(-1000000000.1), -1000000000.0)
+
+        self.assertEqual(round(0.9), 1.0)
+        self.assertEqual(round(9.9), 10.0)
+        self.assertEqual(round(999999999.9), 1000000000.0)
+
+        self.assertEqual(round(-0.9), -1.0)
+        self.assertEqual(round(-9.9), -10.0)
+        self.assertEqual(round(-999999999.9), -1000000000.0)
+
+        self.assertEqual(round(-8.0, -1), -10.0)
+
+        # test new kwargs
+        self.assertEqual(round(number=-8.0, ndigits=-1), -10.0)
+
+        self.assertRaises(TypeError, round)
+
+    def test_setattr(self):
+        setattr(sys, 'spam', 1)
+        self.assertEqual(sys.spam, 1)
+        self.assertRaises(TypeError, setattr, sys, 1, 'spam')
+        self.assertRaises(TypeError, setattr)
+
+    def test_str(self):
+        self.assertEqual(str(''), '')
+        self.assertEqual(str(0), '0')
+        self.assertEqual(str(0L), '0')
+        self.assertEqual(str(()), '()')
+        self.assertEqual(str([]), '[]')
+        self.assertEqual(str({}), '{}')
+        a = []
+        a.append(a)
+        self.assertEqual(str(a), '[[...]]')
+        a = {}
+        a[0] = a
+        self.assertEqual(str(a), '{0: {...}}')
+
+    def test_sum(self):
+        self.assertEqual(sum([]), 0)
+        self.assertEqual(sum(range(2,8)), 27)
+        self.assertEqual(sum(iter(range(2,8))), 27)
+        self.assertEqual(sum(Squares(10)), 285)
+        self.assertEqual(sum(iter(Squares(10))), 285)
+        self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])
+
+        self.assertRaises(TypeError, sum)
+        self.assertRaises(TypeError, sum, 42)
+        self.assertRaises(TypeError, sum, ['a', 'b', 'c'])
+        self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '')
+        self.assertRaises(TypeError, sum, [[1], [2], [3]])
+        self.assertRaises(TypeError, sum, [{2:3}])
+        self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3})
+
+        class BadSeq:
+            def __getitem__(self, index):
+                raise ValueError
+        self.assertRaises(ValueError, sum, BadSeq())
+
+    def test_tuple(self):
+        self.assertEqual(tuple(()), ())
+        t0_3 = (0, 1, 2, 3)
+        t0_3_bis = tuple(t0_3)
+        self.assert_(t0_3 is t0_3_bis)
+        self.assertEqual(tuple([]), ())
+        self.assertEqual(tuple([0, 1, 2, 3]), (0, 1, 2, 3))
+        self.assertEqual(tuple(''), ())
+        self.assertEqual(tuple('spam'), ('s', 'p', 'a', 'm'))
+
+    def test_type(self):
+        self.assertEqual(type(''),  type('123'))
+        self.assertNotEqual(type(''), type(()))
+
+    def test_unichr(self):
+        if have_unicode:
+            self.assertEqual(unichr(32), unicode(' '))
+            self.assertEqual(unichr(65), unicode('A'))
+            self.assertEqual(unichr(97), unicode('a'))
+            self.assertEqual(
+                unichr(sys.maxunicode),
+                unicode('\\U%08x' % (sys.maxunicode), 'unicode-escape')
+            )
+            self.assertRaises(ValueError, unichr, sys.maxunicode+1)
+            self.assertRaises(TypeError, unichr)
+
+    # We don't want self in vars(), so these are static methods
+
+    @staticmethod
+    def get_vars_f0():
+        return vars()
+
+    @staticmethod
+    def get_vars_f2():
+        BuiltinTest.get_vars_f0()
+        a = 1
+        b = 2
+        return vars()
+
+    def test_vars(self):
+        self.assertEqual(set(vars()), set(dir()))
+        import sys
+        self.assertEqual(set(vars(sys)), set(dir(sys)))
+        self.assertEqual(self.get_vars_f0(), {})
+        self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2})
+        self.assertRaises(TypeError, vars, 42, 42)
+        self.assertRaises(TypeError, vars, 42)
+
+    def test_zip(self):
+        a = (1, 2, 3)
+        b = (4, 5, 6)
+        t = [(1, 4), (2, 5), (3, 6)]
+        self.assertEqual(zip(a, b), t)
+        b = [4, 5, 6]
+        self.assertEqual(zip(a, b), t)
+        b = (4, 5, 6, 7)
+        self.assertEqual(zip(a, b), t)
+        class I:
+            def __getitem__(self, i):
+                if i < 0 or i > 2: raise IndexError
+                return i + 4
+        self.assertEqual(zip(a, I()), t)
+        self.assertEqual(zip(), [])
+        self.assertEqual(zip(*[]), [])
+        self.assertRaises(TypeError, zip, None)
+        class G:
+            pass
+        self.assertRaises(TypeError, zip, a, G())
+
+        # Make sure zip doesn't try to allocate a billion elements for the
+        # result list when one of its arguments doesn't say how long it is.
+        # A MemoryError is the most likely failure mode.
+        class SequenceWithoutALength:
+            def __getitem__(self, i):
+                if i == 5:
+                    raise IndexError
+                else:
+                    return i
+        self.assertEqual(
+            zip(SequenceWithoutALength(), xrange(2**30)),
+            list(enumerate(range(5)))
+        )
+
+        class BadSeq:
+            def __getitem__(self, i):
+                if i == 5:
+                    raise ValueError
+                else:
+                    return i
+        self.assertRaises(ValueError, zip, BadSeq(), BadSeq())
+
+class TestSorted(unittest.TestCase):
+
+    def test_basic(self):
+        data = range(100)
+        copy = data[:]
+        random.shuffle(copy)
+        self.assertEqual(data, sorted(copy))
+        self.assertNotEqual(data, copy)
+
+        data.reverse()
+        random.shuffle(copy)
+        self.assertEqual(data, sorted(copy, cmp=lambda x, y: cmp(y,x)))
+        self.assertNotEqual(data, copy)
+        random.shuffle(copy)
+        self.assertEqual(data, sorted(copy, key=lambda x: -x))
+        self.assertNotEqual(data, copy)
+        random.shuffle(copy)
+        self.assertEqual(data, sorted(copy, reverse=1))
+        self.assertNotEqual(data, copy)
+
+    def test_inputtypes(self):
+        s = 'abracadabra'
+        types = [list, tuple]
+        if have_unicode:
+            types.insert(0, unicode)
+        for T in types:
+            self.assertEqual(sorted(s), sorted(T(s)))
+
+        s = ''.join(dict.fromkeys(s).keys())  # unique letters only
+        types = [set, frozenset, list, tuple, dict.fromkeys]
+        if have_unicode:
+            types.insert(0, unicode)
+        for T in types:
+            self.assertEqual(sorted(s), sorted(T(s)))
+
+    def test_baddecorator(self):
+        data = 'The quick Brown fox Jumped over The lazy Dog'.split()
+        self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0)
+
+def test_main(verbose=None):
+    test_classes = (BuiltinTest, TestSorted)
+
+    run_unittest(*test_classes)
+
+    # verify reference counting
+    if verbose and hasattr(sys, "gettotalrefcount"):
+        import gc
+        counts = [None] * 5
+        for i in xrange(len(counts)):
+            run_unittest(*test_classes)
+            gc.collect()
+            counts[i] = sys.gettotalrefcount()
+        print counts
+
+
+if __name__ == "__main__":
+    test_main(verbose=True)

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_bz2.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_bz2.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,372 @@
+#!/usr/bin/python
+from test import test_support
+from test.test_support import TESTFN
+
+import unittest
+from cStringIO import StringIO
+import os
+import popen2
+import sys
+
+import bz2
+from bz2 import BZ2File, BZ2Compressor, BZ2Decompressor
+
+has_cmdline_bunzip2 = sys.platform not in ("win32", "os2emx", "riscos")
+
+class BaseTest(unittest.TestCase):
+    "Base for other testcases."
+    TEXT = 'root:x:0:0:root:/root:/bin/bash\nbin:x:1:1:bin:/bin:\ndaemon:x:2:2:daemon:/sbin:\nadm:x:3:4:adm:/var/adm:\nlp:x:4:7:lp:/var/spool/lpd:\nsync:x:5:0:sync:/sbin:/bin/sync\nshutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\nhalt:x:7:0:halt:/sbin:/sbin/halt\nmail:x:8:12:mail:/var/spool/mail:\nnews:x:9:13:news:/var/spool/news:\nuucp:x:10:14:uucp:/var/spool/uucp:\noperator:x:11:0:operator:/root:\ngames:x:12:100:games:/usr/games:\ngopher:x:13:30:gopher:/usr/lib/gopher-data:\nftp:x:14:50:FTP User:/var/ftp:/bin/bash\nnobody:x:65534:65534:Nobody:/home:\npostfix:x:100:101:postfix:/var/spool/postfix:\nniemeyer:x:500:500::/home/niemeyer:/bin/bash\npostgres:x:101:102:PostgreSQL Server:/var/lib/pgsql:/bin/bash\nmysql:x:102:103:MySQL server:/var/lib/mysql:/bin/bash\nwww:x:103:104::/var/www:/bin/false\n'
+    DATA = 'BZh91AY&SY.\xc8N\x18\x00\x01>_\x80\x00\x10@\x02\xff\xf0\x01\x07n\x00?\xe7\xff\xe00\x01\x99\xaa\x00\xc0\x03F\x86\x8c#&\x83F\x9a\x03\x06\xa6\xd0\xa6\x93M\x0fQ\xa7\xa8\x06\x804hh\x12$\x11\xa4i4\xf14S\xd2<Q\xb5\x0fH\xd3\xd4\xdd\xd5\x87\xbb\xf8\x94\r\x8f\xafI\x12\xe1\xc9\xf8/E\x00pu\x89\x12]\xc9\xbbDL\nQ\x0e\t1\x12\xdf\xa0\xc0\x97\xac2O9\x89\x13\x94\x0e\x1c7\x0ed\x95I\x0c\xaaJ\xa4\x18L\x10\x05#\x9c\xaf\xba\xbc/\x97\x8a#C\xc8\xe1\x8cW\xf9\xe2\xd0\xd6M\xa7\x8bXa<e\x84t\xcbL\xb3\xa7\xd9\xcd\xd1\xcb\x84.\xaf\xb3\xab\xab\xad`n}\xa0lh\tE,\x8eZ\x15\x17VH>\x88\xe5\xcd9gd6\x0b\n\xe9\x9b\xd5\x8a\x99\xf7\x08.K\x8ev\xfb\xf7xw\xbb\xdf\xa1\x92\xf1\xdd|/";\xa2\xba\x9f\xd5\xb1#A\xb6\xf6\xb3o\xc9\xc5y\\\xebO\xe7\x85\x9a\xbc\xb6f8\x952\xd5\xd7"%\x89>V,\xf7\xa6z\xe2\x9f\xa3\xdf\x11\x11"\xd6E)I\xa9\x13^\xca\xf3r\xd0\x03U\x922\xf26\xec\xb6\xed\x8b\xc3U\x13\x9d\xc5\x170\xa4\xfa^\x92\xacDF\x8a\x97\xd6\x19\xfe\xdd\xb8\xbd\x1a\x9a\x19\xa3\x80ankR\x8b\xe5\xd83]\xa9\xc6\x08\x82f\xf6\xb9"6l$\xb8j@\xc0\x8a\xb0l1..\xbak\x83ls\x15\xbc\xf4\xc1\x13\xbe\xf8E\xb8\x9d\r\xa8\x9dk\x84\xd3n\xfa\xacQ\x07\xb1%y\xaav\xb4\x08\xe0z\x1b\x16\xf5\x04\xe9\xcc\xb9\x08z\x1en7.G\xfc]\xc9\x14\xe1B@\xbb!8`'
+    DATA_CRLF = 'BZh91AY&SY\xaez\xbbN\x00\x01H\xdf\x80\x00\x12@\x02\xff\xf0\x01\x07n\x00?\xe7\xff\xe0@\x01\xbc\xc6`\x86*\x8d=M\xa9\x9a\x86\xd0L@\x0fI\xa6!\xa1\x13\xc8\x88jdi\x8d@\x03@\x1a\x1a\x0c\x0c\x83 \x00\xc4h2\x19\x01\x82D\x84e\t\xe8\x99\x89\x19\x1ah\x00\r\x1a\x11\xaf\x9b\x0fG\xf5(\x1b\x1f?\t\x12\xcf\xb5\xfc\x95E\x00ps\x89\x12^\xa4\xdd\xa2&\x05(\x87\x04\x98\x89u\xe40%\xb6\x19\'\x8c\xc4\x89\xca\x07\x0e\x1b!\x91UIFU%C\x994!DI\xd2\xfa\xf0\xf1N8W\xde\x13A\xf5\x9cr%?\x9f3;I45A\xd1\x8bT\xb1<l\xba\xcb_\xc00xY\x17r\x17\x88\x08\x08@\xa0\ry@\x10\x04$)`\xf2\xce\x89z\xb0s\xec\x9b.iW\x9d\x81\xb5-+t\x9f\x1a\'\x97dB\xf5x\xb5\xbe.[.\xd7\x0e\x81\xe7\x08\x1cN`\x88\x10\xca\x87\xc3!"\x80\x92R\xa1/\xd1\xc0\xe6mf\xac\xbd\x99\xcca\xb3\x8780>\xa4\xc7\x8d\x1a\\"\xad\xa1\xabyBg\x15\xb9l\x88\x88\x91k"\x94\xa4\xd4\x89\xae*\xa6\x0b\x10\x0c\xd6\xd4m\xe86\xec\xb5j\x8a\x86j\';\xca.\x01I\xf2\xaaJ\xe8\x88\x8cU+t3\xfb\x0c\n\xa33\x13r2\r\x16\xe0\xb3(\xbf\x1d\x83r\xe7M\xf0D\x1365\xd8\x88\xd3\xa4\x92\xcb2\x06\x04\\\xc1\xb0\xea//\xbek&\xd8\xe6+t\xe5\xa1\x13\xada\x16\xder5"w]\xa2i\xb7[\x97R \xe2IT\xcd;Z\x04dk4\xad\x8a\t\xd3\x81z\x10\xf1:^`\xab\x1f\xc5\xdc\x91N\x14$+\x9e\xae\xd3\x80'
+
+    if has_cmdline_bunzip2:
+        def decompress(self, data):
+            pop = popen2.Popen3("bunzip2", capturestderr=1)
+            pop.tochild.write(data)
+            pop.tochild.close()
+            ret = pop.fromchild.read()
+            pop.fromchild.close()
+            if pop.wait() != 0:
+                ret = bz2.decompress(data)
+            return ret
+
+    else:
+        # popen2.Popen3 doesn't exist on Windows, and even if it did, bunzip2
+        # isn't available to run.
+        def decompress(self, data):
+            return bz2.decompress(data)
+
+class BZ2FileTest(BaseTest):
+    "Test BZ2File type miscellaneous methods."
+
+    def setUp(self):
+        self.filename = TESTFN
+
+    def tearDown(self):
+        if os.path.isfile(self.filename):
+            os.unlink(self.filename)
+
+    def createTempFile(self, crlf=0):
+        f = open(self.filename, "wb")
+        if crlf:
+            data = self.DATA_CRLF
+        else:
+            data = self.DATA
+        f.write(data)
+        f.close()
+
+    def testRead(self):
+        # "Test BZ2File.read()"
+        self.createTempFile()
+        bz2f = BZ2File(self.filename)
+        self.assertRaises(TypeError, bz2f.read, None)
+        self.assertEqual(bz2f.read(), self.TEXT)
+        bz2f.close()
+
+    def testReadChunk10(self):
+        # "Test BZ2File.read() in chunks of 10 bytes"
+        self.createTempFile()
+        bz2f = BZ2File(self.filename)
+        text = ''
+        while 1:
+            str = bz2f.read(10)
+            if not str:
+                break
+            text += str
+        self.assertEqual(text, text)
+        bz2f.close()
+
+    def testRead100(self):
+        # "Test BZ2File.read(100)"
+        self.createTempFile()
+        bz2f = BZ2File(self.filename)
+        self.assertEqual(bz2f.read(100), self.TEXT[:100])
+        bz2f.close()
+
+    def testReadLine(self):
+        # "Test BZ2File.readline()"
+        self.createTempFile()
+        bz2f = BZ2File(self.filename)
+        self.assertRaises(TypeError, bz2f.readline, None)
+        sio = StringIO(self.TEXT)
+        for line in sio.readlines():
+            self.assertEqual(bz2f.readline(), line)
+        bz2f.close()
+
+    def testReadLines(self):
+        # "Test BZ2File.readlines()"
+        self.createTempFile()
+        bz2f = BZ2File(self.filename)
+        self.assertRaises(TypeError, bz2f.readlines, None)
+        sio = StringIO(self.TEXT)
+        self.assertEqual(bz2f.readlines(), sio.readlines())
+        bz2f.close()
+
+    def testIterator(self):
+        # "Test iter(BZ2File)"
+        self.createTempFile()
+        bz2f = BZ2File(self.filename)
+        sio = StringIO(self.TEXT)
+        self.assertEqual(list(iter(bz2f)), sio.readlines())
+        bz2f.close()
+
+    def testXReadLines(self):
+        # "Test BZ2File.xreadlines()"
+        self.createTempFile()
+        bz2f = BZ2File(self.filename)
+        sio = StringIO(self.TEXT)
+        self.assertEqual(list(bz2f.xreadlines()), sio.readlines())
+        bz2f.close()
+
+    def testUniversalNewlinesLF(self):
+        # "Test BZ2File.read() with universal newlines (\\n)"
+        self.createTempFile()
+        bz2f = BZ2File(self.filename, "rU")
+        self.assertEqual(bz2f.read(), self.TEXT)
+        self.assertEqual(bz2f.newlines, "\n")
+        bz2f.close()
+
+    def testUniversalNewlinesCRLF(self):
+        # "Test BZ2File.read() with universal newlines (\\r\\n)"
+        self.createTempFile(crlf=1)
+        bz2f = BZ2File(self.filename, "rU")
+        self.assertEqual(bz2f.read(), self.TEXT)
+        self.assertEqual(bz2f.newlines, "\r\n")
+        bz2f.close()
+
+    def testWrite(self):
+        # "Test BZ2File.write()"
+        bz2f = BZ2File(self.filename, "w")
+        self.assertRaises(TypeError, bz2f.write)
+        bz2f.write(self.TEXT)
+        bz2f.close()
+        f = open(self.filename, 'rb')
+        self.assertEqual(self.decompress(f.read()), self.TEXT)
+        f.close()
+
+    def testWriteChunks10(self):
+        # "Test BZ2File.write() with chunks of 10 bytes"
+        bz2f = BZ2File(self.filename, "w")
+        n = 0
+        while 1:
+            str = self.TEXT[n*10:(n+1)*10]
+            if not str:
+                break
+            bz2f.write(str)
+            n += 1
+        bz2f.close()
+        f = open(self.filename, 'rb')
+        self.assertEqual(self.decompress(f.read()), self.TEXT)
+        f.close()
+
+    def testWriteLines(self):
+        # "Test BZ2File.writelines()"
+        bz2f = BZ2File(self.filename, "w")
+        self.assertRaises(TypeError, bz2f.writelines)
+        sio = StringIO(self.TEXT)
+        bz2f.writelines(sio.readlines())
+        bz2f.close()
+        # patch #1535500
+        self.assertRaises(ValueError, bz2f.writelines, ["a"])
+        f = open(self.filename, 'rb')
+        self.assertEqual(self.decompress(f.read()), self.TEXT)
+        f.close()
+
+    def testWriteMethodsOnReadOnlyFile(self):
+        bz2f = BZ2File(self.filename, "w")
+        bz2f.write("abc")
+        bz2f.close()
+
+        bz2f = BZ2File(self.filename, "r")
+        self.assertRaises(IOError, bz2f.write, "a")
+        self.assertRaises(IOError, bz2f.writelines, ["a"])
+
+    def testSeekForward(self):
+        # "Test BZ2File.seek(150, 0)"
+        self.createTempFile()
+        bz2f = BZ2File(self.filename)
+        self.assertRaises(TypeError, bz2f.seek)
+        bz2f.seek(150)
+        self.assertEqual(bz2f.read(), self.TEXT[150:])
+        bz2f.close()
+
+    def testSeekBackwards(self):
+        # "Test BZ2File.seek(-150, 1)"
+        self.createTempFile()
+        bz2f = BZ2File(self.filename)
+        bz2f.read(500)
+        bz2f.seek(-150, 1)
+        self.assertEqual(bz2f.read(), self.TEXT[500-150:])
+        bz2f.close()
+
+    def testSeekBackwardsFromEnd(self):
+        # "Test BZ2File.seek(-150, 2)"
+        self.createTempFile()
+        bz2f = BZ2File(self.filename)
+        bz2f.seek(-150, 2)
+        self.assertEqual(bz2f.read(), self.TEXT[len(self.TEXT)-150:])
+        bz2f.close()
+
+    def testSeekPostEnd(self):
+        # "Test BZ2File.seek(150000)"
+        self.createTempFile()
+        bz2f = BZ2File(self.filename)
+        bz2f.seek(150000)
+        self.assertEqual(bz2f.tell(), len(self.TEXT))
+        self.assertEqual(bz2f.read(), "")
+        bz2f.close()
+
+    def testSeekPostEndTwice(self):
+        # "Test BZ2File.seek(150000) twice"
+        self.createTempFile()
+        bz2f = BZ2File(self.filename)
+        bz2f.seek(150000)
+        bz2f.seek(150000)
+        self.assertEqual(bz2f.tell(), len(self.TEXT))
+        self.assertEqual(bz2f.read(), "")
+        bz2f.close()
+
+    def testSeekPreStart(self):
+        # "Test BZ2File.seek(-150, 0)"
+        self.createTempFile()
+        bz2f = BZ2File(self.filename)
+        bz2f.seek(-150)
+        self.assertEqual(bz2f.tell(), 0)
+        self.assertEqual(bz2f.read(), self.TEXT)
+        bz2f.close()
+
+    def testOpenDel(self):
+        # "Test opening and deleting a file many times"
+        self.createTempFile()
+        for i in xrange(10000):
+            o = BZ2File(self.filename)
+            o.close()
+            del o
+
+    def testOpenNonexistent(self):
+        # "Test opening a nonexistent file"
+        self.assertRaises(IOError, BZ2File, "/non/existent")
+
+    def testModeU(self):
+        # Bug #1194181: bz2.BZ2File opened for write with mode "U"
+        self.createTempFile()
+        bz2f = BZ2File(self.filename, "U")
+        bz2f.close()
+        f = file(self.filename)
+        f.seek(0, 2)
+        self.assertEqual(f.tell(), len(self.DATA))
+        f.close()
+
+    def testBug1191043(self):
+        # readlines() for files containing no newline
+        data = 'BZh91AY&SY\xd9b\x89]\x00\x00\x00\x03\x80\x04\x00\x02\x00\x0c\x00 \x00!\x9ah3M\x13<]\xc9\x14\xe1BCe\x8a%t'
+        f = open(self.filename, "wb")
+        f.write(data)
+        f.close()
+        bz2f = BZ2File(self.filename)
+        lines = bz2f.readlines()
+        bz2f.close()
+        self.assertEqual(lines, ['Test'])
+        bz2f = BZ2File(self.filename)
+        xlines = list(bz2f.xreadlines())
+        bz2f.close()
+        self.assertEqual(xlines, ['Test'])
+
+
+class BZ2CompressorTest(BaseTest):
+    def testCompress(self):
+        # "Test BZ2Compressor.compress()/flush()"
+        bz2c = BZ2Compressor()
+        self.assertRaises(TypeError, bz2c.compress)
+        data = bz2c.compress(self.TEXT)
+        data += bz2c.flush()
+        self.assertEqual(self.decompress(data), self.TEXT)
+
+    def testCompressChunks10(self):
+        # "Test BZ2Compressor.compress()/flush() with chunks of 10 bytes"
+        bz2c = BZ2Compressor()
+        n = 0
+        data = ''
+        while 1:
+            str = self.TEXT[n*10:(n+1)*10]
+            if not str:
+                break
+            data += bz2c.compress(str)
+            n += 1
+        data += bz2c.flush()
+        self.assertEqual(self.decompress(data), self.TEXT)
+
+class BZ2DecompressorTest(BaseTest):
+    def test_Constructor(self):
+        self.assertRaises(TypeError, BZ2Decompressor, 42)
+
+    def testDecompress(self):
+        # "Test BZ2Decompressor.decompress()"
+        bz2d = BZ2Decompressor()
+        self.assertRaises(TypeError, bz2d.decompress)
+        text = bz2d.decompress(self.DATA)
+        self.assertEqual(text, self.TEXT)
+
+    def testDecompressChunks10(self):
+        # "Test BZ2Decompressor.decompress() with chunks of 10 bytes"
+        bz2d = BZ2Decompressor()
+        text = ''
+        n = 0
+        while 1:
+            str = self.DATA[n*10:(n+1)*10]
+            if not str:
+                break
+            text += bz2d.decompress(str)
+            n += 1
+        self.assertEqual(text, self.TEXT)
+
+    def testDecompressUnusedData(self):
+        # "Test BZ2Decompressor.decompress() with unused data"
+        bz2d = BZ2Decompressor()
+        unused_data = "this is unused data"
+        text = bz2d.decompress(self.DATA+unused_data)
+        self.assertEqual(text, self.TEXT)
+        self.assertEqual(bz2d.unused_data, unused_data)
+
+    def testEOFError(self):
+        # "Calling BZ2Decompressor.decompress() after EOS must raise EOFError"
+        bz2d = BZ2Decompressor()
+        text = bz2d.decompress(self.DATA)
+        self.assertRaises(EOFError, bz2d.decompress, "anything")
+
+
+class FuncTest(BaseTest):
+    "Test module functions"
+
+    def testCompress(self):
+        # "Test compress() function"
+        data = bz2.compress(self.TEXT)
+        self.assertEqual(self.decompress(data), self.TEXT)
+
+    def testDecompress(self):
+        # "Test decompress() function"
+        text = bz2.decompress(self.DATA)
+        self.assertEqual(text, self.TEXT)
+
+    def testDecompressEmpty(self):
+        # "Test decompress() function with empty string"
+        text = bz2.decompress("")
+        self.assertEqual(text, "")
+
+    def testDecompressIncomplete(self):
+        # "Test decompress() function with incomplete data"
+        self.assertRaises(ValueError, bz2.decompress, self.DATA[:-10])
+
+def test_main():
+    test_support.run_unittest(
+        BZ2FileTest,
+        BZ2CompressorTest,
+        BZ2DecompressorTest,
+        FuncTest
+    )
+    test_support.reap_children()
+
+if __name__ == '__main__':
+    test_main()
+
+# vim:ts=4:sw=4

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_class.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_class.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,415 @@
+"Test the functionality of Python classes implementing operators."
+
+from test.test_support import TestFailed
+
+testmeths = [
+
+# Binary operations
+    "add",
+    "radd",
+    "sub",
+    "rsub",
+    "mul",
+    "rmul",
+    "div",
+    "rdiv",
+    "mod",
+    "rmod",
+    "divmod",
+    "rdivmod",
+    "pow",
+    "rpow",
+    "rshift",
+    "rrshift",
+    "lshift",
+    "rlshift",
+    "and",
+    "rand",
+    "or",
+    "ror",
+    "xor",
+    "rxor",
+
+# List/dict operations
+    "contains",
+    "getitem",
+    "getslice",
+    "setitem",
+    "setslice",
+    "delitem",
+    "delslice",
+
+# Unary operations
+    "neg",
+    "pos",
+    "abs",
+
+# generic operations
+    "init",
+    ]
+
+# These need to return something other than None
+#    "coerce",
+#    "hash",
+#    "str",
+#    "repr",
+#    "int",
+#    "long",
+#    "float",
+#    "oct",
+#    "hex",
+
+# These are separate because they can influence the test of other methods.
+#    "getattr",
+#    "setattr",
+#    "delattr",
+
+class AllTests:
+    def __coerce__(self, *args):
+        print "__coerce__:", args
+        return (self,) + args
+
+    def __hash__(self, *args):
+        print "__hash__:", args
+        return hash(id(self))
+
+    def __str__(self, *args):
+        print "__str__:", args
+        return "AllTests"
+
+    def __repr__(self, *args):
+        print "__repr__:", args
+        return "AllTests"
+
+    def __int__(self, *args):
+        print "__int__:", args
+        return 1
+
+    def __float__(self, *args):
+        print "__float__:", args
+        return 1.0
+
+    def __long__(self, *args):
+        print "__long__:", args
+        return 1L
+
+    def __oct__(self, *args):
+        print "__oct__:", args
+        return '01'
+
+    def __hex__(self, *args):
+        print "__hex__:", args
+        return '0x1'
+
+    def __cmp__(self, *args):
+        print "__cmp__:", args
+        return 0
+
+    def __del__(self, *args):
+        print "__del__:", args
+
+# Synthesize AllTests methods from the names in testmeths.
+
+method_template = """\
+def __%(method)s__(self, *args):
+    print "__%(method)s__:", args
+"""
+
+for method in testmeths:
+    exec method_template % locals() in AllTests.__dict__
+
+del method, method_template
+
+# this also tests __init__ of course.
+testme = AllTests()
+
+# Binary operations
+
+testme + 1
+1 + testme
+
+testme - 1
+1 - testme
+
+testme * 1
+1 * testme
+
+if 1/2 == 0:
+    testme / 1
+    1 / testme
+else:
+    # True division is in effect, so "/" doesn't map to __div__ etc; but
+    # the canned expected-output file requires that __div__ etc get called.
+    testme.__coerce__(1)
+    testme.__div__(1)
+    testme.__coerce__(1)
+    testme.__rdiv__(1)
+
+testme % 1
+1 % testme
+
+divmod(testme,1)
+divmod(1, testme)
+
+testme ** 1
+1 ** testme
+
+testme >> 1
+1 >> testme
+
+testme << 1
+1 << testme
+
+testme & 1
+1 & testme
+
+testme | 1
+1 | testme
+
+testme ^ 1
+1 ^ testme
+
+
+# List/dict operations
+
+class Empty: pass
+
+try:
+    1 in Empty()
+    print 'failed, should have raised TypeError'
+except TypeError:
+    pass
+
+1 in testme
+
+testme[1]
+testme[1] = 1
+del testme[1]
+
+testme[:42]
+testme[:42] = "The Answer"
+del testme[:42]
+
+testme[2:1024:10]
+testme[2:1024:10] = "A lot"
+del testme[2:1024:10]
+
+testme[:42, ..., :24:, 24, 100]
+testme[:42, ..., :24:, 24, 100] = "Strange"
+del testme[:42, ..., :24:, 24, 100]
+
+
+# Now remove the slice hooks to see if converting normal slices to slice
+# object works.
+
+del AllTests.__getslice__
+del AllTests.__setslice__
+del AllTests.__delslice__
+
+import sys
+if sys.platform[:4] != 'java':
+    testme[:42]
+    testme[:42] = "The Answer"
+    del testme[:42]
+else:
+    # This works under Jython, but the actual slice values are
+    # different.
+    print "__getitem__: (slice(0, 42, None),)"
+    print "__setitem__: (slice(0, 42, None), 'The Answer')"
+    print "__delitem__: (slice(0, 42, None),)"
+
+# Unary operations
+
+-testme
++testme
+abs(testme)
+int(testme)
+long(testme)
+float(testme)
+oct(testme)
+hex(testme)
+
+# And the rest...
+
+hash(testme)
+repr(testme)
+str(testme)
+
+testme == 1
+testme < 1
+testme > 1
+testme <> 1
+testme != 1
+1 == testme
+1 < testme
+1 > testme
+1 <> testme
+1 != testme
+
+# This test has to be last (duh.)
+
+del testme
+if sys.platform[:4] == 'java':
+    import java
+    java.lang.System.gc()
+else:
+    import gc
+    gc.collect()
+
+# Interfering tests
+
+class ExtraTests:
+    def __getattr__(self, *args):
+        print "__getattr__:", args
+        return "SomeVal"
+
+    def __setattr__(self, *args):
+        print "__setattr__:", args
+
+    def __delattr__(self, *args):
+        print "__delattr__:", args
+
+testme = ExtraTests()
+testme.spam
+testme.eggs = "spam, spam, spam and ham"
+del testme.cardinal
+
+
+# return values of some method are type-checked
+class BadTypeClass:
+    def __int__(self):
+        return None
+    __float__ = __int__
+    __long__ = __int__
+    __str__ = __int__
+    __repr__ = __int__
+    __oct__ = __int__
+    __hex__ = __int__
+
+def check_exc(stmt, exception):
+    """Raise TestFailed if executing 'stmt' does not raise 'exception'
+    """
+    try:
+        exec stmt
+    except exception:
+        pass
+    else:
+        raise TestFailed, "%s should raise %s" % (stmt, exception)
+
+check_exc("int(BadTypeClass())", TypeError)
+check_exc("float(BadTypeClass())", TypeError)
+check_exc("long(BadTypeClass())", TypeError)
+check_exc("str(BadTypeClass())", TypeError)
+check_exc("repr(BadTypeClass())", TypeError)
+check_exc("oct(BadTypeClass())", TypeError)
+check_exc("hex(BadTypeClass())", TypeError)
+
+# mixing up ints and longs is okay
+class IntLongMixClass:
+    def __int__(self):
+        return 0L
+
+    def __long__(self):
+        return 0
+
+try:
+    int(IntLongMixClass())
+except TypeError:
+    raise TestFailed, "TypeError should not be raised"
+
+try:
+    long(IntLongMixClass())
+except TypeError:
+    raise TestFailed, "TypeError should not be raised"
+
+
+# Test correct errors from hash() on objects with comparisons but no __hash__
+
+class C0:
+    pass
+
+hash(C0()) # This should work; the next two should raise TypeError
+
+class C1:
+    def __cmp__(self, other): return 0
+
+check_exc("hash(C1())", TypeError)
+
+class C2:
+    def __eq__(self, other): return 1
+
+check_exc("hash(C2())", TypeError)
+
+# Test for SF bug 532646
+
+class A:
+    pass
+A.__call__ = A()
+a = A()
+try:
+    a() # This should not segfault
+except RuntimeError:
+    pass
+else:
+    raise TestFailed, "how could this not have overflowed the stack?"
+
+
+# Tests for exceptions raised in instance_getattr2().
+
+def booh(self):
+    raise AttributeError, "booh"
+
+class A:
+    a = property(booh)
+try:
+    A().a # Raised AttributeError: A instance has no attribute 'a'
+except AttributeError, x:
+    if str(x) != "booh":
+        print "attribute error for A().a got masked:", str(x)
+
+class E:
+    __eq__ = property(booh)
+E() == E() # In debug mode, caused a C-level assert() to fail
+
+class I:
+    __init__ = property(booh)
+try:
+    I() # In debug mode, printed XXX undetected error and raises AttributeError
+except AttributeError, x:
+    pass
+else:
+    print "attribute error for I.__init__ got masked"
+
+
+# Test comparison and hash of methods
+class A:
+    def __init__(self, x):
+        self.x = x
+    def f(self):
+        pass
+    def g(self):
+        pass
+    def __eq__(self, other):
+        return self.x == other.x
+    def __hash__(self):
+        return self.x
+class B(A):
+    pass
+
+a1 = A(1)
+a2 = A(2)
+assert a1.f == a1.f
+assert a1.f != a2.f
+assert a1.f != a1.g
+assert a1.f == A(1).f
+assert hash(a1.f) == hash(a1.f)
+assert hash(a1.f) == hash(A(1).f)
+
+assert A.f != a1.f
+assert A.f != A.g
+assert B.f == A.f
+assert hash(B.f) == hash(A.f)
+
+# the following triggers a SystemError in 2.4
+a = A(hash(A.f.im_func)^(-1))
+hash(a.f)

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_codeop.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_codeop.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,195 @@
+"""
+   Test cases for codeop.py
+   Nick Mathewson
+"""
+import unittest
+from test.test_support import run_unittest, is_jython
+
+from codeop import compile_command, PyCF_DONT_IMPLY_DEDENT
+
+if is_jython:
+    import sys
+    import cStringIO
+
+    def unify_callables(d):
+        for n,v in d.items():
+            if callable(v):
+                d[n] = callable
+        return d
+
+class CodeopTests(unittest.TestCase):
+
+    def assertValid(self, str, symbol='single'):
+        '''succeed iff str is a valid piece of code'''
+        if is_jython:
+            code = compile_command(str, "<input>", symbol)
+            self.assert_(code)
+            if symbol == "single":
+                d,r = {},{}
+                saved_stdout = sys.stdout
+                sys.stdout = cStringIO.StringIO()
+                try:
+                    exec code in d
+                    exec compile(str,"<input>","single") in r
+                finally:
+                    sys.stdout = saved_stdout
+            elif symbol == 'eval':
+                ctx = {'a': 2}
+                d = { 'value': eval(code,ctx) }
+                r = { 'value': eval(str,ctx) }
+            self.assertEquals(unify_callables(r),unify_callables(d))
+        else:
+            expected = compile(str, "<input>", symbol, PyCF_DONT_IMPLY_DEDENT)
+            self.assertEquals( compile_command(str, "<input>", symbol), expected)
+
+    def assertIncomplete(self, str, symbol='single'):
+        '''succeed iff str is the start of a valid piece of code'''
+        self.assertEquals( compile_command(str, symbol=symbol), None)
+
+    def assertInvalid(self, str, symbol='single', is_syntax=1):
+        '''succeed iff str is the start of an invalid piece of code'''
+        try:
+            compile_command(str,symbol=symbol)
+            self.fail("No exception thrown for invalid code")
+        except SyntaxError:
+            self.assert_(is_syntax)
+        except OverflowError:
+            self.assert_(not is_syntax)
+
+    def test_valid(self):
+        av = self.assertValid
+
+        # special case
+        if not is_jython:
+            self.assertEquals(compile_command(""),
+                            compile("pass", "<input>", 'single',
+                                    PyCF_DONT_IMPLY_DEDENT))
+            self.assertEquals(compile_command("\n"),
+                            compile("pass", "<input>", 'single',
+                                    PyCF_DONT_IMPLY_DEDENT))
+        else:
+            av("")
+            av("\n")
+
+        av("a = 1")
+        av("\na = 1")
+        av("a = 1\n")
+        av("a = 1\n\n")
+        av("\n\na = 1\n\n")
+
+        av("def x():\n  pass\n")
+        av("if 1:\n pass\n")
+
+        av("\n\nif 1: pass\n")
+        av("\n\nif 1: pass\n\n")
+
+        av("def x():\n\n pass\n")
+        av("def x():\n  pass\n  \n")
+        av("def x():\n  pass\n \n")
+
+        av("pass\n")
+        av("3**3\n")
+
+        av("if 9==3:\n   pass\nelse:\n   pass\n")
+        av("if 1:\n pass\n if 1:\n  pass\n else:\n  pass\n")
+
+        av("#a\n#b\na = 3\n")
+        av("#a\n\n   \na=3\n")
+        av("a=3\n\n")
+        av("a = 9+ \\\n3")
+
+        av("3**3","eval")
+        av("(lambda z: \n z**3)","eval")
+
+        av("9+ \\\n3","eval")
+        av("9+ \\\n3\n","eval")
+
+        av("\n\na**3","eval")
+        av("\n \na**3","eval")
+        av("#a\n#b\na**3","eval")
+
+    def test_incomplete(self):
+        ai = self.assertIncomplete
+
+        ai("(a **")
+        ai("(a,b,")
+        ai("(a,b,(")
+        ai("(a,b,(")
+        ai("a = (")
+        ai("a = {")
+        ai("b + {")
+
+        ai("if 9==3:\n   pass\nelse:")
+        ai("if 9==3:\n   pass\nelse:\n")
+        ai("if 9==3:\n   pass\nelse:\n   pass")
+        ai("if 1:")
+        ai("if 1:\n")
+        ai("if 1:\n pass\n if 1:\n  pass\n else:")
+        ai("if 1:\n pass\n if 1:\n  pass\n else:\n")
+        ai("if 1:\n pass\n if 1:\n  pass\n else:\n  pass")
+
+        ai("def x():")
+        ai("def x():\n")
+        ai("def x():\n\n")
+
+        ai("def x():\n  pass")
+        ai("def x():\n  pass\n ")
+        ai("def x():\n  pass\n  ")
+        ai("\n\ndef x():\n  pass")
+
+        ai("a = 9+ \\")
+        ai("a = 'a\\")
+        ai("a = '''xy")
+
+        ai("","eval")
+        ai("\n","eval")
+        ai("(","eval")
+        ai("(\n\n\n","eval")
+        ai("(9+","eval")
+        ai("9+ \\","eval")
+        ai("lambda z: \\","eval")
+
+    def test_invalid(self):
+        ai = self.assertInvalid
+        ai("a b")
+
+        ai("a @")
+        ai("a b @")
+        ai("a ** @")
+
+        ai("a = ")
+        ai("a = 9 +")
+
+        ai("def x():\n\npass\n")
+
+        ai("\n\n if 1: pass\n\npass")
+
+        ai("a = 9+ \\\n")
+        ai("a = 'a\\ ")
+        ai("a = 'a\\\n")
+
+        # XXX for PyPy: disable these tests (using compile_command with eval
+        #               doesn't raise a SyntaxError if it appears to be an
+        #               incomplete multi-line stmt)
+        # ai("a = 1","eval")
+        # ai("a = (","eval")
+        # ai("]","eval")
+        # ai("())","eval")
+        # ai("[}","eval")
+        # ai("9+","eval")
+        # ai("lambda z:","eval")
+        # ai("a b","eval")
+
+    def test_filename(self):
+        self.assertEquals(compile_command("a = 1\n", "abc").co_filename,
+                          compile("a = 1\n", "abc", 'single').co_filename)
+        self.assertNotEquals(compile_command("a = 1\n", "abc").co_filename,
+                             compile("a = 1\n", "def", 'single').co_filename)
+
+
+def test_main():
+    run_unittest(CodeopTests)
+
+
+if __name__ == "__main__":
+    test_main()

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_compile.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_compile.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,402 @@
+import unittest
+import warnings
+import sys
+from test import test_support
+
+class TestSpecifics(unittest.TestCase):
+
+    def test_debug_assignment(self):
+        # catch assignments to __debug__
+        self.assertRaises(SyntaxError, compile, '__debug__ = 1', '?', 'single')
+        import __builtin__
+        prev = __builtin__.__debug__
+        setattr(__builtin__, '__debug__', 'sure')
+        setattr(__builtin__, '__debug__', prev)
+
+    def test_argument_handling(self):
+        # detect duplicate positional and keyword arguments
+        self.assertRaises(SyntaxError, eval, 'lambda a,a:0')
+        self.assertRaises(SyntaxError, eval, 'lambda a,a=1:0')
+        self.assertRaises(SyntaxError, eval, 'lambda a=1,a=1:0')
+        try:
+            exec 'def f(a, a): pass'
+            self.fail("duplicate arguments")
+        except SyntaxError:
+            pass
+        try:
+            exec 'def f(a = 0, a = 1): pass'
+            self.fail("duplicate keyword arguments")
+        except SyntaxError:
+            pass
+        try:
+            exec 'def f(a): global a; a = 1'
+            self.fail("variable is global and local")
+        except SyntaxError:
+            pass
+
+    def test_syntax_error(self):
+        self.assertRaises(SyntaxError, compile, "1+*3", "filename", "exec")
+
+    def test_duplicate_global_local(self):
+        try:
+            exec 'def f(a): global a; a = 1'
+            self.fail("variable is global and local")
+        except SyntaxError:
+            pass
+
+    def test_exec_with_general_mapping_for_locals(self):
+
+        class M:
+            "Test mapping interface versus possible calls from eval()."
+            def __getitem__(self, key):
+                if key == 'a':
+                    return 12
+                raise KeyError
+            def __setitem__(self, key, value):
+                self.results = (key, value)
+            def keys(self):
+                return list('xyz')
+
+        m = M()
+        g = globals()
+        exec 'z = a' in g, m
+        self.assertEqual(m.results, ('z', 12))
+        try:
+            exec 'z = b' in g, m
+        except NameError:
+            pass
+        else:
+            self.fail('Did not detect a KeyError')
+        exec 'z = dir()' in g, m
+        self.assertEqual(m.results, ('z', list('xyz')))
+        exec 'z = globals()' in g, m
+        self.assertEqual(m.results, ('z', g))
+        exec 'z = locals()' in g, m
+        self.assertEqual(m.results, ('z', m))
+        try:
+            exec 'z = b' in m
+        except NameError:
+            pass
+        else:
+            self.fail('PyPy should accept not real dict globals ')
+
+        class A:
+            "Non-mapping"
+            pass
+        m = A()
+        try:
+            exec 'z = a' in g, m
+        except TypeError:
+            pass
+        else:
+            self.fail('Did not validate locals as a mapping')
+
+        # Verify that dict subclasses work as well
+        class D(dict):
+            def __getitem__(self, key):
+                if key == 'a':
+                    return 12
+                return dict.__getitem__(self, key)
+        d = D()
+        exec 'z = a' in g, d
+        self.assertEqual(d['z'], 12)
+
+    def test_extended_arg(self):
+        longexpr = 'x = x or ' + '-x' * 2500
+        code = '''
+def f(x):
+    %s
+    %s
+    %s
+    %s
+    %s
+    %s
+    %s
+    %s
+    %s
+    %s
+    # the expressions above have no effect, x == argument
+    while x:
+        x -= 1
+        # EXTENDED_ARG/JUMP_ABSOLUTE here
+    return x
+''' % ((longexpr,)*10)
+        exec code
+        self.assertEqual(f(5), 0)
+
+    def test_complex_args(self):
+
+        def comp_args((a, b)):
+            return a,b
+        self.assertEqual(comp_args((1, 2)), (1, 2))
+
+        def comp_args((a, b)=(3, 4)):
+            return a, b
+        self.assertEqual(comp_args((1, 2)), (1, 2))
+        self.assertEqual(comp_args(), (3, 4))
+
+        def comp_args(a, (b, c)):
+            return a, b, c
+        self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3))
+
+        def comp_args(a=2, (b, c)=(3, 4)):
+            return a, b, c
+        self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3))
+        self.assertEqual(comp_args(), (2, 3, 4))
+
+    def test_argument_order(self):
+        try:
+            exec 'def f(a=1, (b, c)): pass'
+            self.fail("non-default args after default")
+        except SyntaxError:
+            pass
+
+    def test_float_literals(self):
+        # testing bad float literals
+        self.assertRaises(SyntaxError, eval, "2e")
+        self.assertRaises(SyntaxError, eval, "2.0e+")
+        self.assertRaises(SyntaxError, eval, "1e-")
+        self.assertRaises(SyntaxError, eval, "3-4e/21")
+
+    def test_indentation(self):
+        # testing compile() of indented block w/o trailing newline"
+        s = """
+if 1:
+    if 2:
+        pass"""
+        compile(s, "<string>", "exec")
+
+    # This test is probably specific to CPython and may not generalize
+    # to other implementations.  We are trying to ensure that when
+    # the first line of code starts after 256, correct line numbers
+    # in tracebacks are still produced.
+    def test_leading_newlines(self):
+        s256 = "".join(["\n"] * 256 + ["spam"])
+        co = compile(s256, 'fn', 'exec')
+        self.assertEqual(co.co_firstlineno, 257)
+        self.assertEqual(co.co_lnotab, '')
+
+    def test_literals_with_leading_zeroes(self):
+        for arg in ["077787", "0xj", "0x.", "0e",  "090000000000000",
+                    "080000000000000", "000000000000009", "000000000000008"]:
+            self.assertRaises(SyntaxError, eval, arg)
+
+        self.assertEqual(eval("0777"), 511)
+        self.assertEqual(eval("0777L"), 511)
+        self.assertEqual(eval("000777"), 511)
+        self.assertEqual(eval("0xff"), 255)
+        self.assertEqual(eval("0xffL"), 255)
+        self.assertEqual(eval("0XfF"), 255)
+        self.assertEqual(eval("0777."), 777)
+        self.assertEqual(eval("0777.0"), 777)
+        self.assertEqual(eval("000000000000000000000000000000000000000000000000000777e0"), 777)
+        self.assertEqual(eval("0777e1"), 7770)
+        self.assertEqual(eval("0e0"), 0)
+        self.assertEqual(eval("0000E-012"), 0)
+        self.assertEqual(eval("09.5"), 9.5)
+        self.assertEqual(eval("0777j"), 777j)
+        self.assertEqual(eval("00j"), 0j)
+        self.assertEqual(eval("00.0"), 0)
+        self.assertEqual(eval("0e3"), 0)
+        self.assertEqual(eval("090000000000000."), 90000000000000.)
+        self.assertEqual(eval("090000000000000.0000000000000000000000"), 90000000000000.)
+        self.assertEqual(eval("090000000000000e0"), 90000000000000.)
+        self.assertEqual(eval("090000000000000e-0"), 90000000000000.)
+        self.assertEqual(eval("090000000000000j"), 90000000000000j)
+        self.assertEqual(eval("000000000000007"), 7)
+        self.assertEqual(eval("000000000000008."), 8.)
+        self.assertEqual(eval("000000000000009."), 9.)
+
+    def test_unary_minus(self):
+        # Verify treatment of unary minus on negative numbers SF bug #660455
+        if sys.maxint == 2147483647:
+            # 32-bit machine
+            all_one_bits = '0xffffffff'
+            self.assertEqual(eval(all_one_bits), 4294967295L)
+            self.assertEqual(eval("-" + all_one_bits), -4294967295L)
+        elif sys.maxint == 9223372036854775807:
+            # 64-bit machine
+            all_one_bits = '0xffffffffffffffff'
+            self.assertEqual(eval(all_one_bits), 18446744073709551615L)
+            self.assertEqual(eval("-" + all_one_bits), -18446744073709551615L)
+        else:
+            self.fail("How many bits *does* this machine have???")
+        # Verify treatment of contant folding on -(sys.maxint+1)
+        # i.e. -2147483648 on 32 bit platforms.  Should return int, not long.
+        self.assertTrue(isinstance(eval("%s" % (-sys.maxint - 1)), int))
+        self.assertTrue(isinstance(eval("%s" % (-sys.maxint - 2)), long))
+
+    if sys.maxint == 9223372036854775807:
+        def test_32_63_bit_values(self):
+            a = +4294967296  # 1 << 32
+            b = -4294967296  # 1 << 32
+            c = +281474976710656  # 1 << 48
+            d = -281474976710656  # 1 << 48
+            e = +4611686018427387904  # 1 << 62
+            f = -4611686018427387904  # 1 << 62
+            g = +9223372036854775807  # 1 << 63 - 1
+            h = -9223372036854775807  # 1 << 63 - 1
+
+            for variable in self.test_32_63_bit_values.func_code.co_consts:
+                if variable is not None:
+                    self.assertTrue(isinstance(variable, int))
+
+    def test_sequence_unpacking_error(self):
+        # Verify sequence packing/unpacking with "or".  SF bug #757818
+        i,j = (1, -1) or (-1, 1)
+        self.assertEqual(i, 1)
+        self.assertEqual(j, -1)
+
+    def test_none_assignment(self):
+        stmts = [
+            'None = 0',
+            'None += 0',
+            '__builtins__.None = 0',
+            'def None(): pass',
+            'class None: pass',
+            '(a, None) = 0, 0',
+            'for None in range(10): pass',
+            'def f(None): pass',
+        ]
+        for stmt in stmts:
+            stmt += "\n"
+            self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'single')
+            self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
+
+    def test_import(self):
+        succeed = [
+            'import sys',
+            'import os, sys',
+            'import os as bar',
+            'import os.path as bar',
+            'from __future__ import nested_scopes, generators',
+            'from __future__ import (nested_scopes,\ngenerators)',
+            'from __future__ import (nested_scopes,\ngenerators,)',
+            'from sys import stdin, stderr, stdout',
+            'from sys import (stdin, stderr,\nstdout)',
+            'from sys import (stdin, stderr,\nstdout,)',
+            'from sys import (stdin\n, stderr, stdout)',
+            'from sys import (stdin\n, stderr, stdout,)',
+            'from sys import stdin as si, stdout as so, stderr as se',
+            'from sys import (stdin as si, stdout as so, stderr as se)',
+            'from sys import (stdin as si, stdout as so, stderr as se,)',
+            ]
+        fail = [
+            'import (os, sys)',
+            'import (os), (sys)',
+            'import ((os), (sys))',
+            'import (sys',
+            'import sys)',
+            'import (os,)',
+            'import os As bar',
+            'import os.path a bar',
+            'from sys import stdin As stdout',
+            'from sys import stdin a stdout',
+            'from (sys) import stdin',
+            'from __future__ import (nested_scopes',
+            'from __future__ import nested_scopes)',
+            'from __future__ import nested_scopes,\ngenerators',
+            'from sys import (stdin',
+            'from sys import stdin)',
+            'from sys import stdin, stdout,\nstderr',
+            'from sys import stdin si',
+            'from sys import stdin,'
+            'from sys import (*)',
+            'from sys import (stdin,, stdout, stderr)',
+            'from sys import (stdin, stdout),',
+            ]
+        for stmt in succeed:
+            compile(stmt, 'tmp', 'exec')
+        for stmt in fail:
+            self.assertRaises(SyntaxError, compile, stmt, 'tmp', 'exec')
+
+    def test_for_distinct_code_objects(self):
+        # SF bug 1048870
+        def f():
+            f1 = lambda x=1: x
+            f2 = lambda x=2: x
+            return f1, f2
+        f1, f2 = f()
+        self.assertNotEqual(id(f1.func_code), id(f2.func_code))
+
+    def test_unicode_encoding(self):
+        code = u"# -*- coding: utf-8 -*-\npass\n"
+        self.assertRaises(SyntaxError, compile, code, "tmp", "exec")
+
+    def test_subscripts(self):
+        # SF bug 1448804
+        # Class to make testing subscript results easy
+        class str_map(object):
+            def __init__(self):
+                self.data = {}
+            def __getitem__(self, key):
+                return self.data[str(key)]
+            def __setitem__(self, key, value):
+                self.data[str(key)] = value
+            def __delitem__(self, key):
+                del self.data[str(key)]
+            def __contains__(self, key):
+                return str(key) in self.data
+        d = str_map()
+        # Index
+        d[1] = 1
+        self.assertEqual(d[1], 1)
+        d[1] += 1
+        self.assertEqual(d[1], 2)
+        del d[1]
+        self.assertEqual(1 in d, False)
+        # Tuple of indices
+        d[1, 1] = 1
+        self.assertEqual(d[1, 1], 1)
+        d[1, 1] += 1
+        self.assertEqual(d[1, 1], 2)
+        del d[1, 1]
+        self.assertEqual((1, 1) in d, False)
+        # Simple slice
+        d[1:2] = 1
+        self.assertEqual(d[1:2], 1)
+        d[1:2] += 1
+        self.assertEqual(d[1:2], 2)
+        del d[1:2]
+        self.assertEqual(slice(1, 2) in d, False)
+        # Tuple of simple slices
+        d[1:2, 1:2] = 1
+        self.assertEqual(d[1:2, 1:2], 1)
+        d[1:2, 1:2] += 1
+        self.assertEqual(d[1:2, 1:2], 2)
+        del d[1:2, 1:2]
+        self.assertEqual((slice(1, 2), slice(1, 2)) in d, False)
+        # Extended slice
+        d[1:2:3] = 1
+        self.assertEqual(d[1:2:3], 1)
+        d[1:2:3] += 1
+        self.assertEqual(d[1:2:3], 2)
+        del d[1:2:3]
+        self.assertEqual(slice(1, 2, 3) in d, False)
+        # Tuple of extended slices
+        d[1:2:3, 1:2:3] = 1
+        self.assertEqual(d[1:2:3, 1:2:3], 1)
+        d[1:2:3, 1:2:3] += 1
+        self.assertEqual(d[1:2:3, 1:2:3], 2)
+        del d[1:2:3, 1:2:3]
+        self.assertEqual((slice(1, 2, 3), slice(1, 2, 3)) in d, False)
+        # Ellipsis
+        d[...] = 1
+        self.assertEqual(d[...], 1)
+        d[...] += 1
+        self.assertEqual(d[...], 2)
+        del d[...]
+        self.assertEqual(Ellipsis in d, False)
+        # Tuple of Ellipses
+        d[..., ...] = 1
+        self.assertEqual(d[..., ...], 1)
+        d[..., ...] += 1
+        self.assertEqual(d[..., ...], 2)
+        del d[..., ...]
+        self.assertEqual((Ellipsis, Ellipsis) in d, False)
+
+def test_main():
+    test_support.run_unittest(TestSpecifics)
+
+if __name__ == "__main__":
+    test_main()

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_complex.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_complex.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,342 @@
+import unittest, os
+from test import test_support
+
+import warnings
+warnings.filterwarnings(
+    "ignore",
+    category=DeprecationWarning,
+    message=".*complex divmod.*are deprecated"
+)
+
+from random import random
+
+# These tests ensure that complex math does the right thing
+
+class ComplexTest(unittest.TestCase):
+
+    def assertAlmostEqual(self, a, b):
+        if isinstance(a, complex):
+            if isinstance(b, complex):
+                unittest.TestCase.assertAlmostEqual(self, a.real, b.real)
+                unittest.TestCase.assertAlmostEqual(self, a.imag, b.imag)
+            else:
+                unittest.TestCase.assertAlmostEqual(self, a.real, b)
+                unittest.TestCase.assertAlmostEqual(self, a.imag, 0.)
+        else:
+            if isinstance(b, complex):
+                unittest.TestCase.assertAlmostEqual(self, a, b.real)
+                unittest.TestCase.assertAlmostEqual(self, 0., b.imag)
+            else:
+                unittest.TestCase.assertAlmostEqual(self, a, b)
+
+    def assertCloseAbs(self, x, y, eps=1e-9):
+        """Return true iff floats x and y "are close\""""
+        # put the one with larger magnitude second
+        if abs(x) > abs(y):
+            x, y = y, x
+        if y == 0:
+            return abs(x) < eps
+        if x == 0:
+            return abs(y) < eps
+        # check that relative difference < eps
+        self.assert_(abs((x-y)/y) < eps)
+
+    def assertClose(self, x, y, eps=1e-9):
+        """Return true iff complexes x and y "are close\""""
+        self.assertCloseAbs(x.real, y.real, eps)
+        self.assertCloseAbs(x.imag, y.imag, eps)
+
+    def assertIs(self, a, b):
+        self.assert_(a is b)
+
+    def check_div(self, x, y):
+        """Compute complex z=x*y, and check that z/x==y and z/y==x."""
+        z = x * y
+        if x != 0:
+            q = z / x
+            self.assertClose(q, y)
+            q = z.__div__(x)
+            self.assertClose(q, y)
+            q = z.__truediv__(x)
+            self.assertClose(q, y)
+        if y != 0:
+            q = z / y
+            self.assertClose(q, x)
+            q = z.__div__(y)
+            self.assertClose(q, x)
+            q = z.__truediv__(y)
+            self.assertClose(q, x)
+
+    def test_div(self):
+        # too slow for PyPy --- simple_real = [float(i) for i in xrange(-5, 6)]
+        simple_real = [-2.0, 0.0, 1.0]
+        simple_complex = [complex(x, y) for x in simple_real for y in simple_real]
+        for x in simple_complex:
+            for y in simple_complex:
+                self.check_div(x, y)
+
+        # A naive complex division algorithm (such as in 2.0) is very prone to
+        # nonsense errors for these (overflows and underflows).
+        self.check_div(complex(1e200, 1e200), 1+0j)
+        self.check_div(complex(1e-200, 1e-200), 1+0j)
+
+        # Just for fun.
+        for i in xrange(100):
+            self.check_div(complex(random(), random()),
+                           complex(random(), random()))
+
+        self.assertRaises(ZeroDivisionError, complex.__div__, 1+1j, 0+0j)
+        # FIXME: The following currently crashes on Alpha
+        # self.assertRaises(OverflowError, pow, 1e200+1j, 1e200+1j)
+
+    def test_truediv(self):
+        self.assertAlmostEqual(complex.__truediv__(2+0j, 1+1j), 1-1j)
+        self.assertRaises(ZeroDivisionError, complex.__truediv__, 1+1j, 0+0j)
+
+    def test_floordiv(self):
+        self.assertAlmostEqual(complex.__floordiv__(3+0j, 1.5+0j), 2)
+        self.assertRaises(ZeroDivisionError, complex.__floordiv__, 3+0j, 0+0j)
+
+    def test_coerce(self):
+        self.assertRaises(OverflowError, complex.__coerce__, 1+1j, 1L<<10000)
+
+    def test_richcompare(self):
+        self.assertRaises(OverflowError, complex.__eq__, 1+1j, 1L<<10000)
+        self.assertEqual(complex.__lt__(1+1j, None), NotImplemented)
+        self.assertIs(complex.__eq__(1+1j, 1+1j), True)
+        self.assertIs(complex.__eq__(1+1j, 2+2j), False)
+        self.assertIs(complex.__ne__(1+1j, 1+1j), False)
+        self.assertIs(complex.__ne__(1+1j, 2+2j), True)
+        self.assertRaises(TypeError, complex.__lt__, 1+1j, 2+2j)
+        self.assertRaises(TypeError, complex.__le__, 1+1j, 2+2j)
+        self.assertRaises(TypeError, complex.__gt__, 1+1j, 2+2j)
+        self.assertRaises(TypeError, complex.__ge__, 1+1j, 2+2j)
+
+    def test_mod(self):
+        self.assertRaises(ZeroDivisionError, (1+1j).__mod__, 0+0j)
+
+        a = 3.33+4.43j
+        try:
+            a % 0
+        except ZeroDivisionError:
+            pass
+        else:
+            self.fail("modulo parama can't be 0")
+
+    def test_divmod(self):
+        self.assertRaises(ZeroDivisionError, divmod, 1+1j, 0+0j)
+
+    def test_pow(self):
+        self.assertAlmostEqual(pow(1+1j, 0+0j), 1.0)
+        self.assertAlmostEqual(pow(0+0j, 2+0j), 0.0)
+        self.assertRaises(ZeroDivisionError, pow, 0+0j, 1j)
+        self.assertAlmostEqual(pow(1j, -1), 1/1j)
+        self.assertAlmostEqual(pow(1j, 200), 1)
+        self.assertRaises(ValueError, pow, 1+1j, 1+1j, 1+1j)
+
+        a = 3.33+4.43j
+        self.assertEqual(a ** 0j, 1)
+        self.assertEqual(a ** 0.+0.j, 1)
+
+        self.assertEqual(3j ** 0j, 1)
+        self.assertEqual(3j ** 0, 1)
+
+        try:
+            0j ** a
+        except ZeroDivisionError:
+            pass
+        else:
+            self.fail("should fail 0.0 to negative or complex power")
+
+        try:
+            0j ** (3-2j)
+        except ZeroDivisionError:
+            pass
+        else:
+            self.fail("should fail 0.0 to negative or complex power")
+
+        # The following is used to exercise certain code paths
+        self.assertEqual(a ** 105, a ** 105)
+        self.assertEqual(a ** -105, a ** -105)
+        self.assertEqual(a ** -30, a ** -30)
+
+        self.assertEqual(0.0j ** 0, 1)
+
+        b = 5.1+2.3j
+        self.assertRaises(ValueError, pow, a, b, 0)
+
+    def test_boolcontext(self):
+        for i in xrange(100):
+            self.assert_(complex(random() + 1e-6, random() + 1e-6))
+        self.assert_(not complex(0.0, 0.0))
+
+    def test_conjugate(self):
+        self.assertClose(complex(5.3, 9.8).conjugate(), 5.3-9.8j)
+
+    def test_constructor(self):
+        class OS:
+            def __init__(self, value): self.value = value
+            def __complex__(self): return self.value
+        class NS(object):
+            def __init__(self, value): self.value = value
+            def __complex__(self): return self.value
+        self.assertEqual(complex(OS(1+10j)), 1+10j)
+        self.assertEqual(complex(NS(1+10j)), 1+10j)
+        self.assertRaises(TypeError, complex, OS(None))
+        self.assertRaises(TypeError, complex, NS(None))
+
+        self.assertAlmostEqual(complex("1+10j"), 1+10j)
+        self.assertAlmostEqual(complex(10), 10+0j)
+        self.assertAlmostEqual(complex(10.0), 10+0j)
+        self.assertAlmostEqual(complex(10L), 10+0j)
+        self.assertAlmostEqual(complex(10+0j), 10+0j)
+        self.assertAlmostEqual(complex(1,10), 1+10j)
+        self.assertAlmostEqual(complex(1,10L), 1+10j)
+        self.assertAlmostEqual(complex(1,10.0), 1+10j)
+        self.assertAlmostEqual(complex(1L,10), 1+10j)
+        self.assertAlmostEqual(complex(1L,10L), 1+10j)
+        self.assertAlmostEqual(complex(1L,10.0), 1+10j)
+        self.assertAlmostEqual(complex(1.0,10), 1+10j)
+        self.assertAlmostEqual(complex(1.0,10L), 1+10j)
+        self.assertAlmostEqual(complex(1.0,10.0), 1+10j)
+        self.assertAlmostEqual(complex(3.14+0j), 3.14+0j)
+        self.assertAlmostEqual(complex(3.14), 3.14+0j)
+        self.assertAlmostEqual(complex(314), 314.0+0j)
+        self.assertAlmostEqual(complex(314L), 314.0+0j)
+        self.assertAlmostEqual(complex(3.14+0j, 0j), 3.14+0j)
+        self.assertAlmostEqual(complex(3.14, 0.0), 3.14+0j)
+        self.assertAlmostEqual(complex(314, 0), 314.0+0j)
+        self.assertAlmostEqual(complex(314L, 0L), 314.0+0j)
+        self.assertAlmostEqual(complex(0j, 3.14j), -3.14+0j)
+        self.assertAlmostEqual(complex(0.0, 3.14j), -3.14+0j)
+        self.assertAlmostEqual(complex(0j, 3.14), 3.14j)
+        self.assertAlmostEqual(complex(0.0, 3.14), 3.14j)
+        self.assertAlmostEqual(complex("1"), 1+0j)
+        self.assertAlmostEqual(complex("1j"), 1j)
+        self.assertAlmostEqual(complex(),  0)
+        self.assertAlmostEqual(complex("-1"), -1)
+        self.assertAlmostEqual(complex("+1"), +1)
+
+        class complex2(complex): pass
+        self.assertAlmostEqual(complex(complex2(1+1j)), 1+1j)
+        self.assertAlmostEqual(complex(real=17, imag=23), 17+23j)
+        self.assertAlmostEqual(complex(real=17+23j), 17+23j)
+        self.assertAlmostEqual(complex(real=17+23j, imag=23), 17+46j)
+        self.assertAlmostEqual(complex(real=1+2j, imag=3+4j), -3+5j)
+
+        c = 3.14 + 1j
+        self.assert_(complex(c) is c)
+        del c
+
+        self.assertRaises(TypeError, complex, "1", "1")
+        self.assertRaises(TypeError, complex, 1, "1")
+
+        self.assertEqual(complex("  3.14+J  "), 3.14+1j)
+        if test_support.have_unicode:
+            self.assertEqual(complex(unicode("  3.14+J  ")), 3.14+1j)
+
+        # SF bug 543840:  complex(string) accepts strings with \0
+        # Fixed in 2.3.
+        self.assertRaises(ValueError, complex, '1+1j\0j')
+
+        self.assertRaises(TypeError, int, 5+3j)
+        self.assertRaises(TypeError, long, 5+3j)
+        self.assertRaises(TypeError, float, 5+3j)
+        self.assertRaises(ValueError, complex, "")
+        self.assertRaises(TypeError, complex, None)
+        self.assertRaises(ValueError, complex, "\0")
+        self.assertRaises(TypeError, complex, "1", "2")
+        self.assertRaises(TypeError, complex, "1", 42)
+        self.assertRaises(TypeError, complex, 1, "2")
+        self.assertRaises(ValueError, complex, "1+")
+        self.assertRaises(ValueError, complex, "1+1j+1j")
+        self.assertRaises(ValueError, complex, "--")
+        if test_support.have_unicode:
+            self.assertRaises(ValueError, complex, unicode("1"*500))
+            self.assertRaises(ValueError, complex, unicode("x"))
+
+        class EvilExc(Exception):
+            pass
+
+        class evilcomplex:
+            def __complex__(self):
+                raise EvilExc
+
+        self.assertRaises(EvilExc, complex, evilcomplex())
+
+        class float2:
+            def __init__(self, value):
+                self.value = value
+            def __float__(self):
+                return self.value
+
+        self.assertAlmostEqual(complex(float2(42.)), 42)
+        self.assertAlmostEqual(complex(real=float2(17.), imag=float2(23.)), 17+23j)
+        self.assertRaises(TypeError, complex, float2(None))
+
+        class complex0(complex):
+            """Test usage of __complex__() when inheriting from 'complex'"""
+            def __complex__(self):
+                return 42j
+
+        class complex1(complex):
+            """Test usage of __complex__() with a __new__() method"""
+            def __new__(self, value=0j):
+                return complex.__new__(self, 2*value)
+            def __complex__(self):
+                return self
+
+        class complex2(complex):
+            """Make sure that __complex__() calls fail if anything other than a
+            complex is returned"""
+            def __complex__(self):
+                return None
+
+        self.assertAlmostEqual(complex(complex0(1j)), 42j)
+        self.assertAlmostEqual(complex(complex1(1j)), 2j)
+        self.assertRaises(TypeError, complex, complex2(1j))
+
+    def test_hash(self):
+        for x in xrange(-30, 30):
+            self.assertEqual(hash(x), hash(complex(x, 0)))
+            x /= 3.0    # now check against floating point
+            self.assertEqual(hash(x), hash(complex(x, 0.)))
+
+    def test_abs(self):
+        nums = [complex(x/3., y/7.) for x in xrange(-9,9) for y in xrange(-9,9)]
+        for num in nums:
+            self.assertAlmostEqual((num.real**2 + num.imag**2)  ** 0.5, abs(num))
+
+    def test_repr(self):
+        self.assertEqual(repr(1+6j), '(1+6j)')
+        self.assertEqual(repr(1-6j), '(1-6j)')
+
+        self.assertNotEqual(repr(-(1+0j)), '(-1+-0j)')
+
+    def test_neg(self):
+        self.assertEqual(-(1+6j), -1-6j)
+
+    def test_file(self):
+        a = 3.33+4.43j
+        b = 5.1+2.3j
+
+        fo = None
+        try:
+            fo = open(test_support.TESTFN, "wb")
+            print >>fo, a, b
+            fo.close()
+            fo = open(test_support.TESTFN, "rb")
+            self.assertEqual(fo.read(), "%s %s\n" % (a, b))
+        finally:
+            if (fo is not None) and (not fo.closed):
+                fo.close()
+            try:
+                os.remove(test_support.TESTFN)
+            except (OSError, IOError):
+                pass
+
+def test_main():
+    test_support.run_unittest(ComplexTest)
+
+if __name__ == "__main__":
+    test_main()

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_copy.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_copy.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,591 @@
+"""Unit tests for the copy module."""
+
+import sys
+import copy
+import copy_reg
+
+import unittest
+from test import test_support
+
+class TestCopy(unittest.TestCase):
+
+    # Attempt full line coverage of copy.py from top to bottom
+
+    def test_exceptions(self):
+        self.assert_(copy.Error is copy.error)
+        self.assert_(issubclass(copy.Error, Exception))
+
+    # The copy() method
+
+    def test_copy_basic(self):
+        x = 42
+        y = copy.copy(x)
+        self.assertEqual(x, y)
+
+    def test_copy_copy(self):
+        class C(object):
+            def __init__(self, foo):
+                self.foo = foo
+            def __copy__(self):
+                return C(self.foo)
+        x = C(42)
+        y = copy.copy(x)
+        self.assertEqual(y.__class__, x.__class__)
+        self.assertEqual(y.foo, x.foo)
+
+    def test_copy_registry(self):
+        class C(object):
+            def __new__(cls, foo):
+                obj = object.__new__(cls)
+                obj.foo = foo
+                return obj
+        def pickle_C(obj):
+            return (C, (obj.foo,))
+        x = C(42)
+        self.assertRaises(TypeError, copy.copy, x)
+        copy_reg.pickle(C, pickle_C, C)
+        y = copy.copy(x)
+
+    def test_copy_reduce_ex(self):
+        class C(object):
+            def __reduce_ex__(self, proto):
+                return ""
+            def __reduce__(self):
+                raise test_support.TestFailed, "shouldn't call this"
+        x = C()
+        y = copy.copy(x)
+        self.assert_(y is x)
+
+    def test_copy_reduce(self):
+        class C(object):
+            def __reduce__(self):
+                return ""
+        x = C()
+        y = copy.copy(x)
+        self.assert_(y is x)
+
+    def test_copy_cant(self):
+        class C(object):
+            def __getattribute__(self, name):
+                if name.startswith("__reduce"):
+                    raise AttributeError, name
+                return object.__getattribute__(self, name)
+        x = C()
+        self.assertRaises(copy.Error, copy.copy, x)
+
+    # Type-specific _copy_xxx() methods
+
+    def test_copy_atomic(self):
+        class Classic:
+            pass
+        class NewStyle(object):
+            pass
+        def f():
+            pass
+        tests = [None, 42, 2L**100, 3.14, True, False, 1j,
+                 "hello", u"hello\u1234", f.func_code,
+                 NewStyle, xrange(10), Classic, max]
+        for x in tests:
+            self.assert_(copy.copy(x) is x, repr(x))
+
+    def test_copy_list(self):
+        x = [1, 2, 3]
+        self.assertEqual(copy.copy(x), x)
+
+    def test_copy_tuple(self):
+        x = (1, 2, 3)
+        self.assertEqual(copy.copy(x), x)
+
+    def test_copy_dict(self):
+        x = {"foo": 1, "bar": 2}
+        self.assertEqual(copy.copy(x), x)
+
+    def test_copy_inst_vanilla(self):
+        class C:
+            def __init__(self, foo):
+                self.foo = foo
+            def __cmp__(self, other):
+                return cmp(self.foo, other.foo)
+        x = C(42)
+        self.assertEqual(copy.copy(x), x)
+
+    def test_copy_inst_copy(self):
+        class C:
+            def __init__(self, foo):
+                self.foo = foo
+            def __copy__(self):
+                return C(self.foo)
+            def __cmp__(self, other):
+                return cmp(self.foo, other.foo)
+        x = C(42)
+        self.assertEqual(copy.copy(x), x)
+
+    def test_copy_inst_getinitargs(self):
+        class C:
+            def __init__(self, foo):
+                self.foo = foo
+            def __getinitargs__(self):
+                return (self.foo,)
+            def __cmp__(self, other):
+                return cmp(self.foo, other.foo)
+        x = C(42)
+        self.assertEqual(copy.copy(x), x)
+
+    def test_copy_inst_getstate(self):
+        class C:
+            def __init__(self, foo):
+                self.foo = foo
+            def __getstate__(self):
+                return {"foo": self.foo}
+            def __cmp__(self, other):
+                return cmp(self.foo, other.foo)
+        x = C(42)
+        self.assertEqual(copy.copy(x), x)
+
+    def test_copy_inst_setstate(self):
+        class C:
+            def __init__(self, foo):
+                self.foo = foo
+            def __setstate__(self, state):
+                self.foo = state["foo"]
+            def __cmp__(self, other):
+                return cmp(self.foo, other.foo)
+        x = C(42)
+        self.assertEqual(copy.copy(x), x)
+
+    def test_copy_inst_getstate_setstate(self):
+        class C:
+            def __init__(self, foo):
+                self.foo = foo
+            def __getstate__(self):
+                return self.foo
+            def __setstate__(self, state):
+                self.foo = state
+            def __cmp__(self, other):
+                return cmp(self.foo, other.foo)
+        x = C(42)
+        self.assertEqual(copy.copy(x), x)
+
+    # The deepcopy() method
+
+    def test_deepcopy_basic(self):
+        x = 42
+        y = copy.deepcopy(x)
+        self.assertEqual(y, x)
+
+    def test_deepcopy_memo(self):
+        # Tests of reflexive objects are under type-specific sections below.
+        # This tests only repetitions of objects.
+        x = []
+        x = [x, x]
+        y = copy.deepcopy(x)
+        self.assertEqual(y, x)
+        self.assert_(y is not x)
+        self.assert_(y[0] is not x[0])
+        self.assert_(y[0] is y[1])
+
+    def test_deepcopy_issubclass(self):
+        # XXX Note: there's no way to test the TypeError coming out of
+        # issubclass() -- this can only happen when an extension
+        # module defines a "type" that doesn't formally inherit from
+        # type.
+        class Meta(type):
+            pass
+        class C:
+            __metaclass__ = Meta
+        self.assertEqual(copy.deepcopy(C), C)
+
+    def test_deepcopy_deepcopy(self):
+        class C(object):
+            def __init__(self, foo):
+                self.foo = foo
+            def __deepcopy__(self, memo=None):
+                return C(self.foo)
+        x = C(42)
+        y = copy.deepcopy(x)
+        self.assertEqual(y.__class__, x.__class__)
+        self.assertEqual(y.foo, x.foo)
+
+    def test_deepcopy_registry(self):
+        class C(object):
+            def __new__(cls, foo):
+                obj = object.__new__(cls)
+                obj.foo = foo
+                return obj
+        def pickle_C(obj):
+            return (C, (obj.foo,))
+        x = C(42)
+        self.assertRaises(TypeError, copy.deepcopy, x)
+        copy_reg.pickle(C, pickle_C, C)
+        y = copy.deepcopy(x)
+
+    def test_deepcopy_reduce_ex(self):
+        class C(object):
+            def __reduce_ex__(self, proto):
+                return ""
+            def __reduce__(self):
+                raise test_support.TestFailed, "shouldn't call this"
+        x = C()
+        y = copy.deepcopy(x)
+        self.assert_(y is x)
+
+    def test_deepcopy_reduce(self):
+        class C(object):
+            def __reduce__(self):
+                return ""
+        x = C()
+        y = copy.deepcopy(x)
+        self.assert_(y is x)
+
+    def test_deepcopy_cant(self):
+        class C(object):
+            def __getattribute__(self, name):
+                if name.startswith("__reduce"):
+                    raise AttributeError, name
+                return object.__getattribute__(self, name)
+        x = C()
+        self.assertRaises(copy.Error, copy.deepcopy, x)
+
+    # Type-specific _deepcopy_xxx() methods
+
+    def test_deepcopy_atomic(self):
+        class Classic:
+            pass
+        class NewStyle(object):
+            pass
+        def f():
+            pass
+        tests = [None, 42, 2L**100, 3.14, True, False, 1j,
+                 "hello", u"hello\u1234", f.func_code,
+                 NewStyle, xrange(10), Classic, max]
+        for x in tests:
+            self.assert_(copy.deepcopy(x) is x, repr(x))
+
+    def test_deepcopy_list(self):
+        x = [[1, 2], 3]
+        y = copy.deepcopy(x)
+        self.assertEqual(y, x)
+        self.assert_(x is not y)
+        self.assert_(x[0] is not y[0])
+
+    def test_deepcopy_reflexive_list(self):
+        x = []
+        x.append(x)
+        y = copy.deepcopy(x)
+        self.assertRaises(RuntimeError, cmp, y, x)
+        self.assert_(y is not x)
+        self.assert_(y[0] is y)
+        self.assertEqual(len(y), 1)
+
+    def test_deepcopy_tuple(self):
+        x = ([1, 2], 3)
+        y = copy.deepcopy(x)
+        self.assertEqual(y, x)
+        self.assert_(x is not y)
+        self.assert_(x[0] is not y[0])
+
+    def test_deepcopy_reflexive_tuple(self):
+        x = ([],)
+        x[0].append(x)
+        y = copy.deepcopy(x)
+        self.assertRaises(RuntimeError, cmp, y, x)
+        self.assert_(y is not x)
+        self.assert_(y[0] is not x[0])
+        self.assert_(y[0][0] is y)
+
+    def test_deepcopy_dict(self):
+        x = {"foo": [1, 2], "bar": 3}
+        y = copy.deepcopy(x)
+        self.assertEqual(y, x)
+        self.assert_(x is not y)
+        self.assert_(x["foo"] is not y["foo"])
+
+    def test_deepcopy_reflexive_dict(self):
+        x = {}
+        x['foo'] = x
+        y = copy.deepcopy(x)
+        self.assertRaises(RuntimeError, cmp, y, x)
+        self.assert_(y is not x)
+        self.assert_(y['foo'] is y)
+        self.assertEqual(len(y), 1)
+
+    def test_deepcopy_keepalive(self):
+        memo = {}
+        x = 42
+        y = copy.deepcopy(x, memo)
+        self.assert_(memo[id(x)] is x)
+
+    def test_deepcopy_inst_vanilla(self):
+        class C:
+            def __init__(self, foo):
+                self.foo = foo
+            def __cmp__(self, other):
+                return cmp(self.foo, other.foo)
+        x = C([42])
+        y = copy.deepcopy(x)
+        self.assertEqual(y, x)
+        self.assert_(y.foo is not x.foo)
+
+    def test_deepcopy_inst_deepcopy(self):
+        class C:
+            def __init__(self, foo):
+                self.foo = foo
+            def __deepcopy__(self, memo):
+                return C(copy.deepcopy(self.foo, memo))
+            def __cmp__(self, other):
+                return cmp(self.foo, other.foo)
+        x = C([42])
+        y = copy.deepcopy(x)
+        self.assertEqual(y, x)
+        self.assert_(y is not x)
+        self.assert_(y.foo is not x.foo)
+
+    def test_deepcopy_inst_getinitargs(self):
+        class C:
+            def __init__(self, foo):
+                self.foo = foo
+            def __getinitargs__(self):
+                return (self.foo,)
+            def __cmp__(self, other):
+                return cmp(self.foo, other.foo)
+        x = C([42])
+        y = copy.deepcopy(x)
+        self.assertEqual(y, x)
+        self.assert_(y is not x)
+        self.assert_(y.foo is not x.foo)
+
+    def test_deepcopy_inst_getstate(self):
+        class C:
+            def __init__(self, foo):
+                self.foo = foo
+            def __getstate__(self):
+                return {"foo": self.foo}
+            def __cmp__(self, other):
+                return cmp(self.foo, other.foo)
+        x = C([42])
+        y = copy.deepcopy(x)
+        self.assertEqual(y, x)
+        self.assert_(y is not x)
+        self.assert_(y.foo is not x.foo)
+
+    def test_deepcopy_inst_setstate(self):
+        class C:
+            def __init__(self, foo):
+                self.foo = foo
+            def __setstate__(self, state):
+                self.foo = state["foo"]
+            def __cmp__(self, other):
+                return cmp(self.foo, other.foo)
+        x = C([42])
+        y = copy.deepcopy(x)
+        self.assertEqual(y, x)
+        self.assert_(y is not x)
+        self.assert_(y.foo is not x.foo)
+
+    def test_deepcopy_inst_getstate_setstate(self):
+        class C:
+            def __init__(self, foo):
+                self.foo = foo
+            def __getstate__(self):
+                return self.foo
+            def __setstate__(self, state):
+                self.foo = state
+            def __cmp__(self, other):
+                return cmp(self.foo, other.foo)
+        x = C([42])
+        y = copy.deepcopy(x)
+        self.assertEqual(y, x)
+        self.assert_(y is not x)
+        self.assert_(y.foo is not x.foo)
+
+    def test_deepcopy_reflexive_inst(self):
+        class C:
+            pass
+        x = C()
+        x.foo = x
+        y = copy.deepcopy(x)
+        self.assert_(y is not x)
+        self.assert_(y.foo is y)
+
+    # _reconstruct()
+
+    def test_reconstruct_string(self):
+        class C(object):
+            def __reduce__(self):
+                return ""
+        x = C()
+        y = copy.copy(x)
+        self.assert_(y is x)
+        y = copy.deepcopy(x)
+        self.assert_(y is x)
+
+    def test_reconstruct_nostate(self):
+        class C(object):
+            def __reduce__(self):
+                return (C, ())
+        x = C()
+        x.foo = 42
+        y = copy.copy(x)
+        self.assert_(y.__class__ is x.__class__)
+        y = copy.deepcopy(x)
+        self.assert_(y.__class__ is x.__class__)
+
+    def test_reconstruct_state(self):
+        class C(object):
+            def __reduce__(self):
+                return (C, (), self.__dict__)
+            def __cmp__(self, other):
+                return cmp(self.__dict__, other.__dict__)
+        x = C()
+        x.foo = [42]
+        y = copy.copy(x)
+        self.assertEqual(y, x)
+        y = copy.deepcopy(x)
+        self.assertEqual(y, x)
+        self.assert_(y.foo is not x.foo)
+
+    def test_reconstruct_state_setstate(self):
+        class C(object):
+            def __reduce__(self):
+                return (C, (), self.__dict__)
+            def __setstate__(self, state):
+                self.__dict__.update(state)
+            def __cmp__(self, other):
+                return cmp(self.__dict__, other.__dict__)
+        x = C()
+        x.foo = [42]
+        y = copy.copy(x)
+        self.assertEqual(y, x)
+        y = copy.deepcopy(x)
+        self.assertEqual(y, x)
+        self.assert_(y.foo is not x.foo)
+
+    def test_reconstruct_reflexive(self):
+        class C(object):
+            pass
+        x = C()
+        x.foo = x
+        y = copy.deepcopy(x)
+        self.assert_(y is not x)
+        self.assert_(y.foo is y)
+
+    # Additions for Python 2.3 and pickle protocol 2
+
+    def test_reduce_4tuple(self):
+        class C(list):
+            def __reduce__(self):
+                return (C, (), self.__dict__, iter(self))
+            def __cmp__(self, other):
+                return (cmp(list(self), list(other)) or
+                        cmp(self.__dict__, other.__dict__))
+        x = C([[1, 2], 3])
+        y = copy.copy(x)
+        self.assertEqual(x, y)
+        self.assert_(x is not y)
+        self.assert_(x[0] is y[0])
+        y = copy.deepcopy(x)
+        self.assertEqual(x, y)
+        self.assert_(x is not y)
+        self.assert_(x[0] is not y[0])
+
+    def test_reduce_5tuple(self):
+        class C(dict):
+            def __reduce__(self):
+                return (C, (), self.__dict__, None, self.iteritems())
+            def __cmp__(self, other):
+                return (cmp(dict(self), list(dict)) or
+                        cmp(self.__dict__, other.__dict__))
+        x = C([("foo", [1, 2]), ("bar", 3)])
+        y = copy.copy(x)
+        self.assertEqual(x, y)
+        self.assert_(x is not y)
+        self.assert_(x["foo"] is y["foo"])
+        y = copy.deepcopy(x)
+        self.assertEqual(x, y)
+        self.assert_(x is not y)
+        self.assert_(x["foo"] is not y["foo"])
+
+    def test_copy_slots(self):
+        class C(object):
+            __slots__ = ["foo"]
+        x = C()
+        x.foo = [42]
+        y = copy.copy(x)
+        self.assert_(x.foo is y.foo)
+
+    def test_deepcopy_slots(self):
+        class C(object):
+            __slots__ = ["foo"]
+        x = C()
+        x.foo = [42]
+        y = copy.deepcopy(x)
+        self.assertEqual(x.foo, y.foo)
+        self.assert_(x.foo is not y.foo)
+
+    def test_copy_list_subclass(self):
+        class C(list):
+            pass
+        x = C([[1, 2], 3])
+        x.foo = [4, 5]
+        y = copy.copy(x)
+        self.assertEqual(list(x), list(y))
+        self.assertEqual(x.foo, y.foo)
+        self.assert_(x[0] is y[0])
+        self.assert_(x.foo is y.foo)
+
+    def test_deepcopy_list_subclass(self):
+        class C(list):
+            pass
+        x = C([[1, 2], 3])
+        x.foo = [4, 5]
+        y = copy.deepcopy(x)
+        self.assertEqual(list(x), list(y))
+        self.assertEqual(x.foo, y.foo)
+        self.assert_(x[0] is not y[0])
+        self.assert_(x.foo is not y.foo)
+
+    def test_copy_tuple_subclass(self):
+        class C(tuple):
+            pass
+        x = C([1, 2, 3])
+        self.assertEqual(tuple(x), (1, 2, 3))
+        y = copy.copy(x)
+        self.assertEqual(tuple(y), (1, 2, 3))
+
+    def test_deepcopy_tuple_subclass(self):
+        class C(tuple):
+            pass
+        x = C([[1, 2], 3])
+        self.assertEqual(tuple(x), ([1, 2], 3))
+        y = copy.deepcopy(x)
+        self.assertEqual(tuple(y), ([1, 2], 3))
+        self.assert_(x is not y)
+        self.assert_(x[0] is not y[0])
+
+    def test_getstate_exc(self):
+        class EvilState(object):
+            def __getstate__(self):
+                raise ValueError, "ain't got no stickin' state"
+        self.assertRaises(ValueError, copy.copy, EvilState())
+
+    def test_copy_function(self):
+        self.assertEqual(copy.copy(global_foo), global_foo)
+        def foo(x, y): return x+y
+        self.assertEqual(copy.copy(foo), foo)
+        bar = lambda: None
+        self.assertEqual(copy.copy(bar), bar)
+
+    def test_deepcopy_function(self):
+        self.assertEqual(copy.deepcopy(global_foo), global_foo)
+        def foo(x, y): return x+y
+        self.assertEqual(copy.deepcopy(foo), foo)
+        bar = lambda: None
+        self.assertEqual(copy.deepcopy(bar), bar)
+
+def global_foo(x, y): return x+y
+
+def test_main():
+    test_support.run_unittest(TestCopy)
+
+if __name__ == "__main__":
+    test_main()

Added: pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_cpickle.py
==============================================================================
--- (empty file)
+++ pypy/branch/2.5-features/lib-python/modified-2.5.1/test/test_cpickle.py	Sun Aug 17 23:48:15 2008
@@ -0,0 +1,103 @@
+import cPickle
+import unittest
+from cStringIO import StringIO
+from test.pickletester import AbstractPickleTests, AbstractPickleModuleTests
+from test import test_support
+
+class cPickleTests(AbstractPickleTests, AbstractPickleModuleTests):
+
+    def setUp(self):
+        self.dumps = cPickle.dumps
+        self.loads = cPickle.loads
+
+    error = cPickle.BadPickleGet
+    module = cPickle
+
+class cPicklePicklerTests(AbstractPickleTests):
+
+    def dumps(self, arg, proto=0):
+        f = StringIO()
+        p = cPickle.Pickler(f, proto)
+        p.dump(arg)
+        f.seek(0)
+        return f.read()
+
+    def loads(self, buf):
+        f = StringIO(buf)
+        p = cPickle.Unpickler(f)
+        return p.load()
+
+    error = cPickle.BadPickleGet
+
+class cPickleListPicklerTests(AbstractPickleTests):
+
+    def dumps(self, arg, proto=0):
+        p = cPickle.Pickler(proto)
+        p.dump(arg)
+        return p.getvalue()
+
+    def loads(self, *args):
+        f = StringIO(args[0])
+        p = cPickle.Unpickler(f)
+        return p.load()
+
+    error = cPickle.BadPickleGet
+
+class cPickleFastPicklerTests(AbstractPickleTests):
+
+    def dumps(self, arg, proto=0):
+        f = StringIO()
+        p = cPickle.Pickler(f, proto)
+        p.fast = 1
+        p.dump(arg)
+        f.seek(0)
+        return f.read()
+
+    def loads(self, *args):
+        f = StringIO(args[0])
+        p = cPickle.Unpickler(f)
+        return p.load()
+
+    error = cPickle.BadPickleGet
+
+    def test_recursive_list(self):
+        self.assertRaises(ValueError,
+                          AbstractPickleTests.test_recursive_list,
+                          self)
+
+    def test_recursive_inst(self):
+        self.assertRaises(ValueError,
+                          AbstractPickleTests.test_recursive_inst,
+                          self)
+
+    def test_recursive_dict(self):
+        self.assertRaises(ValueError,
+                          AbstractPickleTests.test_recursive_dict,
+                          self)
+
+    def test_recursive_multi(self):
+        self.assertRaises(ValueError,
+                          AbstractPickleTests.test_recursive_multi,
+                          self)
+
+    def test_nonrecursive_deep(self):
+        # If it's not cyclic, it should pickle OK even if the nesting
+        # depth exceeds PY_CPICKLE_FAST_LIMIT.  That happens to be
+        # 50 today.  Jack Jansen reported stack overflow on Mac OS 9
+        # at 64.
+        a = []
+        for i in range(60):
+            a = [a]
+        b = self.loads(self.dumps(a))
+        self.assertEqual(a, b)
+
+def test_main():
+    test_support.run_unittest(
+        cPickleTests,
+        cPicklePicklerTests,
+        cPickleListPicklerTests,
+        # XXX undocumented, not supported by PyPy: cPickleFastPicklerTests
+    )
+
+if __name__ == "__main__":
+    test_main()



More information about the Pypy-commit mailing list