def access_and_check_pattern(access_pattern, msg, check_pattern=None, access_type=None): """Access and check(if it exists) the patterns received. :param access_pattern: pattern to find and access if access_type is not None. :param msg: Message to display on test result :param check_pattern: pattern to assert after accessing 'find_pattern'. :param access_type: action to be performed on the access_pattern image. TODO Add more actions when needed :return: None. """ try: exists = wait(access_pattern, 10) logger.debug("%s pattern is displayed properly." % access_pattern) if access_type and access_type == "click": click(access_pattern) except FindError: raise APIHelperError("Can't find the %s pattern, aborting." % access_pattern.get_filename()) if check_pattern: try: exists = wait(check_pattern, 15) logger.debug("%s pattern has been found." % check_pattern.get_filename()) except FindError: raise APIHelperError("Can't find the %s option, aborting." % check_pattern.get_filename()) return Step(exists, "%s was accessed and displayed properly." % msg)
def remove_zoom_indicator_from_toolbar(): """Remove the zoom indicator from toolbar by clicking on the 'Remove from Toolbar' button. """ zoom_control_toolbar_decrease_pattern = NavBar.ZOOM_OUT remove_from_toolbar_pattern = Pattern("remove_from_toolbar.png") try: wait(zoom_control_toolbar_decrease_pattern, FirefoxSettings.FIREFOX_TIMEOUT) logger.debug("'Decrease' zoom control found.") right_click(zoom_control_toolbar_decrease_pattern) except FindError: raise APIHelperError( "Can't find the 'Decrease' zoom control button in the page, \ aborting.") try: wait(remove_from_toolbar_pattern, FirefoxSettings.FIREFOX_TIMEOUT) logger.debug("'Remove from Toolbar' option found.") click(remove_from_toolbar_pattern) except FindError: raise APIHelperError( "Can't find the 'Remove from Toolbar' option in the page, \ aborting.") try: wait_vanish(zoom_control_toolbar_decrease_pattern, FirefoxSettings.FIREFOX_TIMEOUT) except FindError: raise APIHelperError( "Zoom indicator not removed from toolbar, aborting.")
def full_screen_control(window_type): """Click on full screen window mode (Applicable only for MAC system). :param window_type: Type of window that need to be maximized in full screen mode. :reurn: None. """ if OSHelper.is_mac(): find_window_controls(window_type) if window_type == "auxiliary": width, height = AuxiliaryWindow.AUXILIARY_WINDOW_CONTROLS.get_size() click( AuxiliaryWindow.AUXILIARY_WINDOW_CONTROLS.target_offset( width - 10, height / 2 ), align=Alignment.TOP_LEFT, ) else: width, height = MainWindow.MAIN_WINDOW_CONTROLS.get_size() click( MainWindow.MAIN_WINDOW_CONTROLS.target_offset(width - 10, height / 2), align=Alignment.TOP_LEFT, ) else: raise APIHelperError("Full screen mode applicable only for MAC")
def click_cancel_button(): """Click cancel button.""" cancel_button_pattern = Pattern("cancel_button.png").similar(0.7) try: wait(cancel_button_pattern, 10) logger.debug("Cancel button found.") click(cancel_button_pattern) except FindError: raise APIHelperError("Can't find the cancel button, aborting.")
def close_customize_page(): """Close the 'Customize...' page by pressing the 'Done' button.""" customize_done_button_pattern = Pattern("customize_done_button.png").similar(0.7) try: wait(customize_done_button_pattern, 10) logger.debug("Done button found.") click(customize_done_button_pattern) time.sleep(Settings.DEFAULT_UI_DELAY_LONG) except FindError: raise APIHelperError("Can't find the Done button in the page, aborting.")
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_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 minimize_window_control(window_type): """Click on minimize window control. :param window_type: Type of window that need to be minimized. :return: None. """ find_window_controls(window_type) if window_type == "auxiliary": if OSHelper.is_mac(): width, height = AuxiliaryWindow.AUXILIARY_WINDOW_CONTROLS.get_size( ) click(AuxiliaryWindow.AUXILIARY_WINDOW_CONTROLS.target_offset( width / 2, height / 2), align=Alignment.TOP_LEFT) else: click(AuxiliaryWindow.MINIMIZE_BUTTON) else: if OSHelper.is_mac(): width, height = MainWindow.MAIN_WINDOW_CONTROLS.get_size() click(MainWindow.MAIN_WINDOW_CONTROLS.target_offset( width / 2, height / 2), align=Alignment.TOP_LEFT) else: click(MainWindow.MINIMIZE_BUTTON)
def maximize_window_control(window_type): """Click on maximize window control. :param window_type: Type of window that need to be maximized. :return: None. """ find_window_controls(window_type) if window_type == "auxiliary": if OSHelper.is_mac(): key_down(Key.ALT) width, height = AuxiliaryWindow.AUXILIARY_WINDOW_CONTROLS.get_size( ) click( AuxiliaryWindow.AUXILIARY_WINDOW_CONTROLS.target_offset( width - 10, height / 2), align=Alignment.TOP_LEFT, ) key_up(Key.ALT) else: click(AuxiliaryWindow.MAXIMIZE_BUTTON) if OSHelper.is_linux(): reset_mouse() else: if OSHelper.is_mac(): key_down(Key.ALT) width, height = MainWindow.MAIN_WINDOW_CONTROLS.get_size() click(MainWindow.MAIN_WINDOW_CONTROLS.target_offset( width - 10, height / 2), align=Alignment.TOP_LEFT) key_up(Key.ALT) else: click(MainWindow.MAXIMIZE_BUTTON)
def restore_firefox_focus(): """Restore Firefox focus by clicking the panel near HOME or REFRESH button.""" try: if exists(NavBar.HOME_BUTTON, Settings.DEFAULT_UI_DELAY): target_pattern = NavBar.HOME_BUTTON else: target_pattern = NavBar.RELOAD_BUTTON w, h = target_pattern.get_size() horizontal_offset = w * 1.7 click_area = target_pattern.target_offset(horizontal_offset, 0) click(click_area) except FindError: raise APIHelperError("Could not restore firefox focus.")
def open_zoom_menu(): """Open the 'Zoom' menu from the 'View' menu.""" if OSHelper.is_mac(): view_menu_pattern = Pattern("view_menu.png") click(view_menu_pattern) repeat_key_down(3) type(text=Key.ENTER) else: type(text="v", modifier=KeyModifier.ALT) repeat_key_down(2) type(text=Key.ENTER)
def click(self, lps=None, duration=None, align=None): """Mouse left click. :param lps: Location, Pattern or String. :param duration: Speed of hovering from current location to target. :param align: Click location alignment could be top_left, center, top_right, bottom_left, bottom_right. :return: None. """ return click(lps, duration, self._area, align)
def select_throttling(option): open_web_console() try: wait(Pattern('network.png'), 10) click(Pattern('network.png')) except FindError: raise APIHelperError('Can\'t find the network menu in the page, aborting test.') try: wait(Pattern('no_throttling.png'), 10) click(Pattern('no_throttling.png')) except FindError: raise APIHelperError('Can\'t find the throttling menu in the page, aborting test.') for i in range(option + 1): type(Key.DOWN) type(Key.ENTER)
def create_region_for_hamburger_menu(): """Create region for hamburger menu pop up.""" hamburger_menu_pattern = NavBar.HAMBURGER_MENU try: wait(hamburger_menu_pattern, 10) click(hamburger_menu_pattern) sign_in_to_firefox_pattern = Pattern("sign_in_to_firefox.png").similar(0.6) wait(sign_in_to_firefox_pattern, 10) if OSHelper.is_linux(): quit_menu_pattern = Pattern("quit.png").similar(0.6) wait(quit_menu_pattern, 5) return RegionUtils.create_region_from_patterns( None, sign_in_to_firefox_pattern, quit_menu_pattern, None, padding_right=20, ) elif OSHelper.is_mac(): help_menu_pattern = Pattern("help.png") wait(help_menu_pattern, 5) return RegionUtils.create_region_from_patterns( None, sign_in_to_firefox_pattern, help_menu_pattern, None, padding_right=20, ) else: exit_menu_pattern = Pattern("exit.png").similar(0.6) wait(exit_menu_pattern, 5) return RegionUtils.create_region_from_patterns( None, sign_in_to_firefox_pattern, exit_menu_pattern, None, padding_right=20, ) except (FindError, ValueError): raise APIHelperError( "Can't create a region for the hamburger menu, aborting test." )
def open_bookmarks_toolbar(): """ Open the Bookmarks Toolbar using the context menu from the navigation bar """ home_button = NavBar.HOME_BUTTON w, h = home_button.get_size() horizontal_offset = w * 1.7 navbar_context_menu = home_button.target_offset(horizontal_offset, 0) try: right_click(navbar_context_menu) click(NavBar.ContextMenu.BOOKMARKS_TOOLBAR) logger.debug( "Click is performed successfully on Bookmarks Toolbar option from navigation bar context menu." ) except FindError: raise APIHelperError( "Could not open the Bookmarks Toolbar using context menu from the navigation bar." ) restore_firefox_focus()
def get_support_info(): """Returns support information as a JSON object from 'about:support' page.""" copy_raw_data_to_clipboard = Pattern( "about_support_copy_raw_data_button.png") new_tab() select_location_bar() paste("about:support") type(Key.ENTER) time.sleep(Settings.DEFAULT_UI_DELAY) try: click(copy_raw_data_to_clipboard) time.sleep(Settings.DEFAULT_UI_DELAY_LONG) json_text = get_clipboard() return json.loads(json_text) except Exception as e: raise APIHelperError( "Failed to retrieve support information value.\n{}".format(e)) finally: close_tab()
def open_library_menu(option): """Open the Library menu with an option as argument. :param option: Library menu option. :return: Custom region created for a more efficient and accurate image pattern search. """ library_menu_pattern = NavBar.LIBRARY_MENU 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(option, 10) logger.debug("Option found.") region.click(option) return region except FindError: raise APIHelperError( "Can't find the option in the page, aborting test.")
def access_bookmarking_tools(option): """Access option from 'Bookmarking Tools'. :param option: Option from 'Bookmarking Tools'. :return: None. """ bookmarking_tools_pattern = LibraryMenu.BookmarksOption.BOOKMARKING_TOOLS open_library_menu(LibraryMenu.BOOKMARKS_OPTION) try: wait(bookmarking_tools_pattern, 10) logger.debug("Bookmarking Tools option has been found.") click(bookmarking_tools_pattern) except FindError: raise APIHelperError("Can't find the Bookmarking Tools option, aborting.") try: wait(option, 15) logger.debug("%s option has been found." % option) click(option) except FindError: raise APIHelperError("Can't find the %s option, aborting." % option)
def download_file( file_to_download, accept_download, max_number_of_attempts=20, expect_accept_download_available=True, ): """ :param file_to_download: Pattern of file to be downloaded. :param accept_download: Accept download pattern. :param max_number_of_attempts: Max number of attempts to locate file_to_download pattern. :param expect_accept_download_available: True if we expect accept_download button, False - if we don't; (in Windows 7 download UI don't have extra accept button in certain cases) :return: None. """ for _ in range(max_number_of_attempts): file_found = exists(file_to_download, FirefoxSettings.FIREFOX_TIMEOUT) if file_found: click(file_to_download) break type(Key.PAGE_DOWN) if exists(DownloadFiles.ABOUT, FirefoxSettings.FIREFOX_TIMEOUT): raise APIHelperError("File to be downloaded not found.") try: wait(DownloadFiles.SAVE_FILE, FirefoxSettings.HEAVY_SITE_LOAD_TIMEOUT) logger.debug("The 'Save file' option is present in the page.") time.sleep( FirefoxSettings.TINY_FIREFOX_TIMEOUT ) # prevent click on inactive button on windows click(DownloadFiles.SAVE_FILE) except FindError: raise APIHelperError( "The 'Save file' option is not present in the page, aborting." ) if expect_accept_download_available: accept_download_button = exists( accept_download, FirefoxSettings.FIREFOX_TIMEOUT ) if accept_download_button: logger.debug("The accept download button found in the page.") click(accept_download) else: raise APIHelperError( "The accept download button was not found in the page." )
def close_window_control(window_type): """Click on close window control. :param window_type: Type of window that need to be closed. :return: None. """ find_window_controls(window_type) if window_type == "auxiliary": if OSHelper.is_mac(): hover(AuxiliaryWindow.RED_BUTTON_PATTERN) click(AuxiliaryWindow.HOVERED_RED_BUTTON) else: click(AuxiliaryWindow.CLOSE_BUTTON) else: if OSHelper.is_mac(): hover(MainWindow.UNHOVERED_MAIN_RED_CONTROL) click(MainWindow.HOVERED_MAIN_RED_CONTROL) else: click(MainWindow.CLOSE_BUTTON)
def get_telemetry_info(): """Returns telemetry information as a JSON object from 'about:telemetry' page. """ copy_raw_data_to_clipboard_pattern = Pattern( "copy_raw_data_to_clipboard.png") raw_json_pattern = Pattern("raw_json.png") raw_data_pattern = Pattern("raw_data.png") new_tab() paste("about:telemetry") type(Key.ENTER) try: wait(raw_json_pattern, 10) logger.debug("'RAW JSON' button is present on the page.") click(raw_json_pattern) except (FindError, ValueError): raise APIHelperError("'RAW JSON' button not present in the page.") try: wait(raw_data_pattern, 10) logger.debug("'Raw Data' button is present on the page.") click(raw_data_pattern) except (FindError, ValueError): close_tab() raise APIHelperError("'Raw Data' button not present in the page.") try: click(copy_raw_data_to_clipboard_pattern) time.sleep(Settings.DEFAULT_UI_DELAY) json_text = get_clipboard() return json.loads(json_text) except Exception: raise APIHelperError( "Failed to retrieve raw message information value.") finally: close_tab()
def cancel_in_progress_downloads_from_the_library(private_window=False): # Open the 'Show Downloads' window and cancel all 'in progress' downloads. global cancel_downloads if private_window: steps = show_all_downloads_from_library_menu_private_window() logger.debug('Creating a region for Private Library window.') try: find_back_button = find(NavBar.BACK_BUTTON) except FindError: raise FindError('Could not get the coordinates of the nav bar back button.') try: find_hamburger_menu = find(NavBar.HAMBURGER_MENU) except FindError: raise FindError('Could not get the coordinates of the hamburger menu.') region = Region(find_back_button.x - 10, find_back_button.y, Screen.SCREEN_WIDTH, Screen.SCREEN_HEIGHT) else: steps = open_show_all_downloads_window_from_library_menu() logger.debug('Creating a region for Non-private Library window.') expected = exists(Library.TITLE, 10) assert expected is True, 'Library successfully opened.' try: find_library = find(Library.TITLE) except FindError: raise FindError('Could not get the x-coordinate of the library window title.') try: find_clear_downloads = find(Library.CLEAR_DOWNLOADS) except FindError: raise FindError('Could not get the x-coordinate of the clear_downloads button.') clear_downloads_width, clear_downloads_height = Library.CLEAR_DOWNLOADS.get_size() region = Region(find_library.x - 10, find_library.y, (find_clear_downloads.x + clear_downloads_width + 20) - find_library.x, 500) # Cancel all 'in progress' downloads. expected = region.exists(DownloadManager.DownloadsPanel.DOWNLOAD_CANCEL, 5) expected_highlighted = region.exists(DownloadManager.DownloadsPanel.DOWNLOAD_CANCEL_HIGHLIGHTED) if expected or expected_highlighted: steps.append(Step(expected, 'The Cancel Download button is displayed properly.')) cancel_downloads = True expected_cancel = True else: steps.append(Step(True, 'There are no downloads to be cancelled.')) cancel_downloads = False cancel_pattern = DownloadManager.DownloadsPanel.DOWNLOAD_CANCEL if expected \ else DownloadManager.DownloadsPanel.DOWNLOAD_CANCEL_HIGHLIGHTED if cancel_downloads: while expected_cancel: expected_cancel = region.exists(cancel_pattern, 10) if expected_cancel: click(cancel_pattern) if not private_window: hover(Library.TITLE) steps.append(Step(True, 'All downloads were cancelled.')) if private_window: close_tab() else: click_window_control('close') return steps
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 open_hamburger_menu(option): """ Opens 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. """ option_list = [ 'Restore Previous Session', 'Add-ons', 'Customize', 'Print', 'Web Developer', 'Help', 'Exit', 'Quit' ] if not isinstance(option, str) or option not in option_list: raise ValueError(INVALID_GENERIC_INPUT) hamburger_menu_pattern = NavBar.HAMBURGER_MENU region = Screen.UPPER_RIGHT_CORNER sign_in_to_firefox_pattern = Pattern("sign_in_to_firefox.png") try: region.wait(hamburger_menu_pattern, 10) 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 == "Restore Previous Session": restore_option_exists = exists( HamburgerMenu.RESTORE_PREVIOUS_SESSION, FirefoxSettings.FIREFOX_TIMEOUT) assert restore_option_exists, "Restore option exists is hamburger menu." click(HamburgerMenu.RESTORE_PREVIOUS_SESSION) elif option == "Add-ons": add_ons_option_exists = exists(HamburgerMenu.ADDONS, FirefoxSettings.FIREFOX_TIMEOUT) assert add_ons_option_exists, "Add-ons option exists is hamburger menu." click(HamburgerMenu.ADDONS) elif option == "Customize": customize_option_exists = exists( HamburgerMenu.CUSTOMIZE, FirefoxSettings.FIREFOX_TIMEOUT) assert customize_option_exists, "Customize option exists is hamburger menu." click(HamburgerMenu.CUSTOMIZE) elif option == "Print": print_option_exists = exists(HamburgerMenu.PRINT, FirefoxSettings.FIREFOX_TIMEOUT) assert print_option_exists, "Print option exists is hamburger menu." click(HamburgerMenu.PRINT) elif option == "Web Developer": web_dev_option_exists = exists(HamburgerMenu.WEB_DEVELOPER, FirefoxSettings.FIREFOX_TIMEOUT) assert web_dev_option_exists, "Web developer option exists is hamburger menu." click(HamburgerMenu.WEB_DEVELOPER) elif option == "Help": help_option_exists = exists(HamburgerMenu.HELP, FirefoxSettings.FIREFOX_TIMEOUT) assert help_option_exists, "Help option exists is hamburger menu." click(HamburgerMenu.HELP) elif (option == "Exit") or (option == "Quit"): if OSHelper.is_mac(): type(Key.Q, KeyModifier.CMD) else: exit_option_exists = exists( HamburgerMenu.EXIT, FirefoxSettings.FIREFOX_TIMEOUT) assert exit_option_exists, "Exit/Quit option exists is hamburger menu." click(HamburgerMenu.EXIT) except FindError: raise APIHelperError("Can't click the menu button. Aborting test.")