Best Python code snippet using tavern
ParseXML.py
Source:ParseXML.py
1"""2Copyright 2008, 2015 Free Software Foundation, Inc.3This file is part of GNU Radio4GNU Radio Companion is free software; you can redistribute it and/or5modify it under the terms of the GNU General Public License6as published by the Free Software Foundation; either version 27of the License, or (at your option) any later version.8GNU Radio Companion is distributed in the hope that it will be useful,9but WITHOUT ANY WARRANTY; without even the implied warranty of10MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the11GNU General Public License for more details.12You should have received a copy of the GNU General Public License13along with this program; if not, write to the Free Software14Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA15"""16from lxml import etree17from .utils import odict18xml_failures = {}19etree.set_default_parser(etree.XMLParser(remove_comments=True))20class XMLSyntaxError(Exception):21 def __init__(self, error_log):22 self._error_log = error_log23 xml_failures[error_log.last_error.filename] = error_log24 def __str__(self):25 return '\n'.join(map(str, self._error_log.filter_from_errors()))26def validate_dtd(xml_file, dtd_file=None):27 """28 Validate an xml file against its dtd.29 Args:30 xml_file: the xml file31 dtd_file: the optional dtd file32 @throws Exception validation fails33 """34 # Perform parsing, use dtd validation if dtd file is not specified35 parser = etree.XMLParser(dtd_validation=not dtd_file)36 try:37 xml = etree.parse(xml_file, parser=parser)38 except etree.LxmlError:39 pass40 if parser.error_log:41 raise XMLSyntaxError(parser.error_log)42 # Perform dtd validation if the dtd file is specified43 if not dtd_file:44 return45 try:46 dtd = etree.DTD(dtd_file)47 if not dtd.validate(xml.getroot()):48 raise XMLSyntaxError(dtd.error_log)49 except etree.LxmlError:50 raise XMLSyntaxError(dtd.error_log)51def from_file(xml_file):52 """53 Create nested data from an xml file using the from xml helper.54 Also get the grc version information.55 Args:56 xml_file: the xml file path57 Returns:58 the nested data with grc version information59 """60 xml = etree.parse(xml_file)61 nested_data = _from_file(xml.getroot())62 # Get the embedded instructions and build a dictionary item63 nested_data['_instructions'] = {}64 xml_instructions = xml.xpath('/processing-instruction()')65 for inst in filter(lambda i: i.target == 'grc', xml_instructions):66 nested_data['_instructions'] = odict(inst.attrib)67 return nested_data68def _from_file(xml):69 """70 Recursively parse the xml tree into nested data format.71 Args:72 xml: the xml tree73 Returns:74 the nested data75 """76 tag = xml.tag77 if not len(xml):78 return odict({tag: xml.text or ''}) # store empty tags (text is None) as empty string79 nested_data = odict()80 for elem in xml:81 key, value = _from_file(elem).items()[0]82 if key in nested_data:83 nested_data[key].append(value)84 else:85 nested_data[key] = [value]86 # Delistify if the length of values is 187 for key, values in nested_data.iteritems():88 if len(values) == 1:89 nested_data[key] = values[0]90 return odict({tag: nested_data})91def to_file(nested_data, xml_file):92 """93 Write to an xml file and insert processing instructions for versioning94 Args:95 nested_data: the nested data96 xml_file: the xml file path97 """98 xml_data = ""99 instructions = nested_data.pop('_instructions', None)100 # Create the processing instruction from the array101 if instructions:102 xml_data += etree.tostring(etree.ProcessingInstruction(103 'grc', ' '.join(104 "{0}='{1}'".format(*item) for item in instructions.iteritems())105 ), xml_declaration=True, pretty_print=True, encoding='utf-8')106 xml_data += etree.tostring(_to_file(nested_data)[0],107 pretty_print=True, encoding='utf-8')108 with open(xml_file, 'w') as fp:109 fp.write(xml_data)110def _to_file(nested_data):111 """112 Recursively parse the nested data into xml tree format.113 Args:114 nested_data: the nested data115 Returns:116 the xml tree filled with child nodes117 """118 nodes = list()119 for key, values in nested_data.iteritems():120 # Listify the values if not a list121 if not isinstance(values, (list, set, tuple)):122 values = [values]123 for value in values:124 node = etree.Element(key)125 if isinstance(value, (str, unicode)):126 node.text = unicode(value)127 else:128 node.extend(_to_file(value))129 nodes.append(node)...
call_for_help.py
Source:call_for_help.py
1test_json = {"records": "563",2 "campaign": [{"id":"2027698","title":"OMFM Client Jet Charter 3 - Smart Inbox intro (average) GLOCKTEST alignable","status":"Completed","scheduledate":"December 13, 2018, 11:23:00 am","starttime":"December 13, 2018, 11:24:24 am","endtime":"December 13, 2018, 11:26:12 am","lastupdate":{},"sent":"41","views":"4","clicks":"3","optouts":"0","conversions":"0"},3 {"id":"2027689","title":"OMFM Client Jet Charter 3 - Smart Inbox intro (average) GLOCKTEST no links","status":"Completed","scheduledate":"December 13, 2018, 10:29:00 am","starttime":"December 13, 2018, 10:30:24 am","endtime":"December 13, 2018, 10:32:10 am","lastupdate":{},"sent":"41","views":"1","clicks":"0","optouts":"0","conversions":"0"}]4 }5def data_multiplication(initial_nested_data):6 out = [{}]7 def data_multiplication_(nested_data):8 if isinstance(nested_data, list) and len(nested_data) > 0:9 base_dic = out[-1]10 print('match')11 print(base_dic)12 for x in nested_data:13 data_multiplication_(x)14 print(base_dic)15 out.append(base_dic)16 elif isinstance(nested_data, dict) or len(nested_data) == 0:17 for x in nested_data:18 if (isinstance(nested_data[x], list) or isinstance(nested_data[x], dict)) and len(nested_data[x]) > 0:19 data_multiplication_(nested_data[x])20 else:21 out[-1][x] = nested_data[x]22 data_multiplication_(initial_nested_data)23 return out24if __name__ == '__main__':...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!