def setup(self, src_file, save_path, **kwargs): """src_file: the xml file you want parser save_path: where the xml file you want save after parser """ self._src_path = src_file self._save_path = save_path self._xml_inst = XML() self._xml_parser = self._xml_inst.parse_xml(self._src_path)
def __init__(self): Screenshot.__init__(self, "C:\\Keyword\\Results") XML.__init__(self, use_lxml=True) """CommonUtil.__init__(self, None, dict , False)""" Telnet.__init__(self, timeout='3 seconds', newline='CRLF', prompt=None, prompt_is_regexp=False, encoding='UTF-8', encoding_errors='ignore', default_log_level='INFO') Process.__init__(self) """Also this doc should be in shown in library doc."""
def __init__(self): self._xml = XML() self._builtin = BuiltIn() self._cache = ConnectionCache()
class SOAP(object): def __init__(self): self._xml = XML() self._builtin = BuiltIn() self._cache = ConnectionCache() def create_soap_client(self, alias, wsdl=None, endpoint=None): """ Creates SOAP client with specified alias. Arguments: | alias | client alias | | wsdl | path or url to service wsdl | | endpoint | url for service under test | Example usage: | Create Soap Client | client_alias | wsdl=path_to_wsdl${/}ws_example.wsdl | endpoint=http://localhost:8080/ | """ session = Session() session.verify = False if wsdl: wsdl = self._get_wsdl(session, wsdl) client = SOAPClient(session, wsdl, endpoint) self._cache.register(client, alias) def call_soap_method(self, alias, name, message, replace=None, endpoint=None, expect_fault=False, xml=True): """ Call SOAP method. Arguments: | alias | client alias | | name | method name | | message | path to SOAP message or SOAP message | | replace | dictionary of old_value: new_value pairs for replace in message | | endpoint | url for service under test, rewrites client endpoint | | expect_fault | if True, not raise exception when receive fault | | xml | return type, if True - return xml object (XML library format), False - string | Example usage: | ${replace} | Create Dictionary | _id_ | 64 | | ${response} | Call Soap Method | client_alias | getUserName | path_to_soap_message${/}example.xml | replace=${replace} | expect_fault=False | xml=True | | Element Should Exist | ${response} | .//{http://www.example.ru/example}requestResult | """ client = self._cache.switch(alias) if endpoint: client.endpoint = endpoint try: ET.fromstring(message) except ET.ParseError: if not path.isfile(message): raise IOError("File not found or message is not well-formed" % message) message = open(message, mode="r", encoding="utf-8").read() if replace: for k, v in replace.items(): message = message.replace(k, v) status_code, response = self._call(client, name, message) expect_fault = self._builtin.convert_to_boolean(expect_fault) is_fault = self._is_fault(status_code) if is_fault and not expect_fault: raise AssertionError("The server did not raise a fault") elif expect_fault and not is_fault: raise AssertionError("The server not raise a fault") if self._builtin.convert_to_boolean(xml): return self._xml.parse_xml(response, keep_clark_notation=True) else: return response @staticmethod def _get_wsdl(session, url_or_path): if not urlparse(url_or_path).scheme: if not path.isfile(url_or_path): raise IOError("File '%s' not found" % url_or_path) wsdl = open(url_or_path, mode="r", encoding="utf-8").read() else: response = session.get(url_or_path) if response.status_code != 200: raise ConnectionError("Server not found or resource '%s' is not available" % url_or_path) wsdl = response.content.decode("utf-8") return wsdl @staticmethod def _is_fault(status_code): if status_code == 200: return False else: return True def _get_soap_action(self, wsdl, name): root = self._xml.parse_xml(wsdl) xpath = ".//*[@name='%s']/operation" % name return self._xml.get_element_attribute(root, "soapAction", xpath=xpath) def _call(self, client, name, message): if client.wsdl: action = self._get_soap_action(client.wsdl, name) else: action = "" headers = {"Accept-Encoding": "gzip,deflate", "Content-Type": "text/xml;charset=UTF-8", "Connection": "Keep-Alive", "SOAPAction": action} logger.info("Execution '%s' soap method" % name) response = client.session.post(client.endpoint, headers=headers, data=message.encode("utf-8")) return response.status_code, response.content.decode("utf-8")
class XmlHandler(object): """find and modify value in .xml file """ def __init__(self): self._log = logging.getLogger(__name__) self._log.setLevel(logging.DEBUG) self._xml_parser = None self._xml_inst = None self._src_path = None self._save_path = None def setup(self, src_file, save_path, **kwargs): """src_file: the xml file you want parser save_path: where the xml file you want save after parser """ self._src_path = src_file self._save_path = save_path self._xml_inst = XML() self._xml_parser = self._xml_inst.parse_xml(self._src_path) #lxml_parser = lxml.etree.ETCompatXMLParser() #self._lxml_parser = lxml.etree.parse(self._src_path) def teardown(self, **kwargs): """pair up the function setup """ self._xml_inst.save_xml(self._xml_parser, self._save_path) def _get_child_absolute_node_by_xpath(self, current_node, x_path, name, node_index): elements = self._xml_inst.get_elements(current_node, x_path) element_atts_dict = {} for ele in elements: element_atts_dict[(self._xml_inst.get_element_attribute( ele, name))] = ele return self._xml_inst.get_element_attributes(element_atts_dict[sorted( element_atts_dict.keys())[int(node_index)]])[name] def _re_config_path(self, path): while True: ret = re.search(r'\[@\w+\="\S+"]\[@(\w+)="(\d)"\]', path) if ret: self._log.debug("ret group:%s", ret.groups()) self._log.debug(path[:path.index('[@%s' % ret.group(1))]) node_new = self._get_child_absolute_node_by_xpath( self._xml_parser, path[:path.index('[@%s' % ret.group(1))], ret.group(1), ret.group(2)) self._log.debug("%s--%s", node_new, ret.groups()) path = path.replace('%s="%s"' % (ret.groups()), '%s="%s"' % (ret.group(1), node_new)) self._log.info("path:%s", path) else: return path def modify_node_text(self, *args): """arg should be like this: './/managedObject[@class="LNBTS"]/p[@name="actDLCAggr"]:false' """ for each_node in args: ret_temp = each_node.split(":") node_path = ":".join(ret_temp[:-1]) node_path = self._re_config_path(node_path) value = ret_temp[-1] self._log.debug("node_path:%s, value:%s", node_path, value) elements = self._xml_inst.get_elements(self._xml_parser, node_path) if not elements: raise TAFileException( "not found any elements, please check your xpath!--%s." % node_path) for ele in elements: self._xml_inst.set_element_text(ele, value) def modify_node_attribute(self, *args): """arg should be like this: './/managedObject[@class\="LNCEL"]:@version\=TL16B' """ for arg in args: node_path = self._re_config_path(arg.split(':@')[0]) value = arg.split("=")[-1] attr_name = arg.split(':@')[-1].split('=')[0] try: self._xml_inst.set_elements_attribute(self._xml_parser, attr_name, value, node_path) except: self._log.debug( "not found any elements, please check your xpath!--%s.", node_path) def add_node(self, *args): """arg should be like this: .//managedObject[@class="LNBTS"]:<list name="dlSectorBFWeightCusProf"><item> <p name="dlSectorBFWeightProfName">customized profile 1</p><p name="modulusOfWeighforAntGrp0">100</p> <p name="modulusOfWeighforAntGrp1">100</p><p name="modulusOfWeighforAntGrp2">100</p> <p name="modulusOfWeighforAntGrp3">100</p><p name="phaseOfWeighforAntGrp0">0</p> <p name="phaseOfWeighforAntGrp1">180</p><p name="phaseOfWeighforAntGrp2">180</p> <p name="phaseOfWeighforAntGrp3">180</p></item></list> """ for each_node in args: if "cmData:" in each_node: ret_temp = each_node.split(":", 1) else: ret_temp = each_node.split(":") node_path = ":".join(ret_temp[:-1]) value = ret_temp[-1] node_path = node_path.rstrip('/') node_path = self._re_config_path(node_path) self._log.debug("node_path:%s", node_path) elements = self._xml_inst.get_elements(self._xml_parser, node_path) if not elements: raise TAFileException( "not found any elements, please check your xpath!--%s." % node_path) for ele in elements: self._xml_inst.add_element(ele, value) def delete_node(self, *args): """arg should be like this: .//managedObject[@class="LNCEL"][@distName="0"]/list/item/p[@name="dFpucchF1b"] """ for each_node in args: each_node = self._re_config_path(each_node) self._log.debug("new_node_path:%s", each_node) elements = self._xml_inst.get_elements(self._xml_parser, each_node) if not elements: raise TAFileException( "not found any elements, please check your xpath!--%s." % each_node) for ele in elements: self._xml_inst.remove_elements(self._xml_parser, each_node) def get_node_text(self, *args): """arg should be like this: .//managedObject[@class="LNCEL"][@distName="0"]/list/item/p[@name="dFpucchF1b"] """ ret_list = [] for each_node in args: each_node = self._re_config_path(each_node) try: elements = self._xml_inst.get_elements(self._xml_parser, each_node) if not elements: raise TAFileException( "not found any elements, please check your xpath!--%s." % each_node) for ele in elements: ret_list.append(self._xml_inst.get_element_text(ele)) except SyntaxError: print '****SyntaxError****' #root = self._lxml_parser.getroot() #elements = root.xpath(each_node) #if not elements: # raise TAFileException("not found any elements, please check your xpath!--%s." % each_node) #for ele in elements: # ret_list.append(ele.text) return ret_list def get_node_attribute(self, *args): """arg should be like this: .//managedObject[@class\="LNCEL"]:@version """ ret_list = [] for arg in args: attr_name = arg.split(':@')[-1] each_node = self._re_config_path(arg.split(':@')[0]) elements = self._xml_inst.get_elements(self._xml_parser, each_node) if not elements: raise TAFileException( "not found any elements, please check your xpath!--%s." % each_node) for ele in elements: ret_list.append( self._xml_inst.get_element_attribute(ele, attr_name)) return ret_list
def __init__(self): Screenshot.__init__(self,"C:\\WebServer\\Results") XML.__init__(self,use_lxml=True) Process.__init__(self)