Fix from_response method to process response from requests

SessionClient uses requests library. It's response class doesn't have
"status" property[1], so in case of any errors(with status code > 400),
from_response method is called and raises AttributeError.

Also, HTTPClient implementation uses requests lib by default[2](if 'http'
argument was not transmitted), so from_response method will raise
AttributeError too.

[1] - http://docs.python-requests.org/en/master/api/#requests.Response.status_code
[2] - https://github.com/openstack/python-ceilometerclient/blob/2.6.0/ceilometerclient/openstack/common/apiclient/client.py#L99-L100

Change-Id: Id8fb2f386e8101951716f30a6365c9aa15bd4b24
Closes-Bug: #1620974
(cherry picked from commit 1b1917ab9b)
This commit is contained in:
Andrey Kurilin 2016-09-07 12:39:12 +03:00
parent 7c6cc05ff0
commit 090e5ffc69
2 changed files with 28 additions and 2 deletions

View File

@ -118,6 +118,16 @@ for obj_name in dir(sys.modules[__name__]):
def from_response(response, details=None):
"""Return an instance of an HTTPException based on httplib response."""
cls = _code_map.get(response.status, HTTPException)
"""Return an instance of an HTTPException based on http response."""
if hasattr(response, "status"):
# it is response from HTTPClient (httplib)
code = response.status
elif hasattr(response, "status_code"):
# it is response from SessionClient (requests)
code = response.status_code
else:
# it is something unexpected
raise TypeError("Function 'from_response' expects only response object"
" from httplib or requests libraries.")
cls = _code_map.get(code, HTTPException)
return cls(details)

View File

@ -69,3 +69,19 @@ class HTTPExceptionsTest(utils.BaseTestCase):
{"error_message": {"faultstring": "oops"}}))
ret_str = k + " (HTTP " + str(exception.code) + ") ERROR oops"
self.assertEqual(ret_str, str(exception))
def test_from_response(self):
class HTTPLibLikeResponse(object):
status = 400
class RequestsLikeResponse(object):
status_code = 401
class UnexpectedResponse(object):
code = 200
self.assertEqual(HTTPLibLikeResponse.status,
exc.from_response(HTTPLibLikeResponse).code)
self.assertEqual(RequestsLikeResponse.status_code,
exc.from_response(RequestsLikeResponse).code)
self.assertRaises(TypeError, exc.from_response, UnexpectedResponse)