Merge "Pass json object when invoking exception handler."

This commit is contained in:
Jenkins
2013-04-18 21:23:53 +00:00
committed by Gerrit Code Review
2 changed files with 36 additions and 11 deletions

View File

@@ -364,19 +364,10 @@ class HTTPClient(object):
self.http_log_resp(resp)
if resp.status_code >= 400:
_logger.debug(
"Request returned failure status: %s",
resp.status_code)
raise exceptions.from_response(resp, resp.text)
elif resp.status_code in (301, 302, 305):
# Redirected. Reissue the request to the new location.
return self.request(resp.headers['location'], method, **kwargs)
if resp.text:
try:
body = json.loads(resp.text)
except ValueError:
except (ValueError, TypeError):
body = None
_logger.debug("Could not decode JSON from body: %s"
% resp.text)
@@ -384,6 +375,15 @@ class HTTPClient(object):
_logger.debug("No body was returned.")
body = None
if resp.status_code >= 400:
_logger.debug(
"Request returned failure status: %s",
resp.status_code)
raise exceptions.from_response(resp, body or resp.text)
elif resp.status_code in (301, 302, 305):
# Redirected. Reissue the request to the new location.
return self.request(resp.headers['location'], method, **kwargs)
return resp, body
def _cs_request(self, url, method, **kwargs):

View File

@@ -1,3 +1,4 @@
import json
import mock
import requests
@@ -52,7 +53,7 @@ class ClientTest(utils.TestCase):
# Automatic JSON parsing
self.assertEqual(body, {"hi": "there"})
def test_get_error(self):
def test_get_error_with_plaintext_resp(self):
cl = get_authed_client()
fake_err_response = utils.TestResponse({
@@ -64,6 +65,30 @@ class ClientTest(utils.TestCase):
with mock.patch.object(requests, "request", err_MOCK_REQUEST):
self.assertRaises(exceptions.BadRequest, cl.get, '/hi')
def test_get_error_with_json_resp(self):
cl = get_authed_client()
err_response = {
"error": {
"code": 400,
"title": "Error title",
"message": "Error message string"
}
}
fake_err_response = utils.TestResponse({
"status_code": 400,
"text": json.dumps(err_response)
})
err_MOCK_REQUEST = mock.Mock(return_value=(fake_err_response))
with mock.patch.object(requests, "request", err_MOCK_REQUEST):
exc_raised = False
try:
cl.get('/hi')
except exceptions.BadRequest as exc:
exc_raised = True
self.assertEqual(exc.message, "Error message string")
self.assertTrue(exc_raised, 'Exception not raised.')
def test_post(self):
cl = get_authed_client()