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='/'
def writeToFile_variables(object, obj, sf_type): # MSuccess_Msg = Message(bottom_frame, text='Printing file ....') # def Error_Delete(): # error_Msg.destroy() # Try_with_Other_object_btn.destroy() # Try_with_Other_object_btn = Button(bottom_frame, text="Try_with_Other_object", fg="black", bg="light blue", # command=Error_Delete) # Try_with_Other_object_btn.grid(row=2, column=2) OS = OperatingSystem() # path = '../Resources/MedvantageApp/PageElements/%s_Page.robot' % object OS.append_to_file(path, '*** Variables ***') OS.append_to_file(path, '\n') # MSuccess_Msg.grid(row=0, column=1) print 'Printing file ....' # if sf_type is 'classic': # OS.append_to_file(path, '\n''# Locators for All Tabs') # OS.append_to_file(path, '\n''${Alltabs_btn_loc} //img[@title=\'All Tabs\']') # OS.append_to_file(path, '\n''${%s_tab_link_loc} //img[@title=\'%s\']'%(object,obj)) # OS.append_to_file(path, '\n') # elif sf_type is 'lightning': # OS.append_to_file(path, '\n''# Locators for All Items(Tabs)') # OS.append_to_file(path, '\n''${All_App_Launcher_loc} //img[@title=\'All Tabs\']') # OS.append_to_file(path, '\n''${%s_tab_link_loc} //img[@title=\'%s\']' % (object, obj)) # OS.append_to_file(path, '\n') try: for xpathdata in xpath_values: OS.append_to_file(path, xpathdata) OS.append_to_file(path, '\n') except: print "No Object" writeToFile_keywords(object, obj, sf_type)
def check_for_environment_variables(): variables = OperatingSystem().get_environment_variables() env_vars = { "RC_API_SECRET_HOST": variables.get("RC_API_SECRET_HOST", None), "RC_WORKSPACE_ID": variables.get("RC_WORKSPACE_ID", None), "RC_API_SECRET_TOKEN": variables.get("RC_API_SECRET_TOKEN", None), } return env_vars
def set_command(): """Access Robocorp Vault in development enviroment """ click.secho("Use Robocorp Vault", fg="white", bold=True, underline=True) dev_account_exist = does_dev_access_account_exist() if dev_account_exist: click.echo("DEV access account already exists") else: ask_for_access_credentials() env_vars = check_for_environment_variables() workspace = click.prompt( "What is your workspace ID?", default=env_vars["RC_WORKSPACE_ID"], show_default=True, ) # token_validity = click.prompt( # "Access token validity time in minutes (max 1440 min = 24 hours)", # default=1440, # type=int, # ) token_validity = 1440 ret = run_command(f"rcc cloud authorize -a DEV -w {workspace} -m {token_validity}") if "Error:" in ret: click.echo(ret) return ret = json.loads(ret) expiry_time = ret["when"] + timedelta(minutes=token_validity).total_seconds() try: OperatingSystem().count_files_in_directory( os.path.join(".", "devdata"), "env.json" ) response = click.confirm( "Do you want to update environment variables in devdata/env.json ?", default=True, ) if response: content = OperatingSystem().get_file("devdata/env.json") content = json.loads(content) content["RC_WORKSPACE_ID"] = workspace content["RC_API_SECRET_TOKEN"] = ret["token"] content["RC_API_SECRET_HOST"] = "https://api.eu1.robocloud.eu" with open("devdata/env.json", "w") as fout: fout.write(json.dumps(content, sort_keys=False, indent=4)) except RuntimeError: response = click.confirm( "devdata/env.json does not exist - do you want to create it ?", default=True ) if response: env_vars["RC_WORKSPACE_ID"] = workspace env_vars["RC_API_SECRET_TOKEN"] = ret["token"] env_vars["RC_API_SECRET_HOST"] = "https://api.eu1.robocloud.eu" OperatingSystem().create_file( os.path.join(".", "devdata/env.json"), json.dumps(env_vars) ) click.echo(f"Token expires at {datetime.fromtimestamp(expiry_time)}")
def __init__(self, output_dir=None, test_log_folder_name='Advanced_Logs'): """ 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.sep = '/'
def __init__(self, application, timeout='60 seconds'): """ApplicationLauncher takes one mandatory and one optional argument. `application` is a required argument, it is the name of the main class or the class that has the main method. `timeout` is the timeout used to wait for importing a remote library. """ self.application = application self.timeout = timestr_to_secs(timeout) self.builtin = BuiltIn() self.operating_system = OperatingSystem() self.rmi_url = None
def create_data_file(self): """Create a file with the given name. The file name must be defined first using `Define File Name` keyword. This keyword leverages the Robot Framework OperatingSystem library keyword `Create File`, so if the directory for the file does not exist, it is created, along with missing intermediate directories.""" if self.absolute_name is None: raise AssertionError("The file name has not been defined. Define it using the 'Define File Name' keyword") else: operating_sys = OperatingSystem() try: operating_sys.create_file(self.absolute_name) self._exists = True except PermissionError as e: logger.error(e.strerror) raise
def remove_data_file(self): """Remove a file with the given name. The file name must be defined first using `Define File Name` keyword. This keyword leverages the Robot Framework OperatingSystem library keyword `Remove File`. If the file does not exist, nothing will happen.""" if self.absolute_name is None: raise AssertionError("The file name has not been defined. Define it using the 'Define File Name' keyword") else: operating_sys = OperatingSystem() try: operating_sys.remove_file(self.absolute_name) self._exists = False except PermissionError as e: logger.error(e.strerror) raise
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 __init__(self): self.params = Parameters() self.headers = Headers(APITEST="1") self.data = Data() self.requestBody = None self.status = Status() self.requestsKW = RequestsKeywords() self.fapiResponse = '' self.os = OperatingSystem() self.toObj = Json2Object()
def maybe_install_sdk(self, engine_memory_size_mb=None): variables = BuiltIn().get_variables() sdk_install_dir = variables['${SDK_INSTALL_DIR}'] use_existing_sdk_installation = variables[ '${USE_EXISTING_SDK_INSTALLATION}'] if use_existing_sdk_installation: OperatingSystem().directory_should_exist(sdk_install_dir) # Ensure we always return a valid result object return Process().run_process('true') try: OperatingSystem().directory_should_not_exist(sdk_install_dir) except: # Ensure maybe_uninstall_sdk will not destroy existing installation BuiltIn().set_global_variable('${USE_EXISTING_SDK_INSTALLATION}', True) raise command = variables['${INSTALLER}'] build_engine_type = variables['${BUILD_ENGINE_TYPE}'] args = [ '--verbose', 'non-interactive=1', 'accept-licenses=1', 'buildEngineType=' + build_engine_type ] result = self._run_process(command, *args, token='installer') if engine_memory_size_mb: args = ['engine', 'set', 'vm.memorySize=' + engine_memory_size_mb] result = self.run_sfdk(*args) if variables['${DO_SSU_REGISTER}']: credentials_file = variables['${CREDENTIALS}'] args = ['engine', 'exec', 'bash', '-c', 'creds=$(<"{}") && sdk-manage register-all --no-sdk --force \ --user "${{creds%%:*}}" --password "${{creds#*:}}"' \ .format(credentials_file)] result = self.run_sfdk(*args) return result
def create_env_json(workspace, token): response = click.confirm( "devdata/env.json does not exist - do you want to create it ?", default=True) if response: OperatingSystem().create_file("devdata/env.json") content = {} content["RC_WORKSPACE_ID"] = workspace content["RC_API_SECRET_TOKEN"] = token content["RC_API_SECRET_HOST"] = PROD_API_URL with open("devdata/env.json", "w", encoding="utf-8") as fout: fout.write(json.dumps(content, sort_keys=False, indent=4))
def __init__(self, output_dir=None, test_log_folder_name='Advanced_Logs'): """ 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.sep = '/'
def __init__(self, application, timeout='60 seconds', libdir=''): """ApplicationLauncher takes one mandatory and two optional arguments. `application` is a required argument, it is the name of the main class (the class that has the main method) or the url to the Java Webstart jnlp descriptor file. In case the `application` is a jnlp url `libdir` must be provided. `timeout` is the timeout used to wait for importing a remote library. `libdir` is the path to the directory which should contain jars which should contain all the dependencies required for running the tests. In another words these jar files should contain jvmconnector jar and libraries that you want to remotely import (packaged in jars). """ self.application = application self.timeout = timestr_to_secs(timeout or '60') self.libdir = libdir self.builtin = BuiltIn() self.operating_system = OperatingSystem() self.rmi_url = None self._assert_invariants()
def copy_file(self, src_path, filename=None, pre_config=None, pos_config=None): """ Copies a file from router Parameters: - `src_path`: a absolute path insides the router - `filename`: a file name under ``result`` folder """ # get current service and add ssh if it is necessary current_services = self.cmd('show configuration system services') if 'ssh' not in current_services: self.cmd('configure', prompt='# ') self.cmd('set system service ssh', prompt='# ') if pre_config is not None: for item in pre_config.split(';'): self.cmd(item, prompt='# ') self.cmd('commit synchronize and-quit') # prepare filepath if filename is None: _filename = os.path.basename(src_path) else: _filename = filename dst_path = '%s/%s' % (Common.get_result_path(), _filename) dst_path = dst_path.replace('(', '\(').replace(')', '\)') # _user = self._vchannel.get_current_channel()['auth']['user'] _pass = self._vchannel.get_current_channel()['auth']['pass'] _ip = self._vchannel.get_current_channel()['ip'] cmd = 'sshpass -p %s scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null %s@%s:%s %s' % ( _pass, _user, _ip, src_path, dst_path) rc, output = OperatingSystem().run_and_return_rc_and_output(cmd) BuiltIn().log(output) # cleanup additional configuration if 'ssh' not in current_services: self.cmd('configure', prompt='# ') self.cmd('delete system services ssh') if pos_config is not None: for item in pos_config.split(';'): self.cmd(item, prompt='# ') self.cmd('commit synchronize and-quit') if rc != 0: BuiltIn().log(output) raise (Exception("ERROR: error while copy a file with error:\n%s" % output)) BuiltIn().log('Copied file from `%s` to `%s`' % (src_path, filename))
def wait_file_count_in_directory(path: str, count: int, pattern: Optional[str] = None, absolute: bool = False, timeout: Union[int, str] = 3): wait_time = time.monotonic() + timestr_to_secs(timeout) while wait_time > time.monotonic(): file_count = len(OperatingSystem().list_files_in_directory( path, pattern, absolute)) logger.info(f"File count in {path} is {file_count}") if file_count == count: return file_count time.sleep(0.42) raise AssertionError( f"File count was {file_count}, but should have been {count} within {timeout}" )
def update_env_json(workspace, token): response = click.confirm( "Do you want to update environment variables in devdata/env.json ?", default=True, ) if response: content = OperatingSystem().get_file("devdata/env.json") if len(content) == 0: content = {} else: try: content = json.loads(content) except json.decoder.JSONDecodeError: output_and_exit( "Can't parse env.json contents. Check the file structure.") content["RC_WORKSPACE_ID"] = workspace content["RC_API_SECRET_TOKEN"] = token content["RC_API_SECRET_HOST"] = PROD_API_URL with open("devdata/env.json", "w", encoding="utf-8") as fout: fout.write(json.dumps(content, sort_keys=False, indent=4))
def __init__(self, application, timeout='60 seconds', libdir=''): """ApplicationLauncher takes one mandatory and two optional arguments. `application` is a required argument, it is the name of the main class (the class that has the main method) or the url to the Java Webstart jnlp descriptor file. In case the `application` is a jnlp url `libdir` must be provided. `timeout` is the timeout used to wait for importing a remote library. `libdir` is the path to the directory which should contain jars which should contain all the dependencies required for running the tests. In another words these jar files should contain jvmconnector jar and libraries that you want to remotely import (packaged in jars). """ self.application = application self.timeout = timestr_to_secs(timeout or '60') self.libdir = libdir self.builtin = BuiltIn() self.operating_system = OperatingSystem() self.rmi_url = None self._assert_invariants()
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)
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 ApplicationLauncher: """A library for starting java application in separate JVM and importing remote libraries for operating it. """ def __init__(self, application, timeout='60 seconds'): """ApplicationLauncher takes one mandatory and one optional argument. `application` is a required argument, it is the name of the main class or the class that has the main method. `timeout` is the timeout used to wait for importing a remote library. """ self.application = application self.timeout = timestr_to_secs(timeout) self.builtin = BuiltIn() self.operating_system = OperatingSystem() self.rmi_url = None def start_application(self, args='', jvm_args=''): """Starts the application with given arguments. `args` optional application arguments.. `jvm_args` optional jvm arguments. Example: | Start Application | one two three | -Dproperty=value | """ pythonpath = self._get_python_path() command = 'jython -Dpython.path=%s %s %s %s %s' % (pythonpath, jvm_args, __file__, self.application, args) self.operating_system.start_process(command) self.application_started() def import_remote_library(self, library_name, *args): """Imports a library with given arguments for the application. Application needs to be started before using this keyword. In case the application is started externally, `Application Started` keyword has to be used beforehand. In case there is multiple applications, there is need to have one ApplicationLauncher per application. In that case, starting application and library imports needs to be in sequence. It is not possible to start multiple applications and then import libraries to those. Examples: | Start Application | arg1 | | Import Remote Library | SwingLibrary | or | Application Started | | Import Remote Library | SwingLibrary | """ library_url = self._run_remote_import(library_name) newargs = self._add_name_to_args_if_necessary(library_name, args) self._prepare_for_reimport_if_necessary(library_url, *newargs) self.builtin.import_library('ApplicationLauncher.RemoteLibrary', library_url, *newargs) def close_application(self): """Closes the active application. If same application is opened multiple times, only the latest one is closed. Therefore you should close the application before starting it again.""" rmi_client = self._connect_to_base_rmi_service() self.rmi_url = None try: rmi_client.getObject().closeService() except RemoteAccessException: return raise RuntimeError('Could not close application.') def application_started(self): """Notifies ApplicationLauncher that application is launched externally. Required before taking libraries into use with `Import Remote Library` when application is started with ApplicationLauncher.py script. """ self.rmi_url = None self._connect_to_base_rmi_service() def _get_python_path(self): for path_entry in sys.path: if path.exists(path.join(path_entry, 'robot')): return path_entry def _add_name_to_args_if_necessary(self, library_name, args): if len(args) >= 2 and args[-2].upper() == 'WITH NAME': return args return sum((args,), ('WITH NAME', library_name)) def _prepare_for_reimport_if_necessary(self, library_url, *args): lib = Importer().import_library('ApplicationLauncher.RemoteLibrary', sum((args,), (library_url,))) testlibs = NAMESPACES.current._testlibs if testlibs.has_key(lib.name): testlibs.pop(lib.name) def _connect_to_base_rmi_service(self): start_time = time.time() while time.time() - start_time < self.timeout: url = self._retrieve_base_rmi_url() try: return self._create_rmi_client(url) except (BeanCreationException, RemoteAccessException, InvalidURLException): time.sleep(2) raise RuntimeError('Could not connect to application %s' % self.application) def _run_remote_import(self, library_name): try: rmi_client = self._connect_to_base_rmi_service() return rmi_client.getObject().importLibrary(library_name) except (BeanCreationException, RemoteAccessException): raise RuntimeError('Could not connect to application %s' % self.application) def _retrieve_base_rmi_url(self): if self.rmi_url: return self.rmi_url return LibraryDb(DATABASE).retrieve_base_rmi_url() def _create_rmi_client(self, url): if not re.match('rmi://[^:]+:\d{1,5}/.*', url): raise InvalidURLException() rmi_client = RmiProxyFactoryBean(serviceUrl=url, serviceInterface=LibraryImporter) rmi_client.prepare() rmi_client.afterPropertiesSet() self._save_base_url_and_clean_db(url) return rmi_client def _save_base_url_and_clean_db(self, url): self.rmi_url = url if path.exists(DATABASE): remove(DATABASE)
def writeToFile_Settings(object, obj, sf_type): global OS, path OS = OperatingSystem() path = '../../Resources/MedvantageApp/PO/%s_Page_%s.robot' % (object, sf_type) OS.create_file(path, '*** Settings ***') print 'Printing Settings ....' OS.append_to_file(path, '\n') OS.append_to_file(path, 'Documentation %s Page Reusable Keywords' % object) OS.append_to_file(path, '\n') OS.append_to_file(path, 'Library Selenium2Library') OS.append_to_file(path, '\n') OS.append_to_file(path, 'Library OperatingSystem') OS.append_to_file(path, '\n') # OS.append_to_file(path, 'Library ../../common-variables.robot') OS.append_to_file(path, '\n') OS.append_to_file(path, 'Resource ../../common-methods.robot') OS.append_to_file(path, '\n') OS.append_to_file(path, 'Library ../../../Library/Libs/datepicker.py') OS.append_to_file(path, '\n') OS.append_to_file(path, '\n') writeToFile_variables(object, obj, sf_type)
def _run_command_with_java_tool_options(self, command, lib_dir, port): orig_java_tool_options = self._get_java_tool_options() os.environ['JAVA_TOOL_OPTIONS'] = self._get_java_agent(lib_dir, port) OperatingSystem().start_process(command) os.environ['JAVA_TOOL_OPTIONS'] = orig_java_tool_options
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)
def __init__(self): self.oslib = OperatingSystem() self.collections = Collections()
def __init__(self): self._builtin = BuiltIn() self._os = OperatingSystem()
class ApplicationLauncher: """A library for starting java application or Java Webstart application and importing remote libraries for operating it. The application is started as a separate process. """ ROBOT_LIBRARY_SCOPE = 'TEST SUITE' def __init__(self, application, timeout='60 seconds', libdir=''): """ApplicationLauncher takes one mandatory and two optional arguments. `application` is a required argument, it is the name of the main class (the class that has the main method) or the url to the Java Webstart jnlp descriptor file. In case the `application` is a jnlp url `libdir` must be provided. `timeout` is the timeout used to wait for importing a remote library. `libdir` is the path to the directory which should contain jars which should contain all the dependencies required for running the tests. In another words these jar files should contain jvmconnector jar and libraries that you want to remotely import (packaged in jars). """ self.application = application self.timeout = timestr_to_secs(timeout or '60') self.libdir = libdir self.builtin = BuiltIn() self.operating_system = OperatingSystem() self.rmi_url = None self._assert_invariants() def start_application(self, args='', jvm_args=''): """Starts the application with given arguments. `args` optional application arguments.. `jvm_args` optional jvm arguments. Example: | Start Application | one two three | -Dproperty=value | """ command = self._create_command(args, jvm_args) self.operating_system.start_process(command) self.application_started() def import_remote_library(self, library_name, *args): """Imports a library with given arguments for the application. Application needs to be started before using this keyword. In case the application is started externally, `Application Started` keyword has to be used beforehand. In case there is multiple applications, there is need to have one ApplicationLauncher per application. In that case, starting application and library imports needs to be in sequence. It is not possible to start multiple applications and then import libraries to those. Examples: | Start Application | arg1 | | Import Remote Library | SwingLibrary | or | Application Started | | Import Remote Library | SwingLibrary | """ library_url = self._run_remote_import(library_name) newargs = self._add_name_to_args_if_necessary(library_name, args) self._prepare_for_reimport_if_necessary(library_url, *newargs) self.builtin.import_library('ApplicationLauncher.RemoteLibrary', library_url, *newargs) def close_application(self): """Closes the active application. If same application is opened multiple times, only the latest one is closed. Therefore you should close the application before starting it again.""" rmi_client = self._connect_to_base_rmi_service() self.rmi_url = None try: rmi_client.getObject().closeService() except RemoteAccessException: return raise RuntimeError('Could not close application.') def application_started(self): """Notifies ApplicationLauncher that application is launched externally. Required before taking libraries into use with `Import Remote Library` when application is started with ApplicationLauncher.py script. """ self.rmi_url = None self._connect_to_base_rmi_service() def _create_command(self, args, jvm_args): if (self._is_jnlp_application()): jnlp = JnlpEnhancer(self.libdir).createRmiEnhancedJnlp(self.application) return 'javaws %s %s' % (jvm_args, jnlp) else: pythonpath = self._get_python_path() out_file, err_file = self._get_output_files() return 'jython -Dpython.path="%s" %s "%s" %s %s 1>%s 2>%s' % (pythonpath, jvm_args, __file__, self.application, args, out_file, err_file) def _is_jnlp_application(self): return self.application.startswith('http') or path.isfile(self.application) def _get_output_files(self): out_file = mktemp('%s.out' % self.application) err_file = mktemp('%s.err' % self.application) return out_file, err_file def _get_python_path(self): for path_entry in sys.path: if path.exists(path.join(path_entry, 'robot')): return path_entry def _add_name_to_args_if_necessary(self, library_name, args): if len(args) >= 2 and args[-2].upper() == 'WITH NAME': return args return sum((args,), ('WITH NAME', library_name)) def _prepare_for_reimport_if_necessary(self, library_url, *args): lib = Importer().import_library('ApplicationLauncher.RemoteLibrary', sum((args,), (library_url,))) testlibs = NAMESPACES.current._testlibs if testlibs.has_key(lib.name): testlibs.pop(lib.name) def _connect_to_base_rmi_service(self): start_time = time.time() while time.time() - start_time < self.timeout: url = self._retrieve_base_rmi_url() try: return self._create_rmi_client(url) except (BeanCreationException, RemoteAccessException, InvalidURLException): time.sleep(2) raise RuntimeError('Could not connect to application %s' % self.application) def _run_remote_import(self, library_name): try: rmi_client = self._connect_to_base_rmi_service() return rmi_client.getObject().importLibrary(library_name) except (BeanCreationException, RemoteAccessException): raise RuntimeError('Could not connect to application %s' % self.application) def _retrieve_base_rmi_url(self): if self.rmi_url: return self.rmi_url return RmiInfoStorage(DATABASE).retrieve() def _create_rmi_client(self, url): if not re.match('rmi://[^:]+:\d{1,5}/.*', url): raise InvalidURLException() rmi_client = RmiProxyFactoryBean(serviceUrl=url, serviceInterface=LibraryImporter) rmi_client.prepare() rmi_client.afterPropertiesSet() self._save_base_url_and_clean_db(url) return rmi_client def _save_base_url_and_clean_db(self, url): self.rmi_url = url if path.exists(DATABASE): remove(DATABASE) def _assert_invariants(self): if self._is_jnlp_application(): self._assert_libdir_is_correct() def _assert_libdir_is_correct(self): if len(self.libdir) == 0: raise RuntimeError('Library directory required for test dependencies.') else: if not path.isdir(self.libdir): raise RuntimeError("Library directory '%s' doesn't exist." % self.libdir)
def opsys(self): return OperatingSystem()
class Utility(object): """Utility keywords for Requests operations.""" def __init__(self): self._builtin = BuiltIn() self._os = OperatingSystem() def get_json_file(self, path): """Returns [http://goo.gl/o0X6Pp|JSON] object from [http://goo.gl/o0X6Pp|JSON] file with all variables replaced. Arguments: - ``path``: The path to JSON file. Examples: _request.json_ | [{ | "bad": ${false}, | "good": ${true}, | "key": 5.5, | "key2": "value2" | }] | @{var} = | Get JSON File | request.json | | # [{'key2': 'value2', 'bad': False, 'good': True, 'key': Decimal('5.5')}] | """ content = self._os.get_file(path) content = self._builtin.replace_variables(content) content = sub(r'(False|True)', lambda match: match.group(1).lower(), content) logger.debug(content) return self.json_loads(content) def json_loads(self, text): # pylint: disable=line-too-long """Returns [http://goo.gl/o0X6Pp|JSON] object from [http://goo.gl/o0X6Pp|JSON] string with object restoration support. Arguments: - ``text``: JSON string. Supported object restoration: | `py/dict` | | `py/tuple` | | `py/set` | | `py/collections.namedtuple` | | `py/collections.OrderedDict` | Examples: | @{var} = | JSON Loads | [{"key":"value"}] | | @{var} = | JSON Loads | [{"py/dict":{"key":"value"}}] | | @{var} = | JSON Loads | [{"py/tuple":(1,2,3)}] | | @{var} = | JSON Loads | [{"py/set":[1,2,3]}] | | @{var} = | JSON Loads | [{"py/collections.namedtuple":{"fields":"a b c","type":"NAME","values":(0,1,2)}}] | | @{var} = | JSON Loads | [{"py/collections.OrderedDict":[("key2",2),("key1",1)]}] | """ # pylint: disable=line-too-long return loads(text, object_hook=self._restore, parse_float=Decimal) def natural_sort_list_of_dictionaries(self, items, key): """Returns natural sorted list of dictionaries. Arguments: - ``items``: List of dictionaries to be sorted. - ``key``: The dictionary key to be used to sort. Examples: | @{var} = | Natural Sort List Of Dictionaries | ${list} | key | """ def _natural_sorter(item): """Returns splitted aphanumeric value list of given dictionary key.""" return [self._cast_alphanumeric(text) for text in split('([0-9]+)', item[key])] return sorted(items, key=_natural_sorter) @staticmethod def _cast_alphanumeric(text): """Casts alphanumeric value.""" return int(text) if text.isdigit() else text.lower() @staticmethod def _restore(dct): """Returns restored object.""" if "py/dict" in dct: return dict(dct["py/dict"]) if "py/tuple" in dct: return tuple(dct["py/tuple"]) if "py/set" in dct: return set(dct["py/set"]) if "py/collections.namedtuple" in dct: data = dct["py/collections.namedtuple"] return namedtuple(data["type"], data["fields"])(*data["values"]) # if "py/numpy.ndarray" in dct: # data = dct["py/numpy.ndarray"] # return np.array(data["values"], dtype=data["dtype"]) if "py/collections.OrderedDict" in dct: return OrderedDict(dct["py/collections.OrderedDict"]) return dct
class ApplicationLauncher: """A library for starting java application or Java Webstart application and importing remote libraries for operating it. The application is started as a separate process. """ ROBOT_LIBRARY_SCOPE = 'TEST SUITE' def __init__(self, application, timeout='60 seconds', libdir=''): """ApplicationLauncher takes one mandatory and two optional arguments. `application` is a required argument, it is the name of the main class (the class that has the main method) or the url to the Java Webstart jnlp descriptor file. In case the `application` is a jnlp url `libdir` must be provided. `timeout` is the timeout used to wait for importing a remote library. `libdir` is the path to the directory which should contain jars which should contain all the dependencies required for running the tests. In another words these jar files should contain jvmconnector jar and libraries that you want to remotely import (packaged in jars). """ self.application = application self.timeout = timestr_to_secs(timeout or '60') self.libdir = libdir self.builtin = BuiltIn() self.operating_system = OperatingSystem() self.rmi_url = None self._assert_invariants() def start_application(self, args='', jvm_args=''): """Starts the application with given arguments. `args` optional application arguments.. `jvm_args` optional jvm arguments. Example: | Start Application | one two three | -Dproperty=value | """ command = self._create_command(args, jvm_args) self.operating_system.start_process(command) self.application_started() def import_remote_library(self, library_name, *args): """Imports a library with given arguments for the application. Application needs to be started before using this keyword. In case the application is started externally, `Application Started` keyword has to be used beforehand. In case there is multiple applications, there is need to have one ApplicationLauncher per application. In that case, starting application and library imports needs to be in sequence. It is not possible to start multiple applications and then import libraries to those. Examples: | Start Application | arg1 | | Import Remote Library | SwingLibrary | or | Application Started | | Import Remote Library | SwingLibrary | """ library_url = self._run_remote_import(library_name) newargs = self._add_name_to_args_if_necessary(library_name, args) self._prepare_for_reimport_if_necessary(library_url, *newargs) self.builtin.import_library('ApplicationLauncher.RemoteLibrary', library_url, *newargs) def close_application(self): """Closes the active application. If same application is opened multiple times, only the latest one is closed. Therefore you should close the application before starting it again.""" rmi_client = self._connect_to_base_rmi_service() self.rmi_url = None try: rmi_client.getObject().closeService() except RemoteAccessException: return raise RuntimeError('Could not close application.') def application_started(self): """Notifies ApplicationLauncher that application is launched externally. Required before taking libraries into use with `Import Remote Library` when application is started with ApplicationLauncher.py script. """ self.rmi_url = None self._connect_to_base_rmi_service() def _create_command(self, args, jvm_args): if (self._is_jnlp_application()): jnlp = JnlpEnhancer(DATABASE, self.libdir).createRmiEnhancedJnlp(self.application) return 'javaws %s %s' % (jvm_args, jnlp) else: pythonpath = self._get_python_path() out_file, err_file = self._get_output_files() return 'jython -Dpython.path="%s" %s "%s" %s %s 1>%s 2>%s' % (pythonpath, jvm_args, __file__, self.application, args, out_file, err_file) def _is_jnlp_application(self): return self.application.startswith('http') and self.application.endswith('jnlp') def _get_output_files(self): out_file = mktemp('%s.out' % self.application) err_file = mktemp('%s.err' % self.application) return out_file, err_file def _get_python_path(self): for path_entry in sys.path: if path.exists(path.join(path_entry, 'robot')): return path_entry def _add_name_to_args_if_necessary(self, library_name, args): if len(args) >= 2 and args[-2].upper() == 'WITH NAME': return args return sum((args,), ('WITH NAME', library_name)) def _prepare_for_reimport_if_necessary(self, library_url, *args): lib = Importer().import_library('ApplicationLauncher.RemoteLibrary', sum((args,), (library_url,))) testlibs = NAMESPACES.current._testlibs if testlibs.has_key(lib.name): testlibs.pop(lib.name) def _connect_to_base_rmi_service(self): start_time = time.time() while time.time() - start_time < self.timeout: url = self._retrieve_base_rmi_url() try: return self._create_rmi_client(url) except (BeanCreationException, RemoteAccessException, InvalidURLException): time.sleep(2) raise RuntimeError('Could not connect to application %s' % self.application) def _run_remote_import(self, library_name): try: rmi_client = self._connect_to_base_rmi_service() return rmi_client.getObject().importLibrary(library_name) except (BeanCreationException, RemoteAccessException): raise RuntimeError('Could not connect to application %s' % self.application) def _retrieve_base_rmi_url(self): if self.rmi_url: return self.rmi_url return RmiInfoStorage(DATABASE).retrieve() def _create_rmi_client(self, url): if not re.match('rmi://[^:]+:\d{1,5}/.*', url): raise InvalidURLException() rmi_client = RmiProxyFactoryBean(serviceUrl=url, serviceInterface=LibraryImporter) rmi_client.prepare() rmi_client.afterPropertiesSet() self._save_base_url_and_clean_db(url) return rmi_client def _save_base_url_and_clean_db(self, url): self.rmi_url = url if path.exists(DATABASE): remove(DATABASE) def _assert_invariants(self): if self._is_jnlp_application(): self._assert_libdir_is_correct() def _assert_libdir_is_correct(self): if len(self.libdir) == 0: raise RuntimeError('Library directory required for test dependencies.') else: if not path.isdir(self.libdir): raise RuntimeError("Library directory '%s' doesn't exist." % self.libdir)
def __init__(self): self._builtin = BuiltIn() self._os = OperatingSystem()
def __init__(self): self.oslib = OperatingSystem() self.collections = Collections()
import os from robot.libraries.OperatingSystem import OperatingSystem root = os.path.dirname(os.path.abspath(__file__)) + "\\.." OS = OperatingSystem()
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()
def run_command(command): ret = OperatingSystem().run(command) return ret
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)
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()
from robot.libraries.OperatingSystem import OperatingSystem os = OperatingSystem() # To make sure that the folders stay the same no matter the environment where we execute our robot, we # will use the normalize_path function provided by the Operating System robotframework library. EXCEL_FILE_PATH = os.normalize_path(__file__ + "/../../devdata/Data.xlsx") PDF_TEMPLATE_PATH = os.normalize_path( __file__ + "/../../devdata/invite.template") PDF_TEMP_OUTPUT_DIRECTORY = os.normalize_path( __file__ + "/../../output/pdf") OUTPUT_DIRECTORY = os.normalize_path( __file__ + "/../../output")
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)