diff options
author | Victor Stinner <vstinner@redhat.com> | 2019-06-25 22:51:05 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-06-25 22:51:05 (GMT) |
commit | 22eb689cf3de7972a2789db3ad01a86949508ab7 (patch) | |
tree | a1d63fa4cf235008e73f92a18ebef57be54ce4a5 /Lib/test/test_bytes.py | |
parent | e1a63c4f21011a3ae77dff624196561070c83446 (diff) | |
download | cpython-22eb689cf3de7972a2789db3ad01a86949508ab7.zip cpython-22eb689cf3de7972a2789db3ad01a86949508ab7.tar.gz cpython-22eb689cf3de7972a2789db3ad01a86949508ab7.tar.bz2 |
bpo-37388: Development mode check encoding and errors (GH-14341)
In development mode and in debug build, encoding and errors arguments
are now checked on string encoding and decoding operations. Examples:
open(), str.encode() and bytes.decode().
By default, for best performances, the errors argument is only
checked at the first encoding/decoding error, and the encoding
argument is sometimes ignored for empty strings.
Diffstat (limited to 'Lib/test/test_bytes.py')
-rw-r--r-- | Lib/test/test_bytes.py | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/Lib/test/test_bytes.py b/Lib/test/test_bytes.py index bbd45c7..b5eeb2b 100644 --- a/Lib/test/test_bytes.py +++ b/Lib/test/test_bytes.py @@ -12,12 +12,14 @@ import copy import functools import pickle import tempfile +import textwrap import unittest import test.support import test.string_tests import test.list_tests from test.support import bigaddrspacetest, MAX_Py_ssize_t +from test.support.script_helper import assert_python_failure if sys.flags.bytes_warning: @@ -315,6 +317,62 @@ class BaseBytesTest: # Default encoding is utf-8 self.assertEqual(self.type2test(b'\xe2\x98\x83').decode(), '\u2603') + def test_check_encoding_errors(self): + # bpo-37388: bytes(str) and bytes.encode() must check encoding + # and errors arguments in dev mode + invalid = 'Boom, Shaka Laka, Boom!' + encodings = ('ascii', 'utf8', 'latin1') + code = textwrap.dedent(f''' + import sys + type2test = {self.type2test.__name__} + encodings = {encodings!r} + + for data in ('', 'short string'): + try: + type2test(data, encoding={invalid!r}) + except LookupError: + pass + else: + sys.exit(21) + + for encoding in encodings: + try: + type2test(data, encoding=encoding, errors={invalid!r}) + except LookupError: + pass + else: + sys.exit(22) + + for data in (b'', b'short string'): + data = type2test(data) + print(repr(data)) + try: + data.decode(encoding={invalid!r}) + except LookupError: + sys.exit(10) + else: + sys.exit(23) + + try: + data.decode(errors={invalid!r}) + except LookupError: + pass + else: + sys.exit(24) + + for encoding in encodings: + try: + data.decode(encoding=encoding, errors={invalid!r}) + except LookupError: + pass + else: + sys.exit(25) + + sys.exit(10) + ''') + proc = assert_python_failure('-X', 'dev', '-c', code) + self.assertEqual(proc.rc, 10, proc) + def test_from_int(self): b = self.type2test(0) self.assertEqual(b, self.type2test()) |