Finish switch from http.client to HTTPStatus

Follow-up on [1]:
We don't need an HTTP client for this, we only
need status codes. Just load that instead.

[1] https://review.opendev.org/762308

Change-Id: Ib24be88c9f33889d5ed705537b0d4c167cad5b3f
This commit is contained in:
Radosław Piliszek 2020-11-11 11:48:24 +01:00
parent 7d10b286ab
commit 77464a1385
15 changed files with 137 additions and 130 deletions

View File

@ -15,7 +15,7 @@
"""The Host API extension."""
from http import client as http
from http import HTTPStatus
from oslo_utils import encodeutils
from oslo_utils import strutils
@ -42,8 +42,8 @@ class HostsController(wsgi.Controller):
def __init__(self):
self.api = host_api.HostAPI()
@extensions.expected_errors((http.BAD_REQUEST, http.FORBIDDEN,
http.NOT_FOUND))
@extensions.expected_errors((HTTPStatus.BAD_REQUEST, HTTPStatus.FORBIDDEN,
HTTPStatus.NOT_FOUND))
def index(self, req, segment_id):
"""Returns a list a hosts."""
context = req.environ['masakari.context']
@ -99,9 +99,9 @@ class HostsController(wsgi.Controller):
builder = views_hosts.get_view_builder(req)
return builder.build_hosts(hosts)
@wsgi.response(http.CREATED)
@extensions.expected_errors((http.BAD_REQUEST, http.FORBIDDEN,
http.NOT_FOUND, http.CONFLICT))
@wsgi.response(HTTPStatus.CREATED)
@extensions.expected_errors((HTTPStatus.BAD_REQUEST, HTTPStatus.FORBIDDEN,
HTTPStatus.NOT_FOUND, HTTPStatus.CONFLICT))
@validation.schema(schema.create)
def create(self, req, segment_id, body):
"""Creates a host."""
@ -120,7 +120,7 @@ class HostsController(wsgi.Controller):
builder = views_hosts.get_view_builder(req)
return {'host': builder.build_host(host)}
@extensions.expected_errors((http.FORBIDDEN, http.NOT_FOUND))
@extensions.expected_errors((HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND))
def show(self, req, segment_id, id):
"""Shows the details of a host."""
context = req.environ['masakari.context']
@ -135,8 +135,8 @@ class HostsController(wsgi.Controller):
builder = views_hosts.get_view_builder(req)
return {'host': builder.build_host(host)}
@extensions.expected_errors((http.BAD_REQUEST, http.FORBIDDEN,
http.NOT_FOUND, http.CONFLICT))
@extensions.expected_errors((HTTPStatus.BAD_REQUEST, HTTPStatus.FORBIDDEN,
HTTPStatus.NOT_FOUND, HTTPStatus.CONFLICT))
@validation.schema(schema.update)
def update(self, req, segment_id, id, body):
"""Updates the existing host."""
@ -157,9 +157,9 @@ class HostsController(wsgi.Controller):
builder = views_hosts.get_view_builder(req)
return {'host': builder.build_host(host)}
@wsgi.response(http.NO_CONTENT)
@extensions.expected_errors((http.FORBIDDEN, http.NOT_FOUND,
http.CONFLICT))
@wsgi.response(HTTPStatus.NO_CONTENT)
@extensions.expected_errors((HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND,
HTTPStatus.CONFLICT))
def delete(self, req, segment_id, id):
"""Removes a host by id."""
context = req.environ['masakari.context']

View File

@ -13,7 +13,7 @@
# License for the specific language governing permissions and limitations
# under the License.
from http import client as http
from http import HTTPStatus
from oslo_utils import timeutils
from webob import exc
@ -52,9 +52,9 @@ class NotificationsController(wsgi.Controller):
def _validate_comp_host_payload(self, req, body):
pass
@wsgi.response(http.ACCEPTED)
@extensions.expected_errors((http.BAD_REQUEST, http.FORBIDDEN,
http.CONFLICT))
@wsgi.response(HTTPStatus.ACCEPTED)
@extensions.expected_errors((HTTPStatus.BAD_REQUEST, HTTPStatus.FORBIDDEN,
HTTPStatus.CONFLICT))
@validation.schema(schema.create)
def create(self, req, body):
"""Creates a new notification."""
@ -84,7 +84,7 @@ class NotificationsController(wsgi.Controller):
return {'notification': notification}
@extensions.expected_errors((http.BAD_REQUEST, http.FORBIDDEN))
@extensions.expected_errors((HTTPStatus.BAD_REQUEST, HTTPStatus.FORBIDDEN))
def index(self, req):
"""Returns a summary list of notifications."""
context = req.environ['masakari.context']
@ -118,7 +118,7 @@ class NotificationsController(wsgi.Controller):
return {'notifications': notifications}
@extensions.expected_errors((http.FORBIDDEN, http.NOT_FOUND))
@extensions.expected_errors((HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND))
def show(self, req, id):
"""Return data about the given notification id."""
context = req.environ['masakari.context']

View File

@ -13,7 +13,7 @@
# License for the specific language governing permissions and limitations
# under the License.
from http import client as http
from http import HTTPStatus
from webob import exc
@ -36,7 +36,7 @@ class SegmentsController(wsgi.Controller):
def __init__(self):
self.api = segment_api.FailoverSegmentAPI()
@extensions.expected_errors((http.BAD_REQUEST, http.FORBIDDEN))
@extensions.expected_errors((HTTPStatus.BAD_REQUEST, HTTPStatus.FORBIDDEN))
def index(self, req):
"""Returns a summary list of failover segments."""
context = req.environ['masakari.context']
@ -62,7 +62,7 @@ class SegmentsController(wsgi.Controller):
return {'segments': segments}
@extensions.expected_errors((http.FORBIDDEN, http.NOT_FOUND))
@extensions.expected_errors((HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND))
def show(self, req, id):
"""Return data about the given segment id."""
context = req.environ['masakari.context']
@ -74,8 +74,8 @@ class SegmentsController(wsgi.Controller):
raise exc.HTTPNotFound(explanation=e.format_message())
return {'segment': segment}
@wsgi.response(http.CREATED)
@extensions.expected_errors((http.FORBIDDEN, http.CONFLICT))
@wsgi.response(HTTPStatus.CREATED)
@extensions.expected_errors((HTTPStatus.FORBIDDEN, HTTPStatus.CONFLICT))
@validation.schema(schema.create, '1.0', '1.1')
@validation.schema(schema.create_v12, '1.2')
def create(self, req, body):
@ -90,8 +90,8 @@ class SegmentsController(wsgi.Controller):
raise exc.HTTPConflict(explanation=e.format_message())
return {'segment': segment}
@extensions.expected_errors((http.FORBIDDEN, http.NOT_FOUND,
http.CONFLICT))
@extensions.expected_errors((HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND,
HTTPStatus.CONFLICT))
@validation.schema(schema.update, '1.0', '1.1')
@validation.schema(schema.update_v12, '1.2')
def update(self, req, id, body):
@ -109,9 +109,9 @@ class SegmentsController(wsgi.Controller):
return {'segment': segment}
@wsgi.response(http.NO_CONTENT)
@extensions.expected_errors((http.FORBIDDEN, http.NOT_FOUND,
http.CONFLICT))
@wsgi.response(HTTPStatus.NO_CONTENT)
@extensions.expected_errors((HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND,
HTTPStatus.CONFLICT))
def delete(self, req, id):
"""Removes a segment by uuid."""
context = req.environ['masakari.context']

View File

@ -14,7 +14,7 @@
# under the License.
import functools
from http import client as http
from http import HTTPStatus
import inspect
import microversion_parse
@ -267,7 +267,7 @@ class ResponseObject(object):
"""Builds a response object."""
self.obj = obj
self._default_code = http.OK
self._default_code = HTTPStatus.OK
self._code = code
self._headers = headers or {}
self.serializer = JSONDictSerializer()
@ -1003,17 +1003,17 @@ class Fault(webob.exc.HTTPException):
"""Wrap webob.exc.HTTPException to provide API friendly response."""
_fault_names = {
http.BAD_REQUEST: "badRequest",
http.UNAUTHORIZED: "unauthorized",
http.FORBIDDEN: "forbidden",
http.NOT_FOUND: "itemNotFound",
http.METHOD_NOT_ALLOWED: "badMethod",
http.CONFLICT: "conflictingRequest",
http.REQUEST_ENTITY_TOO_LARGE: "overLimit",
http.UNSUPPORTED_MEDIA_TYPE: "badMediaType",
http.NOT_IMPLEMENTED: "notImplemented",
http.SERVICE_UNAVAILABLE: "serviceUnavailable",
http.TOO_MANY_REQUESTS: "overLimit"
HTTPStatus.BAD_REQUEST: "badRequest",
HTTPStatus.UNAUTHORIZED: "unauthorized",
HTTPStatus.FORBIDDEN: "forbidden",
HTTPStatus.NOT_FOUND: "itemNotFound",
HTTPStatus.METHOD_NOT_ALLOWED: "badMethod",
HTTPStatus.CONFLICT: "conflictingRequest",
HTTPStatus.REQUEST_ENTITY_TOO_LARGE: "overLimit",
HTTPStatus.UNSUPPORTED_MEDIA_TYPE: "badMediaType",
HTTPStatus.NOT_IMPLEMENTED: "notImplemented",
HTTPStatus.SERVICE_UNAVAILABLE: "serviceUnavailable",
HTTPStatus.TOO_MANY_REQUESTS: "overLimit"
}
def __init__(self, exception):
@ -1040,7 +1040,7 @@ class Fault(webob.exc.HTTPException):
fault_name: {
'code': code,
'message': explanation}}
if code == http.REQUEST_ENTITY_TOO_LARGE or code == 429:
if code == HTTPStatus.REQUEST_ENTITY_TOO_LARGE or code == 429:
retry = self.wrapped_exc.headers.get('Retry-After', None)
if retry:
fault_data[fault_name]['retryAfter'] = retry

View File

@ -22,7 +22,7 @@ SHOULD include dedicated exception logging.
"""
import functools
from http import client as http
from http import HTTPStatus
import inspect
import sys
@ -116,7 +116,7 @@ class MasakariException(Exception):
"""
msg_fmt = _("An unknown exception occurred.")
code = http.INTERNAL_SERVER_ERROR
code = HTTPStatus.INTERNAL_SERVER_ERROR
headers = {}
safe = False
@ -171,12 +171,12 @@ class APITimeout(APIException):
class Conflict(MasakariException):
msg_fmt = _("Conflict")
code = http.CONFLICT
code = HTTPStatus.CONFLICT
class Invalid(MasakariException):
msg_fmt = _("Bad Request - Invalid Parameters")
code = http.BAD_REQUEST
code = HTTPStatus.BAD_REQUEST
class InvalidName(Invalid):
@ -201,7 +201,7 @@ class MalformedRequestBody(MasakariException):
# appropriate to be returned
class NotFound(MasakariException):
msg_fmt = _("Resource could not be found.")
code = http.NOT_FOUND
code = HTTPStatus.NOT_FOUND
class ConfigNotFound(NotFound):
@ -210,7 +210,7 @@ class ConfigNotFound(NotFound):
class Forbidden(MasakariException):
msg_fmt = _("Forbidden")
code = http.FORBIDDEN
code = HTTPStatus.FORBIDDEN
class AdminRequired(Forbidden):
@ -291,7 +291,7 @@ class HostExists(MasakariException):
class Unauthorized(MasakariException):
msg_fmt = _("Not authorized.")
code = http.UNAUTHORIZED
code = HTTPStatus.UNAUTHORIZED
class ObjectActionError(MasakariException):
@ -304,12 +304,12 @@ class OrphanedObjectError(MasakariException):
class DuplicateNotification(Invalid):
msg_fmt = _('Duplicate notification received for type: %(type)s')
code = http.CONFLICT
code = HTTPStatus.CONFLICT
class HostOnMaintenanceError(Invalid):
msg_fmt = _('Host %(host_name)s is already under maintenance.')
code = http.CONFLICT
code = HTTPStatus.CONFLICT
class HostRecoveryFailureException(MasakariException):

View File

@ -15,7 +15,7 @@
"""Tests for the hosts api."""
from http import client as http
from http import HTTPStatus
from unittest import mock
import ddt
@ -254,7 +254,7 @@ class HostTestCase(test.TestCase):
fake_req.method = 'POST'
fake_req.body = jsonutils.dump_as_bytes(body)
resp = fake_req.get_response(self.app)
self.assertEqual(http.CREATED, resp.status_code)
self.assertEqual(HTTPStatus.CREATED, resp.status_code)
@mock.patch.object(ha_api.HostAPI, 'create_host')
def test_create_with_duplicate_host_name(self, mock_create):
@ -465,7 +465,7 @@ class HostTestCase(test.TestCase):
fake_req.headers['Content-Type'] = 'application/json'
fake_req.method = 'DELETE'
resp = fake_req.get_response(self.app)
self.assertEqual(http.NO_CONTENT, resp.status_code)
self.assertEqual(HTTPStatus.NO_CONTENT, resp.status_code)
@mock.patch.object(ha_api.HostAPI, 'delete_host')
def test_delete_host_not_found(self, mock_delete):

View File

@ -16,7 +16,7 @@
"""Tests for the notifications api."""
import copy
from http import client as http
from http import HTTPStatus
from unittest import mock
import ddt
@ -229,7 +229,7 @@ class NotificationTestCase(test.TestCase):
fake_req.method = 'POST'
fake_req.body = jsonutils.dump_as_bytes(body)
resp = fake_req.get_response(self.app)
self.assertEqual(http.ACCEPTED, resp.status_code)
self.assertEqual(HTTPStatus.ACCEPTED, resp.status_code)
@mock.patch.object(ha_api.NotificationAPI, 'create_notification')
def test_create_host_not_found(self, mock_create):
@ -424,7 +424,7 @@ class NotificationTestCase(test.TestCase):
fake_req.headers['Content-Type'] = 'application/json'
fake_req.method = method
resp = fake_req.get_response(self.app)
self.assertEqual(http.METHOD_NOT_ALLOWED, resp.status_code)
self.assertEqual(HTTPStatus.METHOD_NOT_ALLOWED, resp.status_code)
class NotificationCasePolicyNotAuthorized(test.NoDBTestCase):

View File

@ -15,7 +15,7 @@
"""Tests for the failover segment api."""
from http import client as http
from http import HTTPStatus
from unittest import mock
import ddt
@ -214,7 +214,7 @@ class FailoverSegmentTestCase(test.TestCase):
fake_req.method = 'POST'
fake_req.body = jsonutils.dump_as_bytes(body)
resp = fake_req.get_response(self.app)
self.assertEqual(http.CREATED, resp.status_code)
self.assertEqual(HTTPStatus.CREATED, resp.status_code)
@ddt.data(
# no segment
@ -407,7 +407,7 @@ class FailoverSegmentTestCase(test.TestCase):
fake_req.headers['Content-Type'] = 'application/json'
fake_req.method = 'DELETE'
resp = fake_req.get_response(self.app)
self.assertEqual(http.NO_CONTENT, resp.status_code)
self.assertEqual(HTTPStatus.NO_CONTENT, resp.status_code)
class FailoverSegmentTestCasePolicyNotAuthorized(test.NoDBTestCase):

View File

@ -14,7 +14,7 @@
# under the License.
import copy
from http import client as http
from http import HTTPStatus
from unittest import mock
from oslo_serialization import jsonutils
@ -262,4 +262,4 @@ class VersionsTest(test.NoDBTestCase):
req = webob.Request.blank('/v1/versions/1234/foo')
req.accept = "application/json"
res = req.get_response(self.wsgi_app)
self.assertEqual(http.NOT_FOUND, res.status_int)
self.assertEqual(HTTPStatus.NOT_FOUND, res.status_int)

View File

@ -13,7 +13,7 @@
# License for the specific language governing permissions and limitations
# under the License.
from http import client as http
from http import HTTPStatus
from unittest import mock
from oslo_config import cfg
@ -56,36 +56,37 @@ class ExtensionLoadingTestCase(test.NoDBTestCase):
self.assertIn('extensions', name_list)
def test_extensions_expected_error(self):
@extensions.expected_errors(http.NOT_FOUND)
@extensions.expected_errors(HTTPStatus.NOT_FOUND)
def fake_func():
raise webob.exc.HTTPNotFound()
self.assertRaises(webob.exc.HTTPNotFound, fake_func)
def test_extensions_expected_error_from_list(self):
@extensions.expected_errors((http.NOT_FOUND, http.FORBIDDEN))
@extensions.expected_errors((HTTPStatus.NOT_FOUND,
HTTPStatus.FORBIDDEN))
def fake_func():
raise webob.exc.HTTPNotFound()
self.assertRaises(webob.exc.HTTPNotFound, fake_func)
def test_extensions_unexpected_error(self):
@extensions.expected_errors(http.NOT_FOUND)
@extensions.expected_errors(HTTPStatus.NOT_FOUND)
def fake_func():
raise webob.exc.HTTPConflict()
self.assertRaises(webob.exc.HTTPInternalServerError, fake_func)
def test_extensions_unexpected_error_from_list(self):
@extensions.expected_errors((http.NOT_FOUND,
http.REQUEST_ENTITY_TOO_LARGE))
@extensions.expected_errors((HTTPStatus.NOT_FOUND,
HTTPStatus.REQUEST_ENTITY_TOO_LARGE))
def fake_func():
raise webob.exc.HTTPConflict()
self.assertRaises(webob.exc.HTTPInternalServerError, fake_func)
def test_extensions_unexpected_policy_not_authorized_error(self):
@extensions.expected_errors(http.NOT_FOUND)
@extensions.expected_errors(HTTPStatus.NOT_FOUND)
def fake_func():
raise exception.PolicyNotAuthorized(action="foo")

View File

@ -13,7 +13,7 @@
# License for the specific language governing permissions and limitations
# under the License.
from http import client as http
from http import HTTPStatus
import inspect
from unittest import mock
@ -238,19 +238,19 @@ class ResourceTest(MicroversionedTest):
req = webob.Request.blank('/tests')
response = req.get_response(app)
self.assertEqual(b'success', response.body)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
req.body = b'{"body": {"key": "value"}}'
response = req.get_response(app)
self.assertEqual(b'success', response.body)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
req.content_type = 'application/json'
response = req.get_response(app)
self.assertEqual(b'success', response.body)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
def test_resource_call_with_method_post(self):
class Controller(object):
@extensions.expected_errors(http.BAD_REQUEST)
@extensions.expected_errors(HTTPStatus.BAD_REQUEST)
def create(self, req, body):
if expected_body != body:
msg = "The request body invalid"
@ -266,20 +266,21 @@ class ResourceTest(MicroversionedTest):
}
}
response = req.get_response(app)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
self.assertEqual(b'success', response.body)
# verify without body
expected_body = None
req.body = None
response = req.get_response(app)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
self.assertEqual(b'success', response.body)
# the body is validated in the controller
expected_body = {'body': None}
response = req.get_response(app)
expected_unsupported_type_body = {'badRequest':
{'message': 'The request body invalid', 'code': http.BAD_REQUEST}}
self.assertEqual(response.status_int, http.BAD_REQUEST)
{'message': 'The request body invalid',
'code': HTTPStatus.BAD_REQUEST}}
self.assertEqual(response.status_int, HTTPStatus.BAD_REQUEST)
self.assertEqual(expected_unsupported_type_body,
jsonutils.loads(response.body))
@ -301,11 +302,11 @@ class ResourceTest(MicroversionedTest):
}
response = req.get_response(app)
self.assertEqual(b'success', response.body)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
req.body = None
expected_body = None
response = req.get_response(app)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
# verify no content_type is contained in the request
req = webob.Request.blank('/tests/test_id', method="PUT",
content_type='application/xml')
@ -314,8 +315,9 @@ class ResourceTest(MicroversionedTest):
response = req.get_response(app)
expected_unsupported_type_body = {'badMediaType':
{'message': 'Unsupported Content-Type',
'code': http.UNSUPPORTED_MEDIA_TYPE}}
self.assertEqual(response.status_int, http.UNSUPPORTED_MEDIA_TYPE)
'code': HTTPStatus.UNSUPPORTED_MEDIA_TYPE}}
self.assertEqual(response.status_int,
HTTPStatus.UNSUPPORTED_MEDIA_TYPE)
self.assertEqual(expected_unsupported_type_body,
jsonutils.loads(response.body))
@ -328,12 +330,12 @@ class ResourceTest(MicroversionedTest):
app = fakes.TestRouter(Controller())
req = webob.Request.blank('/tests/test_id', method="DELETE")
response = req.get_response(app)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
self.assertEqual(b'success', response.body)
# ignore the body
req.body = b'{"body": {"key": "value"}}'
response = req.get_response(app)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
self.assertEqual(b'success', response.body)
def test_resource_not_authorized(self):
@ -344,7 +346,7 @@ class ResourceTest(MicroversionedTest):
req = webob.Request.blank('/tests')
app = fakes.TestRouter(Controller())
response = req.get_response(app)
self.assertEqual(response.status_int, http.FORBIDDEN)
self.assertEqual(response.status_int, HTTPStatus.FORBIDDEN)
def test_dispatch(self):
class Controller(object):
@ -510,7 +512,7 @@ class ResourceTest(MicroversionedTest):
response = req.get_response(app)
self.assertIn('masakari.context', req.environ)
self.assertEqual(b'{"foo": "bar"}', response.body)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
def test_str_response_body(self):
@ -524,7 +526,7 @@ class ResourceTest(MicroversionedTest):
expected_header = self.get_req_id_header_name(req)
self.assertFalse(hasattr(response.headers, expected_header))
self.assertEqual(b'foo', response.body)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
def test_get_no_response_body(self):
@ -537,7 +539,7 @@ class ResourceTest(MicroversionedTest):
response = req.get_response(app)
self.assertIn('masakari.context', req.environ)
self.assertEqual(b'', response.body)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
def test_deserialize_default(self):
class Controller(object):
@ -869,10 +871,10 @@ class ResourceTest(MicroversionedTest):
foo() # generate a TypeError
self.fail("Should have raised a Fault (HTTP 400)")
except wsgi.Fault as fault:
self.assertEqual(http.BAD_REQUEST, fault.status_int)
self.assertEqual(HTTPStatus.BAD_REQUEST, fault.status_int)
def test_resource_headers_py2_are_utf8(self):
resp = webob.Response(status_int=http.ACCEPTED)
resp = webob.Response(status_int=HTTPStatus.ACCEPTED)
resp.headers['x-header1'] = 1
resp.headers['x-header2'] = 'header2'
resp.headers['x-header3'] = 'header3'
@ -902,7 +904,7 @@ class ResourceTest(MicroversionedTest):
app = fakes.TestRouter(Controller())
response = req.get_response(app)
self.assertEqual(response.body, expected_body)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
def test_resource_invalid_utf8(self):
class Controller(object):
@ -920,21 +922,21 @@ class ResourceTest(MicroversionedTest):
class ResponseObjectTest(test.NoDBTestCase):
def test_default_code(self):
robj = wsgi.ResponseObject({})
self.assertEqual(robj.code, http.OK)
self.assertEqual(robj.code, HTTPStatus.OK)
def test_modified_code(self):
robj = wsgi.ResponseObject({})
robj._default_code = http.ACCEPTED
self.assertEqual(robj.code, http.ACCEPTED)
robj._default_code = HTTPStatus.ACCEPTED
self.assertEqual(robj.code, HTTPStatus.ACCEPTED)
def test_override_default_code(self):
robj = wsgi.ResponseObject({}, code=http.NOT_FOUND)
self.assertEqual(robj.code, http.NOT_FOUND)
robj = wsgi.ResponseObject({}, code=HTTPStatus.NOT_FOUND)
self.assertEqual(robj.code, HTTPStatus.NOT_FOUND)
def test_override_modified_code(self):
robj = wsgi.ResponseObject({}, code=http.NOT_FOUND)
robj._default_code = http.ACCEPTED
self.assertEqual(robj.code, http.NOT_FOUND)
robj = wsgi.ResponseObject({}, code=HTTPStatus.NOT_FOUND)
robj._default_code = HTTPStatus.ACCEPTED
self.assertEqual(robj.code, HTTPStatus.NOT_FOUND)
def test_set_header(self):
robj = wsgi.ResponseObject({})

View File

@ -11,7 +11,7 @@
# License for the specific language governing permissions and limitations
# under the License.
from http import client as http
from http import HTTPStatus
from oslo_middleware import request_id
from oslo_serialization import jsonutils
@ -44,32 +44,32 @@ class TestMasakariKeystoneContextMiddleware(test.NoDBTestCase):
def test_no_user_or_user_id(self):
response = self.request.get_response(self.middleware)
self.assertEqual(response.status_int, http.UNAUTHORIZED)
self.assertEqual(response.status_int, HTTPStatus.UNAUTHORIZED)
def test_user_id_only(self):
self.request.headers['X_USER_ID'] = 'testuserid'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
self.assertEqual(self.context.user_id, 'testuserid')
def test_user_only(self):
self.request.headers['X_USER'] = 'testuser'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
self.assertEqual(self.context.user_id, 'testuser')
def test_user_id_trumps_user(self):
self.request.headers['X_USER_ID'] = 'testuserid'
self.request.headers['X_USER'] = 'testuser'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
self.assertEqual(self.context.user_id, 'testuserid')
def test_invalid_service_catalog(self):
self.request.headers['X_USER'] = 'testuser'
self.request.headers['X_SERVICE_CATALOG'] = "bad json"
response = self.request.get_response(self.middleware)
self.assertEqual(response.status_int, http.INTERNAL_SERVER_ERROR)
self.assertEqual(response.status_int, HTTPStatus.INTERNAL_SERVER_ERROR)
def test_request_id_extracted_from_env(self):
req_id = 'dummy-request-id'
@ -97,32 +97,32 @@ class TestNoAuthMiddleware(test.NoDBTestCase):
def test_no_user_or_user_id(self):
response = self.request.get_response(self.middleware)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
def test_user_id_only(self):
self.request.headers['X_USER_ID'] = 'testuserid'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
self.assertEqual(self.context.user_id, 'testuserid')
def test_user_only(self):
self.request.headers['X_USER'] = 'testuser'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
self.assertEqual(self.context.user_id, 'testuser')
def test_user_id_trumps_user(self):
self.request.headers['X_USER_ID'] = 'testuserid'
self.request.headers['X_USER'] = 'testuser'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(response.status_int, HTTPStatus.OK)
self.assertEqual(self.context.user_id, 'testuserid')
def test_invalid_service_catalog(self):
self.request.headers['X_USER'] = 'testuser'
self.request.headers['X_SERVICE_CATALOG'] = "bad json"
response = self.request.get_response(self.middleware)
self.assertEqual(response.status_int, http.INTERNAL_SERVER_ERROR)
self.assertEqual(response.status_int, HTTPStatus.INTERNAL_SERVER_ERROR)
def test_request_id_extracted_from_env(self):
req_id = 'dummy-request-id'

View File

@ -12,7 +12,7 @@
# License for the specific language governing permissions and limitations
# under the License.
from http import client as http
from http import HTTPStatus
from unittest import mock
from keystoneauth1 import exceptions as keystone_exception
@ -164,7 +164,7 @@ class NovaApiTestCase(test.TestCase):
@mock.patch('masakari.compute.nova.novaclient')
def test_get_failed_not_found(self, mock_novaclient):
mock_novaclient.return_value.servers.get.side_effect = (
nova_exception.NotFound(http.NOT_FOUND, '404'))
nova_exception.NotFound(HTTPStatus.NOT_FOUND, '404'))
self.assertRaises(exception.NotFound,
self.api.get_server, self.ctx, uuidsentinel.fake_server)
@ -172,7 +172,7 @@ class NovaApiTestCase(test.TestCase):
@mock.patch('masakari.compute.nova.novaclient')
def test_get_failed_bad_request(self, mock_novaclient):
mock_novaclient.return_value.servers.get.side_effect = (
nova_exception.BadRequest(http.BAD_REQUEST, '400'))
nova_exception.BadRequest(HTTPStatus.BAD_REQUEST, '400'))
self.assertRaises(exception.InvalidInput,
self.api.get_server, self.ctx, uuidsentinel.fake_server)

View File

@ -13,7 +13,7 @@
# License for the specific language governing permissions and limitations
# under the License.
from http import client as http
from http import HTTPStatus
import re
import fixtures
@ -99,7 +99,7 @@ class APIValidationTestCase(test.NoDBTestCase):
try:
method(body=body, req=req,)
except exception.ValidationError as ex:
self.assertEqual(http.BAD_REQUEST, ex.kwargs['code'])
self.assertEqual(HTTPStatus.BAD_REQUEST, ex.kwargs['code'])
if isinstance(expected_detail, list):
self.assertIn(ex.kwargs['detail'], expected_detail,
'Exception details did not match expected')
@ -595,7 +595,7 @@ class VersionedApiValidationTestCase(APIValidationTestCase):
try:
self.post(body=body, req=req)
except exception.ValidationError as ex:
self.assertEqual(http.BAD_REQUEST, ex.kwargs['code'])
self.assertEqual(HTTPStatus.BAD_REQUEST, ex.kwargs['code'])
except Exception as ex:
self.fail('An unexpected exception happens: %s' % ex)
else:

View File

@ -14,7 +14,7 @@
# License for the specific language governing permissions and limitations
# under the License.
from http import client as http
from http import HTTPStatus
import inspect
from webob.util import status_reasons
@ -39,7 +39,7 @@ class MasakariExceptionTestCase(test.NoDBTestCase):
class FakeMasakariException(exception.MasakariException):
msg_fmt = "default message: %(code)s"
exc = FakeMasakariException(code=int(http.INTERNAL_SERVER_ERROR))
exc = FakeMasakariException(code=int(HTTPStatus.INTERNAL_SERVER_ERROR))
self.assertEqual('default message: 500', str(exc))
self.assertEqual('default message: 500', exc.message)
@ -47,24 +47,24 @@ class MasakariExceptionTestCase(test.NoDBTestCase):
class FakeMasakariException(exception.MasakariException):
msg_fmt = "default message: %(misspelled_code)s"
exc = FakeMasakariException(code=int(http.INTERNAL_SERVER_ERROR),
exc = FakeMasakariException(code=int(HTTPStatus.INTERNAL_SERVER_ERROR),
misspelled_code='blah')
self.assertEqual('default message: blah', str(exc))
self.assertEqual('default message: blah', exc.message)
def test_default_error_code(self):
class FakeMasakariException(exception.MasakariException):
code = http.NOT_FOUND
code = HTTPStatus.NOT_FOUND
exc = FakeMasakariException()
self.assertEqual(http.NOT_FOUND, exc.kwargs['code'])
self.assertEqual(HTTPStatus.NOT_FOUND, exc.kwargs['code'])
def test_error_code_from_kwarg(self):
class FakeMasakariException(exception.MasakariException):
code = http.INTERNAL_SERVER_ERROR
code = HTTPStatus.INTERNAL_SERVER_ERROR
exc = FakeMasakariException(code=http.NOT_FOUND)
self.assertEqual(exc.kwargs['code'], http.NOT_FOUND)
exc = FakeMasakariException(code=HTTPStatus.NOT_FOUND)
self.assertEqual(exc.kwargs['code'], HTTPStatus.NOT_FOUND)
def test_format_message_local(self):
class FakeMasakariException(exception.MasakariException):
@ -98,15 +98,17 @@ class MasakariExceptionTestCase(test.NoDBTestCase):
class ConvertedExceptionTestCase(test.NoDBTestCase):
def test_instantiate(self):
exc = exception.ConvertedException(int(http.BAD_REQUEST),
exc = exception.ConvertedException(int(HTTPStatus.BAD_REQUEST),
'Bad Request', 'reason')
self.assertEqual(exc.code, http.BAD_REQUEST)
self.assertEqual(exc.code, HTTPStatus.BAD_REQUEST)
self.assertEqual(exc.title, 'Bad Request')
self.assertEqual(exc.explanation, 'reason')
def test_instantiate_without_title_known_code(self):
exc = exception.ConvertedException(int(http.INTERNAL_SERVER_ERROR))
self.assertEqual(exc.title, status_reasons[http.INTERNAL_SERVER_ERROR])
exc = exception.ConvertedException(
int(HTTPStatus.INTERNAL_SERVER_ERROR))
self.assertEqual(exc.title,
status_reasons[HTTPStatus.INTERNAL_SERVER_ERROR])
def test_instantiate_without_title_unknown_code(self):
exc = exception.ConvertedException(499)
@ -119,7 +121,7 @@ class ConvertedExceptionTestCase(test.NoDBTestCase):
class ExceptionTestCase(test.NoDBTestCase):
@staticmethod
def _raise_exc(exc):
raise exc(int(http.INTERNAL_SERVER_ERROR))
raise exc(int(HTTPStatus.INTERNAL_SERVER_ERROR))
def test_exceptions_raise(self):
# NOTE(Dinesh_Bhor): disable format errors since we are not passing
@ -127,7 +129,9 @@ class ExceptionTestCase(test.NoDBTestCase):
self.flags(fatal_exception_format_errors=False)
for name in dir(exception):
exc = getattr(exception, name)
if isinstance(exc, type):
# NOTE(yoctozepto): we skip HTTPStatus as it is not an exception
# but a type also present in that module.
if isinstance(exc, type) and name != 'HTTPStatus':
self.assertRaises(exc, self._raise_exc, exc)