Skip to content

Commit 8d5d809

Browse files
committed
Merge branch 'master' into v0.16.x
2 parents 9fcde90 + 97f8eca commit 8d5d809

File tree

4 files changed

+34
-1
lines changed

4 files changed

+34
-1
lines changed

src/future/types/newbytes.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,8 @@ def __new__(cls, *args, **kwargs):
100100
newargs.append(errors)
101101
value = args[0].encode(*newargs)
102102
###
103+
elif hasattr(args[0], '__bytes__'):
104+
value = args[0].__bytes__()
103105
elif isinstance(args[0], Iterable):
104106
if len(args[0]) == 0:
105107
# This could be an empty list or tuple. Return b'' as on Py3.

src/future/utils/surrogateescape.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ def replace_surrogate_encode(mystring):
8383
# The following magic comes from Py3.3's Python/codecs.c file:
8484
if not 0xD800 <= code <= 0xDCFF:
8585
# Not a surrogate. Fail with the original exception.
86-
raise exc
86+
raise NotASurrogateError
8787
# mybytes = [0xe0 | (code >> 12),
8888
# 0x80 | ((code >> 6) & 0x3f),
8989
# 0x80 | (code & 0x3f)]

tests/test_future/test_bytes.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -707,6 +707,31 @@ def test_issue_171_part_b(self):
707707
b = nativebytes(bytes(b'asdf'))
708708
self.assertEqual(b, b'asdf')
709709

710+
def test_cast_to_bytes(self):
711+
"""
712+
Tests whether __bytes__ method is called
713+
"""
714+
715+
class TestObject:
716+
def __bytes__(self):
717+
return b'asdf'
718+
719+
self.assertEqual(bytes(TestObject()), b'asdf')
720+
721+
def test_cast_to_bytes_iter_precedence(self):
722+
"""
723+
Tests that call to __bytes__ is preferred to iteration
724+
"""
725+
726+
class TestObject:
727+
def __bytes__(self):
728+
return b'asdf'
729+
730+
def __iter__(self):
731+
return iter(b'hjkl')
732+
733+
self.assertEqual(bytes(TestObject()), b'asdf')
734+
710735

711736
if __name__ == '__main__':
712737
unittest.main()

tests/test_future/test_surrogateescape.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,12 @@ def test_encode_ascii_surrogateescape(self):
3333
b = payload.encode('ascii', 'surrogateescape')
3434
self.assertEqual(b, b'cMO2c3RhbA\xc3\xa1=\n')
3535

36+
def test_encode_ascii_unicode(self):
37+
"""
38+
Verify that exceptions are raised properly.
39+
"""
40+
self.assertRaises(UnicodeEncodeError, u'\N{SNOWMAN}'.encode, 'US-ASCII', 'surrogateescape')
41+
3642
@expectedFailurePY2
3743
def test_encode_ascii_surrogateescape_non_newstr(self):
3844
"""

0 commit comments

Comments
 (0)