From 576b447a3708cce7c6d0c26695ca980b11c4bdc9 Mon Sep 17 00:00:00 2001 From: Nate Prewitt Date: Thu, 8 Dec 2016 15:00:37 -0700 Subject: [PATCH] adding string casting for non-bytes values --- requests/auth.py | 18 ++++++++++++++++-- tests/test_requests.py | 11 +++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/requests/auth.py b/requests/auth.py index 3460c8b5..bd2fe7d8 100644 --- a/requests/auth.py +++ b/requests/auth.py @@ -15,7 +15,7 @@ import threading from base64 import b64encode -from .compat import urlparse, str +from .compat import urlparse, str, basestring from .cookies import extract_cookies_to_jar from ._internal_utils import to_native_string from .utils import parse_dict_header @@ -27,7 +27,21 @@ CONTENT_TYPE_MULTI_PART = 'multipart/form-data' def _basic_auth_str(username, password): """Returns a Basic Auth string.""" - + + # "I want us to put a big-ol' comment on top of it that + # says that this behaviour is dumb but we need to preserve + # it because people are relying on it." + # - Lukasa + # + # These are here solely to maintain backwards compatibility + # for things like ints. This will be removed in 3.0.0. + if not isinstance(username, basestring): + username = str(username) + + if not isinstance(password, basestring): + password = str(password) + # -- End Removal -- + if isinstance(username, str): username = username.encode('latin1') diff --git a/tests/test_requests.py b/tests/test_requests.py index 49417717..211296dd 100755 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -484,6 +484,7 @@ class TestRequests: 'username, password', ( ('user', 'pass'), (u'имя'.encode('utf-8'), u'пароль'.encode('utf-8')), + (42, 42) )) def test_set_basicauth(self, httpbin, username, password): auth = (username, password) @@ -494,6 +495,16 @@ class TestRequests: assert p.headers['Authorization'] == _basic_auth_str(username, password) + def test_basicauth_encodes_byte_strings(self): + """Ensure b'test' formats as the byte string "test" rather + than the unicode string "b'test'" in Python 3. + """ + auth = (b'\xc5\xafsername', b'test\xc6\xb6') + r = requests.Request('GET', 'http://localhost', auth=auth) + p = r.prepare() + + assert p.headers['Authorization'] == 'Basic xa9zZXJuYW1lOnRlc3TGtg==' + @pytest.mark.parametrize( 'url, exception', ( # Connecting to an unknown domain should raise a ConnectionError