Commits

Philip Jenvey  committed 7cbe47c Merge

Merged in mjacob/pypy/py3k (pull request #120)

Random py3k fixes

  • Participants
  • Parent commits 38bdcc0, bb99cde
  • Branches py3k

Comments (0)

Files changed (11)

File lib-python/3.2/test/pickletester.py

 
 from test.support import (
     TestFailed, TESTFN, run_with_locale,
-    _2G, _4G, bigmemtest,
+    _2G, _4G, bigmemtest, impl_detail
     )
 
 from pickle import bytes_types
                              "Failed protocol %d: %r != %r"
                              % (proto, obj, loaded))
 
+    @impl_detail("pypy does not store attribute names", pypy=False)
     def test_attribute_name_interning(self):
         # Test that attribute names of pickled objects are interned when
         # unpickling.

File lib-python/3.2/test/test_array.py

             if a.itemsize>1:
                 self.assertRaises(ValueError, b.fromstring, "x")
                 nb_warnings += 1
-        self.assertEqual(len(r), nb_warnings)
+        if support.check_impl_detail():
+            # PyPy's multimethod dispatch is different from CPython's
+            # on CPython the warning is emitted before checking the arguments
+            self.assertEqual(len(r), nb_warnings)
 
     def test_tofrombytes(self):
         a = array.array(self.typecode, 2*self.example)

File lib-python/3.2/test/test_bytes.py

         self.assertRaises(TypeError, bytes, A())
 
     # Test PyBytes_FromFormat()
+    @test.support.impl_detail("don't test cpyext here")
     def test_from_format(self):
         test.support.import_module('ctypes')
         from ctypes import pythonapi, py_object, c_int, c_char_p
         self.assertEqual(b, b1)
         self.assertTrue(b is b1)
 
+    @test.support.impl_detail("undocumented bytes.__alloc__()")
     def test_alloc(self):
         b = bytearray()
         alloc = b.__alloc__()
         self.assertEqual(b, b"")
         self.assertEqual(c, b"")
 
+    @test.support.impl_detail(
+        "resizing semantics of CPython rely on refcounting")
     def test_resize_forbidden(self):
         # #4509: can't resize a bytearray when there are buffer exports, even
         # if it wouldn't reallocate the underlying buffer.
         self.assertRaises(BufferError, delslice)
         self.assertEqual(b, orig)
 
+    @test.support.impl_detail("resizing semantics", cpython=False)
+    def test_resize_forbidden_non_cpython(self):
+        # on non-CPython implementations, we cannot prevent changes to
+        # bytearrays just because there are buffers around.  Instead,
+        # we get (on PyPy) a buffer that follows the changes and resizes.
+        b = bytearray(range(10))
+        v = memoryview(b)
+        b[5] = 99
+        self.assertIn(v[5], (99, bytes([99])))
+        b[5] = 100
+        b += b
+        b += b
+        b += b
+        self.assertEquals(len(v), 80)
+        self.assertIn(v[5], (100, bytes([100])))
+        self.assertIn(v[79], (9, bytes([9])))
+        del b[10:]
+        self.assertRaises(IndexError, lambda: v[10])
+        self.assertEquals(len(v), 10)
+
 
 class AssortedBytesTest(unittest.TestCase):
     #

File lib-python/3.2/test/test_copy.py

         x = {}
         x['foo'] = x
         y = copy.deepcopy(x)
-        for op in order_comparisons:
-            self.assertRaises(TypeError, op, y, x)
+        if support.check_impl_detail():
+            for op in order_comparisons:
+                self.assertRaises(TypeError, op, y, x)
+        else:
+            # this is an implementation detail
+            # equality comparisons raise RuntimeError on CPython, too
+            for op in order_comparisons:
+                self.assertRaises(RuntimeError, op, y, x)
         for op in equality_comparisons:
             self.assertRaises(RuntimeError, op, y, x)
         self.assertTrue(y is not x)

File lib-python/3.2/test/test_csv.py

     """
     def _test_arg_valid(self, ctor, arg):
         self.assertRaises(TypeError, ctor)
-        self.assertRaises(TypeError, ctor, None)
+        # PyPy gets an AttributeError instead of a TypeError
+        self.assertRaises((TypeError, AttributeError), ctor, None)
         self.assertRaises(TypeError, ctor, arg, bad_attr = 0)
         self.assertRaises(TypeError, ctor, arg, delimiter = 0)
         self.assertRaises(TypeError, ctor, arg, delimiter = 'XX')
                              expect + writer.dialect.lineterminator)
 
     def test_write_arg_valid(self):
-        self.assertRaises(csv.Error, self._write_test, None, '')
+        # PyPy gets a TypeError instead of a csv.Error for "not a sequence"
+        self.assertRaises((csv.Error, TypeError), self._write_test, None, '')
         self._write_test((), '')
         self._write_test([None], '""')
         self.assertRaises(csv.Error, self._write_test,
                           ['ab\0c'], None, strict = 1)
         self._read_test(['"ab"c'], [['abc']], doublequote = 0)
 
-        self.assertRaises(csv.Error, self._read_test,
+        # PyPy gets a TypeError instead of a csv.Error for bytes input
+        self.assertRaises((csv.Error, TypeError), self._read_test,
                           [b'ab\0c'], None)
 
 

File lib-python/3.2/test/test_dict.py

                     self.assertEqual(va, int(ka))
                     kb, vb = tb = b.popitem()
                     self.assertEqual(vb, int(kb))
-                    self.assertFalse(copymode < 0 and ta != tb)
+                    if test_support.check_impl_detail():
+                        self.assertFalse(copymode < 0 and ta != tb)
                 self.assertFalse(a)
                 self.assertFalse(b)
 

File lib-python/3.2/test/test_generators.py

 """
 
 coroutine_tests = """\
+A helper function to call gc.collect() without printing
+>>> import gc
+>>> def gc_collect(): gc.collect()
+
 Sending a value into a started generator:
 
 >>> def f():
 
 >>> g = f()
 >>> next(g)
->>> del g
+>>> del g; gc_collect()
 exiting
 
 
 
 >>> g = f()
 >>> next(g)
->>> del g
+>>> del g; gc_collect()
 finally
 
 
 >>> g = f()
 >>> next(g)
 >>> del g
+>>> gc_collect()
 >>> sys.stderr.getvalue().startswith(
 ...     "Exception RuntimeError: 'generator ignored GeneratorExit' in "
 ... )
 references. We add it to the standard suite so the routine refleak-tests
 would trigger if it starts being uncleanable again.
 
+>>> import gc
+>>> def gc_collect(): gc.collect()
+
 >>> import itertools
 >>> def leak():
 ...     class gen:
 ...
 ...     l = Leaker()
 ...     del l
+...     gc_collect()
 ...     err = sys.stderr.getvalue().strip()
 ...     err.startswith(
-...         "Exception RuntimeError: RuntimeError() in <"
+...         "Exception RuntimeError: RuntimeError() in "
 ...     )
 ...     err.endswith("> ignored")
 ...     len(err.splitlines())

File lib-python/3.2/test/test_mutants.py

-from test.support import verbose, TESTFN
+from test.support import verbose, TESTFN, check_impl_detail
 import random
 import os
 
     while dict1 and len(dict1) == len(dict2):
         if verbose:
             print(".", end=' ')
-        c = dict1 == dict2
+        try:
+            c = dict1 == dict2
+        except RuntimeError:
+            # CPython never raises RuntimeError here, but other implementations
+            # might, and it's fine.
+            if check_impl_detail(cpython=True):
+                raise
     if verbose:
         print()
 

File lib-python/3.2/test/test_socket.py

                          "'complex' does not support the buffer interface")
         with self.assertRaises(TypeError) as cm:
             s.sendto(b'foo', None)
-        self.assertIn('not NoneType',str(cm.exception))
+        self.assertIn('NoneType', str(cm.exception))
         # 3 args
         with self.assertRaises(TypeError) as cm:
             s.sendto('\u2620', 0, sockname)
                          "'complex' does not support the buffer interface")
         with self.assertRaises(TypeError) as cm:
             s.sendto(b'foo', 0, None)
-        self.assertIn('not NoneType', str(cm.exception))
+        if support.check_impl_detail():
+            self.assertIn('not NoneType', str(cm.exception))
         with self.assertRaises(TypeError) as cm:
             s.sendto(b'foo', 'bar', sockname)
-        self.assertIn('an integer is required', str(cm.exception))
+        self.assertIn('integer', str(cm.exception))
         with self.assertRaises(TypeError) as cm:
             s.sendto(b'foo', None, None)
-        self.assertIn('an integer is required', str(cm.exception))
+        if support.check_impl_detail():
+            self.assertIn('an integer is required', str(cm.exception))
         # wrong number of args
         with self.assertRaises(TypeError) as cm:
             s.sendto(b'foo')
-        self.assertIn('(1 given)', str(cm.exception))
+        self.assertIn(' given)', str(cm.exception))
         with self.assertRaises(TypeError) as cm:
             s.sendto(b'foo', 0, sockname, 4)
-        self.assertIn('(4 given)', str(cm.exception))
+        self.assertIn(' given)', str(cm.exception))
 
     def testCrucialConstants(self):
         # Testing for mission critical constants
             socket.htonl(k)
             socket.htons(k)
         for k in bad_values:
-            self.assertRaises(OverflowError, socket.ntohl, k)
-            self.assertRaises(OverflowError, socket.ntohs, k)
-            self.assertRaises(OverflowError, socket.htonl, k)
-            self.assertRaises(OverflowError, socket.htons, k)
+            self.assertRaises((OverflowError, ValueError), socket.ntohl, k)
+            self.assertRaises((OverflowError, ValueError), socket.ntohs, k)
+            self.assertRaises((OverflowError, ValueError), socket.htonl, k)
+            self.assertRaises((OverflowError, ValueError), socket.htons, k)
 
     def testGetServBy(self):
         eq = self.assertEqual
         if udpport is not None:
             eq(socket.getservbyport(udpport, 'udp'), service)
         # Make sure getservbyport does not accept out of range ports.
-        self.assertRaises(OverflowError, socket.getservbyport, -1)
-        self.assertRaises(OverflowError, socket.getservbyport, 65536)
+        self.assertRaises((OverflowError, ValueError), socket.getservbyport, -1)
+        self.assertRaises((OverflowError, ValueError), socket.getservbyport, 65536)
 
     def testDefaultTimeout(self):
         # Testing default timeout
         neg_port = port - 65536
         sock = socket.socket()
         try:
-            self.assertRaises(OverflowError, sock.bind, (host, big_port))
-            self.assertRaises(OverflowError, sock.bind, (host, neg_port))
+            self.assertRaises((OverflowError, ValueError), sock.bind, (host, big_port))
+            self.assertRaises((OverflowError, ValueError), sock.bind, (host, neg_port))
             sock.bind((host, port))
         finally:
             sock.close()
         self.write_file.flush()
 
     def testMakefileCloseSocketDestroy(self):
-        refcount_before = sys.getrefcount(self.cli_conn)
-        self.read_file.close()
-        refcount_after = sys.getrefcount(self.cli_conn)
-        self.assertEqual(refcount_before - 1, refcount_after)
+        if hasattr(sys, "getrefcount"):
+            refcount_before = sys.getrefcount(self.cli_conn)
+            self.read_file.close()
+            refcount_after = sys.getrefcount(self.cli_conn)
+            self.assertEqual(refcount_before - 1, refcount_after)
 
     def _testMakefileCloseSocketDestroy(self):
         pass

File pypy/module/array/interp_array.py

 
             if len(__args__.arguments_w) > 0:
                 w_initializer = __args__.arguments_w[0]
-                if space.type(w_initializer) is space.w_bytes:
-                    a.fromstring(space.bytes_w(w_initializer))
+                if space.lookup(w_initializer, '__buffer__') is not None:
+                    if isinstance(w_initializer, W_ArrayBase):
+                        a.extend(w_initializer, True)
+                    else:
+                        a.fromstring(space.bufferstr_w(w_initializer))
                 elif space.type(w_initializer) is space.w_list:
                     a.fromlist(w_initializer)
                 else:
         self.fromlist(w_lst)
 
     def array_frombytes__Array_ANY(space, self, w_s):
-        self.fromstring(space.bytes_w(w_s))
+        self.fromstring(space.bufferstr_w(w_s))
 
     def array_fromstring__Array_ANY(space, self, w_s):
         space.warn("fromstring() is deprecated. Use frombytes() instead.",
             return space.wrap("array('%s')" % self.typecode)
         elif self.typecode == "u":
             r = space.repr(array_tounicode__Array(space, self))
-            s = "array('%s', %s)" % (self.typecode, space.str_w(r))
+            s = u"array('u', %s)" % space.unicode_w(r)
             return space.wrap(s)
         else:
             r = space.repr(array_tolist__Array(space, self))

File pypy/module/array/test/test_array.py

         assert l
         assert l[0] is None or len(l[0]) == 0
 
+    def test_bytearray(self):
+        a = self.array('u', 'hi')
+        b = self.array('u')
+        b.frombytes(bytearray(a.tobytes()))
+        assert a == b
+        assert self.array('u', bytearray(a.tobytes())) == a
+
+    def test_repr(self):
+        s = '\x00="\'a\\b\x80\xff\u0000\u0001\u1234'
+        a = self.array('u', s)
+        assert repr(a) == "array('u', {!r})".format(s)
+        assert eval(repr(a), {'array': self.array}) == a
+
 
 class DontTestCPythonsOwnArray(BaseArrayTests):