Replace HTTP 'magic numbers' with constants

Replace HTTP 'magic numbers' (also known as unnamed numerical constants)
with constants provided by the http_client/httplib library.

For example, use 'http_client.OK' instead of '200'

Change-Id: I7fc70ec0c5fee128054c026a78671d07c48d5eaf
This commit is contained in:
John L. Villalovos 2015-12-06 08:11:53 -08:00
parent fe422e57ab
commit 868082af61
5 changed files with 101 additions and 87 deletions
ironicclient
common
tests/unit/common

@ -29,6 +29,7 @@ import copy
from oslo_utils import strutils from oslo_utils import strutils
import six import six
from six.moves import http_client
from six.moves.urllib import parse from six.moves.urllib import parse
from ironicclient.common.apiclient import exceptions from ironicclient.common.apiclient import exceptions
@ -148,7 +149,7 @@ class BaseManager(HookableMixin):
:param url: a partial URL, e.g., '/servers' :param url: a partial URL, e.g., '/servers'
""" """
resp = self.client.head(url) resp = self.client.head(url)
return resp.status_code == 204 return resp.status_code == http_client.NO_CONTENT
def _post(self, url, json, response_key=None, return_raw=False): def _post(self, url, json, response_key=None, return_raw=False):
"""Create an object. """Create an object.

@ -25,6 +25,7 @@ import inspect
import sys import sys
import six import six
from six.moves import http_client
from ironicclient.common.i18n import _ from ironicclient.common.i18n import _
@ -153,7 +154,7 @@ class MultipleChoices(HTTPRedirection):
Indicates multiple options for the resource that the client may follow. Indicates multiple options for the resource that the client may follow.
""" """
http_status = 300 http_status = http_client.MULTIPLE_CHOICES
message = _("Multiple Choices") message = _("Multiple Choices")
@ -162,7 +163,7 @@ class BadRequest(HTTPClientError):
The request cannot be fulfilled due to bad syntax. The request cannot be fulfilled due to bad syntax.
""" """
http_status = 400 http_status = http_client.BAD_REQUEST
message = _("Bad Request") message = _("Bad Request")
@ -172,7 +173,7 @@ class Unauthorized(HTTPClientError):
Similar to 403 Forbidden, but specifically for use when authentication Similar to 403 Forbidden, but specifically for use when authentication
is required and has failed or has not yet been provided. is required and has failed or has not yet been provided.
""" """
http_status = 401 http_status = http_client.UNAUTHORIZED
message = _("Unauthorized") message = _("Unauthorized")
@ -181,7 +182,7 @@ class PaymentRequired(HTTPClientError):
Reserved for future use. Reserved for future use.
""" """
http_status = 402 http_status = http_client.PAYMENT_REQUIRED
message = _("Payment Required") message = _("Payment Required")
@ -191,7 +192,7 @@ class Forbidden(HTTPClientError):
The request was a valid request, but the server is refusing to respond The request was a valid request, but the server is refusing to respond
to it. to it.
""" """
http_status = 403 http_status = http_client.FORBIDDEN
message = _("Forbidden") message = _("Forbidden")
@ -201,7 +202,7 @@ class NotFound(HTTPClientError):
The requested resource could not be found but may be available again The requested resource could not be found but may be available again
in the future. in the future.
""" """
http_status = 404 http_status = http_client.NOT_FOUND
message = _("Not Found") message = _("Not Found")
@ -211,7 +212,7 @@ class MethodNotAllowed(HTTPClientError):
A request was made of a resource using a request method not supported A request was made of a resource using a request method not supported
by that resource. by that resource.
""" """
http_status = 405 http_status = http_client.METHOD_NOT_ALLOWED
message = _("Method Not Allowed") message = _("Method Not Allowed")
@ -221,7 +222,7 @@ class NotAcceptable(HTTPClientError):
The requested resource is only capable of generating content not The requested resource is only capable of generating content not
acceptable according to the Accept headers sent in the request. acceptable according to the Accept headers sent in the request.
""" """
http_status = 406 http_status = http_client.NOT_ACCEPTABLE
message = _("Not Acceptable") message = _("Not Acceptable")
@ -230,7 +231,7 @@ class ProxyAuthenticationRequired(HTTPClientError):
The client must first authenticate itself with the proxy. The client must first authenticate itself with the proxy.
""" """
http_status = 407 http_status = http_client.PROXY_AUTHENTICATION_REQUIRED
message = _("Proxy Authentication Required") message = _("Proxy Authentication Required")
@ -239,7 +240,7 @@ class RequestTimeout(HTTPClientError):
The server timed out waiting for the request. The server timed out waiting for the request.
""" """
http_status = 408 http_status = http_client.REQUEST_TIMEOUT
message = _("Request Timeout") message = _("Request Timeout")
@ -249,7 +250,7 @@ class Conflict(HTTPClientError):
Indicates that the request could not be processed because of conflict Indicates that the request could not be processed because of conflict
in the request, such as an edit conflict. in the request, such as an edit conflict.
""" """
http_status = 409 http_status = http_client.CONFLICT
message = _("Conflict") message = _("Conflict")
@ -259,7 +260,7 @@ class Gone(HTTPClientError):
Indicates that the resource requested is no longer available and will Indicates that the resource requested is no longer available and will
not be available again. not be available again.
""" """
http_status = 410 http_status = http_client.GONE
message = _("Gone") message = _("Gone")
@ -269,7 +270,7 @@ class LengthRequired(HTTPClientError):
The request did not specify the length of its content, which is The request did not specify the length of its content, which is
required by the requested resource. required by the requested resource.
""" """
http_status = 411 http_status = http_client.LENGTH_REQUIRED
message = _("Length Required") message = _("Length Required")
@ -279,7 +280,7 @@ class PreconditionFailed(HTTPClientError):
The server does not meet one of the preconditions that the requester The server does not meet one of the preconditions that the requester
put on the request. put on the request.
""" """
http_status = 412 http_status = http_client.PRECONDITION_FAILED
message = _("Precondition Failed") message = _("Precondition Failed")
@ -288,7 +289,7 @@ class RequestEntityTooLarge(HTTPClientError):
The request is larger than the server is willing or able to process. The request is larger than the server is willing or able to process.
""" """
http_status = 413 http_status = http_client.REQUEST_ENTITY_TOO_LARGE
message = _("Request Entity Too Large") message = _("Request Entity Too Large")
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -305,7 +306,7 @@ class RequestUriTooLong(HTTPClientError):
The URI provided was too long for the server to process. The URI provided was too long for the server to process.
""" """
http_status = 414 http_status = http_client.REQUEST_URI_TOO_LONG
message = _("Request-URI Too Long") message = _("Request-URI Too Long")
@ -315,7 +316,7 @@ class UnsupportedMediaType(HTTPClientError):
The request entity has a media type which the server or resource does The request entity has a media type which the server or resource does
not support. not support.
""" """
http_status = 415 http_status = http_client.UNSUPPORTED_MEDIA_TYPE
message = _("Unsupported Media Type") message = _("Unsupported Media Type")
@ -325,7 +326,7 @@ class RequestedRangeNotSatisfiable(HTTPClientError):
The client has asked for a portion of the file, but the server cannot The client has asked for a portion of the file, but the server cannot
supply that portion. supply that portion.
""" """
http_status = 416 http_status = http_client.REQUESTED_RANGE_NOT_SATISFIABLE
message = _("Requested Range Not Satisfiable") message = _("Requested Range Not Satisfiable")
@ -334,7 +335,7 @@ class ExpectationFailed(HTTPClientError):
The server cannot meet the requirements of the Expect request-header field. The server cannot meet the requirements of the Expect request-header field.
""" """
http_status = 417 http_status = http_client.EXPECTATION_FAILED
message = _("Expectation Failed") message = _("Expectation Failed")
@ -344,7 +345,7 @@ class UnprocessableEntity(HTTPClientError):
The request was well-formed but was unable to be followed due to semantic The request was well-formed but was unable to be followed due to semantic
errors. errors.
""" """
http_status = 422 http_status = http_client.UNPROCESSABLE_ENTITY
message = _("Unprocessable Entity") message = _("Unprocessable Entity")
@ -353,7 +354,7 @@ class InternalServerError(HttpServerError):
A generic error message, given when no more specific message is suitable. A generic error message, given when no more specific message is suitable.
""" """
http_status = 500 http_status = http_client.INTERNAL_SERVER_ERROR
message = _("Internal Server Error") message = _("Internal Server Error")
@ -364,7 +365,7 @@ class HttpNotImplemented(HttpServerError):
The server either does not recognize the request method, or it lacks The server either does not recognize the request method, or it lacks
the ability to fulfill the request. the ability to fulfill the request.
""" """
http_status = 501 http_status = http_client.NOT_IMPLEMENTED
message = _("Not Implemented") message = _("Not Implemented")
@ -374,7 +375,7 @@ class BadGateway(HttpServerError):
The server was acting as a gateway or proxy and received an invalid The server was acting as a gateway or proxy and received an invalid
response from the upstream server. response from the upstream server.
""" """
http_status = 502 http_status = http_client.BAD_GATEWAY
message = _("Bad Gateway") message = _("Bad Gateway")
@ -383,7 +384,7 @@ class ServiceUnavailable(HttpServerError):
The server is currently unavailable. The server is currently unavailable.
""" """
http_status = 503 http_status = http_client.SERVICE_UNAVAILABLE
message = _("Service Unavailable") message = _("Service Unavailable")
@ -393,7 +394,7 @@ class GatewayTimeout(HttpServerError):
The server was acting as a gateway or proxy and did not receive a timely The server was acting as a gateway or proxy and did not receive a timely
response from the upstream server. response from the upstream server.
""" """
http_status = 504 http_status = http_client.GATEWAY_TIMEOUT
message = _("Gateway Timeout") message = _("Gateway Timeout")
@ -402,7 +403,7 @@ class HttpVersionNotSupported(HttpServerError):
The server does not support the HTTP protocol version used in the request. The server does not support the HTTP protocol version used in the request.
""" """
http_status = 505 http_status = http_client.HTTP_VERSION_NOT_SUPPORTED
message = _("HTTP Version Not Supported") message = _("HTTP Version Not Supported")
@ -456,9 +457,12 @@ def from_response(response, method, url):
try: try:
cls = _code_map[response.status_code] cls = _code_map[response.status_code]
except KeyError: except KeyError:
if 500 <= response.status_code < 600: # 5XX status codes are server errors
if response.status_code >= http_client.INTERNAL_SERVER_ERROR:
cls = HttpServerError cls = HttpServerError
elif 400 <= response.status_code < 500: # 4XX status codes are client request errors
elif (http_client.BAD_REQUEST <= response.status_code <
http_client.INTERNAL_SERVER_ERROR):
cls = HTTPClientError cls = HTTPClientError
else: else:
cls = HttpError cls = HttpError

@ -27,6 +27,7 @@ import time
from keystoneclient import adapter from keystoneclient import adapter
from oslo_utils import strutils from oslo_utils import strutils
import six import six
from six.moves import http_client
import six.moves.urllib.parse as urlparse import six.moves.urllib.parse as urlparse
from ironicclient.common import filecache from ironicclient.common import filecache
@ -323,7 +324,7 @@ class HTTPClient(VersionNegotiationMixin):
# to servers that did not support microversions. Details here: # to servers that did not support microversions. Details here:
# http://specs.openstack.org/openstack/ironic-specs/specs/kilo/api-microversions.html#use-case-3b-new-client-communicating-with-a-old-ironic-user-specified # noqa # http://specs.openstack.org/openstack/ironic-specs/specs/kilo/api-microversions.html#use-case-3b-new-client-communicating-with-a-old-ironic-user-specified # noqa
if resp.status == 406: if resp.status == http_client.NOT_ACCEPTABLE:
negotiated_ver = self.negotiate_version(conn, resp) negotiated_ver = self.negotiate_version(conn, resp)
kwargs['headers']['X-OpenStack-Ironic-API-Version'] = ( kwargs['headers']['X-OpenStack-Ironic-API-Version'] = (
negotiated_ver) negotiated_ver)
@ -350,15 +351,16 @@ class HTTPClient(VersionNegotiationMixin):
else: else:
self.log_http_response(resp) self.log_http_response(resp)
if 400 <= resp.status < 600: if resp.status >= http_client.BAD_REQUEST:
error_json = _extract_error_json(body_str) error_json = _extract_error_json(body_str)
raise exc.from_response( raise exc.from_response(
resp, error_json.get('faultstring'), resp, error_json.get('faultstring'),
error_json.get('debuginfo'), method, url) error_json.get('debuginfo'), method, url)
elif resp.status in (301, 302, 305): elif resp.status in (http_client.MOVED_PERMANENTLY, http_client.FOUND,
http_client.USE_PROXY):
# Redirected. Reissue the request to the new location. # Redirected. Reissue the request to the new location.
return self._http_request(resp['location'], method, **kwargs) return self._http_request(resp['location'], method, **kwargs)
elif resp.status == 300: elif resp.status == http_client.MULTIPLE_CHOICES:
raise exc.from_response(resp, method=method, url=url) raise exc.from_response(resp, method=method, url=url)
return resp, body_iter return resp, body_iter
@ -374,7 +376,8 @@ class HTTPClient(VersionNegotiationMixin):
resp, body_iter = self._http_request(url, method, **kwargs) resp, body_iter = self._http_request(url, method, **kwargs)
content_type = resp.getheader('content-type', None) content_type = resp.getheader('content-type', None)
if resp.status == 204 or resp.status == 205 or content_type is None: if (resp.status in (http_client.NO_CONTENT, http_client.RESET_CONTENT)
or content_type is None):
return resp, list() return resp, list()
if 'application/json' in content_type: if 'application/json' in content_type:
@ -499,20 +502,21 @@ class SessionClient(VersionNegotiationMixin, adapter.LegacyJsonAdapter):
resp = self.session.request(url, method, resp = self.session.request(url, method,
raise_exc=False, **kwargs) raise_exc=False, **kwargs)
if resp.status_code == 406: if resp.status_code == http_client.NOT_ACCEPTABLE:
negotiated_ver = self.negotiate_version(self.session, resp) negotiated_ver = self.negotiate_version(self.session, resp)
kwargs['headers']['X-OpenStack-Ironic-API-Version'] = ( kwargs['headers']['X-OpenStack-Ironic-API-Version'] = (
negotiated_ver) negotiated_ver)
return self._http_request(url, method, **kwargs) return self._http_request(url, method, **kwargs)
if 400 <= resp.status_code < 600: if resp.status_code >= http_client.BAD_REQUEST:
error_json = _extract_error_json(resp.content) error_json = _extract_error_json(resp.content)
raise exc.from_response(resp, error_json.get('faultstring'), raise exc.from_response(resp, error_json.get('faultstring'),
error_json.get('debuginfo'), method, url) error_json.get('debuginfo'), method, url)
elif resp.status_code in (301, 302, 305): elif resp.status_code in (http_client.MOVED_PERMANENTLY,
http_client.FOUND, http_client.USE_PROXY):
# Redirected. Reissue the request to the new location. # Redirected. Reissue the request to the new location.
location = resp.headers.get('location') location = resp.headers.get('location')
resp = self._http_request(location, method, **kwargs) resp = self._http_request(location, method, **kwargs)
elif resp.status_code == 300: elif resp.status_code == http_client.MULTIPLE_CHOICES:
raise exc.from_response(resp, method=method, url=url) raise exc.from_response(resp, method=method, url=url)
return resp return resp
@ -528,7 +532,8 @@ class SessionClient(VersionNegotiationMixin, adapter.LegacyJsonAdapter):
body = resp.content body = resp.content
content_type = resp.headers.get('content-type', None) content_type = resp.headers.get('content-type', None)
status = resp.status_code status = resp.status_code
if status == 204 or status == 205 or content_type is None: if (status in (http_client.NO_CONTENT, http_client.RESET_CONTENT) or
content_type is None):
return resp, list() return resp, list()
if 'application/json' in content_type: if 'application/json' in content_type:
try: try:

@ -15,6 +15,7 @@
from oslotest import base as test_base from oslotest import base as test_base
import six import six
from six.moves import http_client
from ironicclient.common.apiclient import exceptions from ironicclient.common.apiclient import exceptions
@ -54,7 +55,7 @@ class ExceptionsArgsTest(test_base.BaseTestCase):
def test_from_response_known(self): def test_from_response_known(self):
method = "GET" method = "GET"
url = "/fake" url = "/fake"
status_code = 400 status_code = http_client.BAD_REQUEST
json_data = {"error": {"message": "fake message", json_data = {"error": {"message": "fake message",
"details": "fake details"}} "details": "fake details"}}
self.assert_exception( self.assert_exception(
@ -75,7 +76,7 @@ class ExceptionsArgsTest(test_base.BaseTestCase):
def test_from_response_non_openstack(self): def test_from_response_non_openstack(self):
method = "POST" method = "POST"
url = "/fake-unknown" url = "/fake-unknown"
status_code = 400 status_code = http_client.BAD_REQUEST
json_data = {"alien": 123} json_data = {"alien": 123}
self.assert_exception( self.assert_exception(
exceptions.BadRequest, method, url, status_code, json_data, exceptions.BadRequest, method, url, status_code, json_data,
@ -84,7 +85,7 @@ class ExceptionsArgsTest(test_base.BaseTestCase):
def test_from_response_with_different_response_format(self): def test_from_response_with_different_response_format(self):
method = "GET" method = "GET"
url = "/fake-wsme" url = "/fake-wsme"
status_code = 400 status_code = http_client.BAD_REQUEST
json_data1 = {"error_message": {"debuginfo": None, json_data1 = {"error_message": {"debuginfo": None,
"faultcode": "Client", "faultcode": "Client",
"faultstring": "fake message"}} "faultstring": "fake message"}}
@ -95,7 +96,8 @@ class ExceptionsArgsTest(test_base.BaseTestCase):
exceptions.BadRequest, method, url, status_code, json_data1, exceptions.BadRequest, method, url, status_code, json_data1,
message, details) message, details)
json_data2 = {"badRequest": {"message": "fake message", "code": 400}} json_data2 = {"badRequest": {"message": "fake message",
"code": http_client.BAD_REQUEST}}
message = six.text_type(json_data2["badRequest"]["message"]) message = six.text_type(json_data2["badRequest"]["message"])
details = six.text_type(json_data2) details = six.text_type(json_data2)
self.assert_exception( self.assert_exception(
@ -105,7 +107,7 @@ class ExceptionsArgsTest(test_base.BaseTestCase):
def test_from_response_with_text_response_format(self): def test_from_response_with_text_response_format(self):
method = "GET" method = "GET"
url = "/fake-wsme" url = "/fake-wsme"
status_code = 400 status_code = http_client.BAD_REQUEST
text_data1 = "error_message: fake message" text_data1 = "error_message: fake message"
ex = exceptions.from_response( ex = exceptions.from_response(
@ -123,7 +125,7 @@ class ExceptionsArgsTest(test_base.BaseTestCase):
def test_from_response_with_text_response_format_with_no_body(self): def test_from_response_with_text_response_format_with_no_body(self):
method = "GET" method = "GET"
url = "/fake-wsme" url = "/fake-wsme"
status_code = 401 status_code = http_client.UNAUTHORIZED
ex = exceptions.from_response( ex = exceptions.from_response(
FakeResponse(status_code=status_code, FakeResponse(status_code=status_code,

@ -18,6 +18,7 @@ import time
import mock import mock
import six import six
from six.moves import http_client
from ironicclient.common import filecache from ironicclient.common import filecache
from ironicclient.common import http from ironicclient.common import http
@ -68,7 +69,8 @@ class VersionNegotiationMixinTest(utils.BaseTestCase):
self.test_object.endpoint = "http://localhost:1234" self.test_object.endpoint = "http://localhost:1234"
self.mock_mcu = mock.MagicMock() self.mock_mcu = mock.MagicMock()
self.test_object._make_connection_url = self.mock_mcu self.test_object._make_connection_url = self.mock_mcu
self.response = utils.FakeResponse({}, status=406) self.response = utils.FakeResponse(
{}, status=http_client.NOT_ACCEPTABLE)
self.test_object.get_server = mock.MagicMock( self.test_object.get_server = mock.MagicMock(
return_value=('localhost', '1234')) return_value=('localhost', '1234'))
@ -209,10 +211,10 @@ class HttpClientTest(utils.BaseTestCase):
def test_server_exception_empty_body(self): def test_server_exception_empty_body(self):
error_body = _get_error_body() error_body = _get_error_body()
fake_resp = utils.FakeResponse({'content-type': 'application/json'}, fake_resp = utils.FakeResponse(
six.StringIO(error_body), {'content-type': 'application/json'},
version=1, six.StringIO(error_body), version=1,
status=500) status=http_client.INTERNAL_SERVER_ERROR)
client = http.HTTPClient('http://localhost/') client = http.HTTPClient('http://localhost/')
client.get_connection = ( client.get_connection = (
lambda *a, **kw: utils.FakeConnection(fake_resp)) lambda *a, **kw: utils.FakeConnection(fake_resp))
@ -225,10 +227,10 @@ class HttpClientTest(utils.BaseTestCase):
def test_server_exception_msg_only(self): def test_server_exception_msg_only(self):
error_msg = 'test error msg' error_msg = 'test error msg'
error_body = _get_error_body(error_msg) error_body = _get_error_body(error_msg)
fake_resp = utils.FakeResponse({'content-type': 'application/json'}, fake_resp = utils.FakeResponse(
six.StringIO(error_body), {'content-type': 'application/json'},
version=1, six.StringIO(error_body), version=1,
status=500) status=http_client.INTERNAL_SERVER_ERROR)
client = http.HTTPClient('http://localhost/') client = http.HTTPClient('http://localhost/')
client.get_connection = ( client.get_connection = (
lambda *a, **kw: utils.FakeConnection(fake_resp)) lambda *a, **kw: utils.FakeConnection(fake_resp))
@ -243,10 +245,10 @@ class HttpClientTest(utils.BaseTestCase):
error_trace = ("\"Traceback (most recent call last):\\n\\n " error_trace = ("\"Traceback (most recent call last):\\n\\n "
"File \\\"/usr/local/lib/python2.7/...") "File \\\"/usr/local/lib/python2.7/...")
error_body = _get_error_body(error_msg, error_trace) error_body = _get_error_body(error_msg, error_trace)
fake_resp = utils.FakeResponse({'content-type': 'application/json'}, fake_resp = utils.FakeResponse(
six.StringIO(error_body), {'content-type': 'application/json'},
version=1, six.StringIO(error_body), version=1,
status=500) status=http_client.INTERNAL_SERVER_ERROR)
client = http.HTTPClient('http://localhost/') client = http.HTTPClient('http://localhost/')
client.get_connection = ( client.get_connection = (
lambda *a, **kw: utils.FakeConnection(fake_resp)) lambda *a, **kw: utils.FakeConnection(fake_resp))
@ -369,7 +371,7 @@ class HttpClientTest(utils.BaseTestCase):
fake_resp = utils.FakeResponse({'content-type': 'text/plain'}, fake_resp = utils.FakeResponse({'content-type': 'text/plain'},
six.StringIO(error_body), six.StringIO(error_body),
version=1, version=1,
status=401) status=http_client.UNAUTHORIZED)
client = http.HTTPClient('http://localhost/') client = http.HTTPClient('http://localhost/')
client.get_connection = ( client.get_connection = (
lambda *a, **kw: utils.FakeConnection(fake_resp)) lambda *a, **kw: utils.FakeConnection(fake_resp))
@ -387,7 +389,7 @@ class HttpClientTest(utils.BaseTestCase):
}, },
six.StringIO(error_body), six.StringIO(error_body),
version=1, version=1,
status=406) status=http_client.NOT_ACCEPTABLE)
expected_result = ('1.1', '1.6') expected_result = ('1.1', '1.6')
client = http.HTTPClient('http://localhost/') client = http.HTTPClient('http://localhost/')
result = client._parse_version_headers(fake_resp) result = client._parse_version_headers(fake_resp)
@ -407,7 +409,7 @@ class HttpClientTest(utils.BaseTestCase):
}, },
six.StringIO(error_body), six.StringIO(error_body),
version=1, version=1,
status=406) status=http_client.NOT_ACCEPTABLE)
client = http.HTTPClient('http://%s:%s/' % (host, port)) client = http.HTTPClient('http://%s:%s/' % (host, port))
mock_getcon.return_value = utils.FakeConnection(fake_resp) mock_getcon.return_value = utils.FakeConnection(fake_resp)
self.assertRaises( self.assertRaises(
@ -433,7 +435,7 @@ class HttpClientTest(utils.BaseTestCase):
}, },
six.StringIO(error_body), six.StringIO(error_body),
version=1, version=1,
status=406) status=http_client.NOT_ACCEPTABLE)
good_resp = utils.FakeResponse( good_resp = utils.FakeResponse(
{'X-OpenStack-Ironic-API-Minimum-Version': '1.1', {'X-OpenStack-Ironic-API-Minimum-Version': '1.1',
'X-OpenStack-Ironic-API-Maximum-Version': '1.6', 'X-OpenStack-Ironic-API-Maximum-Version': '1.6',
@ -441,12 +443,12 @@ class HttpClientTest(utils.BaseTestCase):
}, },
six.StringIO("We got some text"), six.StringIO("We got some text"),
version=1, version=1,
status=200) status=http_client.OK)
client = http.HTTPClient('http://localhost/') client = http.HTTPClient('http://localhost/')
mock_getcon.side_effect = iter([utils.FakeConnection(bad_resp), mock_getcon.side_effect = iter([utils.FakeConnection(bad_resp),
utils.FakeConnection(good_resp)]) utils.FakeConnection(good_resp)])
response, body_iter = client._http_request('/v1/resources', 'GET') response, body_iter = client._http_request('/v1/resources', 'GET')
self.assertEqual(200, response.status) self.assertEqual(http_client.OK, response.status)
self.assertEqual(1, mock_negotiate.call_count) self.assertEqual(1, mock_negotiate.call_count)
@mock.patch.object(http.LOG, 'debug', autospec=True) @mock.patch.object(http.LOG, 'debug', autospec=True)
@ -480,7 +482,7 @@ class SessionClientTest(utils.BaseTestCase):
fake_session = utils.FakeSession({'Content-Type': 'application/json'}, fake_session = utils.FakeSession({'Content-Type': 'application/json'},
error_body, error_body,
500) http_client.INTERNAL_SERVER_ERROR)
client = _session_client(session=fake_session) client = _session_client(session=fake_session)
@ -499,7 +501,7 @@ class SessionClientTest(utils.BaseTestCase):
fake_session = utils.FakeSession({'Content-Type': 'application/json'}, fake_session = utils.FakeSession({'Content-Type': 'application/json'},
error_body, error_body,
500) http_client.INTERNAL_SERVER_ERROR)
client = _session_client(session=fake_session) client = _session_client(session=fake_session)
@ -517,7 +519,7 @@ class SessionClientTest(utils.BaseTestCase):
'content-type': 'text/plain', 'content-type': 'text/plain',
}, },
None, None,
506) http_client.HTTP_VERSION_NOT_SUPPORTED)
expected_result = ('1.1', '1.6') expected_result = ('1.1', '1.6')
client = _session_client(session=fake_session) client = _session_client(session=fake_session)
result = client._parse_version_headers(fake_session) result = client._parse_version_headers(fake_session)
@ -534,7 +536,7 @@ class RetriesTestCase(utils.BaseTestCase):
{'content-type': 'text/plain'}, {'content-type': 'text/plain'},
six.StringIO(error_body), six.StringIO(error_body),
version=1, version=1,
status=409) status=http_client.CONFLICT)
client = http.HTTPClient('http://localhost/', max_retries=0) client = http.HTTPClient('http://localhost/', max_retries=0)
mock_getcon.return_value = utils.FakeConnection(bad_resp) mock_getcon.return_value = utils.FakeConnection(bad_resp)
self.assertRaises(exc.Conflict, client._http_request, self.assertRaises(exc.Conflict, client._http_request,
@ -548,17 +550,17 @@ class RetriesTestCase(utils.BaseTestCase):
{'content-type': 'text/plain'}, {'content-type': 'text/plain'},
six.StringIO(error_body), six.StringIO(error_body),
version=1, version=1,
status=409) status=http_client.CONFLICT)
good_resp = utils.FakeResponse( good_resp = utils.FakeResponse(
{'content-type': 'text/plain'}, {'content-type': 'text/plain'},
six.StringIO("meow"), six.StringIO("meow"),
version=1, version=1,
status=200) status=http_client.OK)
client = http.HTTPClient('http://localhost/') client = http.HTTPClient('http://localhost/')
mock_getcon.side_effect = iter((utils.FakeConnection(bad_resp), mock_getcon.side_effect = iter((utils.FakeConnection(bad_resp),
utils.FakeConnection(good_resp))) utils.FakeConnection(good_resp)))
response, body_iter = client._http_request('/v1/resources', 'GET') response, body_iter = client._http_request('/v1/resources', 'GET')
self.assertEqual(200, response.status) self.assertEqual(http_client.OK, response.status)
self.assertEqual(2, mock_getcon.call_count) self.assertEqual(2, mock_getcon.call_count)
@mock.patch.object(http.HTTPClient, 'get_connection', autospec=True) @mock.patch.object(http.HTTPClient, 'get_connection', autospec=True)
@ -568,17 +570,17 @@ class RetriesTestCase(utils.BaseTestCase):
{'content-type': 'text/plain'}, {'content-type': 'text/plain'},
six.StringIO(error_body), six.StringIO(error_body),
version=1, version=1,
status=503) status=http_client.SERVICE_UNAVAILABLE)
good_resp = utils.FakeResponse( good_resp = utils.FakeResponse(
{'content-type': 'text/plain'}, {'content-type': 'text/plain'},
six.StringIO("meow"), six.StringIO("meow"),
version=1, version=1,
status=200) status=http_client.OK)
client = http.HTTPClient('http://localhost/') client = http.HTTPClient('http://localhost/')
mock_getcon.side_effect = iter((utils.FakeConnection(bad_resp), mock_getcon.side_effect = iter((utils.FakeConnection(bad_resp),
utils.FakeConnection(good_resp))) utils.FakeConnection(good_resp)))
response, body_iter = client._http_request('/v1/resources', 'GET') response, body_iter = client._http_request('/v1/resources', 'GET')
self.assertEqual(200, response.status) self.assertEqual(http_client.OK, response.status)
self.assertEqual(2, mock_getcon.call_count) self.assertEqual(2, mock_getcon.call_count)
@mock.patch.object(http.HTTPClient, 'get_connection', autospec=True) @mock.patch.object(http.HTTPClient, 'get_connection', autospec=True)
@ -587,12 +589,12 @@ class RetriesTestCase(utils.BaseTestCase):
{'content-type': 'text/plain'}, {'content-type': 'text/plain'},
six.StringIO("meow"), six.StringIO("meow"),
version=1, version=1,
status=200) status=http_client.OK)
client = http.HTTPClient('http://localhost/') client = http.HTTPClient('http://localhost/')
mock_getcon.side_effect = iter((exc.ConnectionRefused(), mock_getcon.side_effect = iter((exc.ConnectionRefused(),
utils.FakeConnection(good_resp))) utils.FakeConnection(good_resp)))
response, body_iter = client._http_request('/v1/resources', 'GET') response, body_iter = client._http_request('/v1/resources', 'GET')
self.assertEqual(200, response.status) self.assertEqual(http_client.OK, response.status)
self.assertEqual(2, mock_getcon.call_count) self.assertEqual(2, mock_getcon.call_count)
@mock.patch.object(http.HTTPClient, 'get_connection', autospec=True) @mock.patch.object(http.HTTPClient, 'get_connection', autospec=True)
@ -602,7 +604,7 @@ class RetriesTestCase(utils.BaseTestCase):
{'content-type': 'text/plain'}, {'content-type': 'text/plain'},
six.StringIO(error_body), six.StringIO(error_body),
version=1, version=1,
status=409) status=http_client.CONFLICT)
client = http.HTTPClient('http://localhost/') client = http.HTTPClient('http://localhost/')
mock_getcon.return_value = utils.FakeConnection(bad_resp) mock_getcon.return_value = utils.FakeConnection(bad_resp)
self.assertRaises(exc.Conflict, client._http_request, self.assertRaises(exc.Conflict, client._http_request,
@ -616,7 +618,7 @@ class RetriesTestCase(utils.BaseTestCase):
{'content-type': 'text/plain'}, {'content-type': 'text/plain'},
six.StringIO(error_body), six.StringIO(error_body),
version=1, version=1,
status=409) status=http_client.CONFLICT)
client = http.HTTPClient('http://localhost/', max_retries=None) client = http.HTTPClient('http://localhost/', max_retries=None)
mock_getcon.return_value = utils.FakeConnection(bad_resp) mock_getcon.return_value = utils.FakeConnection(bad_resp)
self.assertRaises(exc.Conflict, client._http_request, self.assertRaises(exc.Conflict, client._http_request,
@ -630,7 +632,7 @@ class RetriesTestCase(utils.BaseTestCase):
{'content-type': 'text/plain'}, {'content-type': 'text/plain'},
six.StringIO(error_body), six.StringIO(error_body),
version=1, version=1,
status=409) status=http_client.CONFLICT)
client = http.HTTPClient('http://localhost/', client = http.HTTPClient('http://localhost/',
max_retries=http.DEFAULT_MAX_RETRIES + 1) max_retries=http.DEFAULT_MAX_RETRIES + 1)
mock_getcon.return_value = utils.FakeConnection(bad_resp) mock_getcon.return_value = utils.FakeConnection(bad_resp)
@ -644,11 +646,11 @@ class RetriesTestCase(utils.BaseTestCase):
fake_resp = utils.FakeSessionResponse( fake_resp = utils.FakeSessionResponse(
{'Content-Type': 'application/json'}, {'Content-Type': 'application/json'},
error_body, error_body,
409) http_client.CONFLICT)
ok_resp = utils.FakeSessionResponse( ok_resp = utils.FakeSessionResponse(
{'Content-Type': 'application/json'}, {'Content-Type': 'application/json'},
b"OK", b"OK",
200) http_client.OK)
fake_session = mock.Mock(spec=utils.FakeSession) fake_session = mock.Mock(spec=utils.FakeSession)
fake_session.request.side_effect = iter((fake_resp, ok_resp)) fake_session.request.side_effect = iter((fake_resp, ok_resp))
@ -662,11 +664,11 @@ class RetriesTestCase(utils.BaseTestCase):
fake_resp = utils.FakeSessionResponse( fake_resp = utils.FakeSessionResponse(
{'Content-Type': 'application/json'}, {'Content-Type': 'application/json'},
error_body, error_body,
503) http_client.SERVICE_UNAVAILABLE)
ok_resp = utils.FakeSessionResponse( ok_resp = utils.FakeSessionResponse(
{'Content-Type': 'application/json'}, {'Content-Type': 'application/json'},
b"OK", b"OK",
200) http_client.OK)
fake_session = mock.Mock(spec=utils.FakeSession) fake_session = mock.Mock(spec=utils.FakeSession)
fake_session.request.side_effect = iter((fake_resp, ok_resp)) fake_session.request.side_effect = iter((fake_resp, ok_resp))
@ -678,7 +680,7 @@ class RetriesTestCase(utils.BaseTestCase):
ok_resp = utils.FakeSessionResponse( ok_resp = utils.FakeSessionResponse(
{'Content-Type': 'application/json'}, {'Content-Type': 'application/json'},
b"OK", b"OK",
200) http_client.OK)
fake_session = mock.Mock(spec=utils.FakeSession) fake_session = mock.Mock(spec=utils.FakeSession)
fake_session.request.side_effect = iter((exc.ConnectionRefused(), fake_session.request.side_effect = iter((exc.ConnectionRefused(),
ok_resp)) ok_resp))
@ -693,7 +695,7 @@ class RetriesTestCase(utils.BaseTestCase):
fake_resp = utils.FakeSessionResponse( fake_resp = utils.FakeSessionResponse(
{'Content-Type': 'application/json'}, {'Content-Type': 'application/json'},
error_body, error_body,
409) http_client.CONFLICT)
fake_session = mock.Mock(spec=utils.FakeSession) fake_session = mock.Mock(spec=utils.FakeSession)
fake_session.request.return_value = fake_resp fake_session.request.return_value = fake_resp
@ -710,7 +712,7 @@ class RetriesTestCase(utils.BaseTestCase):
fake_resp = utils.FakeSessionResponse( fake_resp = utils.FakeSessionResponse(
{'Content-Type': 'application/json'}, {'Content-Type': 'application/json'},
error_body, error_body,
409) http_client.CONFLICT)
fake_session = mock.Mock(spec=utils.FakeSession) fake_session = mock.Mock(spec=utils.FakeSession)
fake_session.request.return_value = fake_resp fake_session.request.return_value = fake_resp
@ -728,7 +730,7 @@ class RetriesTestCase(utils.BaseTestCase):
fake_resp = utils.FakeSessionResponse( fake_resp = utils.FakeSessionResponse(
{'Content-Type': 'application/json'}, {'Content-Type': 'application/json'},
error_body, error_body,
409) http_client.CONFLICT)
fake_session = mock.Mock(spec=utils.FakeSession) fake_session = mock.Mock(spec=utils.FakeSession)
fake_session.request.return_value = fake_resp fake_session.request.return_value = fake_resp