コード例 #1
0
def getLinesBetweenMatchingLines(srcfile, dstfile, start, end, no_of_search=1):
    lines = open(srcfile, 'r').readlines()
    #print_info ("lines:%s"% lines)
    i = 0
    iteration = 0
    resultantList = []
    if no_of_search == 0:
        print_error("no of searches should be a non-zero number")
        return False
    while (i < len(lines)):
        #print lines[i]

        printable_only = filter(lambda x: x in string.printable, lines[i])

        if printable_only == start:
            resultantList.append(lines[i])
            i += 1
            while (i < len(lines)):
                printable_only = filter(lambda x: x in string.printable,
                                        lines[i])
                if printable_only == end:
                    resultantList.append(lines[i])
                    iteration += 1
                    break
                else:
                    resultantList.append(lines[i])
                    i += 1

        if no_of_search == 'EOF' or no_of_search == 'eof' or iteration < no_of_search:
            i += 1
        elif no_of_search == iteration:
            break

    if len(resultantList) == 0: print "no match found in the file"
    open(dstfile, 'w+').writelines(resultantList)
コード例 #2
0
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)
            if value != list_of_expected_api_responses[index]:
                status = False
                print_error("For the given {0} the expected response value is"
                            " {1} but the actual response"
                            " value is {2}".format(xpath_pattern,
                            list_of_expected_api_responses[index], value))
    return status
コード例 #3
0
def move_to_position(fd, offset, **kwargs):
    """
    Sets the file's current position
    :Arguments:
        fd - file descriptor got from open_file
        offset - number of bytes to be moved
    :Optional:
        whence -
            0 - move offset positions from beginning of file
            1 - move offset positions from current position of file
            2 - move offset positions from end of file
    :Return:
        current position after movement
    """
    curpos = -1
    try:
        if "whence" in kwargs:
            curpos = fd.seek(offset, kwargs["whence"])
        else:
            curpos = fd.seek(offset)
    except ValueError:
        print_error("file is already closed...")
    except Exception as e:
        print_error("found exception {} while moving to position on {}".format(
            str(e), fd))
    return curpos
コード例 #4
0
def getAbsPath(relative_path, start_directory="."):
    """This function is used to manipulate the path according to the
        relative path that is specified

        :Arguments:

            1. @param relative_path: The relative path of directory or file
            2. @param start_directory: The actual dir path where the file must be



          :Returns:

                  1. @return: Returns the abspath with the relative path specified

     """
    value = False
    if relative_path and start_directory:
        relative_path = relative_path.strip()
        try:
            #print relative_path
            os.chdir(start_directory)
            path = os.path.abspath(relative_path)
            value = path
        except Exception, err:
            print_error("{0} file does not exist in provided path".format(
                relative_path))
            print(err)
コード例 #5
0
def verifyNodesValueMatch(datafile,
                          pnode,
                          cnode,
                          cvalue,
                          rnode,
                          rvalue,
                          bnode,
                          bvalue,
                          dnode=None,
                          dvalue=None):
    """
    Searches XML file for the parent node. Finds the 1st child node and checks its value
    if value is a match, then search for second child and check if its value matches
    datafile = xml file searched
    pnode = parent node
    cnode = child node
    cvalue = child node value
    rnode = reference node
    rvalue = refernce node value
    """
    try:
        tree = ElementTree.parse(datafile)
        root = tree.getroot()
    except Exception, e:
        print_error("unexpected error %s" % str(e))
        return False
コード例 #6
0
def get_tree_from_file(filepath):
    """ Get the tree from the xml file"""
    if file_Utils.fileExists(filepath):
            tree = ElementTree.parse(filepath)
    else:
        print_error("xml file does not exist in provided path {0}".format(filepath))
        tree = False
    return tree
コード例 #7
0
    def close(self):
        '''Calls the telnetlib close and terminates the telnet session'''
        try:
            self.tnet.close()
            print_debug("TELNET CONNECTION CLOSING...")

        except Exception:
            print_error("Error occured while closing telnet session")
            return False
コード例 #8
0
def getRoot(filename):
    """ Get the Root of the xml file"""
    try:
        tree = ElementTree.parse(filename)
        root = tree.getroot()
    except ElementTree.ParseError, msg:
        print_error("The xml file: {0} is {1}".format(filename, msg))
        print_info("DONE 1")
        sys.exit(0)
コード例 #9
0
ファイル: file_Utils.py プロジェクト: pavithra-gowda/warrior
def log_result(oper, result):
    """the methods in file_actions class use this to log the result of
    its operation
    """
    resmsg = "completed successfully" if result else "failed"
    msg = "file {} operation {}".format(oper, resmsg)
    if result:
        print_info(msg)
    else:
        print_error(msg)
コード例 #10
0
ファイル: file_Utils.py プロジェクト: pavithra-gowda/warrior
def delFolder(path):
    """ check if folder exists and delete it with its content"""
    status = False
    if dirExists(path):
        try:
            shutil.rmtree(path)
            status = True
        except OSError:
            print_error("Cannot remove folder {}".format(path))
    return status
コード例 #11
0
ファイル: file_Utils.py プロジェクト: pavithra-gowda/warrior
def get_absolute_path_from_start_directory(relative_path, start_directory, extension=".json"):
    """
    DEPRECATED IN 2.9

    Keyword developer must be aware that relative path can be relative to
    1. testcase file
    2. data file (if path is given in tag= value)
    start_directory must be an absolute path
    """
    print_error("This function is deprecated in 2.9, use check_extension_get_absolute_path or getAbspath instead")
    return check_extension_get_absolute_path(relative_path, start_directory, extension)
コード例 #12
0
ファイル: file_Utils.py プロジェクト: pavithra-gowda/warrior
def get_absolute_path_of_directory(relative_path_of_dir, start_directory):
    """
    DEPRECATED IN 2.9

    When provided with a start directory and a relative path of a directory, this function
    returns the absolute path. Else returns the relative path

    Keyword developer must be aware that relative path can be relative to
    1. testcase file
    2. data file (if path is given in tag= value)
    start_directory must be an absolute path
    """
    print_error("This function is deprecated in 2.9, use check_extension_get_absolute_path or getAbspath instead")
    return getAbsPath(relative_path_of_dir, start_directory)
コード例 #13
0
def get_file_mode(fd):
    """
    Returns access mode with which file was opened.
    :Arguments:
        fd - file descriptor got from open_file
    :Return:
        mode
    """
    mode = ""
    try:
        mode = fd.mode
    except ValueError:
        print_error("file is already closed...")
    except Exception as e:
        print_error("found exception {} while getting file mode of {}".format(
            str(e), fd))
    return mode
コード例 #14
0
ファイル: file_Utils.py プロジェクト: pavithra-gowda/warrior
def createDir(path, dirname):
    """Creates a new directory with name = dirname under the provided path, ignores if directory with same name already exists
    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 = 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
コード例 #15
0
def isatty(fd):
    """
    Returns True if the file is connected to a tty(-like) device, else False.
    :Arguments:
        fd - file descriptor got from open_file
    :Return:
        True/False - description above
    """
    status = False
    try:
        status = fd.isatty()
    except ValueError:
        print_error("file is already closed...")
    except Exception as e:
        print_error("found exception {} while checking atty of {}".format(
            str(e), fd))
    return status
コード例 #16
0
def is_softspace_required(fd):
    """
    Returns false if space explicitly required with print, true otherwise.
    :Arguments:
        fd - file descriptor got from open_file
    :Return:
        True/False - description above
    """
    status = False
    try:
        status = fd.softspace
    except ValueError:
        print_error("file is already closed...")
    except Exception as e:
        print_error("found exception {} while getting file mode of {}".format(
            str(e), fd))
    return status
コード例 #17
0
ファイル: file_Utils.py プロジェクト: pavithra-gowda/warrior
def get_current_position(fd):
    """
    Returns the file's current position
    :Arguments:
        fd - file descriptor got from open_file
    :Return:
        current position of the file, -1 if error occurred
    """
    curpos = -1
    try:
        curpos = fd.tell()
    except ValueError:
        print_error("file is already closed...")
    except Exception as e:
        print_error("found exception {} while getting current position on {}".
                    format(str(e), fd))
    return curpos
コード例 #18
0
def is_file_closed(fd):
    """
    Returns true if file is closed, false otherwise.
    :Arguments:
        fd - file descriptor got from open_file
    :Return:
        True/False - description above
    """
    status = False
    try:
        status = fd.closed
    except ValueError:
        print_error("file is already closed...")
    except Exception as e:
        print_error("found exception {} while getting file mode of {}".format(
            str(e), fd))
    return status
コード例 #19
0
def get_file_name(fd):
    """
    Returns name of the file.
    :Arguments:
        fd - file descriptor got from open_file
    :Return:
        name of the file, empty string if there was an exception
    """
    fname = ""
    try:
        fname = fd.name
    except ValueError:
        print_error("file is already closed...")
    except Exception as e:
        print_error("found exception {} while getting file name of {}".format(
            str(e), fd))
    return fname
コード例 #20
0
def flush(fd):
    """
    Flush the internal buffer, like stdio's fflush. This may be a no-op on some
    file-like objects.
    :Arguments:
        fd - file descriptor got from open_file
    :Return:
        True/False - based on the success/failure of the operation
    """
    status = False
    try:
        status = fd.flush()
    except ValueError:
        print_error("file is already closed...")
    except Exception as e:
        print_error("found exception {} while flushing {}".format(str(e), fd))
    return status
コード例 #21
0
def remove(nfile):
    """
    removes the file from the filesystem
    :Arguments:
        nfile - filepath to be removed
    :Return:
        True/False - based on the success/failure of the operation
    """
    status = False
    try:
        os.remove(nfile)
        print_info(nfile + " removed from filesystem")
        status = True
    except Exception as e:
        print_error("removing file {} raised exception {}".format(
            nfile, str(e)))
    return status
コード例 #22
0
def fileno(fd):
    """
    Returns the integer file descriptor that is used by the underlying
    implementation to request I/O operations from the operating system.
    :Arguments:
        fd - file descriptor got from open_file
    :Return:
        integer file descriptor
    """
    ifd = -1
    try:
        ifd = fd.fileno()
    except ValueError:
        print_error("file is already closed...")
    except Exception as e:
        print_error("found exception {} while getting integer file descriptor "
                    "of {}".format(str(e), fd))
    return ifd
コード例 #23
0
def get_next_line(fd):
    """
    Returns the next line from the file each time it is being called.
    :Arguments:
        fd - file descriptor got from open_file
    :Return:
        next line
    """
    try:
        line = fd.next()
    except ValueError:
        print_error("file is already closed...")
        line = False
    except Exception as e:
        print_error("found exception {} while getting line of {}".format(
            str(e), fd))
        line = False
    return line
コード例 #24
0
def copyfileobj(fsrc, fdst):
    """
    Copy the contents of the file-like object fsrc to the file-like object
    fdst.
    :Arguments:
        fsrc - file descriptor of the file to be copied
        fdst - file descriptor of the file on which to be copied
    :Return:
        True/False - based on the success/failure of the operation
    """
    status = False
    try:
        shutil.copyfileobj(fsrc, fdst)
        status = True
    except Exception as e:
        print_error("copying file {} to file {} raised exception {}".format(
            fsrc, fdst, str(e)))
    return status
コード例 #25
0
def write(fd, string):
    """
    Writes a string to the file.
    :Arguments:
        fd - file descriptor got from open_file
        str - string to write
    :Return:
        True/False - based on the success/failure of the operation
    """
    status = False
    try:
        fd.write(string)
        print_info("written to file " + fd.name)
        status = True
    except ValueError:
        print_error("file is already closed...")
    except Exception as e:
        print_error("found exception {} while writing {}".format(str(e), fd))
    return status
コード例 #26
0
def copyfile(src, dst):
    """
    Copy the contents (no metadata) of the file named src to a file named dst.
    dst must be the complete target file name.
    :Arguments:
        src - file to be copied
        dst - file on which to be copied
    :Return:
        True/False - based on the success/failure of the operation
    """
    status = False
    try:
        shutil.copyfile(src, dst)
        print_info("src {} copied to dst {} successfully".format(src, dst))
        status = True
    except Exception as e:
        print_error("copying file {} to file {} raised exception {}".format(
            src, dst, str(e)))
    return status
コード例 #27
0
ファイル: file_Utils.py プロジェクト: pavithra-gowda/warrior
def copymode(src, dst):
    """
    Copy the permission bits from src to dst. The file contents, owner, and
    group are unaffected. src and dst are path names given as strings.
    :Arguments:
        src - mode of the file to be copied
        dst - file on which mode has to be copied
    :Return:
        True/False - based on the success/failure of the operation
    """
    status = False
    try:
        shutil.copymode(src, dst)
        print_info("mode of src {} copied to dst {} successfully".
                   format(src, dst))
        status = True
    except Exception as e:
        print_error("copying file mode from {} to file {} raised exception {}".
                    format(src, dst, str(e)))
    return status
コード例 #28
0
def writelines(fd, seq):
    """
    Writes a sequence of strings to the file. The sequence can be any
    iterable object producing strings, typically a list of strings.
    :Arguments:
        fd - file descriptor got from open_file
        sequence - sequence of lines to be written
    :Return:
        True/False - based on the success/failure of the operation
    """
    status = False
    try:
        fd.writelines(seq)
        print_info("written seq to the file " + fd.name)
        status = True
    except ValueError:
        print_error("file is already closed...")
    except Exception as e:
        print_error("found exception {} while writing {}".format(str(e), fd))
    return status
コード例 #29
0
def readline(fd, **kwargs):
    """
    Reads one entire line from the file. A trailing newline character is kept
    in the string.
    :Arguments:
        fd - file descriptor got from open_file
    :Return:
        the line read
    """
    try:
        line = fd.readline(**kwargs)
        print_info("read a line from file " + fd.name)
    except ValueError:
        print_error("file is already closed...")
        line = False
    except Exception as e:
        print_error("found exception {} while reading line in {}".format(
            str(e), fd))
        line = False
    return line
コード例 #30
0
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