def servicecontent2xml(): # https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch06s05.html elem = E('returnval') #elem = E() for k, v in servicecontent.items(): child = E(k) if type(v.get('value', None)) == dict: for k2, v2 in v['value'].items(): newchild = E(k2) newchild.text = v2 child.append(newchild) else: child.text = v.get('value', capfirst(k)) if v.get('type') != 'UNSET': child.set('type', v.get('type', capfirst(k))) elem.append(child) # http://stackoverflow.com/questions/749796/pretty-printing-xml-in-python rxml = xml.dom.minidom.parseString(TS(elem)) pxml = rxml.toprettyxml() # get rid of the xml header lines = [x for x in pxml.split('\n')] pxml = '\n'.join(lines[1:]) return pxml
def _detail2xml(self, tag, name, value): r = E(tag, {'name': name}) if isinstance(value, (dict, tuple, list)): r = self._build_xml(r, value) else: r.attrib['value'] = value return r
def _get_test_case_element(self, test): return E( 'testcase', dict(name=str(test), classname="{}.{}".format(test.__class__.__module__, test.__class__.__name__), time="0"))
def _add_error(self, errortype): exc_type, exc_value, exc_tb = exc_info = sys.exc_info() test_element = self._xunit_elements[-1] error_element = E(errortype, dict(type=exc_type.__name__, message=str(exc_value))) error_element.text = get_traceback_string(exc_info) test_element.append(error_element)
def probe_metric(service_url, metric): ''' Query the service at the given URL for the given metric value. Assumptions are made about the name of the method and output parameters which are only valid for the WanCommonInterfaceConfig service. ''' envelope = E( QName(ns['s'], 'Envelope'), { QName(ns['s'], 'encodingStyle'): 'http://schemas.xmlsoap.org/soap/encoding/' }) body = sE(envelope, QName(ns['s'], 'Body')) method = sE(body, QName(ns['i'], 'Get{}'.format(metric))) request_tree = ET(envelope) with io.BytesIO() as out: out.write(b'<?xml version="1.0"?>') request_tree.write(out, encoding='utf-8') out.write(b'\r\n') # or else my Belkin F5D8236-4 never responds... req = urllib.request.Request(service_url, out.getvalue()) req.add_header('Content-Type', 'text/xml') req.add_header('SOAPAction', '"{}#{}"'.format(ns['i'], 'Get{}'.format(metric))) with urllib.request.urlopen(req) as result: result_tree = ElementTree.parse(result) return int( result_tree.findtext('.//New{}'.format(metric), namespaces=ns))
def mergeLogs(fromFilePath, toFilePath, outputFilePath): utf8open = lambda s: open(s, 'r', 'utf8') outputDoc = E('html') with utf8open(fromFilePath) as fromFile, utf8open(toFilePath) as toFile: # the body and HTML tags are left open so the app can just append # when a new message comes in. we have to close them. # note: this could also be taken care of by BeautifulSoup or # perhaps lxml.html fromDoc = fromstring(fromFile.read() + '</BODY></HTML>') toDoc = fromstring(toFile.read() + '</BODY></HTML>') # copy the head tag so formatting and stuff is preserved in our new doc outputDoc.append(fromDoc.find('HEAD').copy()) fromMessages = fromDoc.findall('./BODY/div') toMessages = toDoc.findall('./BODY/div') allMessages = list(fromMessages) + list(toMessages) allMessages.sort(key=lambda e: time.strptime(e.attrib['timestamp'], '%Y-%m-%d %H:%M:%S')) body = SE(outputDoc, 'BODY', attrib=fromDoc.find('BODY').attrib) body.extend(x.copy() for x in allMessages) ElementTree(outputDoc).write(outputFilePath, 'utf8')
def session_end(self): if config.root.parallel.worker_id is not None: return suite_time = sum([ result.get_duration() for result in context.session.results.iter_test_results() ], datetime.timedelta()).total_seconds() e = E( 'testsuite', { "name": "slash-suite", "hostname": socket.getfqdn(), "timestamp": self._start_time.isoformat().rsplit(".", 1)[0], "time": str(suite_time), "tests": str(context.session.results.get_num_results()), "errors": str(context.session.results.get_num_errors()), "failures": str(context.session.results.get_num_failures()), "skipped": str(context.session.results.get_num_skipped()), }) self._add_errors(e, context.session.results.global_result) for result in context.session.results.iter_test_results(): test = E( "testcase", { "name": result.test_metadata.address, "classname": result.test_metadata.class_name or '', "time": str(result.get_duration().total_seconds()) }) self._add_errors(test, result) for skip in result.get_skips(): self._add_element(test, 'skipped', {'type': skip or ''}) for detail_name, detail_value in result.details.all().items(): if not isinstance(detail_value, list): detail_value = [detail_value] for value in detail_value: value = self._detail2xml('detail', detail_name, value) test.append(value) e.append(test) with open(slash_config.root.plugin_config.xunit.filename, "wb") as outfile: outfile.write(xml_to_string(e))
def test_start(self): self._xunit_elements.append( E( "testcase", { "name": str(context.test), "classname": type(context.test).__name__, "time": "0" }))
def _add_element(self, tag, attrib, text=None): if not context.test: return test_element = self._get_xunit_elements_list()[-1] element = E(tag, attrib) if text is not None: element.text = text test_element.append(element)
def test_start(self): self._get_xunit_elements_list().append( E( "testcase", { "name": context.test.__slash__.address, "classname": context.test.__slash__.class_name or '', "time": "0" }))
def session_end(self): if config.root.parallel.worker_id is not None: return e = E('testsuite', { "name": "slash-suite", "hostname": socket.getfqdn(), "timestamp": self._start_time.isoformat().rsplit(".", 1)[0], "time": "0", "tests": str(context.session.results.get_num_results()), "errors": str(context.session.results.get_num_errors()), "failures": str(context.session.results.get_num_failures()), "skipped": str(context.session.results.get_num_skipped()), }) self._add_errors(e, context.session.results.global_result) for result in context.session.results.iter_test_results(): test = E("testcase", { "name": result.test_metadata.address, "classname": result.test_metadata.class_name or '', "time": "0" }) self._add_errors(test, result) for skip in result.get_skips(): self._add_element(test, 'skipped', {'type': skip or ''}) for detail_name, detail_value in result.details.all().items(): self._add_element(test, 'detail', {'name': detail_name, 'value': detail_value}) e.append(test) with open(slash_config.root.plugin_config.xunit.filename, "wb") as outfile: outfile.write(xml_to_string(e))
def result_summary(self): e = E('testsuite', { "name": "slash-suite", "hostname": socket.getfqdn(), "timestamp": self._start_time.isoformat().rsplit(".", 1)[0], "time": "0", "tests": str(context.session.results.get_num_results()), "errors": str(context.session.results.get_num_errors()), "failures": str(context.session.results.get_num_failures()), "skipped": str(context.session.results.get_num_skipped()), }) for element in self._get_xunit_elements_list(): e.append(element) with open(slash_config.root.plugin_config.xunit.filename, "wb") as outfile: outfile.write(xml_to_string(e))
from pprint import pprint import xml.etree.ElementTree as ET from xml.etree.ElementTree import Element as E from xml.etree.ElementTree import tostring as TS f = open('fixtures/vc550_RetrievePropertiesExResponse.xml', 'r') fdata = f.read() f.close() # let's try to deserialize and reserialize this resp fdata = fdata.replace('\n', '') root = ET.fromstring(fdata) # make some fake VMs for x in range(1, 2): vm = E('ManagedObjectReference') vm.text = 'vm-%s' % x vm.set('type', 'VirtualMachine') vm.set('xsi:type', 'ManagedObjectReference') #root[0][0][0][0][0].append(vm) root[0][0][0] #returnval root[0][0][0][0] #objects root[0][0][0][0][0] #obj:containerview root[0][0][0][0][1] #propset root[0][0][0][0][1][0] #name root[0][0][0][0][1][1] #val root[0][0][0][0][1][1].append(vm) import pdb pdb.set_trace()
def _add_element(self, parent, tag, attrib, text=None): element = E(tag, attrib) if text is not None: element.text = text parent.append(element)
def test_skip(self, reason): test_element = self._xunit_elements[-1] test_element.append(E('skipped', type=reason))
def test_skip(self, reason): test_element = self._get_xunit_elements_list()[-1] test_element.append(E('skipped', type=reason or ''))