def test_serialize_content_type_json(self): """Test serialize with content type json.""" input_data = {'servers': ['test=pass']} content_type = 'application/json' serializer = wsgi.Serializer() result = serializer.serialize(input_data, content_type) self.assertEqual('{"servers": ["test=pass"]}', result)
def test_deserialize_raise_bad_request(self): """Test serialize verifies that exception is raises.""" content_type = 'application/unknown' data_string = 'test' serializer = wsgi.Serializer() self.assertRaises(webob.exc.HTTPBadRequest, serializer.deserialize, data_string, content_type)
def serialize(self, data): '''Serializes a dictionary with a single key.''' if isinstance(data, dict): return wsgi.Serializer().serialize(data, self.content_type()) elif data: raise TypeError(_("unable to serialize object type: '%s'") % type(data))
def test_serialize_unknown_content_type(self): """Verify that exception InvalidContentType is raised.""" input_dict = {'servers': {'test': 'pass'}} content_type = 'application/unknown' serializer = wsgi.Serializer() self.assertRaises(exception.InvalidContentType, serializer.serialize, input_dict, content_type)
def test_get_deserialize_handler_unknown_content_type(self): """Verify that exception InvalidContentType is raised.""" content_type = 'application/unknown' serializer = wsgi.Serializer() self.assertRaises( exception.InvalidContentType, serializer.get_deserialize_handler, content_type)
def test_deserialize_json_content_type(self): """Test Serializer.deserialize with content type json.""" content_type = 'application/json' data_string = '{"servers": ["test=pass"]}' serializer = wsgi.Serializer() result = serializer.deserialize(data_string, content_type) self.assertEqual({'body': {u'servers': [u'test=pass']}}, result)
def _deserialize(self, data, status_code): """ Deserialize an XML string into a dictionary. :param data: XML string from the HTTP response :param status_code: integer status code from the HTTP response :return: data in the form of dict """ if status_code == 204: return data return wsgi.Serializer(self._serialization_metadata).deserialize( data, self._set_content_type('xml'))
def test_deserialize_xml_content_type(self): """Test deserialize with content type xml.""" content_type = 'application/xml' data_string = ('<servers xmlns="fake">' '<server>test=pass</server>' '</servers>') serializer = wsgi.Serializer(default_xmlns="fake", metadata={'xmlns': 'fake'}) result = serializer.deserialize(data_string, content_type) expected = {'body': {'servers': {'server': 'test=pass'}}} self.assertEqual(expected, result)
def _serialize(self, data): """ Serialize a dictionary with a single key into either xml or json. :param data: data in the form of dict """ if data is None: return None elif type(data) is dict: return wsgi.Serializer().serialize(data, self._set_content_type()) else: raise Exception( _("Unable to serialize object of type = '%s'") % type(data))
def _do_request(self, method, path, data=None, params=None, action=None): content_type = 'application/json' body = None if data is not None: # empty dict is valid body = wsgi.Serializer().serialize(data, content_type) req = testlib_api.create_request( path, body, content_type, method, query_string=params) res = req.get_response(self._api) if res.status_code >= 400: raise webexc.HTTPClientError(detail=res.body, code=res.status_code) if res.status_code != webexc.HTTPNoContent.code: return res.json
def test_serialize_xml_root_is_None(self): input_dict = {'test': 'pass'} content_type = 'application/xml' serializer = wsgi.Serializer(default_xmlns="fake") result = serializer.serialize(input_dict, content_type) result = result.replace('\n', '').replace(' ', '') expected = ('<?xmlversion=\'1.0\'' 'encoding=\'UTF-8\'?>' '<testxmlns="http://openstack.org/quantum/api/v2.0"' 'xmlns:quantum="http://openstack.org/quantum/api/v2.0"' 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' 'pass</test>') self.assertEqual(result, expected)
def test_serialize_content_type_xml(self): """Test serialize with content type xml.""" input_data = {'servers': ['test=pass']} content_type = 'application/xml' serializer = wsgi.Serializer(default_xmlns="fake") result = serializer.serialize(input_data, content_type) expected = ('<?xml version=\'1.0\'' ' encoding=\'UTF-8\'?>\n' '<servers xmlns="http://openstack.org/quantum/api/v2.0" ' 'xmlns:quantum="http://openstack.org/quantum/api/v2.0" ' 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' '<server>test=pass</server></servers>') self.assertEqual(expected, result)
def test_serialize_xml_root_key_is_dict(self): """Test Serializer.serialize with content type xml with meta dict.""" content_type = 'application/xml' data = {'servers': {'network': (2, 3)}} metadata = {'xmlns': 'fake'} serializer = wsgi.Serializer(default_xmlns="fake", metadata=metadata) result = serializer.serialize(data, content_type) result = result.replace('\n', '') expected = ('<?xml version=\'1.0\' encoding=\'UTF-8\'?>' '<servers xmlns="fake" xmlns:quantum="fake" ' 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' '<network>(2, 3)</network></servers>') self.assertEqual(result, expected)
def test_deserialize_xml_content_type_with_meta(self): """Test deserialize with content type xml with meta.""" content_type = 'application/xml' data_string = ('<servers>' '<server name="s1">' '<test test="a">passed</test>' '</server>' '</servers>') metadata = {'plurals': {'servers': 'server'}, 'xmlns': 'fake'} serializer = wsgi.Serializer(default_xmlns="fake", metadata=metadata) result = serializer.deserialize(data_string, content_type) expected = {'body': {'servers': [{'name': 's1', 'test': 'passed'}]}} self.assertEqual(expected, result)
def __call__(self, req): metadata = {} layout = [] for name, collection in six.iteritems(self.resources): href = urlparse.urljoin(req.path_url, collection) resource = {'name': name, 'collection': collection, 'links': [{'rel': 'self', 'href': href}]} layout.append(resource) response = dict(resources=layout) content_type = req.best_match_content_type() body = wsgi.Serializer(metadata=metadata).serialize(response, content_type) return webob.Response(body=body, content_type=content_type)
def deserialize(self, data, status_code): '''Deserializes an xml or json string into a dictionary.''' # NOTE(mb): Temporary fix for backend controller requirement data = data.replace("router_external", "router:external") if status_code == httplib.NO_CONTENT: return data try: deserialized_data = wsgi.Serializer( metadata=self._s_meta).deserialize(data, self.content_type()) deserialized_data = deserialized_data['body'] except Exception: deserialized_data = data return deserialized_data
def test_serialize_xml_root_key_is_list(self): """Test serialize with content type xml with meta list.""" input_dict = {'servers': ['test=pass']} content_type = 'application/xml' metadata = {'application/xml': {'xmlns': 'fake'}} serializer = wsgi.Serializer(default_xmlns="fake", metadata=metadata) result = serializer.serialize(input_dict, content_type) result = result.replace('\n', '').replace(' ', '') expected = ('<?xmlversion=\'1.0\'' 'encoding=\'UTF-8\'?>' '<serversxmlns="http://openstack.org/quantum/api/v2.0"' 'xmlns:quantum="http://openstack.org/quantum/api/v2.0"' 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' '<server>test=pass</server></servers>') self.assertEqual(result, expected)
def __call__(self, req): """Generate a WSGI response. Response is generated based on the exception passed to constructor. """ # Replace the body with fault details. code = self.wrapped_exc.status_int fault_name = self._fault_names.get(code, "neutronServiceFault") fault_data = { fault_name: { 'code': code, 'message': self.wrapped_exc.explanation } } # 'code' is an attribute on the fault tag itself content_type = req.best_match_content_type() self.wrapped_exc.body = wsgi.Serializer().serialize( fault_data, content_type) self.wrapped_exc.content_type = content_type return self.wrapped_exc
def __call__(self, req): """Respond to a request for all Neutron API versions.""" version_objs = [ { "id": "v2.0", "status": "CURRENT", }, ] if req.path != '/': language = req.best_match_language() msg = _('Unknown API version specified') msg = gettextutils.translate(msg, language) return webob.exc.HTTPNotFound(explanation=msg) builder = versions_view.get_view_builder(req) versions = [builder.build(version) for version in version_objs] response = dict(versions=versions) metadata = { "application/xml": { "attributes": { "version": ["status", "id"], "link": ["rel", "href"], } } } content_type = req.best_match_content_type() body = (wsgi.Serializer(metadata=metadata). serialize(response, content_type)) response = webob.Response() response.content_type = content_type response.body = body return response
def serialize(self, data): ctype = 'application/%s' % self.fmt result = wsgi.Serializer().serialize(data, ctype) return result
def serialize(self, data): ctype = 'application/%s' % self.fmt result = wsgi.Serializer(attributes.get_attr_metadata()).serialize( data, ctype) return result
def __call__(self, req): """ { "resources": [ { "links": [ { "href": "http://controller:9696/v2.0/subnets", "rel": "self" } ], "name": "subnet", "collection": "subnets" }, { "links": [ { "href": "http://controller:9696/v2.0/subnetpools", "rel": "self" } ], "name": "subnetpool", "collection": "subnetpools" }, { "links": [ { "href": "http://controller:9696/v2.0/networks", "rel": "self" } ], "name": "network", "collection": "networks" }, { "links": [ { "href": "http://controller:9696/v2.0/ports", "rel": "self" } ], "name": "port", "collection": "ports" } ] } """ metadata = {} layout = [] for name, collection in six.iteritems(self.resources): href = urlparse.urljoin(req.path_url, collection) resource = { 'name': name, 'collection': collection, 'links': [{ 'rel': 'self', 'href': href }] } layout.append(resource) response = dict(resources=layout) content_type = req.best_match_content_type() body = wsgi.Serializer(metadata=metadata).serialize( response, content_type) return webob.Response(body=body, content_type=content_type)