Handle HTTP byte returns in python 3

The returns from requests' response.content is a bytes type. Under
python 3 this fails in error handling and string conversion. The
response.text variable should be used to treat a response body as a
string.

Closes-Bug: #1407531
Change-Id: Ifd588b5f6820ef21beb186d88d0b3f1a267695aa
This commit is contained in:
Jamie Lennox 2015-01-05 11:46:13 +10:00
parent aebbcff100
commit 62df6c669f
3 changed files with 11 additions and 4 deletions

View File

@ -226,7 +226,7 @@ class HTTPClient(object):
if not resp.ok: if not resp.ok:
LOG.debug("Request returned failure status %s." % resp.status_code) LOG.debug("Request returned failure status %s." % resp.status_code)
raise exc.from_response(resp, resp.content) raise exc.from_response(resp, resp.text)
elif resp.status_code == requests.codes.MULTIPLE_CHOICES: elif resp.status_code == requests.codes.MULTIPLE_CHOICES:
raise exc.from_response(resp) raise exc.from_response(resp)
@ -239,7 +239,7 @@ class HTTPClient(object):
body_iter = resp.iter_content(chunk_size=CHUNKSIZE) body_iter = resp.iter_content(chunk_size=CHUNKSIZE)
self.log_http_response(resp) self.log_http_response(resp)
else: else:
content = resp.content content = resp.text
self.log_http_response(resp, content) self.log_http_response(resp, content)
if content_type and content_type.startswith('application/json'): if content_type and content_type.startswith('application/json'):
# Let's use requests json method, # Let's use requests json method,

View File

@ -221,7 +221,7 @@ class TestClient(testtools.TestCase):
def test_http_json(self): def test_http_json(self):
data = {"test": "json_request"} data = {"test": "json_request"}
fake = utils.FakeResponse({}, "OK") fake = utils.FakeResponse({}, b"OK")
def test_json(passed_data): def test_json(passed_data):
""" """

View File

@ -132,8 +132,15 @@ class FakeResponse(object):
return self.body.read() return self.body.read()
return self.body return self.body
@property
def text(self):
if isinstance(self.content, six.binary_type):
return self.content.decode('utf-8')
return self.content
def json(self, **kwargs): def json(self, **kwargs):
return self.body and json.loads(self.content) or "" return self.body and json.loads(self.text) or ""
def iter_content(self, chunk_size=1, decode_unicode=False): def iter_content(self, chunk_size=1, decode_unicode=False):
while True: while True: