Пример #1
0
class ArchiveKeywords(object):
    ROBOT_LIBRARY_SCOPE = 'Global'

    tars = ['.tar', '.tar.bz2', '.tar.gz', '.tgz', '.tz2']

    zips = ['.docx', '.egg', '.jar', '.odg', '.odp', '.ods', '.xlsx', '.odt',
            '.pptx', 'zip']

    def __init__(self):
        self.oslib = OperatingSystem()
        self.collections = Collections()

    def extract_zip_file(self, zfile, dest=None):
        ''' Extract a ZIP file

        `zfile` the path to the ZIP file

        `dest` optional destination folder. Assumes current working directory if it is none
               It will be created if It doesn't exist.
        '''
        
        if dest:
            self.oslib.create_directory(dest)
            self.oslib.directory_should_exist(dest)
        else:
            dest = os.getcwd()
       
        cwd = os.getcwd()

        unzipper = Unzip()

        # Dont know why I a have `gotta catch em all` exception handler here
        try:
            unzipper.extract(zfile, dest)
        except:
            raise
        finally:
            os.chdir(cwd)

    def extract_tar_file(self, tfile, dest=None):
        ''' Extract a TAR file

        `tfile` the path to the TAR file

        `dest` optional destination folder. Assumes current working directory if it is none
               It will be created if It doesn't exist.
        '''
        if dest:
            self.oslib.create_directory(dest)
        else:
            dest = os.getcwd()
            
        self.oslib.file_should_exist(tfile)

        untarrer = Untar()
        untarrer.extract(tfile, dest)

    def archive_should_contain_file(self, zfile, filename):
        ''' Check if a file exists in the ZIP file without extracting it

        `zfile` the path to the ZIP file

        `filename` name of the file to search for in `zfile`
        '''
        self.oslib.file_should_exist(zfile)

        files = []
        if zipfile.is_zipfile(zfile):
            files = zipfile.ZipFile(zfile).namelist()
        else:
            files = tarfile.open(name=zfile).getnames()
        files = [os.path.normpath(item) for item in files]

        self.collections.list_should_contain_value(files, filename)

    def create_tar_from_files_in_directory(self, directory, filename):
        ''' Take all files in a directory and create a tar package from them

        `directory` Path to the directory that holds our files

        `filename` Path to our destination TAR package.
        '''
        if not directory.endswith("/"):
            directory = directory + "/"
        tar = tarfile.open(filename, "w")
        files = os.listdir(directory)
        for name in files:
            tar.add(directory + name, arcname=name)
        tar.close()
		
    def create_zip_from_files_in_directory(self, directory, filename):
        ''' Take all files in a directory and create a zip package from them

        `directory` Path to the directory that holds our files

        `filename` Path to our destination ZIP package.
        '''
        if not directory.endswith("/"):
            directory = directory + "/"
        zip = zipfile.ZipFile(filename, "w")
        files = os.listdir(directory)
        for name in files:
            zip.write(directory + name, arcname=name)
        zip.close()
class ArchiveKeywords(object):
    ROBOT_LIBRARY_SCOPE = 'Global'

    tars = ['.tar', '.tar.bz2', '.tar.gz', '.tgz', '.tz2']

    zips = [
        '.docx', '.egg', '.jar', '.odg', '.odp', '.ods', '.xlsx', '.odt',
        '.pptx', 'zip'
    ]

    def __init__(self):
        self.oslib = OperatingSystem()
        self.collections = Collections()

    def extract_zip_file(self, zfile, dest=None):
        ''' Extract a ZIP file

        `zfile` the path to the ZIP file

        `dest` optional destination folder. It will be created if It doesn't exist.
        '''

        if dest:
            self.oslib.create_directory(dest)
            self.oslib.directory_should_exist(dest)

        cwd = os.getcwd()

        unzipper = Unzip()

        # Dont know why I a have `gotta catch em all` exception handler here
        try:
            unzipper.extract(zfile, dest)
        except:
            raise
        finally:
            os.chdir(cwd)

    def extract_tar_file(self, tfile, dest=None):
        ''' Extract a TAR file

        `tfile` the path to the TAR file

        `dest` optional destination folder. It will be created if It doesn't exist.
        '''
        if dest:
            self.oslib.create_directory(dest)

        self.oslib.file_should_exist(tfile)

        untarrer = Untar()
        untarrer.extract(tfile, dest)

    def archive_should_contain_file(self, zfile, filename):
        ''' Check if a file exists in the ZIP file without extracting it

        `zfile` the path to the ZIP file

        `filename` name of the file to search for in `zfile`
        '''
        self.oslib.file_should_exist(zfile)

        files = []
        if zipfile.is_zipfile(zfile):
            files = zipfile.ZipFile(zfile).namelist()
        else:
            files = tarfile.open(name=zfile).getnames()
        files = [os.path.normpath(item) for item in files]

        self.collections.list_should_contain_value(files, filename)
Пример #3
0
class ArchiveKeywords(object):
    ROBOT_LIBRARY_SCOPE = 'Global'

    tars = ['.tar', '.tar.bz2', '.tar.gz', '.tgz', '.tz2']

    zips = ['.docx', '.egg', '.jar', '.odg', '.odp', '.ods', '.xlsx', '.odt',
            '.pptx', 'zip']

    def __init__(self):
        self.oslib = OperatingSystem()
        self.collections = Collections()

    def extract_zip_file(self, zfile, dest=None):
        ''' Extract a ZIP file

        `zfile` the path to the ZIP file

        `dest` optional destination folder. Assumes current working directory if it is none
               It will be created if It doesn't exist.
        '''
        
        if dest:
            self.oslib.create_directory(dest)
            self.oslib.directory_should_exist(dest)
        else:
            dest = os.getcwd()
       
        cwd = os.getcwd()

        unzipper = Unzip()

        # Dont know why I a have `gotta catch em all` exception handler here
        try:
            unzipper.extract(zfile, dest)
        except:
            raise
        finally:
            os.chdir(cwd)

    def extract_tar_file(self, tfile, dest=None):
        ''' Extract a TAR file

        `tfile` the path to the TAR file

        `dest` optional destination folder. Assumes current working directory if it is none
               It will be created if It doesn't exist.
        '''
        if dest:
            self.oslib.create_directory(dest)
        else:
            dest = os.getcwd()
            
        self.oslib.file_should_exist(tfile)

        untarrer = Untar()
        untarrer.extract(tfile, dest)

    def archive_should_contain_file(self, zfile, filename):
        ''' Check if a file exists in the ZIP file without extracting it

        `zfile` the path to the ZIP file

        `filename` name of the file to search for in `zfile`
        '''
        self.oslib.file_should_exist(zfile)

        files = []
        if zipfile.is_zipfile(zfile):
            files = zipfile.ZipFile(zfile).namelist()
        else:
            files = tarfile.open(name=zfile).getnames()
        files = [os.path.normpath(item) for item in files]

        self.collections.list_should_contain_value(files, filename)

    def create_tar_from_files_in_directory(self, directory, filename):
        ''' Take all files in a directory and create a tar package from them

        `directory` Path to the directory that holds our files

        `filename` Path to our destination TAR package.
        '''
        if not directory.endswith("/"):
            directory = directory + "/"
        tar = tarfile.open(filename, "w")
        files = os.listdir(directory)
        for name in files:
            tar.add(directory + name, arcname=name)
        tar.close()
		
    def create_zip_from_files_in_directory(self, directory, filename):
        ''' Take all files in a directory and create a zip package from them

        `directory` Path to the directory that holds our files

        `filename` Path to our destination ZIP package.
        '''
        if not directory.endswith("/"):
            directory = directory + "/"
        zip = zipfile.ZipFile(filename, "w")
        files = os.listdir(directory)
        for name in files:
            zip.write(directory + name, arcname=name)
        zip.close()
class AdvancedLogging(object):
    """
    Creating additional logs when testing.
    If during the test you want to add any additional information in the file, then this library
    provide a hierarchy of folders and files for logging.
    Folder hierarchy is created as follows: output_dir/test_log_folder_name/Test_Suite/Test_Suite/Test_Case/file.log
    Log files and folders are not removed before the test, and overwritten of new files.
    
     == Dependency: ==
    | robot framework | http://robotframework.org |
    -------
    
    When initializing the library, you can define two optional arguments
    | *Argument Name*      |  *Default value*  | *Description*                                                 |
    | output_dir           |  ${OUTPUT_DIR}    | The directory in which create the folder with additional logs |
    | test_log_folder_name |  Advanced_Logs    | Name of the folder from which to build a hierarchy of logs    |
    -------
    
    == Example: ==
    | *Settings*  |  *Value*           | *Value*  |  *Value*        |
    | Library     |  AdvancedLogging   | C:/Temp  |   LogFromServer |
    | Library     |  SSHLibrary        |          |                 |
    
    | *Test cases*              | *Action*                  | *Argument*             |  *Argument*            |
    | Example_TestCase          | ${out}=                   | Execute Command        |  grep error output.log |
    |                           | Write advanced testlog    | error.log              |  ${out}                |
    =>\n
    File C:/Temp/LogFromServer/TestSuite name/Example_TestCase/error.log  with content from variable ${out}
    """

    ROBOT_LIBRARY_SCOPE='TEST SUITE'

    def __init__(self, output_dir = None, test_log_folder_name = 'Advanced_Logs'):
        self.os=OperatingSystem()
        self.bi=BuiltIn()

        self.output_dir=output_dir
        self.test_log_folder_name=test_log_folder_name
        self.sep='/'

    @property
    def _suite_folder (self):
        """
        Define variables that are initialized by a call 'TestSuite'
        """


        if self.output_dir==None :
            self.output_dir=self.bi.get_variable_value('${OUTPUT_DIR}')

        suite_name=self.bi.get_variable_value('${SUITE_NAME}')
        suite_name=suite_name.replace('.', self.sep)
        self.output_dir=os.path.normpath(self.output_dir)
        self.test_log_folder_name=os.path.normpath(self.test_log_folder_name)

        suite_folder=self.output_dir+self.sep+self.test_log_folder_name+self.sep+suite_name
        return os.path.normpath(suite_folder)

    def Write_Advanced_Testlog (self, filename, content):
        """ 
        Inclusion content in additional log file
        
        Return: path to filename
        
        Example:
        | Write advanced testlog   | log_for_test.log  |  test message |
        =>\n
        File ${OUTPUT_DIR}/Advanced_Logs/<TestSuite name>/<TestCase name>/log_for_test.log with content 'test message'
        """

        test_name=BuiltIn().get_variable_value('${TEST_NAME}')

        if not test_name:
            log_folder=self._suite_folder+self.sep
        else:
            log_folder=self._suite_folder+self.sep+test_name

        self.os.create_file(log_folder+self.sep+filename, content)

        return os.path.normpath(log_folder+self.sep+filename)

    def Create_Advanced_Logdir (self):
        """  
        Creating a folder hierarchy for TestSuite
        
        Return: path to folder
        
        Example:
        | *Settings* | *Value* |
        | Library    |        AdvancedLogging |
        | Library    |       OperatingSystem |
        
        | *Test Cases* | *Action* | *Argument* |
        | ${ADV_LOGS_DIR}=   | Create advanced logdir            |                |
        | Create file        | ${ADV_LOGS_DIR}/log_for_suite.log |   test message |
        =>\n
        File ${OUTPUT_DIR}/Advanced_Logs/<TestSuite name>/log_for_suite.log with content 'test message'
        """

        test_name=self.bi.get_variable_value('${TEST_NAME}')

        if not test_name:
            log_folder=self._suite_folder+self.sep
        else:
            log_folder=self._suite_folder+self.sep+test_name

        self.os.create_directory(os.path.normpath(log_folder))

        return os.path.normpath(log_folder)
Пример #5
0
class AdvancedLogging(object):
    """
    Creating additional logs when testing.
    If during the test you want to add any additional information in the file, then this library
    provide a hierarchy of folders and files for logging.
    Folder hierarchy is created as follows: output_dir/test_log_folder_name/Test_Suite/Test_Suite/Test_Case/file.log
    Log files and folders are not removed before the test, and overwritten of new files.

     == Dependency: ==
    | robot framework | http://robotframework.org |
    -------

    When initializing the library, you can define two optional arguments
    | *Argument Name*      |  *Default value*  | *Description*                                                 |
    | output_dir           |  ${OUTPUT_DIR}    | The directory in which create the folder with additional logs |
    | test_log_folder_name |  Advanced_Logs    | Name of the folder from which to build a hierarchy of logs    |
    -------

    == Example: ==
    | *Settings*  |  *Value*           | *Value*  |  *Value*        |
    | Library     |  AdvancedLogging   | C:/Temp  |   LogFromServer |
    | Library     |  SSHLibrary        |          |                 |

    | *Test cases*              | *Action*                  | *Argument*             |  *Argument*            |
    | Example_TestCase          | ${out}=                   | Execute Command        |  grep error output.log |
    |                           | Write advanced testlog    | error.log              |  ${out}                |
    =>\n
    File C:/Temp/LogFromServer/TestSuite name/Example_TestCase/error.log  with content from variable ${out}
    """

    ROBOT_LIBRARY_SCOPE = 'TEST SUITE'

    def __init__(self,
                 output_dir: str = None,
                 test_log_folder_name: str = 'Advanced_Logs') -> None:
        """ Initialisation

        *Args*:\n
            _output_dir_: output directory.\n
            _test_log_folder_name_: name for log folder.
        """
        self.os = OperatingSystem()
        self.bi = BuiltIn()

        self.output_dir = output_dir
        self.test_log_folder_name = test_log_folder_name
        self.win_platform = 'Windows' in platform()

    def _get_suite_names(self) -> Iterator[str]:
        """
        Get List with the current suite name and all its parents names

        *Returns:*\n
            Iterator of the current suite name and all its parents names
        """
        suite = EXECUTION_CONTEXTS.current.suite
        result = [suite.name]
        while suite.parent:
            suite = suite.parent
            result.append(suite.name)
        return reversed(result)

    @property
    def _suite_folder(self) -> str:
        """ Define variables that are initialized by a call 'TestSuite'

        *Returns:*\n
            Path to suite folder.
        """
        output = self.output_dir

        if output is None:
            output = self.bi.get_variable_value('${OUTPUT_DIR}')

        suite_name = path_join(*self._get_suite_names())

        if self.win_platform:
            # Look at MSDN knowledge base: https://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath
            long_path_support_prefix = '\\\\?\\'
            output = long_path_support_prefix + output

        suite_folder = path_join(output, self.test_log_folder_name, suite_name)

        return normpath(suite_folder)

    def write_advanced_testlog(self,
                               filename: str,
                               content: Union[bytes, str],
                               content_encoding: str = 'UTF-8') -> str:
        """ Inclusion content in additional log file

        *Args:*\n
            _filename_ - name of log file;
            _content_ - content for logging;
            _content_encoding_ - encoding of content (if it's in bytes).

        *Returns:*\n
             Path to filename.

        *Example*:\n
        | Write advanced testlog   | log_for_test.log  |  test message |
        =>\n
        File ${OUTPUT_DIR}/Advanced_Logs/<TestSuite name>/<TestCase name>/log_for_test.log with content 'test message'
        """
        if isinstance(content, bytes):
            content = content.decode(content_encoding)
        test_name = self.bi.get_variable_value('${TEST_NAME}', default='')
        log_file_path = path_join(self._suite_folder, test_name, filename)
        self.os.create_file(log_file_path, content)
        return normpath(log_file_path)

    def create_advanced_logdir(self) -> str:
        """ Creating a folder hierarchy for TestSuite

        *Returns:*\n
             Path to folder.

        *Example*:\n
        | *Settings* | *Value* |
        | Library    |        AdvancedLogging |
        | Library    |       OperatingSystem |

        | *Test Cases* | *Action* | *Argument* |
        | ${ADV_LOGS_DIR}=   | Create advanced logdir            |                |
        | Create file        | ${ADV_LOGS_DIR}/log_for_suite.log |   test message |
        =>\n
        File ${OUTPUT_DIR}/Advanced_Logs/<TestSuite name>/log_for_suite.log with content 'test message'
        """
        test_name = self.bi.get_variable_value('${TEST_NAME}', default='')
        log_folder = path_join(self._suite_folder, test_name)
        old_log_level = BuiltIn().set_log_level("ERROR")
        self.os.create_directory(log_folder)
        BuiltIn().set_log_level(old_log_level)
        return normpath(log_folder)
class ArchiveKeywords(object):
    ROBOT_LIBRARY_SCOPE = 'Global'

    tars = ['.tar', '.tar.bz2', '.tar.gz', '.tgz', '.tz2']

    zips = ['.docx', '.egg', '.jar', '.odg', '.odp', '.ods', '.xlsx', '.odt',
            '.pptx', 'zip']

    def __init__(self):
        self.oslib = OperatingSystem()
        self.collections = Collections()

    def extract_zip_file(self, zfile, dest=None):
        ''' Extract a ZIP file

        `zfile` the path to the ZIP file

        `dest` optional destination folder. It will be created if It doesn't exist.
        '''

        if dest:
            self.oslib.create_directory(dest)
            self.oslib.directory_should_exist(dest)

        cwd = os.getcwd()

        unzipper = Unzip()

        # Dont know why I a have `gotta catch em all` exception handler here
        try:
            unzipper.extract(zfile, dest)
        except:
            raise
        finally:
            os.chdir(cwd)

    def extract_tar_file(self, tfile, dest=None):
        ''' Extract a TAR file

        `tfile` the path to the TAR file

        `dest` optional destination folder. It will be created if It doesn't exist.
        '''
        if dest:
            self.oslib.create_directory(dest)

        self.oslib.file_should_exist(tfile)

        untarrer = Untar()
        untarrer.extract(tfile, dest)

    def archive_should_contain_file(self, zfile, filename):
        ''' Check if a file exists in the ZIP file without extracting it

        `zfile` the path to the ZIP file

        `filename` name of the file to search for in `zfile`
        '''
        self.oslib.file_should_exist(zfile)

        files = []
        if zipfile.is_zipfile(zfile):
            files = zipfile.ZipFile(zfile).namelist()
        else:
            files = tarfile.open(name=zfile).getnames()

        self.collections.list_should_contain_value(files, filename)
Пример #7
0
class ArchiveKeywords:
    ROBOT_LIBRARY_SCOPE = 'Global'

    compressions = {
        "stored": zipfile.ZIP_STORED,
        "deflated": zipfile.ZIP_DEFLATED,
        "bzip2": zipfile.ZIP_BZIP2,
        "lzma": zipfile.ZIP_LZMA
    }

    tars = ['.tar', '.tar.bz2', '.tar.gz', '.tgz', '.tz2']

    zips = [
        '.docx', '.egg', '.jar', '.odg', '.odp', '.ods', '.xlsx', '.odt',
        '.pptx', 'zip'
    ]

    def __init__(self):
        self.oslib = OperatingSystem()
        self.collections = Collections()

    def extract_zip_file(self, zip_file, dest=None):
        """ Extract a ZIP file

        `zip_file` the path to the ZIP file

        `dest` optional destination folder. Assumes current working directory if it is none
               It will be created if It doesn't exist.
        """

        if dest:
            self.oslib.create_directory(dest)
            self.oslib.directory_should_exist(dest)
        else:
            dest = os.getcwd()

        cwd = os.getcwd()

        # Dont know why I a have `gotta catch em all` exception handler here
        try:
            Unzip().extract(zip_file, dest)
        except:
            raise
        finally:
            os.chdir(cwd)

    def extract_tar_file(self, tar_file, dest=None):
        """ Extract a TAR file

        `tar_file` the path to the TAR file

        `dest` optional destination folder. Assumes current working directory if it is none
               It will be created if It doesn't exist.
        """
        if dest:
            self.oslib.create_directory(dest)
        else:
            dest = os.getcwd()

        self.oslib.file_should_exist(tar_file)

        Untar().extract(tar_file, dest)

    def archive_should_contain_file(self, zip_file, filename):
        """ Check if a file exists in the ZIP file without extracting it

        `zip_file` the path to the ZIP file

        `filename` name of the file to search for in `zip_file`
        """
        self.oslib.file_should_exist(zip_file)

        files = zipfile.ZipFile(zip_file).namelist() if zipfile.is_zipfile(
            zip_file) else tarfile.open(zip_file).getnames()

        files = [os.path.normpath(item) for item in files]

        self.collections.list_should_contain_value(files, filename)

    def create_tar_from_files_in_directory(self,
                                           directory,
                                           filename,
                                           sub_directories=True):
        """ Take all files in a directory and create a tar package from them

        `directory` Path to the directory that holds our files

        `filename` Path to our destination TAR package.

        `sub_directories` Shall files in sub-directories be included - True by default.        
        """
        tar = tarfile.open(filename, "w")

        files = return_files_lists(directory, sub_directories)
        for filepath, name in files:
            tar.add(filepath, arcname=name)

        tar.close()

    @classmethod
    def create_zip_from_files_in_directory(cls,
                                           directory,
                                           filename,
                                           sub_directories=False,
                                           compression="stored"):
        """ Take all files in a directory and create a zip package from them

        `directory` Path to the directory that holds our files

        `filename` Path to our destination ZIP package.

        `sub_directories` Shall files in sub-directories be included - False by default.

        `compression` stored (default; no compression), deflated, bzip2 (with python >= 3.3), lzma (with python >= 3.3)
        """

        if cls.compressions.get(compression) is None:
            raise ValueError("Unknown compression method")
        comp_method = cls.compressions.get(compression)

        the_zip = zipfile.ZipFile(filename, "w", comp_method)

        files = return_files_lists(directory, sub_directories)
        for filepath, name in files:
            the_zip.write(filepath, arcname=name)

        the_zip.close()