def add(self):
params = None
try:
params = utils.CNIParameters(flask.request.get_json())
LOG.debug('Received addNetwork request. CNI Params: %s', params)
vif = self.plugin.add(params)
data = jsonutils.dumps(vif.obj_to_primitive())
except exceptions.ResourceNotReady as e:
LOG.error("Timed out waiting for requested pod to appear in "
"registry: %s.", e)
return '', httplib.GATEWAY_TIMEOUT, self.headers
except Exception:
LOG.exception('Error when processing addNetwork request. CNI '
'Params: %s', params)
return '', httplib.INTERNAL_SERVER_ERROR, self.headers
return data, httplib.ACCEPTED, self.headers
python类INTERNAL_SERVER_ERROR的实例源码
def delete(self):
params = None
try:
params = utils.CNIParameters(flask.request.get_json())
LOG.debug('Received delNetwork request. CNI Params: %s', params)
self.plugin.delete(params)
except exceptions.ResourceNotReady as e:
# NOTE(dulek): It's better to ignore this error - most of the time
# it will happen when pod is long gone and kubelet
# overzealously tries to delete it from the network.
# We cannot really do anything without VIF annotation,
# so let's just tell kubelet to move along.
LOG.warning("Timed out waiting for requested pod to appear in "
"registry: %s. Ignoring.", e)
return '', httplib.NO_CONTENT, self.headers
except Exception:
LOG.exception('Error when processing delNetwork request. CNI '
'Params: %s.', params)
return '', httplib.INTERNAL_SERVER_ERROR, self.headers
return '', httplib.NO_CONTENT, self.headers
def test_get_new_token_should_throw_ecsclientexception_500(self):
self.requests_mock.register_uri('GET', 'https://127.0.0.1:4443/login',
status_code=http_client.INTERNAL_SERVER_ERROR)
with super(testtools.TestCase, self).assertRaises(ECSClientException) as error:
self.token_request.get_new_token()
exception = error.exception
self.assertEqual(exception.http_status, http_client.INTERNAL_SERVER_ERROR)
def test_token_validation_500(self, mock_get_existing_token):
self.requests_mock.register_uri('GET', 'https://127.0.0.1:4443/user/whoami',
status_code=http_client.INTERNAL_SERVER_ERROR)
mock_get_existing_token.return_value = 'EXISTING-TOKEN-123'
with super(testtools.TestCase, self).assertRaises(ECSClientException) as error:
self.token_request.get_token()
exception = error.exception
self.assertEqual(exception.message, "Token validation error (Code: 500)")
self.assertEqual(exception.http_status, http_client.INTERNAL_SERVER_ERROR)
def test_list_nodes_throw_exception(self, mock_get_token):
self.requests_mock.register_uri('GET', 'https://127.0.0.1:4443/vdc/nodes',
status_code=http_client.INTERNAL_SERVER_ERROR,
text='Server Error')
mock_get_token.return_value = 'FAKE-TOKEN-123'
with super(testtools.TestCase, self).assertRaises(ECSClientException) as error:
self.client.node.list()
exception = error.exception
self.assertEqual(self.requests_mock.last_request.method, 'GET')
self.assertEqual(self.requests_mock.last_request.url, 'https://127.0.0.1:4443/vdc/nodes')
self.assertEqual(self.requests_mock.last_request.headers['x-sds-auth-token'], 'FAKE-TOKEN-123')
self.assertEqual(exception.http_response_content, 'Server Error')
self.assertEqual(exception.http_status, http_client.INTERNAL_SERVER_ERROR)
def test_server_error(self):
self.request.return_value.status_code = (
http_client.INTERNAL_SERVER_ERROR)
self.request.return_value.json.side_effect = ValueError('no json')
with self.assertRaisesRegex(exceptions.ServerSideError,
'unknown error') as cm:
self.conn._op('GET', 'http://foo.bar')
exc = cm.exception
self.assertEqual(http_client.INTERNAL_SERVER_ERROR, exc.status_code)
def raise_for_response(method, url, response):
"""Raise a correct error class, if needed."""
if response.status_code < http_client.BAD_REQUEST:
return
elif response.status_code == http_client.NOT_FOUND:
raise ResourceNotFoundError(method, url, response)
elif response.status_code == http_client.BAD_REQUEST:
raise BadRequestError(method, url, response)
elif response.status_code in (http_client.UNAUTHORIZED,
http_client.FORBIDDEN):
raise AccessError(method, url, response)
elif response.status_code >= http_client.INTERNAL_SERVER_ERROR:
raise ServerSideError(method, url, response)
else:
raise HTTPError(method, url, response)
def test__do_refresh_request_basic_failure(self):
response = http_mock.ResponseMock(
{'status': http_client.INTERNAL_SERVER_ERROR})
content = u'{}'
error_msg = 'Invalid response {0}.'.format(int(response.status))
self._do_refresh_request_test_helper(response, content, error_msg)
def test__do_revoke_basic_failure(self):
response = http_mock.ResponseMock(
{'status': http_client.INTERNAL_SERVER_ERROR})
content = u'{}'
error_msg = 'Invalid response {0}.'.format(response.status)
self._do_revoke_test_helper(response, content, error_msg)
def test__do_retrieve_scopes_basic_failure(self):
response = http_mock.ResponseMock(
{'status': http_client.INTERNAL_SERVER_ERROR})
content = u'{}'
error_msg = 'Invalid response {0}.'.format(response.status)
self._do_retrieve_scopes_test_helper(response, content, error_msg)
def test_step1_get_device_and_user_codes_basic_failure(self):
status = int(http_client.INTERNAL_SERVER_ERROR)
content = b'{}'
error_msg = 'Invalid response {0}.'.format(status)
self._step1_get_device_and_user_codes_fail_helper(status, content,
error_msg)
def test__do_refresh_request_basic_failure(self):
response = http_mock.ResponseMock(
{'status': http_client.INTERNAL_SERVER_ERROR})
content = u'{}'
error_msg = 'Invalid response {0}.'.format(int(response.status))
self._do_refresh_request_test_helper(response, content, error_msg)
def test__do_revoke_basic_failure(self):
response = http_mock.ResponseMock(
{'status': http_client.INTERNAL_SERVER_ERROR})
content = u'{}'
error_msg = 'Invalid response {0}.'.format(response.status)
self._do_revoke_test_helper(response, content, error_msg)
def test__do_retrieve_scopes_basic_failure(self):
response = http_mock.ResponseMock(
{'status': http_client.INTERNAL_SERVER_ERROR})
content = u'{}'
error_msg = 'Invalid response {0}.'.format(response.status)
self._do_retrieve_scopes_test_helper(response, content, error_msg)
def test_step1_get_device_and_user_codes_basic_failure(self):
status = int(http_client.INTERNAL_SERVER_ERROR)
content = b'{}'
error_msg = 'Invalid response {0}.'.format(status)
self._step1_get_device_and_user_codes_fail_helper(status, content,
error_msg)
def test_delete_composednode_fail(self, mock_request, mock_get_url,
mock_make_response):
mock_get_url.return_value = '/redfish/v1/Nodes'
delete_result = fakes.fake_delete_composednode_fail()
fake_resp = fakes.mock_request_get(delete_result,
http_client.INTERNAL_SERVER_ERROR)
mock_request.return_value = fake_resp
self.assertRaises(exception.RedfishException,
redfish.delete_composed_node, 101)
self.assertFalse(mock_make_response.called)
def handle_error(self, error):
if issubclass(error.__class__, exception.ValenceError):
LOG.debug(traceback.format_exc())
return utils.make_response(error.status, error.as_dict())
elif hasattr(error, 'status'):
LOG.debug(traceback.format_exc())
return utils.make_response(error.code,
exception.httpexception(error))
else:
# Valence will not throw general exception in normal case, so use
# LOG.error() to record it.
LOG.error(traceback.format_exc())
exc = exception.generalexception(error,
http_client.INTERNAL_SERVER_ERROR)
return utils.make_response(http_client.INTERNAL_SERVER_ERROR, exc)
def test_server_exception_empty_body(self):
error_body = _get_error_body()
kwargs = {"valence_url": "http://localhost"}
client = http.HTTPClient(**kwargs)
client.session = utils.mockSession(
{'Content-Type': 'application/json'},
error_body,
version=1,
status_code=http_client.INTERNAL_SERVER_ERROR)
self.assertRaises(exc.InternalServerError,
client.json_request,
'GET', 'redfish/v1')
def test_server_exception_msg_only(self):
error_body = "test error msg"
error_body = _get_error_body(detail=error_body)
kwargs = {"valence_url": "http://localhost"}
client = http.HTTPClient(**kwargs)
client.session = utils.mockSession(
{'Content-Type': 'application/json'},
error_body,
version=1,
status_code=http_client.INTERNAL_SERVER_ERROR)
self.assertRaises(exc.InternalServerError,
client.json_request,
'GET', 'redfish/v1')
def test_get_bad_json(self, resp_mock):
"""Test treadmill.restclient.get bad JSON"""
resp_mock.return_value.status_code = http_client.INTERNAL_SERVER_ERROR
resp_mock.return_value.text = '{"bad json"'
resp_mock.return_value.json.side_effect = sjs.JSONDecodeError(
'Foo', '{"bad json"', 1
)
self.assertRaises(
restclient.MaxRequestRetriesError,
restclient.get, 'http://foo.com', '/', retries=1)
def unexpected_error(e):
"""Handle exceptions by returning swagger-compliant json."""
logging.exception('An error occured while processing the request.')
response = jsonify({
'code': http_client.INTERNAL_SERVER_ERROR,
'message': 'Exception: {}'.format(e)})
response.status_code = http_client.INTERNAL_SERVER_ERROR
return response
def unexpected_error(e):
"""Handle exceptions by returning swagger-compliant json."""
logging.exception('An error occured while processing the request.')
response = jsonify({
'code': http_client.INTERNAL_SERVER_ERROR,
'message': 'Exception: {}'.format(e)})
response.status_code = http_client.INTERNAL_SERVER_ERROR
return response
compliance.py 文件源码
项目:google-auth-library-python
作者: GoogleCloudPlatform
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def server(self):
"""Provides a test HTTP server.
The test server is automatically created before
a test and destroyed at the end. The server is serving a test
application that can be used to verify requests.
"""
app = flask.Flask(__name__)
app.debug = True
# pylint: disable=unused-variable
# (pylint thinks the flask routes are unusued.)
@app.route('/basic')
def index():
header_value = flask.request.headers.get('x-test-header', 'value')
headers = {'X-Test-Header': header_value}
return 'Basic Content', http_client.OK, headers
@app.route('/server_error')
def server_error():
return 'Error', http_client.INTERNAL_SERVER_ERROR
@app.route('/wait')
def wait():
time.sleep(3)
return 'Waited'
# pylint: enable=unused-variable
server = WSGIServer(application=app.wsgi_app)
server.start()
yield server
server.stop()
compliance.py 文件源码
项目:google-auth-library-python
作者: GoogleCloudPlatform
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def test_request_error(self, server):
request = self.make_request()
response = request(url=server.url + '/server_error', method='GET')
assert response.status == http_client.INTERNAL_SERVER_ERROR
assert response.data == b'Error'
def test_default_error_msg_with_kwargs(self):
class FakeMasakariException(exception.MasakariException):
msg_fmt = "default message: %(code)s"
exc = FakeMasakariException(code=int(http.INTERNAL_SERVER_ERROR))
self.assertEqual('default message: 500', six.text_type(exc))
self.assertEqual('default message: 500', exc.message)
def test_error_msg_exception_with_kwargs(self):
class FakeMasakariException(exception.MasakariException):
msg_fmt = "default message: %(misspelled_code)s"
exc = FakeMasakariException(code=int(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_error_code_from_kwarg(self):
class FakeMasakariException(exception.MasakariException):
code = http.INTERNAL_SERVER_ERROR
exc = FakeMasakariException(code=http.NOT_FOUND)
self.assertEqual(exc.kwargs['code'], http.NOT_FOUND)
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])
def _raise_exc(exc):
raise exc(int(http.INTERNAL_SERVER_ERROR))
def test_call_raises_exception(self):
class FakeController(object):
def index(self, shirt, pants=None):
return (shirt, pants)
resource = wsgi.Resource(FakeController(), None, None)
with mock.patch('glare.common.wsgi.Resource.dispatch',
side_effect=Exception("test exception")):
request = wsgi.Request.blank('/')
response = resource.__call__(request)
self.assertIsInstance(response, webob.exc.HTTPInternalServerError)
self.assertEqual(http.INTERNAL_SERVER_ERROR, response.status_code)