Skip to content

Commit 090e5ff

Browse files
committed
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 1b1917a)
1 parent 7c6cc05 commit 090e5ff

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

ceilometerclient/exc.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,16 @@ class HTTPServiceUnavailable(HTTPException):
118118

119119

120120
def from_response(response, details=None):
121-
"""Return an instance of an HTTPException based on httplib response."""
122-
cls = _code_map.get(response.status, HTTPException)
121+
"""Return an instance of an HTTPException based on http response."""
122+
if hasattr(response, "status"):
123+
# it is response from HTTPClient (httplib)
124+
code = response.status
125+
elif hasattr(response, "status_code"):
126+
# it is response from SessionClient (requests)
127+
code = response.status_code
128+
else:
129+
# it is something unexpected
130+
raise TypeError("Function 'from_response' expects only response object"
131+
" from httplib or requests libraries.")
132+
cls = _code_map.get(code, HTTPException)
123133
return cls(details)

ceilometerclient/tests/unit/test_exc.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,3 +69,19 @@ def test_str_faultstring(self):
6969
{"error_message": {"faultstring": "oops"}}))
7070
ret_str = k + " (HTTP " + str(exception.code) + ") ERROR oops"
7171
self.assertEqual(ret_str, str(exception))
72+
73+
def test_from_response(self):
74+
class HTTPLibLikeResponse(object):
75+
status = 400
76+
77+
class RequestsLikeResponse(object):
78+
status_code = 401
79+
80+
class UnexpectedResponse(object):
81+
code = 200
82+
83+
self.assertEqual(HTTPLibLikeResponse.status,
84+
exc.from_response(HTTPLibLikeResponse).code)
85+
self.assertEqual(RequestsLikeResponse.status_code,
86+
exc.from_response(RequestsLikeResponse).code)
87+
self.assertRaises(TypeError, exc.from_response, UnexpectedResponse)

0 commit comments

Comments
 (0)