Beispiel #1
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(deserializer.deserialize(data), as_dict)
Beispiel #2
0
 def setUp(self):
     super(WebTestCase, self).setUp()
     json_deserializer = wsgi.JSONDeserializer()
     xml_deserializer = wsgi.XMLDeserializer(attributes.get_attr_metadata())
     self._deserializers = {
         'application/json': json_deserializer,
         'application/xml': xml_deserializer,
     }
Beispiel #3
0
    def test_default_raise_Malformed_Exception(self):
        """
        Test verifies JsonDeserializer.default
        raises exception MalformedRequestBody correctly
        """
        data_string = ""
        deserializer = wsgi.JSONDeserializer()

        self.assertRaises(exception.MalformedRequestBody, deserializer.default,
                          data_string)
Beispiel #4
0
def create_resource(version, controller_dict):
    """
    Generic function for creating a wsgi resource
    The function takes as input:
     - desired version
     - controller and metadata dictionary
       e.g.: {'1.0': [ctrl_v10, meta_v10, xml_ns],
              '1.1': [ctrl_v11, meta_v11, xml_ns]}

    """
    # the first element of the iterable is expected to be the controller
    controller = controller_dict[version][0]
    # the second element should be the metadata
    metadata = controller_dict[version][1]
    # and the third element the xml namespace
    xmlns = controller_dict[version][2]
    # and also the function for building the fault body
    fault_body_function = faults.fault_body_function(version)

    headers_serializers = {
        '1.0': HeaderSerializer10(),
        '1.1': HeaderSerializer11()
    }
    xml_serializer = wsgi.XMLDictSerializer(metadata, xmlns)
    json_serializer = wsgi.JSONDictSerializer()
    xml_deserializer = wsgi.XMLDeserializer(metadata)
    json_deserializer = wsgi.JSONDeserializer()

    body_serializers = {
        'application/xml': xml_serializer,
        'application/json': json_serializer,
    }

    body_deserializers = {
        'application/xml': xml_deserializer,
        'application/json': json_deserializer,
    }

    serializer = wsgi.ResponseSerializer(body_serializers,
                                         headers_serializers[version])
    deserializer = wsgi.RequestDeserializer(body_deserializers)

    return wsgi.Resource(controller,
                         fault_body_function,
                         deserializer,
                         serializer)
    def test_unmapped_quantum_error_with_json(self):
        msg = u'\u7f51\u7edc'

        class TestException(q_exc.QuantumException):
            message = msg

        expected_res = {'body': {'QuantumError': msg}}
        controller = mock.MagicMock()
        controller.test.side_effect = TestException()

        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(res.status_int, exc.HTTPInternalServerError.code)
        self.assertEqual(wsgi.JSONDeserializer().deserialize(res.body),
                         expected_res)
    def test_unhandled_error_with_json(self):
        expected_res = {
            'body': {
                'QuantumError':
                _('Request Failed: internal server error '
                  'while processing your request.')
            }
        }
        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(res.status_int, exc.HTTPInternalServerError.code)
        self.assertEqual(wsgi.JSONDeserializer().deserialize(res.body),
                         expected_res)
Beispiel #7
0
def Resource(controller, faults=None, deserializers=None, serializers=None):
    """Represents an API entity resource and the associated serialization and
    deserialization logic
    """
    xml_deserializer = wsgi.XMLDeserializer(attributes.get_attr_metadata())
    default_deserializers = {'application/xml': xml_deserializer,
                             'application/json': wsgi.JSONDeserializer()}
    xml_serializer = wsgi.XMLDictSerializer(attributes.get_attr_metadata())
    default_serializers = {'application/xml': xml_serializer,
                           'application/json': wsgi.JSONDictSerializer()}
    format_types = {'xml': 'application/xml',
                    '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())
        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 (exceptions.QuantumException,
                netaddr.AddrFormatError) as e:
            LOG.exception(_('%s failed'), action)
            body = serializer.serialize({'QuantumError': e})
            kwargs = {'body': body, 'content_type': content_type}
            for fault in faults:
                if isinstance(e, fault):
                    raise faults[fault](**kwargs)
            raise webob.exc.HTTPInternalServerError(**kwargs)
        except webob.exc.HTTPException as e:
            LOG.exception(_('%s failed'), action)
            e.body = serializer.serialize({'QuantumError': e})
            e.content_type = content_type
            raise
        except Exception as e:
            # NOTE(jkoelker) Everyting else is 500
            LOG.exception(_('%s failed'), action)
            # Do not expose details of 500 error to clients.
            msg = _('Request Failed: internal server error while '
                    'processing your request.')
            body = serializer.serialize({'QuantumError': msg})
            kwargs = {'body': body, 'content_type': content_type}
            raise webob.exc.HTTPInternalServerError(**kwargs)

        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
Beispiel #8
0
 def test_json_with_unicode(self):
     data = '{"a": "\u7f51\u7edc"}'
     as_dict = {'body': {'a': u'\u7f51\u7edc'}}
     deserializer = wsgi.JSONDeserializer()
     self.assertEqual(deserializer.deserialize(data), as_dict)
Beispiel #9
0
 def test_json_with_utf8(self):
     data = '{"a": "\xe7\xbd\x91\xe7\xbb\x9c"}'
     as_dict = {'body': {'a': u'\u7f51\u7edc'}}
     deserializer = wsgi.JSONDeserializer()
     self.assertEqual(deserializer.deserialize(data), as_dict)