def createDir_addtimestamp(path, dirname): """Creates a new directory with name = dirname under the provided path, if directory with same name already exists adds date+timestamp to the name and creates a new directory with name = dirname+date×tamp Arguments: 1. path = (string) full path of an existing directory where a new directory need to be created 2. dirname = (string) name of the new directory to be created """ if dirExists(path): dirpath = os.path.abspath(path) + os.sep + dirname if dirExists(dirpath): dirpath = addTimeDate(dirpath) try: os.makedirs(dirpath) except Exception as exception: # print_exception(exception) print_info( "Add date time and try to create directory one more time") dirpath = addTimeDate(dirpath) os.makedirs(dirpath) #print_info("A new '%s' directory created : '%s'" % (dirname, dirpath)) return dirpath else: print_warning( "Directory does not exist in provided path: {0}".format(path)) return False
def getChildElementWithSpecificXpath(start, xpath): """ This method takes a xml file or parent element as input and finds the first child containing specified xpath Returns the child element. Arguments: start = xml file or parent element xpath = a valid xml path value as supported by python, refer https://docs.python.org/2/library/xml.etree.elementtree.html """ node = False if isinstance(start, (file, str)): # check if file exist here if file_Utils.fileExists(start): node = ElementTree.parse(start).getroot() else: print_warning('The file={0} is not found.'.format(start)) elif isinstance(start, ElementTree.Element): node = start if node is not False or node is not None: element = node.find(xpath) else: element = False return element
def getNodeText(filename, node): """Get the Text of the Node""" root = ElementTree.parse(filename).getroot() node = root.find(node) if node is not None: text = node.text return text else: print_warning("node not found")
def del_tag_from_element(ele, tag): """ Delete a subelement with specific tag from an xml element object return the deleted subelement if pass return False if subelement not found """ if ele.find(tag) is not None: ele.remove(ele.find(tag)) return ele else: print_warning("cannot found {0} in element".format(str(tag))) return False
def open_target(self): ''' Connects to a NE using telnet protocol with provided login credentials''' print_info('telnet Target open') host = self.target port = self.port print_info("OPENING TELNET Connection...\n") print_info("HOST: {0} PORT: {1}".format(host, port)) try: self.tnet.open(host, port) self.log = open(self.logfile, 'w') except socket.error, err: print_warning("Login failed {0}".format(str(err))) return False
def close(fd): """ Close the file. A closed file cannot be read or written any more. :Arguments: fd - file descriptor got from open_file :Return: True/False - based on the success/failure of the operation """ try: name = fd.name status = fd.close() print_info("file {} closed successfully".format(name)) except ValueError: print_warning("file is already closed...") status = True except Exception as e: print_error("found exception {} while closing {}".format(str(e), fd)) status = False return status
def check_and_create_dir(dirpath): """Checks if dir exists in provided path. If dir exists returns True Elseif dir does not exists, tries to create a directory - If dir created successfully, returns True. - If dir creation failed returns false """ status = False if pathExists(dirpath): print_info("Directory exists in provided path '{0}': ".format(dirpath)) status = True elif not pathExists(dirpath): try: os.makedirs(dirpath) except Exception as exception: print_warning("Creating directory at '{0}' failed.".format(dirpath)) print_exception(exception) status = False else: status = True return status
def compare_xml_using_xpath(response, list_of_xpath, list_of_expected_api_responses): """ Will get each xpath in list of xpath and get the value of that xpath in xml response Compares the value with the expected_api_response If all values matches returns True else False """ status = True if len(list_of_xpath) != len(list_of_expected_api_responses): print_error("The number of xpath given is different" "from the number of expected response" "Please check the value" "\nlist_of_xpath: {}" "\nlist_of_expected_response: {}".format( list_of_xpath, list_of_expected_api_responses)) status = False if status: for index, xpath_pattern in enumerate(list_of_xpath): xpath = xpath_pattern.strip("xpath=") value = getValuebyTagFromStringWithXpath(response, xpath, None) # Equality_match: Check if the expected response is equal to API response match = True if value == list_of_expected_api_responses[index] else False # Perform Regex_search if equality match fails if match is False: try: # Regex_search: Check if the expected response pattern is in API response match = re.search(list_of_expected_api_responses[index], value) except Exception: print_warning("Python regex search failed, invalid " "expected_response_pattern '{}' is " "provided".format(list_of_expected_api_responses[index])) if not match: status = False print_error("For the given '{0}' the expected response value is '{1}'. " "It doesn't match or available in the actual response value " "'{2}'".format(xpath_pattern, list_of_expected_api_responses[index], value)) return status
def getElementWithTagAttribValueMatch(start, tag, attrib, value): """ When start is an xml datafile, it finds the root and first element with: tag, attrib, value. Or when it's an xml element, it finds the first child element with: tag, attrib, value. If there is not a match, it returns False. """ node = False if isinstance(start, (file, str)): # check if file exist here if file_Utils.fileExists(start): node = ElementTree.parse(start).getroot() else: print_warning('The file={0} is not found.'.format(start)) elif isinstance(start, ElementTree.Element): node = start if node is not False and node is not None: elementName = ".//%s[@%s='%s']" % (tag, attrib, value) element = node.find(elementName) else: element = node return element
def recursive_findfile(file_name, src_dir): """ Finds the file_name in the given directory. :Arguments: 1. file_name(string) - name of the file(with extension) to be searched 2. src_dir(string) - path of the dir where the file will be searched :Return: 1. output_path(string) - Path of the file(from src_dir) with extension if the file exists else False """ output_path = False if dirExists(src_dir): for root, _, files in os.walk(src_dir): for f in files: if f == file_name: output = os.path.join(root, f) return output else: print_warning("Directory does not exist in the provided " "path: {}".format(src_dir)) return output_path
2. dirname = (string) name of the new directory to be created """ if dirExists(path): dirpath = path + os.sep + dirname if dirExists(dirpath): return dirpath try: os.makedirs(dirpath) except Exception, e: print_error(str(e)) #print_info("A new '%s' directory created : '%s'" % (dirname, dirpath)) return dirpath else: print_warning( "Directory does not exist in provided path: {0}".format(path)) return False def check_and_create_dir(dirpath): """Checks if dir exists in provided path. If dir exists returns True Elseif dir does not exists, tries to create a directory - If dir created successfully, returns True. - If dir creation failed returns false """ status = False if pathExists(dirpath): print_info("Directory exists in provided path '{0}': ".format(dirpath)) status = True elif not pathExists(dirpath):