[pypy-commit] pypy py3.6: #3166

arigo pypy.commits at gmail.com
Fri Feb 7 04:33:38 EST 2020


Author: Armin Rigo <arigo at tunes.org>
Branch: py3.6
Changeset: r98680:f13039d71ef7
Date: 2020-02-07 10:32 +0100
http://bitbucket.org/pypy/pypy/changeset/f13039d71ef7/

Log:	#3166

	Obscure ordering-of-which-error-to-report-first issue

diff --git a/pypy/objspace/std/test/test_unicodeobject.py b/pypy/objspace/std/test/test_unicodeobject.py
--- a/pypy/objspace/std/test/test_unicodeobject.py
+++ b/pypy/objspace/std/test/test_unicodeobject.py
@@ -1281,6 +1281,15 @@
         assert str(e.value) == 'decoding str is not supported'
         e = raises(TypeError, str, z, 'supposedly_the_encoding')
         assert str(e.value) == 'decoding str is not supported'
+        #
+        e = raises(TypeError, str, 42, 'supposedly_the_encoding')
+        assert str(e.value) in [
+            'decoding to str: a bytes-like object is required, not int',
+            'decoding to str: need a bytes-like object, int found']
+        e = raises(TypeError, str, None, 'supposedly_the_encoding')
+        assert str(e.value) in [
+            'decoding to str: a bytes-like object is required, not None',
+            'decoding to str: need a bytes-like object, NoneType found']
 
     def test_reduce_iterator(self):
         it = iter(u"abcdef")
diff --git a/pypy/objspace/std/unicodeobject.py b/pypy/objspace/std/unicodeobject.py
--- a/pypy/objspace/std/unicodeobject.py
+++ b/pypy/objspace/std/unicodeobject.py
@@ -1370,14 +1370,23 @@
 
 def decode_object(space, w_obj, encoding, errors=None):
     from pypy.module._codecs.interp_codecs import _call_codec, lookup_text_codec
+    # in all cases, call space.charbuf_w() first.  This will fail with a
+    # TypeError if w_obj is of a random type.  Do this even if we're not
+    # going to use 's'
+    try:
+        s = space.charbuf_w(w_obj)
+    except OperationError as e:
+        if not e.match(space, space.w_TypeError):
+            raise
+        raise oefmt(space.w_TypeError, "decoding to str: %S",
+            e.get_w_value(space))
+    #
     if errors == 'strict' or errors is None:
         # fast paths
         if encoding == 'ascii':
-            s = space.charbuf_w(w_obj)
             unicodehelper.check_ascii_or_raise(space, s)
             return space.newtext(s, len(s))
         if encoding == 'utf-8' or encoding == 'utf8':
-            s = space.charbuf_w(w_obj)
             lgt = unicodehelper.check_utf8_or_raise(space, s)
             return space.newutf8(s, lgt)
     if encoding is None:


More information about the pypy-commit mailing list