Extracted HTTP response codes to constants

There are several places in the source code where HTTP response
codes are used as numeric values.

All of the used status codes are replaced with symbolic constants
from six.moves.http_client to improve code readibility.

Closes-Bug: #1520159

Change-Id: Ic5e439fb1f33962979536fe1ac5e5320e2c50c40
This commit is contained in:
Dinesh Bhor 2017-01-03 15:17:25 +05:30
parent c8cc838de3
commit 4f4c42bd8d
15 changed files with 128 additions and 102 deletions

View File

@ -15,6 +15,7 @@
"""The Host API extension."""
from six.moves import http_client as http
from webob import exc
from masakari.api.openstack import common
@ -36,7 +37,8 @@ class HostsController(wsgi.Controller):
def __init__(self):
self.api = host_api.HostAPI()
@extensions.expected_errors((400, 403, 404))
@extensions.expected_errors((http.BAD_REQUEST, http.FORBIDDEN,
http.NOT_FOUND))
def index(self, req, segment_id):
"""Returns a list a hosts."""
context = req.environ['masakari.context']
@ -79,8 +81,9 @@ class HostsController(wsgi.Controller):
return {'hosts': hosts}
@wsgi.response(201)
@extensions.expected_errors((403, 404, 409))
@wsgi.response(http.CREATED)
@extensions.expected_errors((http.FORBIDDEN, http.NOT_FOUND,
http.CONFLICT))
@validation.schema(schema.create)
def create(self, req, segment_id, body):
"""Creates a host."""
@ -96,7 +99,7 @@ class HostsController(wsgi.Controller):
return {'host': host}
@extensions.expected_errors((403, 404))
@extensions.expected_errors((http.FORBIDDEN, http.NOT_FOUND))
def show(self, req, segment_id, id):
"""Shows the details of a host."""
context = req.environ['masakari.context']
@ -109,7 +112,8 @@ class HostsController(wsgi.Controller):
raise exc.HTTPNotFound(explanation=e.format_message())
return {'host': host}
@extensions.expected_errors((403, 404, 409))
@extensions.expected_errors((http.FORBIDDEN, http.NOT_FOUND,
http.CONFLICT))
@validation.schema(schema.update)
def update(self, req, segment_id, id, body):
"""Updates the existing host."""
@ -127,8 +131,8 @@ class HostsController(wsgi.Controller):
return {'host': host}
@wsgi.response(204)
@extensions.expected_errors((403, 404))
@wsgi.response(http.NO_CONTENT)
@extensions.expected_errors((http.FORBIDDEN, http.NOT_FOUND))
def delete(self, req, segment_id, id):
"""Removes a host by id."""
context = req.environ['masakari.context']

View File

@ -14,6 +14,7 @@
# under the License.
from oslo_utils import timeutils
from six.moves import http_client as http
from webob import exc
from masakari.api.openstack import common
@ -35,8 +36,9 @@ class NotificationsController(wsgi.Controller):
def __init__(self):
self.api = notification_api.NotificationAPI()
@wsgi.response(202)
@extensions.expected_errors((400, 403, 409))
@wsgi.response(http.ACCEPTED)
@extensions.expected_errors((http.BAD_REQUEST, http.FORBIDDEN,
http.CONFLICT))
@validation.schema(schema.create)
def create(self, req, body):
"""Creates a new notification."""
@ -55,7 +57,7 @@ class NotificationsController(wsgi.Controller):
return {'notification': notification}
@extensions.expected_errors((400, 403))
@extensions.expected_errors((http.BAD_REQUEST, http.FORBIDDEN))
def index(self, req):
"""Returns a summary list of notifications."""
context = req.environ['masakari.context']
@ -89,7 +91,7 @@ class NotificationsController(wsgi.Controller):
return {'notifications': notifications}
@extensions.expected_errors((403, 404))
@extensions.expected_errors((http.FORBIDDEN, http.NOT_FOUND))
def show(self, req, id):
"""Return data about the given notification id."""
context = req.environ['masakari.context']

View File

@ -13,6 +13,7 @@
# License for the specific language governing permissions and limitations
# under the License.
from six.moves import http_client as http
from webob import exc
from masakari.api.openstack import common
@ -34,7 +35,7 @@ class SegmentsController(wsgi.Controller):
def __init__(self):
self.api = segment_api.FailoverSegmentAPI()
@extensions.expected_errors((400, 403))
@extensions.expected_errors((http.BAD_REQUEST, http.FORBIDDEN))
def index(self, req):
"""Returns a summary list of failover segments."""
context = req.environ['masakari.context']
@ -61,7 +62,7 @@ class SegmentsController(wsgi.Controller):
return {'segments': segments}
@extensions.expected_errors((403, 404))
@extensions.expected_errors((http.FORBIDDEN, http.NOT_FOUND))
def show(self, req, id):
"""Return data about the given segment id."""
context = req.environ['masakari.context']
@ -73,8 +74,8 @@ class SegmentsController(wsgi.Controller):
raise exc.HTTPNotFound(explanation=e.format_message())
return {'segment': segment}
@wsgi.response(201)
@extensions.expected_errors((403, 409))
@wsgi.response(http.CREATED)
@extensions.expected_errors((http.FORBIDDEN, http.CONFLICT))
@validation.schema(schema.create)
def create(self, req, body):
"""Creates a new failover segment."""
@ -88,7 +89,8 @@ class SegmentsController(wsgi.Controller):
raise exc.HTTPConflict(explanation=e.format_message())
return {'segment': segment}
@extensions.expected_errors((403, 404, 409))
@extensions.expected_errors((http.FORBIDDEN, http.NOT_FOUND,
http.CONFLICT))
@validation.schema(schema.update)
def update(self, req, id, body):
"""Updates the existing segment."""
@ -105,8 +107,8 @@ class SegmentsController(wsgi.Controller):
return {'segment': segment}
@wsgi.response(204)
@extensions.expected_errors((403, 404))
@wsgi.response(http.NO_CONTENT)
@extensions.expected_errors((http.FORBIDDEN, http.NOT_FOUND))
def delete(self, req, id):
"""Removes a segment by uuid."""
context = req.environ['masakari.context']

View File

@ -21,6 +21,7 @@ from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import strutils
import six
from six.moves import http_client as http
import webob
from masakari.api import api_version_request as api_version
@ -271,7 +272,7 @@ class ResponseObject(object):
"""Builds a response object."""
self.obj = obj
self._default_code = 200
self._default_code = http.OK
self._code = code
self._headers = headers or {}
self.serializer = JSONDictSerializer()
@ -1012,17 +1013,19 @@ class Fault(webob.exc.HTTPException):
"""Wrap webob.exc.HTTPException to provide API friendly response."""
_fault_names = {
400: "badRequest",
401: "unauthorized",
403: "forbidden",
404: "itemNotFound",
405: "badMethod",
409: "conflictingRequest",
413: "overLimit",
415: "badMediaType",
429: "overLimit",
501: "notImplemented",
503: "serviceUnavailable"
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",
# TODO(Dinesh_Bhor) Replace it with symbolic constant when it is
# defined in six.moves.http_client
429: "overLimit"
}
def __init__(self, exception):
@ -1049,7 +1052,7 @@ class Fault(webob.exc.HTTPException):
fault_name: {
'code': code,
'message': explanation}}
if code == 413 or code == 429:
if code == http.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

@ -28,6 +28,7 @@ import sys
from oslo_log import log as logging
from oslo_utils import excutils
import six
from six.moves import http_client as http
import webob.exc
from webob import util as woutil
@ -115,7 +116,7 @@ class MasakariException(Exception):
"""
msg_fmt = _("An unknown exception occurred.")
code = 500
code = http.INTERNAL_SERVER_ERROR
headers = {}
safe = False
@ -170,12 +171,12 @@ class APITimeout(APIException):
class Conflict(MasakariException):
msg_fmt = _("Conflict")
code = 409
code = http.CONFLICT
class Invalid(MasakariException):
msg_fmt = _("Bad Request - Invalid Parameters")
code = 400
code = http.BAD_REQUEST
class InvalidName(Invalid):
@ -200,7 +201,7 @@ class MalformedRequestBody(MasakariException):
# appropriate to be returned
class NotFound(MasakariException):
msg_fmt = _("Resource could not be found.")
code = 404
code = http.NOT_FOUND
class ConfigNotFound(NotFound):
@ -209,7 +210,7 @@ class ConfigNotFound(NotFound):
class Forbidden(MasakariException):
msg_fmt = _("Forbidden")
code = 403
code = http.FORBIDDEN
class AdminRequired(Forbidden):
@ -285,7 +286,7 @@ class HostExists(MasakariException):
class Unauthorized(MasakariException):
msg_fmt = _("Not authorized.")
code = 401
code = http.UNAUTHORIZED
class ObjectActionError(MasakariException):
@ -298,12 +299,12 @@ class OrphanedObjectError(MasakariException):
class DuplicateNotification(Invalid):
msg_fmt = _('Duplicate notification received for type: %(type)s')
code = 409
code = http.CONFLICT
class HostOnMaintenanceError(Invalid):
msg_fmt = _('Host %(host_name)s is already under maintenance.')
code = 409
code = http.CONFLICT
class AutoRecoveryFailureException(MasakariException):

View File

@ -17,6 +17,7 @@
import mock
from oslo_serialization import jsonutils
from six.moves import http_client as http
from webob import exc
from masakari.api.openstack.ha import hosts
@ -176,7 +177,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(201, resp.status_code)
self.assertEqual(http.CREATED, resp.status_code)
@mock.patch.object(ha_api.HostAPI, 'create_host')
def test_create_with_duplicate_host_name(self, mock_create):
@ -380,7 +381,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(204, resp.status_code)
self.assertEqual(http.NO_CONTENT, resp.status_code)
@mock.patch.object(ha_api.HostAPI, 'delete_host')
def test_delete_host_not_found(self, mock_delete):

View File

@ -18,6 +18,7 @@
import mock
from oslo_serialization import jsonutils
from oslo_utils import timeutils
from six.moves import http_client as http
from webob import exc
from masakari.api.openstack.ha import notifications
@ -168,7 +169,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(202, resp.status_code)
self.assertEqual(http.ACCEPTED, resp.status_code)
def test_create_invalid_type(self):
body = {
@ -289,7 +290,7 @@ class NotificationTestCase(test.TestCase):
fake_req.headers['Content-Type'] = 'application/json'
fake_req.method = 'DELETE'
resp = fake_req.get_response(self.app)
self.assertEqual(405, resp.status_code)
self.assertEqual(http.METHOD_NOT_ALLOWED, resp.status_code)
@mock.patch('masakari.rpc.get_client')
def test_update_notification(self, mock_client):
@ -298,7 +299,7 @@ class NotificationTestCase(test.TestCase):
fake_req.headers['Content-Type'] = 'application/json'
fake_req.method = 'PUT'
resp = fake_req.get_response(self.app)
self.assertEqual(405, resp.status_code)
self.assertEqual(http.METHOD_NOT_ALLOWED, resp.status_code)
class NotificationCasePolicyNotAuthorized(test.NoDBTestCase):

View File

@ -17,6 +17,7 @@
import mock
from oslo_serialization import jsonutils
from six.moves import http_client as http
from webob import exc
from masakari.api.openstack.ha import segments
@ -161,7 +162,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(201, resp.status_code)
self.assertEqual(http.CREATED, resp.status_code)
def test_create_with_no_segment(self):
body = {
@ -338,7 +339,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(204, resp.status_code)
self.assertEqual(http.NO_CONTENT, resp.status_code)
class FailoverSegmentTestCasePolicyNotAuthorized(test.NoDBTestCase):

View File

@ -17,6 +17,7 @@ import copy
import mock
from oslo_serialization import jsonutils
from six.moves import http_client as http
import webob
from masakari.api import api_version_request as avr
@ -217,7 +218,7 @@ class VersionsTest(test.NoDBTestCase):
req = webob.Request.blank('/v1')
req.accept = "application/json"
res = req.get_response(self.wsgi_app)
self.assertEqual(302, res.status_int)
self.assertEqual(http.FOUND, res.status_int)
redirect_req = webob.Request.blank('/v1/')
self.assertEqual(redirect_req.url, res.location)
@ -226,4 +227,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(404, res.status_int)
self.assertEqual(http.NOT_FOUND, res.status_int)

View File

@ -15,6 +15,7 @@
import mock
from oslo_config import cfg
from six.moves import http_client as http
import webob.exc
from masakari.api.openstack import extensions
@ -54,35 +55,36 @@ class ExtensionLoadingTestCase(test.NoDBTestCase):
self.assertIn('extensions', name_list)
def test_extensions_expected_error(self):
@extensions.expected_errors(404)
@extensions.expected_errors(http.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((404, 403))
@extensions.expected_errors((http.NOT_FOUND, http.FORBIDDEN))
def fake_func():
raise webob.exc.HTTPNotFound()
self.assertRaises(webob.exc.HTTPNotFound, fake_func)
def test_extensions_unexpected_error(self):
@extensions.expected_errors(404)
@extensions.expected_errors(http.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((404, 413))
@extensions.expected_errors((http.NOT_FOUND,
http.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(404)
@extensions.expected_errors(http.NOT_FOUND)
def fake_func():
raise exception.PolicyNotAuthorized(action="foo")

View File

@ -17,6 +17,7 @@ import inspect
import mock
import six
from six.moves import http_client as http
import testscenarios
import webob
@ -234,19 +235,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, 200)
self.assertEqual(response.status_int, http.OK)
req.body = b'{"body": {"key": "value"}}'
response = req.get_response(app)
self.assertEqual(b'success', response.body)
self.assertEqual(response.status_int, 200)
self.assertEqual(response.status_int, http.OK)
req.content_type = 'application/json'
response = req.get_response(app)
self.assertEqual(b'success', response.body)
self.assertEqual(response.status_int, 200)
self.assertEqual(response.status_int, http.OK)
def test_resource_call_with_method_post(self):
class Controller(object):
@extensions.expected_errors(400)
@extensions.expected_errors(http.BAD_REQUEST)
def create(self, req, body):
if expected_body != body:
msg = "The request body invalid"
@ -262,20 +263,20 @@ class ResourceTest(MicroversionedTest):
}
}
response = req.get_response(app)
self.assertEqual(response.status_int, 200)
self.assertEqual(response.status_int, http.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, 200)
self.assertEqual(response.status_int, http.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': 400}}
self.assertEqual(response.status_int, 400)
{'message': 'The request body invalid', 'code': http.BAD_REQUEST}}
self.assertEqual(response.status_int, http.BAD_REQUEST)
self.assertEqual(expected_unsupported_type_body,
jsonutils.loads(response.body))
@ -297,11 +298,11 @@ class ResourceTest(MicroversionedTest):
}
response = req.get_response(app)
self.assertEqual(b'success', response.body)
self.assertEqual(response.status_int, 200)
self.assertEqual(response.status_int, http.OK)
req.body = None
expected_body = None
response = req.get_response(app)
self.assertEqual(response.status_int, 200)
self.assertEqual(response.status_int, http.OK)
# verify no content_type is contained in the request
req = webob.Request.blank('/tests/test_id', method="PUT",
content_type='application/xml')
@ -309,8 +310,9 @@ class ResourceTest(MicroversionedTest):
req.body = b'{"body": {"key": "value"}}'
response = req.get_response(app)
expected_unsupported_type_body = {'badMediaType':
{'message': 'Unsupported Content-Type', 'code': 415}}
self.assertEqual(response.status_int, 415)
{'message': 'Unsupported Content-Type',
'code': http.UNSUPPORTED_MEDIA_TYPE}}
self.assertEqual(response.status_int, http.UNSUPPORTED_MEDIA_TYPE)
self.assertEqual(expected_unsupported_type_body,
jsonutils.loads(response.body))
@ -323,12 +325,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, 200)
self.assertEqual(response.status_int, http.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, 200)
self.assertEqual(response.status_int, http.OK)
self.assertEqual(b'success', response.body)
def test_resource_not_authorized(self):
@ -339,7 +341,7 @@ class ResourceTest(MicroversionedTest):
req = webob.Request.blank('/tests')
app = fakes.TestRouter(Controller())
response = req.get_response(app)
self.assertEqual(response.status_int, 403)
self.assertEqual(response.status_int, http.FORBIDDEN)
def test_dispatch(self):
class Controller(object):
@ -505,7 +507,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, 200)
self.assertEqual(response.status_int, http.OK)
def test_str_response_body(self):
@ -519,7 +521,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, 200)
self.assertEqual(response.status_int, http.OK)
def test_get_no_response_body(self):
@ -532,7 +534,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, 200)
self.assertEqual(response.status_int, http.OK)
def test_deserialize_default(self):
class Controller(object):
@ -864,10 +866,10 @@ class ResourceTest(MicroversionedTest):
foo() # generate a TypeError
self.fail("Should have raised a Fault (HTTP 400)")
except wsgi.Fault as fault:
self.assertEqual(400, fault.status_int)
self.assertEqual(http.BAD_REQUEST, fault.status_int)
def test_resource_headers_are_utf8(self):
resp = webob.Response(status_int=202)
resp = webob.Response(status_int=http.ACCEPTED)
resp.headers['x-header1'] = 1
resp.headers['x-header2'] = u'header2'
resp.headers['x-header3'] = u'header3'
@ -899,7 +901,7 @@ class ResourceTest(MicroversionedTest):
app = fakes.TestRouter(Controller())
response = req.get_response(app)
self.assertEqual(response.body, expected_body)
self.assertEqual(response.status_int, 200)
self.assertEqual(response.status_int, http.OK)
def test_resource_invalid_utf8(self):
class Controller(object):
@ -917,21 +919,21 @@ class ResourceTest(MicroversionedTest):
class ResponseObjectTest(test.NoDBTestCase):
def test_default_code(self):
robj = wsgi.ResponseObject({})
self.assertEqual(robj.code, 200)
self.assertEqual(robj.code, http.OK)
def test_modified_code(self):
robj = wsgi.ResponseObject({})
robj._default_code = 202
self.assertEqual(robj.code, 202)
robj._default_code = http.ACCEPTED
self.assertEqual(robj.code, http.ACCEPTED)
def test_override_default_code(self):
robj = wsgi.ResponseObject({}, code=404)
self.assertEqual(robj.code, 404)
robj = wsgi.ResponseObject({}, code=http.NOT_FOUND)
self.assertEqual(robj.code, http.NOT_FOUND)
def test_override_modified_code(self):
robj = wsgi.ResponseObject({}, code=404)
robj._default_code = 202
self.assertEqual(robj.code, 404)
robj = wsgi.ResponseObject({}, code=http.NOT_FOUND)
robj._default_code = http.ACCEPTED
self.assertEqual(robj.code, http.NOT_FOUND)
def test_set_header(self):
robj = wsgi.ResponseObject({})

View File

@ -13,6 +13,7 @@
from oslo_middleware import request_id
from oslo_serialization import jsonutils
from six.moves import http_client as http
import webob
import webob.exc
@ -42,32 +43,32 @@ class TestMasakariKeystoneContextMiddleware(test.NoDBTestCase):
def test_no_user_or_user_id(self):
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '401 Unauthorized')
self.assertEqual(response.status_int, http.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, '200 OK')
self.assertEqual(response.status_int, http.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, '200 OK')
self.assertEqual(response.status_int, http.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, '200 OK')
self.assertEqual(response.status_int, http.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, '500 Internal Server Error')
self.assertEqual(response.status_int, http.INTERNAL_SERVER_ERROR)
def test_request_id_extracted_from_env(self):
req_id = 'dummy-request-id'

View File

@ -13,6 +13,7 @@
# under the License.
import mock
from six.moves import http_client as http
from keystoneauth1 import exceptions as keystone_exception
from novaclient import exceptions as nova_exception
@ -137,7 +138,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(404, '404'))
nova_exception.NotFound(http.NOT_FOUND, '404'))
self.assertRaises(exception.NotFound,
self.api.get_server, self.ctx, uuidsentinel.fake_server)
@ -145,7 +146,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(400, '400'))
nova_exception.BadRequest(http.BAD_REQUEST, '400'))
self.assertRaises(exception.InvalidInput,
self.api.get_server, self.ctx, uuidsentinel.fake_server)

View File

@ -18,6 +18,7 @@ import re
import fixtures
from jsonschema import exceptions as jsonschema_exc
import six
from six.moves import http_client as http
import sys
from masakari.api import api_version_request as api_version
@ -98,7 +99,7 @@ class APIValidationTestCase(test.NoDBTestCase):
try:
method(body=body, req=req,)
except exception.ValidationError as ex:
self.assertEqual(400, ex.kwargs['code'])
self.assertEqual(http.BAD_REQUEST, ex.kwargs['code'])
if not re.match(expected_detail, ex.kwargs['detail']):
self.assertEqual(expected_detail, ex.kwargs['detail'],
'Exception details did not match expected')

View File

@ -17,6 +17,7 @@
import inspect
import six
from six.moves import http_client as http
from webob.util import status_reasons
from masakari import exception
@ -39,7 +40,7 @@ class MasakariExceptionTestCase(test.NoDBTestCase):
class FakeMasakariException(exception.MasakariException):
msg_fmt = "default message: %(code)s"
exc = FakeMasakariException(code=500)
exc = FakeMasakariException(code=http.INTERNAL_SERVER_ERROR)
self.assertEqual('default message: 500', six.text_type(exc))
self.assertEqual('default message: 500', exc.message)
@ -47,23 +48,24 @@ class MasakariExceptionTestCase(test.NoDBTestCase):
class FakeMasakariException(exception.MasakariException):
msg_fmt = "default message: %(misspelled_code)s"
exc = FakeMasakariException(code=500, misspelled_code='blah')
exc = FakeMasakariException(code=http.INTERNAL_SERVER_ERROR,
misspelled_code='blah')
self.assertEqual('default message: blah', six.text_type(exc))
self.assertEqual('default message: blah', exc.message)
def test_default_error_code(self):
class FakeMasakariException(exception.MasakariException):
code = 404
code = http.NOT_FOUND
exc = FakeMasakariException()
self.assertEqual(404, exc.kwargs['code'])
self.assertEqual(http.NOT_FOUND, exc.kwargs['code'])
def test_error_code_from_kwarg(self):
class FakeMasakariException(exception.MasakariException):
code = 500
code = http.INTERNAL_SERVER_ERROR
exc = FakeMasakariException(code=404)
self.assertEqual(exc.kwargs['code'], 404)
exc = FakeMasakariException(code=http.NOT_FOUND)
self.assertEqual(exc.kwargs['code'], http.NOT_FOUND)
def test_format_message_local(self):
class FakeMasakariException(exception.MasakariException):
@ -101,14 +103,15 @@ class MasakariExceptionTestCase(test.NoDBTestCase):
class ConvertedExceptionTestCase(test.NoDBTestCase):
def test_instantiate(self):
exc = exception.ConvertedException(400, 'Bad Request', 'reason')
self.assertEqual(exc.code, 400)
exc = exception.ConvertedException(http.BAD_REQUEST,
'Bad Request', 'reason')
self.assertEqual(exc.code, http.BAD_REQUEST)
self.assertEqual(exc.title, 'Bad Request')
self.assertEqual(exc.explanation, 'reason')
def test_instantiate_without_title_known_code(self):
exc = exception.ConvertedException(500)
self.assertEqual(exc.title, status_reasons[500])
exc = exception.ConvertedException(http.INTERNAL_SERVER_ERROR)
self.assertEqual(exc.title, status_reasons[http.INTERNAL_SERVER_ERROR])
def test_instantiate_without_title_unknown_code(self):
exc = exception.ConvertedException(499)
@ -121,7 +124,7 @@ class ConvertedExceptionTestCase(test.NoDBTestCase):
class ExceptionTestCase(test.NoDBTestCase):
@staticmethod
def _raise_exc(exc):
raise exc(500)
raise exc(http.INTERNAL_SERVER_ERROR)
def test_exceptions_raise(self):
# NOTE(Dinesh_Bhor): disable format errors since we are not passing