Beispiel #1
0
    def test_unhandled_error_with_json(self):
        expected_res = {
            'body': {
                'ApmecError': {
                    'detail':
                    '',
                    'message':
                    _('Request Failed: internal server error'
                      ' while processing your request.'),
                    'type':
                    'HTTPInternalServerError'
                }
            }
        }
        controller = mock.MagicMock()
        controller.test.side_effect = Exception()

        resource = webtest.TestApp(wsgi_resource.Resource(controller))

        environ = {
            'wsgiorg.routing_args': (None, {
                'action': 'test',
                'format': 'json'
            })
        }
        res = resource.get('', extra_environ=environ, expect_errors=True)
        self.assertEqual(exc.HTTPInternalServerError.code, res.status_int)
        self.assertEqual(expected_res,
                         wsgi.JSONDeserializer().deserialize(res.body))
Beispiel #2
0
    def test_mapped_apmec_error_with_json(self):
        msg = u'\u7f51\u7edc'

        class TestException(n_exc.ApmecException):
            message = msg

        expected_res = {
            'body': {
                'ApmecError': {
                    'type': 'TestException',
                    'message': msg,
                    'detail': ''
                }
            }
        }
        controller = mock.MagicMock()
        controller.test.side_effect = TestException()

        faults = {TestException: exc.HTTPGatewayTimeout}
        resource = webtest.TestApp(
            wsgi_resource.Resource(controller, faults=faults))

        environ = {
            'wsgiorg.routing_args': (None, {
                'action': 'test',
                'format': 'json'
            })
        }
        res = resource.get('', extra_environ=environ, expect_errors=True)
        self.assertEqual(exc.HTTPGatewayTimeout.code, res.status_int)
        self.assertEqual(expected_res,
                         wsgi.JSONDeserializer().deserialize(res.body))
Beispiel #3
0
    def test_mapped_apmec_error_localized(self, mock_translation):
        msg_translation = 'Translated error'
        mock_translation.return_value = msg_translation
        msg = _('Unmapped error')

        class TestException(n_exc.ApmecException):
            message = msg

        controller = mock.MagicMock()
        controller.test.side_effect = TestException()
        faults = {TestException: exc.HTTPGatewayTimeout}
        resource = webtest.TestApp(
            wsgi_resource.Resource(controller, faults=faults))

        environ = {
            'wsgiorg.routing_args': (None, {
                'action': 'test',
                'format': 'json'
            })
        }

        res = resource.get('', extra_environ=environ, expect_errors=True)
        self.assertEqual(exc.HTTPGatewayTimeout.code, res.status_int)
        self.assertIn(msg_translation,
                      str(wsgi.JSONDeserializer().deserialize(res.body)))
Beispiel #4
0
 def test_json(self):
     data = """{"a": {
             "a1": "1",
             "a2": "2",
             "bs": ["1", "2", "3", {"c": {"c1": "1"}}],
             "d": {"e": "1"},
             "f": "1"}}"""
     as_dict = {
         'body': {
             'a': {
                 'a1': '1',
                 'a2': '2',
                 'bs': ['1', '2', '3', {
                     'c': {
                         'c1': '1'
                     }
                 }],
                 'd': {
                     'e': '1'
                 },
                 'f': '1'
             }
         }
     }
     deserializer = wsgi.JSONDeserializer()
     self.assertEqual(as_dict, deserializer.deserialize(data))
Beispiel #5
0
    def test_default_raise_Malformed_Exception(self):
        """Test JsonDeserializer.default.

        Test verifies JsonDeserializer.default raises exception
        MalformedRequestBody correctly.
        """
        data_string = ""
        deserializer = wsgi.JSONDeserializer()

        self.assertRaises(exception.MalformedRequestBody, deserializer.default,
                          data_string)
Beispiel #6
0
def Resource(controller, faults=None, deserializers=None, serializers=None):
    """API entity resource.

    Represents an API entity resource and the associated serialization and
    deserialization logic
    """
    default_deserializers = {'application/json': wsgi.JSONDeserializer()}
    default_serializers = {'application/json': wsgi.JSONDictSerializer()}
    format_types = {'json': 'application/json'}
    action_status = dict(create=201, delete=204)

    default_deserializers.update(deserializers or {})
    default_serializers.update(serializers or {})

    deserializers = default_deserializers
    serializers = default_serializers
    faults = faults or {}

    @webob.dec.wsgify(RequestClass=Request)
    def resource(request):
        route_args = request.environ.get('wsgiorg.routing_args')
        if route_args:
            args = route_args[1].copy()
        else:
            args = {}

        # NOTE(jkoelker) by now the controller is already found, remove
        #                it from the args if it is in the matchdict
        args.pop('controller', None)
        fmt = args.pop('format', None)
        action = args.pop('action', None)
        content_type = format_types.get(fmt,
                                        request.best_match_content_type())
        language = request.best_match_language()
        deserializer = deserializers.get(content_type)
        serializer = serializers.get(content_type)

        try:
            if request.body:
                args['body'] = deserializer.deserialize(request.body)['body']

            method = getattr(controller, action)

            result = method(request=request, **args)
        except Exception as e:
            mapped_exc = api_common.convert_exception_to_http_exc(e, faults,
                                                                  language)
            if hasattr(mapped_exc, 'code') and 400 <= mapped_exc.code < 500:
                LOG.info('%(action)s failed (client error): %(exc)s',
                         {'action': action, 'exc': mapped_exc})
            else:
                LOG.exception('%(action)s failed: %(details)s',
                              {'action': action,
                               'details': extract_exc_details(e)})
            raise mapped_exc

        status = action_status.get(action, 200)
        body = serializer.serialize(result)
        # NOTE(jkoelker) Comply with RFC2616 section 9.7
        if status == 204:
            content_type = ''
            body = None

        return webob.Response(request=request, status=status,
                              content_type=content_type,
                              body=body)
    return resource
 def setUp(self):
     super(WebTestCase, self).setUp()
     json_deserializer = wsgi.JSONDeserializer()
     self._deserializers = {
         'application/json': json_deserializer,
     }
Beispiel #8
0
 def test_json_with_unicode(self):
     data = b'{"a": "\u7f51\u7edc"}'
     as_dict = {'body': {'a': u'\u7f51\u7edc'}}
     deserializer = wsgi.JSONDeserializer()
     self.assertEqual(as_dict, deserializer.deserialize(data))
Beispiel #9
0
 def test_json_with_utf8(self):
     data = b'{"a": "\xe7\xbd\x91\xe7\xbb\x9c"}'
     as_dict = {'body': {'a': u'\u7f51\u7edc'}}
     deserializer = wsgi.JSONDeserializer()
     self.assertEqual(as_dict, deserializer.deserialize(data))