def get_full_image_path(icon): """Return image's full path.""" if icon.endswith('.png') or icon.endswith('.jpg'): full_path = download.get_path(icon) else: full_path = download.get_path('{}.png'.format(icon)) return full_path
def verify_file(filename): """Verify file exists. If reference file are not in default folders (images, files, downloads) then path should be defined. Returns path. Examples -------- .. code-block:: robotframework VerifyFile cat1.jpg VerifyFile C:/this/is/path/to/cat1.jpg ${path} VerifyFile dog.jpg Parameters ---------- filename : str Filename or path to find. """ try: path = download.get_path(filename) logger.info('File found. Filepath is {}'.format(path)) return path except QWebFileNotFoundError as e: raise QWebFileNotFoundError( 'File not found from default folders. ' 'It\'s not exists or you may need a full path.') from e
def move_files(files_to_move, destination_folder): r"""Move files. Examples -------- .. code-block:: robotframework MoveFiles cat1.jpg C:/secret_cat_pictures MoveFiles cat1.jpg, cat666.jpg, cat4.jpg C:/secret_cat_pictures Parameters ---------- files_to_move : str Files to move, separated by "," in case of multiple files. destination_folder : str Destination folder of the moved files. Related keywords ---------------- \`RemoveFile\`, \`SaveFile\`, \`UploadFile\`, \`VerifyFile\` """ if not os.path.isdir(destination_folder): raise QWebValueError('Destination folder does not exist.') files = files_to_move.split(',') for file in files: file = str(download.get_path(file.strip())) shutil.move(file, destination_folder)
def verify_input_values(input_values, timeout='0'): """Verify input fields have given values. Accepts a .txt file or Robot FW dictionary as a parameter. If using a text file, the locator and the expected value should be separated with a comma on each row. Examples -------- .. code-block:: robotframework VerifyInputValues list_of_locators_and_values.txt VerifyInputValues C:/Users/pace/Desktop/textfile.txt ${cool_dict}= Create Dictionary Name=Jane [email protected] ... Phone=04049292243923 Address=Yellow street 33 C 44 VerifyInputValues ${cool_dict} """ if isinstance(input_values, dict): for locator in input_values: logger.info('Locator: {}, Expected value: {}'.format(locator, input_values[locator]), also_console=True) verify_input_value(locator, input_values[locator]) elif input_values.endswith('.txt') or input_values.endswith('.csv'): file = download.get_path(input_values) with open(file, 'rb') as txt_file: params = [line.rstrip() for line in txt_file] for x in params: x = x.decode('utf-8').split(',') locator, value = x[0].strip(), x[1].strip() logger.info('Locator: {}, Expected value: {}'.format(locator, value), also_console=True) verify_input_value(locator, value, timeout=timeout) else: raise QWebValueError('Unknown input value. Text file or dictionary required.')
def type_texts(input_texts, timeout='0'): """Type text to multiple fields. Accepts a .txt file or Robot FW dictionary as a parameter. If using a text file, the locator and the text should be separated with a comma on each row. Examples -------- .. code-block:: robotframework TypeTexts list_of_locators_and_texts.txt TypeTexts C:/Users/pace/Desktop/textfile.txt ${cool_dict}= Create Dictionary Name=Jane [email protected] ... Phone=04049292243923 Address=Yellow street 33 C 44 TypeTexts ${cool_dict} """ if isinstance(input_texts, dict): for locator in input_texts: logger.info('Typing "{}", locator "{}"'.format(locator, input_texts[locator])) type_text(locator, input_texts[locator]) elif input_texts.endswith('.txt') or input_texts.endswith('.csv'): file = download.get_path(input_texts) with open(file, 'rb') as txt_file: params = [line.rstrip() for line in txt_file] for x in params: x = x.decode('utf-8').split(',') locator, text = x[0].strip(), x[1].strip() logger.info('Typing "{}", locator "{}"'.format(text, locator)) type_text(locator, text, timeout=timeout) else: raise QWebValueError('Unknown input value. Text file or dictionary required.')
def upload_file(locator, filename, anchor='1', timeout=0, index=1, **kwargs): r"""Upload file. Examples -------- .. code-block:: robotframework UploadFile Upload text.txt UploadFile Foo C:/path/to/file/test.pdf UploadFile 1 text.txt #Using index as locator With table(Pick table with use table keyword first): .. code-block:: robotframework UploadFile r1c1 text.txt Parameters ---------- locator : str Text or index that locates the upload element. filename : file to upload Default folders = users/downloads and project_dir/files anchor : str Index number or text near the input field's locator element. If the page contains many places where the locator is then anchor is used to select the wanted element. Index number selects the item from the list of matching entries starting with 1. Text selects the entry with the closest distance. timeout : str | int How long we find element before failing. Default 10 (seconds) index : int If table cell contains more than one input elements or if there is some kind of nested structure inside of given input index may needed. Default = 1 (first) kwargs : | Accepted kwargs: | limit_traverse : False. If limit traverse is set to false we are heading up to | fifth parent element if needed when finding relative input element for some label. Raises ------ ValueError: File not found Related keywords ---------------- \`SaveFile\` """ kwargs['css'] = kwargs.get('css', '[type="file"]') kwargs['upload'] = util.par2bool(kwargs.get('upload', True)) filepath = download.get_path(filename) if filepath: input_element = input_.get_input_elements_from_all_documents( locator, anchor, timeout=timeout, index=index, **kwargs) input_element.send_keys(str(filepath.resolve())) return raise QWebFileNotFoundError( 'Unable to find file {}. Tried from project/files and users/downloads'. format(filename))
def create_text_file_instance(filename): filepath = download.get_path(filename) try: with open(filepath, 'rb') as txt_file: data = txt_file.read() data = data.decode("utf-8") if data != '': return File(data, filepath) raise QWebValueMismatchError( 'Text not found. Seems that the file is empty.') except TypeError as e: raise QWebFileNotFoundError( 'File not found. Got {} instead.'.format(e)) from e
def create_pdf_instance(filename): all_text = '' filepath = download.get_path(filename) try: with open(filepath, 'rb') as pdf_obj: pdf = slate_pdf_reader.PDF(pdf_obj) for page in pdf: all_text += page.strip() if all_text != '': return File(all_text, filepath) raise QWebValueMismatchError( 'Text not found. Seems that the pdf is empty.') except TypeError as e: raise QWebFileNotFoundError( f'File not found. Got {e} instead.') from e except PSEOF as e: raise QWebFileNotFoundError( f'File found, but it\'s not valid pdf-file: {e}') from e
def zip_files(name_of_zip, files_to_zip): """Zip files. Examples -------- .. code-block:: robotframework ZipFiles my_zip_file rabbit.txt ZipFiles my_zip_file_2 dog.txt ZipFiles my_zip_file_3 rabbit.txt, dog.txt ZipFiles my_zip_file_4 C:/Users/pace/secrets/cat.txt ZipFiles my_zip_file_5 C:/Users/pace/secrets/cat.txt, C:/automation/kangaroo.txt Parameters ---------- name_of_zip : str Name of the zip file created. files_to_zip : str Files to be zipped, separated by "," in case of multiple files. """ if not name_of_zip.endswith('.zip'): name_of_zip += '.zip' files = files_to_zip.split(',') try: with ZipFile(name_of_zip, 'w') as zipped: for file in files: file = download.get_path(file.strip()) if os.path.isdir(file): for root, _, files2 in os.walk(file): for file2 in files2: zipped.write(os.path.join(root, file2)) else: zipped.write(file, basename(file)) except OSError as e: raise QWebValueError('\nFile name "{}" contained illegal characters.' '\nError message: {}'.format(name_of_zip, str(e))) logger.info('Zipped files {} into the file {}'.format( str(files), name_of_zip), also_console=True)