def repeat_key_up_until_image_found(image_pattern, num_of_key_up_presses=10, delay_between_presses=1): """ Press the Key Up button until specified image pattern is found. :param image_pattern: Image Pattern to search. :param num_of_key_up_presses: Number of presses of the Key Up button. :param delay_between_presses: Number of seconds to wait between the Key Down presses :return: Boolean. True if image pattern found during the Key Up button pressing, False otherwise """ if not isinstance(image_pattern, Pattern): raise ValueError(INVALID_GENERIC_INPUT) pattern_found = False for _ in range(num_of_key_up_presses): pattern_found = exists(image_pattern) if pattern_found: break type(Key.UP) time.sleep(delay_between_presses) return pattern_found
def close_tab(): """Close the currently focused tab (Except for app tabs).""" if OSHelper.is_mac(): type(text="w", modifier=KeyModifier.CMD) else: type(text="w", modifier=KeyModifier.CTRL) time.sleep(Settings.DEFAULT_UI_DELAY)
def select_search_bar(): """If the search bar is present, select the search bar, otherwise this selects the location bar.""" if OSHelper.is_mac(): type(text='k', modifier=KeyModifier.CMD) else: type(text='k', modifier=KeyModifier.CTRL) time.sleep(Settings.DEFAULT_UI_DELAY_LONG)
def new_tab(): """Open a new browser tab.""" if OSHelper.is_mac(): type(text='t', modifier=KeyModifier.CMD) else: type(text='t', modifier=KeyModifier.CTRL) time.sleep(Settings.DEFAULT_UI_DELAY)
def maximize_window(): """Maximize the browser window to fill the screen. This is NOT Full Screen mode. """ if OSHelper.is_mac(): # There is no keyboard shortcut for this on Mac. We'll do it the old fashioned way. # This image is of the three window control buttons at top left of the window. # We have to resize the window to ensure maximize works properly in all cases. window_controls_pattern = Pattern('window_controls.png') controls_location = find(window_controls_pattern) xcoord = controls_location.x ycoord = controls_location.y width, height = window_controls_pattern.get_size() drag_start = Location(xcoord + 70, ycoord + 5) drag_end = Location(xcoord + 75, ycoord + 5) Mouse().drag_and_drop(drag_start, drag_end, duration=0.1) # Alt key changes maximize button from full screen to maximize window. maximize_button = window_controls_pattern.target_offset(width / 2 - 3, 0) key_down(Key.ALT) click(maximize_button) key_up(Key.ALT) elif OSHelper.is_windows(): type(text=Key.UP, modifier=KeyModifier.WIN) else: type(text=Key.UP, modifier=[KeyModifier.CTRL, KeyModifier.META]) time.sleep(Settings.DEFAULT_UI_DELAY)
def select_zoom_menu_option(option_number): """Open the 'Zoom' menu from the 'View' menu and select option.""" open_zoom_menu() repeat_key_down(option_number) type(text=Key.ENTER)
def restore_window_from_taskbar(option=None): """Restore firefox from task bar.""" if OSHelper.is_mac(): try: click(Pattern("main_menu_window.png")) if option == "browser_console": click(Pattern("window_browser_console.png")) else: click(Pattern("window_firefox.png")) except FindError: raise APIHelperError("Restore window from taskbar unsuccessful.") elif OSHelper.get_os_version() == "win7": try: click(Pattern("firefox_start_bar.png")) if option == "library_menu": click(Pattern("firefox_start_bar_library.png")) if option == "browser_console": click(Pattern("firefox_start_bar_browser_console.png")) except FindError: raise APIHelperError("Restore window from taskbar unsuccessful.") else: type(text=Key.TAB, modifier=KeyModifier.ALT) if OSHelper.is_linux(): Mouse().move(Location(0, 50)) time.sleep(Settings.DEFAULT_UI_DELAY)
def right_click_and_type(target, delay=None, keyboard_action=None): right_click(target) if delay: time.sleep(delay) else: time.sleep(Settings.DEFAULT_UI_DELAY_LONG) type(text=keyboard_action)
def paste(text: str): """ :param text: Text to be pasted. :return: None. """ pyperclip.copy(text) text_copied = False wait_scan_rate = float(Settings.wait_scan_rate) interval = 1 / wait_scan_rate max_attempts = int(Settings.auto_wait_timeout * wait_scan_rate) attempt = 0 while not text_copied and attempt < max_attempts: if pyperclip.paste() == text: text_copied = True else: time.sleep(interval) attempt += 1 if not text_copied: raise FindError("Paste method failed.") if OSHelper.is_mac(): type(text="v", modifier=KeyModifier.CMD) else: type(text="v", modifier=KeyModifier.CTRL) pyperclip.copy("")
def history_sidebar(): """Toggle open/close the history sidebar.""" if OSHelper.is_mac(): type(text='h', modifier=[KeyModifier.CMD, KeyModifier.SHIFT]) else: type(text='h', modifier=KeyModifier.CTRL) time.sleep(Settings.DEFAULT_UI_DELAY)
def close_window(): """Close the currently focused window.""" if OSHelper.is_mac(): type(text="w", modifier=[KeyModifier.CMD, KeyModifier.SHIFT]) else: type(text="w", modifier=[KeyModifier.CTRL, KeyModifier.SHIFT]) time.sleep(Settings.DEFAULT_UI_DELAY)
def bookmark_all_tabs(): """Open the Bookmark All Tabs dialog.""" if OSHelper.is_mac(): type(text='d', modifier=[KeyModifier.CMD, KeyModifier.SHIFT]) else: type(text='d', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT]) # Wait for the Bookmark All Tabs dialog to be opened. time.sleep(Settings.DEFAULT_UI_DELAY_LONG)
def restart_via_console(): """ restarts Firefox if web console is opened """ if OSHelper.is_mac(): type(text='r', modifier=[KeyModifier.CMD, KeyModifier.ALT]) else: type(text='r', modifier=[KeyModifier.CTRL, KeyModifier.ALT])
def select_location_bar(): """Set focus to the location bar.""" if OSHelper.is_mac(): type(text='l', modifier=KeyModifier.CMD) else: type(text='l', modifier=KeyModifier.CTRL) # Wait to allow the location bar to become responsive. time.sleep(Settings.DEFAULT_UI_DELAY_LONG)
def open_browser_console(): """ Opens the Browser Console. """ if OSHelper.is_mac(): type(text="j", modifier=[KeyModifier.CMD, KeyModifier.SHIFT]) else: type(text="j", modifier=[KeyModifier.CTRL, KeyModifier.SHIFT])
def select_folder_location_bar(): """Set focus to the location bar/open folder popup in previously opened file manager (e.g. "Open file", "Import bookmark") to navigate to path""" if OSHelper.is_mac(): type(text='g', modifier=[KeyModifier.SHIFT, KeyModifier.CMD]) else: type(text='l', modifier=KeyModifier.CTRL)
def change_search_previous(): """If the search bar has focus, change the search engine to the previous in the list. (side effect: this also opens the search engine manager, if it wasn't already open). """ if OSHelper.is_mac(): type(text=Key.UP, modifier=KeyModifier.CMD) else: type(text=Key.UP, modifier=KeyModifier.CTRL)
def find_previous(): """Find the previous occurrence of term, if find is already active on a search term. Find previous can also find the previous occurrence of a term without opening the find toolbar. """ if OSHelper.is_mac(): type(text='g', modifier=[KeyModifier.CMD, KeyModifier.SHIFT]) else: type(text='g', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT])
def repeat_key_down(num): """Repeat DOWN keystroke a given number of times. :param num: Number of times to repeat DOWN key stroke. :return: None. """ for i in range(num): type(Key.DOWN) time.sleep(Settings.DEFAULT_UI_DELAY_SHORT)
def repeat_key_up(num): """Repeat UP keystroke a given number of times. :param num: Number of times to repeat UP key stroke. :return: None. """ for i in range(num): type(Key.UP) time.sleep(1)
def find_next(): """Find next occurrence of term, if find is already active on a search term. Find next (again) can also find the next occurrence of a term without opening the find toolbar. """ if OSHelper.is_mac(): type(text='g', modifier=KeyModifier.CMD) else: type(text='g', modifier=KeyModifier.CTRL)
def open_firefox_menu(): """ Opens Firefox top menu """ if OSHelper.is_linux(): key_down(Key.ALT) time.sleep(0.5) key_up(Key.ALT) elif OSHelper.is_windows(): type(Key.ALT)
def bookmark_page(): """Bookmark the current page.""" if OSHelper.is_mac(): type(text='d', modifier=KeyModifier.CMD) else: type(text='d', modifier=KeyModifier.CTRL) try: wait(LocationBar.STAR_BUTTON_STARRED, 10) logger.debug('Page was successfully bookmarked') except FindError: raise APIHelperError('Page can not be bookmarked')
def navigate(url): """Navigates, via the location bar, to a given URL. :param url: The string to type into the location bar. :return: None. """ try: select_location_bar() paste(url) time.sleep(Settings.DEFAULT_UI_DELAY_SHORT) type(Key.ENTER) except Exception: raise APIHelperError("No active window found, cannot navigate to page.")
def confirm_close_multiple_tabs(): """Click confirm 'Close all tabs' for warning popup when multiple tabs are opened. """ close_all_tabs_button_pattern = Pattern("close_all_tabs_button.png") try: wait(close_all_tabs_button_pattern, 5) logger.debug('"Close all tabs" warning popup found.') type(Key.ENTER) except FindError: logger.debug('Couldn\'t find the "Close all tabs" warning popup.') pass
def open_library_menu(option): """Open a specific option from 'Library' menu with an option as an argument. :param option: Library menu option to be selected. :return: None """ library_menu_pattern = NavBar.LIBRARY_MENU library_option_list = { 'Bookmarks': 1, 'View Pocket List': 2, 'History': 3, 'Downloads': 4, 'Synced Tabs': 5 } if OSHelper.is_windows(): value = 5 else: value = 4 try: wait(library_menu_pattern, 10) region = Region( image_find(library_menu_pattern).x - Screen().width / value, image_find(library_menu_pattern).y, Screen().width / value, Screen().height / value, ) logger.debug("Library menu found.") except FindError: raise APIHelperError( "Can't find the library menu in the page, aborting test.") else: time.sleep(Settings.DEFAULT_UI_DELAY_LONG) click(library_menu_pattern) time.sleep(Settings.DEFAULT_UI_DELAY_SHORT) try: time.sleep(Settings.DEFAULT_UI_DELAY_SHORT) region.wait(LibraryMenu.BOOKMARKS_OPTION, 10) option_number_in_library_list = library_option_list[option] for _ in range(option_number_in_library_list): time.sleep(0.5) type(Key.TAB) time.sleep(1) type(Key.ENTER) except FindError: raise APIHelperError( "Can't find the option in the page, aborting test.")
def delete_selected_file(): """Delete selected file/files inside a folder.""" if OSHelper.is_mac(): type(text=Key.BACKSPACE, modifier=KeyModifier.CMD) elif OSHelper.get_os_version() == 'win7': type(text=Key.DELETE) type(text='y') else: type(text=Key.DELETE)
def key_to_one_off_search(highlighted_pattern, direction="left"): """Iterate through the one of search engines list until the given one is highlighted. param: highlighted_pattern: The pattern image to search for. param: direction: direction to key to: right or left (default) return: None. """ max_attempts = 7 while max_attempts > 0: if exists(highlighted_pattern, 1): max_attempts = 0 else: if direction == "right": type(Key.RIGHT) else: type(Key.LEFT) max_attempts -= 1
def select_file_in_folder(directory, filename_pattern, file_option, max_num_of_attempts=3): """ Opens directory, selects file in opened directory, and provides action with it (e.g. copy, cut, delete), and closes opened directory. :param directory: Folder on hard drive to open. :param filename_pattern: File Pattern to select. :param file_option: File processing function. Appropriate methods are: edit_copy, edit_cut, edit_delete. :param max_num_of_attempts: Attempts to find pattern of file name. Default: 3 """ finder_list_view = '2' type_delay = 0.5 if not isinstance(directory, str): raise ValueError(INVALID_GENERIC_INPUT) if not isinstance(filename_pattern, Pattern): raise ValueError(INVALID_GENERIC_INPUT) if not callable(file_option): raise ValueError(INVALID_GENERIC_INPUT) open_directory(directory) try: for attempt in range(1, max_num_of_attempts + 1): file_located = exists(filename_pattern) if file_located: logger.debug('File {} in directory {} is available.'.format(filename_pattern, directory)) break else: if attempt == max_num_of_attempts: logger.debug('File {} is not available after {} attempt(s).'.format(filename_pattern, attempt)) raise Exception time.sleep(Settings.DEFAULT_UI_DELAY_LONG) if OSHelper.is_mac(): type(text=finder_list_view, modifier=KeyModifier.CMD, interval=type_delay) click(filename_pattern) file_option() except Exception: raise APIHelperError('Could not find file {} in folder {}.'.format(filename_pattern, directory)) finally: if OSHelper.is_windows(): type(text='w', modifier=KeyModifier.CTRL) elif OSHelper.is_linux(): type(text='q', modifier=KeyModifier.CTRL) elif OSHelper.is_mac(): type(text='w', modifier=[KeyModifier.CMD, KeyModifier.ALT])
def open_hamburger_menu(option=None): """Open a specific option from the hamburger menu. If no option is given, just open the menu. In that case, the calling test must close the menu on its own. :param option: Hamburger menu option to be selected. :return: None. """ hamburger_menu_pattern = NavBar.HAMBURGER_MENU region = Screen.UPPER_RIGHT_CORNER sign_in_to_firefox_pattern = Pattern("sign_in_to_firefox.png") option_list = { 'Restore Previous Session': 5, 'Customize': 14, 'Print': 17, 'Web Developer': 20, 'Help': 22, 'Exit': 23, 'Quit': 23 } try: region.wait(hamburger_menu_pattern, 5) logger.debug("Hamburger menu found.") except FindError: raise APIHelperError( 'Can\'t find the "hamburger menu" in the page, aborting test.') else: try: region.click(hamburger_menu_pattern) region.wait(sign_in_to_firefox_pattern, 10) if option is not None: reps = option_list[option] count = 0 while count < reps: time.sleep(0.5) type(Key.TAB) count = count + 1 time.sleep(1) type(Key.ENTER) except FindError: raise APIHelperError("Can't click the menu button. Aborting test.")