From 7a8da48a306dfc8e43239d7f2a141c465e40ab77 Mon Sep 17 00:00:00 2001 From: Maximilian Hils Date: Wed, 25 May 2016 19:16:02 -0700 Subject: [PATCH] escaped_str_to_bytes: support unicode on python 2 --- netlib/utils.py | 6 +++++- test/netlib/test_utils.py | 9 ++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/netlib/utils.py b/netlib/utils.py index 7499f71fc..fe11cb5be 100644 --- a/netlib/utils.py +++ b/netlib/utils.py @@ -439,10 +439,14 @@ def escaped_str_to_bytes(data): """ Take an escaped string and return the unescaped bytes equivalent. """ - if not isinstance(data, str): + if not isinstance(data, six.string_types): + if six.PY2: + raise ValueError("data must be str or unicode") raise ValueError("data must be str") if six.PY2: + if isinstance(data, unicode): + data = data.encode("utf8") return data.decode("string-escape") # This one is difficult - we use an undocumented Python API here diff --git a/test/netlib/test_utils.py b/test/netlib/test_utils.py index 1d8f7b0f9..671ae66c4 100644 --- a/test/netlib/test_utils.py +++ b/test/netlib/test_utils.py @@ -182,6 +182,9 @@ def test_bytes_to_escaped_str(): def test_escaped_str_to_bytes(): assert utils.escaped_str_to_bytes("foo") == b"foo" - assert utils.escaped_str_to_bytes(r"\x08") == b"\b" - assert utils.escaped_str_to_bytes(r"&!?=\\)") == br"&!?=\)" - assert utils.escaped_str_to_bytes(r"ü") == b'\xc3\xbc' + assert utils.escaped_str_to_bytes("\x08") == b"\b" + assert utils.escaped_str_to_bytes("&!?=\\\\)") == br"&!?=\)" + assert utils.escaped_str_to_bytes("ü") == b'\xc3\xbc' + assert utils.escaped_str_to_bytes(u"\\x08") == b"\b" + assert utils.escaped_str_to_bytes(u"&!?=\\\\)") == br"&!?=\)" + assert utils.escaped_str_to_bytes(u"ü") == b'\xc3\xbc' \ No newline at end of file