def test_circular_reference(self): data = { 'root' : { 'child_a' : 'text_a' } } data['root']['child_b'] = data['root'] with self.assertRaises(RuntimeError) as cm: simplexml.dumps(data, check_circular=False) self.assertGreaterEqual(cm.exception.message.find('maximum recursion depth exceeded'), 0)
def test_circular_reference(self): data = { 'root' : { 'child_a' : 'text_a' } } data['root']['child_b'] = data['root'] with self.assertRaises(ValueError) as cm: simplexml.dumps(data) self.assertGreaterEqual(cm.exception.message.find('Circular reference detected'), 0)
def test_can_dumps_node_with_root_attr(): sometag = { 'someTag': { '_attrs': { 'attr': 'value' }, 'name': 'Should be name', 'child': { 'id': 90 }, 'itens': [{ 'type': 'Should Be Type item1' }, { 'type': 'Should Be Type item2' }] } } response = simplexml.dumps(sometag) assert '<someTag attr="value">' in response assert '<child><id>90</id></child>' in response assert '<itens><iten><type>Should Be Type item1</type></iten><iten><type>Should Be Type item2</type></iten></itens>' in response assert '<name>Should be name</name>' in response assert '</someTag>' in response
def output_xml(app, data, code, headers=None): """Makes a Flask response with a XML encoded body""" resp = HTTPResponse(dumps({'response': data}), status=code, headers=headers) resp.headers.extend(headers or {}) return resp
def post(self, response_format): data = estimator(request.get_json(force=True)) if response_format == 'xml': response = make_response(dumps({'response': data}), 200) response.headers['content-type'] = 'application/xml' return response return data
def upload(self, file_name, dirname, title, description, channel, privacy=0, metatags=''): video_dados = { 'video': { 'titulo': title, 'descricao': description, 'canal': channel, 'privacidade': privacy, 'metatags': metatags } } headers = { 'Content-Type': "application/x-www-form-urlencoded" } content = self._make_request('POST', '/video.xml', params=simplexml.dumps(video_dados), headers=headers) video_uuid = simplexml.loads(content)['video']['uuid'] file_path = "%s/%s" % (dirname.rstrip('/'), file_name) if not os.path.isfile(file_path): raise ValueError("File does not exist %s" % file_path) file_data = open(file_path).read() try: self.post_multipart(selector='/video/%s/upload' % video_uuid, files=(("video", file_name, file_data),), headers=headers) return True except APIError, e: _logger.info("Error uploading video %s: %s" % (file_name, e)) return False
def test_item_sort_key(self): data = { 'root' : { 'child_a' : 'text_a', 'child_b' : {'_attr' : {'id' : "b"}, '_text' : 'text_b'}, 'child_c' : {'_attr' : {'id' : "c"}, '_text' : 'text_c'}, 'child_d' : 'text_d', 'child_1' : {'_attr' : {'id' : "1"}, '_text' : 'text_1'}, } } def get_attr(kv): key, value = kv if isinstance(value, dict): if value.has_key('_attr'): return value['_attr']['id'] return key item_sort_key = lambda kv : get_attr(kv) xml = simplexml.dumps(data, item_sort_key=get_attr) expected_xml = '''<root> <child_1 id="1">text_1</child_1> <child_b id="b">text_b</child_b> <child_c id="c">text_c</child_c> <child_a>text_a</child_a> <child_d>text_d</child_d> </root>''' expected_xml = re.sub('\n *', '', expected_xml) self.assertEqual(xml, expected_xml)
def export(request: HttpRequest, data, name): if request.method == 'GET': data = {name: [{name[0:name.__len__() - 1]: dict_from_class(el)} for el in data]} export = simplexml.dumps(data) response = HttpResponse(export, content_type='application/json') response['Content-Disposition'] = 'attachment; filename="%s.xml"' % (name) return response
def test_can_dumps_with_node_value(): sometag = { 'someTag': { 'name': 'Should be name', 'child': { 'id': 90 }, 'item': [{ 'type': { '_attrs': { 'id': 1 }, '_value': 'Should Be Type item1' } }, { 'type': 'Should Be Type item2' }] } } response = simplexml.dumps(sometag) assert '<item><type id="1">Should Be Type item1</type></item><item><type>Should Be Type item2</type></item>' in response assert '<name>Should be name</name>' in response assert '<child><id>90</id></child>' in response
def xml(data, code, headers): data[DATA][TEXT] = { 'line-' + str(num): item for num, item in enumerate(data[DATA][TEXT]) } myResponse = make_response(dumps({'response': data}), code) myResponse.headers.extend(headers) return myResponse
def test_can_dumps_with_node_value(): sometag = {'someTag': {'name': 'Should be name', 'child': {'id': 90}, 'item': [{'type': {'_attrs': {'id': 1}, '_value': 'Should Be Type item1'}}, {'type': 'Should Be Type item2'}]}} response = simplexml.dumps(sometag) assert '<item><type id="1">Should Be Type item1</type></item><item><type>Should Be Type item2</type></item>' in response assert '<name>Should be name</name>' in response assert '<child><id>90</id></child>' in response
def test_can_dumps_diff_cdata(): sometag = {'someTag': {'value': 'hello world', 'scaped': 'Should Be <b>bold</b>'}} response = simplexml.dumps(sometag) assert '<someTag><' in response assert '></someTag>' in response assert '<scaped><![CDATA[Should Be <b>bold</b>]]></scaped>' in response assert '<value>hello world</value>' in response
def export(request, data, dbmodelname): if request.method == 'GET': data = {dbmodelname: [{dbmodelname[:-1]: el} for el in data]} xml_to_export = simplexml.dumps(data) response = HttpResponse(xml_to_export, content_type='application/json') response[ 'Content-Disposition'] = 'attachment; filename="%s.xml"' % dbmodelname return response return HttpResponse(status=400)
def post_xml(): # get the json string from the request body req_data = request.get_json() req_time = datetime.now(tz=timezone.utc).timestamp() * 1000 route = request.path rsp = process(req_time, route, req_data) """Makes a Flask response with a XML encoded body""" resp = make_response(dumps({'estimation': rsp})) resp.headers.extend({"mimetype": "text/xml"}) return resp
def test_can_dumps(): sometag = {'someTag': {'name': 'Should be name', 'child': {'id': 90}, 'itens': [{'type': 'Should Be Type item1'}, {'type': 'Should Be Type item2'}]}} response = simplexml.dumps(sometag) assert '<someTag><' in response assert '></someTag>' in response assert '<itens><iten><type>Should Be Type item1</type></iten><iten><type>Should Be Type item2</type></iten></itens>' in response assert '<name>Should be name</name>' in response assert '<child><id>90</id></child>' in response
def test_can_dumps_node_with_root_attr(): sometag = {'someTag': {'_attrs': {'attr': 'value'}, 'name': 'Should be name', 'child': {'id': 90}, 'itens': [{'type': 'Should Be Type item1'}, {'type': 'Should Be Type item2'}]}} response = simplexml.dumps(sometag) assert '<someTag attr="value">' in response assert '<child><id>90</id></child>' in response assert '<itens><iten><type>Should Be Type item1</type></iten><iten><type>Should Be Type item2</type></iten></itens>' in response assert '<name>Should be name</name>' in response assert '</someTag>' in response
def output_xml(data, code, headers=None): """Outputs data in XML format :param data: output data :param code: HTTP code :param headers: None or XML format :return: response """ response = make_response(simplexml.dumps({'response': data}), code) response.headers.extend(headers or {}) return response
def output_xml(data, code, headers=None): """ Makes a Flask response with a XML encoded body. :param data: Payload used for generating a xml formatted response. :param code: HTTP status code. :param headers: HTTP extra headers. :return: Properly xml encoded response. """ resp = make_response(dumps({'response': data}), code) resp.headers.extend(headers or {}) return resp
def save_config(config, directory="."): """ save PGEMConfig in dict format to xml :param config: dict to save to xml :param directory: directory to store all the xml files :return: xml string """ filename = config["partnumber"] + "-" + config["revision"] + ".xml" filepath = os.path.join(directory, filename) result = dumps(config, "entity") with open(filepath, "wb") as f: f.truncate() f.write(result) return result
def test_can_dumps_diff_cdata(): sometag = { 'someTag': { 'value': 'hello world', 'scaped': 'Should Be <b>bold</b>' } } response = simplexml.dumps(sometag) assert '<someTag><' in response assert '></someTag>' in response assert '<scaped><![CDATA[Should Be <b>bold</b>]]></scaped>' in response assert '<value>hello world</value>' in response
def test_can_loads_attributes(): docxml = u'<?xml version="1.0" ?><tags><tag attr="should be tag value"/><tag attr="value2">value3</tag></tags>' response = simplexml.loads(docxml) assert type(response['tags']) == list assert type(response['tags'][0]) == dict assert response['tags'][0]['tag']['_attrs']['attr'] == 'should be tag value' assert response['tags'][1]['tag']['_attrs']['attr'] == 'value2' assert response['tags'][1]['tag']['_value'] == 'value3' final_docxml = simplexml.dumps(response) assert docxml == final_docxml
def post(self, tiporegla_id, regla_id): if request.content_type == 'application/json': json_data = request.get_json(force=True) json_str = json.dumps(json_data) data = app.get_resul_regla(json_str, tiporegla_id, regla_id) return data else: if request.content_type == 'application/xml': xml_str = request.get_data() xml_data = simplexml.loads(xml_str) data = app.get_resul_regla(str(simplexml.dumps(xml_data)), tiporegla_id, regla_id) return data else: return {'status': 'error', 'message': 'formato no implementado'}
def test_can_dumps_with_first_node_list(): sometag = { 'someTags': [{ 'someTag': { 'nome': 'Should Be Nome' } }, { 'someTag': { 'nome': 'Should Be Nome' } }] } response = simplexml.dumps(sometag) assert '<someTags><someTag><nome>Should Be Nome</nome></someTag><someTag><nome>Should Be Nome</nome></someTag></someTags>' in response
def test_can_upload_video(self, HTTPConnection): expected_response = {"video": {"uuid": "shouldBeUUID"}} file_name = 'ShouldBeFileName' dirname = 'ShouldBeDirName' title = 'ShouldBeTitle' description = 'ShouldBeDescription' channel = 'ShouldBeChannel' privacy = 0 metatags = 'ShouldBeMetatags' video_dados = { 'video': { 'titulo': title, 'descricao': description, 'canal': channel, 'privacidade': privacy, 'metatags': metatags } } headers = { 'Token': 'shouldBeToken', 'Autenticacao': 'shouldBeAuth', 'Content-Type': 'application/x-www-form-urlencoded' } self.httpconnection_mock(HTTPConnection, 'POST', '<api_url>', '/video.xml', simplexml.dumps(video_dados), headers, simplexml.dumps(expected_response)) video_api = Video("<api_url>", "shouldBeToken") video_api._auth_hash = 'shouldBeAuth' video_api.post_multipart = fudge.Fake(callable=True) os_fake = fudge.Fake(callable=True) os_fake.path = fudge.Fake(callable=True) os_fake.path.isfile = fudge.Fake(callable=True).returns(True) with fudge.patched_context(video, "os", os_fake): with fudge.patch("__builtin__.open") as open_fake: open_fake.is_callable().with_args('ShouldBeDirName/ShouldBeFileName').returns_fake().expects('read').returns('shouldBeFileData') video_upload = video_api.upload(file_name=file_name, dirname=dirname, title=title, description=description, channel=channel, privacy=privacy, metatags=metatags) self.assertTrue(video_upload)
def test_can_dumps_with_list_non_plural(): sometag = { 'someTag': { 'name': 'Should be name', 'child': { 'id': 90 }, 'item': [{ 'type': 'Should Be Type item1' }, { 'type': 'Should Be Type item2' }] } } response = simplexml.dumps(sometag) assert '<item><type>Should Be Type item1</type></item><item><type>Should Be Type item2</type></item>' in response
def create_response(data): items_list = [] for x in data: items_list.append({ 'id': x[0], 'date_time': str(x[1]), 'address': x[2], 'city': x[3], 'caller_id': x[4], 'additional_information': x[5], 'name': x[7], 'last_name': x[8], 'phone': x[9] }) return dumps( {'response': { 'items': items_list, 'items_count': len(items_list) }})
def test_encode(self): data = { 'root' : { 'child_a' : 'text_a', 'child_b' : ['text_b1', 'text_b2'], 'child_c' : [ {'_attr' : {'id' : 'id_c1'}, '_text' : 'text_c1'}, {'_text' : 'text_c2'}, {'child_d' : [ {'_attr' : {'id' : 'id_d1'}, '_text' : 'text_d1'}, 'text_d2', ]}, ], 'child_e' : { '_attr': {'id': 'id_e'}, '_text': 'text_e', 'child_f' : {'_attr': {'class': 'class_f', 'id': 'id_f'}}, 'child_g' : {"_cdata": "<ha>haha</ha>"}, } } } xml = simplexml.dumps(data, sort_keys=True) expected_xml = '''<root> <child_a>text_a</child_a> <child_b>text_b1</child_b> <child_b>text_b2</child_b> <child_c id="id_c1">text_c1</child_c> <child_c>text_c2</child_c> <child_c> <child_d id="id_d1">text_d1</child_d> <child_d>text_d2</child_d> </child_c> <child_e id="id_e"> text_e <child_f class="class_f" id="id_f"/> <child_g><![CDATA[<ha>haha</ha>]]></child_g> </child_e> </root>''' expected_xml = re.sub('\n *', '', expected_xml) self.assertEqual(xml, expected_xml)
def test_return_element(self): data = { 'root' : { 'child_a' : 'text_a', 'child_b' : {'_attr' : {'id' : "b"}, '_text' : 'text_b'}, 'child_c' : {'_attr' : {'id' : "c"}, '_text' : 'text_c'}, 'child_d' : 'text_d', 'child_1' : {'_attr' : {'id' : "1"}, '_text' : 'text_1'}, } } root = simplexml.dumps(data, sort_keys=True, return_element=True) expected_xml = '''<root> <child_1 id="1">text_1</child_1> <child_a>text_a</child_a> <child_b id="b">text_b</child_b> <child_c id="c">text_c</child_c> <child_d>text_d</child_d> </root>''' expected_xml = re.sub('\n *', '', expected_xml) self.assertEqual(etree.tostring(root), expected_xml)
def test_can_dumps(): sometag = { 'someTag': { 'name': 'Should be name', 'child': { 'id': 90 }, 'itens': [{ 'type': 'Should Be Type item1' }, { 'type': 'Should Be Type item2' }] } } response = simplexml.dumps(sometag) assert '<someTag><' in response assert '></someTag>' in response assert '<itens><iten><type>Should Be Type item1</type></iten><iten><type>Should Be Type item2</type></iten></itens>' in response assert '<name>Should be name</name>' in response assert '<child><id>90</id></child>' in response
def output_xml(data, code, headers=None): resp = make_response(simplexml.dumps({'root': data}), code) resp.headers.extend(headers or {}) return resp
def dict2xmlbody(self, dic): return simplexml.dumps(dic)
def output_xml(data, code, headers=None): resp = flask.make_response(simplexml.dumps({'response': data}), code) resp.headers.extend(headers or {}) return resp
def test_can_dumps_with_first_node_list(): sometag = {'someTags':[{'someTag':{'nome':'Should Be Nome'}} , {'someTag':{'nome':'Should Be Nome'}}]} response = simplexml.dumps(sometag) assert '<someTags><someTag><nome>Should Be Nome</nome></someTag><someTag><nome>Should Be Nome</nome></someTag></someTags>' in response
def test_can_dumps_with_list_non_plural_with_attrs(): sometag = {'someTag':{'name':'Should be name', 'child':{'id':90},'item':[{'_attrs':{'attr':'value'}, 'type':'Should Be Type item1'},{'type':'Should Be Type item2'}]}} response = simplexml.dumps(sometag) assert '<someTag><item attr="value"><type>Should Be Type item1</type></item><item><type>Should Be Type item2</type></item><name>Should be name</name><child><id>90</id></child></someTag>' in response
def output_xml(data, code, headers=None): """Makes a Flask response with a XML encoded body""" resp = make_response(dumps({'response': data}), code) resp.headers.extend(headers or {}) return resp
def output_xml(data, code, headers=None): resp = make_response(dumps(data), code) resp.headers.extend(headers or {}) return resp
def get_estimation_xml(): req_data = request.get_json() res = dumps({'response': estimator(req_data)}) return res
def render_to_xml(self, data, request_handler=None, **kw): assert simplexml, "Module simplexml needs to be installed to use this method" self.set_header("Content-Type", "text/xml; charset=UTF-8") return simplexml.dumps(data)
def get_estimate_xml(): req_data = request.get_json() res = dumps({"response": estimator(req_data)}) return res
def output_xml(data, code, headers=None): """Makes a Flask response with a XML encoded body""" result = make_response(dumps({'response': data}), code) result.headers.extend(headers or {}) return result
def output_xml(data, code, headers=None): resp = make_response(dumps({'root': data}), code) resp.headers.extend({"content-type": "application/xml"}) return resp
def test_can_dumps_with_list_non_plural(): sometag = {'someTag': {'name': 'Should be name', 'child': {'id': 90}, 'item': [{'type': 'Should Be Type item1'}, {'type': 'Should Be Type item2'}]}} response = simplexml.dumps(sometag) assert '<item><type>Should Be Type item1</type></item><item><type>Should Be Type item2</type></item>' in response
def render_to_xml(self, data, request_handler, **kw): request_handler.set_header("Content-Type", "text/xml; charset=UTF-8") return simplexml.dumps(data)
''' from lib import HttpUtil, Util from isp import Define, XPath from isp.nsmUtil import NsmUtil from pprint import pprint from isp.responseVerification import ResponseVerification import simplexml if __name__ == '__main__': person = {'person':{'name':'joaquim','age':15,'cars':[{'id':1},{'id':2}]}} print simplexml.dumps(person) person = simplexml.loads('<?xml version="1.0" ?><person><cars><car><id>1</id></car><car><id>2</id></car></cars><age>15</age><name>joaquim</name></person>') print person['person']['name'] print person filePath = '/Users/huhe/Install/workspace/NSM-NBAPI-Jython/response/create/response-create-default/My-Default-Internet-Edge-Zone-Layer-3-VLAN-create-001.xml' result = simplexml.loads(Util.readFile(filePath)) print result print result['task']['result']['name'] print result['task']['result']['properties']
def xml_response(data, code=200): ''' Return Response object wich containce XML ''' resp = make_response(dumps({'response': data}), code) resp.headers['Content-Type'] = 'application/xml' return resp
def output_xml(data, status=200, headers=None): resp = make_response(dumps(dict(result=data)), status) resp.headers.extend(headers or {}) return resp