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 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 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("Bookmarks") 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 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 bookmarks_sidebar(option: str): """Toggle open/close the bookmarks sidebar.""" if OSHelper.is_mac(): type(text="b", modifier=KeyModifier.CMD) else: type(text="b", modifier=KeyModifier.CTRL) bookmark_sidebar_header_pattern = SidebarBookmarks.BOOKMARKS_HEADER if option == "open": try: wait(bookmark_sidebar_header_pattern, 10) logger.debug("Sidebar is opened.") except FindError: raise APIHelperError( "Sidebar is NOT present on the page, aborting.") elif option == "close": try: wait_vanish(bookmark_sidebar_header_pattern, 10) logger.debug("Sidebar is closed.") except FindError: raise APIHelperError("Sidebar is NOT closed, aborting.") else: raise APIHelperError("Option is not supported, aborting")
def get_firefox_build_id_from_about_config(): """Returns the Firefox build id from 'about:config' page.""" pref_1 = "browser.startup.homepage_override.buildID" pref_2 = "extensions.lastAppBuildId" try: return get_pref_value(pref_1) except APIHelperError: try: return get_pref_value(pref_2) except APIHelperError: raise APIHelperError( "Could not retrieve firefox build id information from about:config page." )
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 bookmarks_sidebar(option: str): """Toggle open/close the bookmarks sidebar.""" if OSHelper.is_mac(): type(text='b', modifier=KeyModifier.CMD) else: type(text='b', modifier=KeyModifier.CTRL) bookmark_sidebar_header_pattern = SidebarBookmarks.BOOKMARKS_HEADER if option == 'open': try: wait(bookmark_sidebar_header_pattern, 10) logger.debug('Sidebar is opened.') except FindError: raise APIHelperError( 'Sidebar is NOT present on the page, aborting.') elif option == 'close': try: wait_vanish(bookmark_sidebar_header_pattern, 10) logger.debug('Sidebar is closed.') except FindError: raise APIHelperError('Sidebar is NOT closed, aborting.') else: raise APIHelperError('Option is not supported, aborting') time.sleep(Settings.DEFAULT_UI_DELAY)
def create_region_for_url_bar(): """Create region for the right side of the url bar.""" try: hamburger_menu_pattern = NavBar.HAMBURGER_MENU show_history_pattern = LocationBar.HISTORY_DROPMARKER select_location_bar() return RegionUtils.create_region_from_patterns( show_history_pattern, hamburger_menu_pattern, padding_top=20, padding_bottom=20, ) except FindError: raise APIHelperError("Could not create region for URL bar.")
def click_hamburger_menu_option(option): """Click on a specific option from the hamburger menu. :param option: Hamburger menu option to be clicked. :return: The region created starting from the hamburger menu pattern. """ hamburger_menu_pattern = NavBar.HAMBURGER_MENU try: 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: ham_region = create_region_for_hamburger_menu() ham_region.click(option) except FindError: raise APIHelperError( "Can't find the option: " + option + " in the hamburger menu. Aborting test." )
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 click_window_control(button, window_type="auxiliary"): """Click window with options: close, minimize, maximize, restore, full_screen. :param button: Auxiliary or main window options. :param window_type: Type of window that need to be controlled. :return: None. """ if button == "close": close_window_control(window_type) elif button == "minimize": minimize_window_control(window_type) elif button == "maximize": maximize_window_control(window_type) elif button == "restore": restore_window_control(window_type) elif button == "full_screen": full_screen_control(window_type) else: raise APIHelperError("Button option is not supported.")
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 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 check_preference(pref_name, value): """Check the value for a specific preference. :param pref_name: Preference to be searched. :param value: Preference's value to be checked. :return: None. """ new_tab() select_location_bar() paste("about:config") time.sleep(Settings.DEFAULT_UI_DELAY) type(Key.ENTER) time.sleep(Settings.DEFAULT_UI_DELAY) type(Key.SPACE) time.sleep(Settings.DEFAULT_UI_DELAY) paste(pref_name) time.sleep(Settings.DEFAULT_UI_DELAY_LONG) type(Key.TAB) time.sleep(Settings.DEFAULT_UI_DELAY_LONG) try: retrieved_value = copy_to_clipboard().split("\t")[1] except Exception as e: raise APIHelperError("Failed to retrieve preference value. %s" % e.message) if retrieved_value == value: return True else: return False
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.")
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 copy_file(original, copy): try: shutil.copy(original, copy) except OSError: raise APIHelperError(f"Cannot copy {original} file")
def _get_image_path(caller, image: str) -> str: """Enforce proper location for all Pattern creation. :param caller: Path of calling Python module. :param image: String filename of image. :return: Full path to image on disk. We will look at all possible paths relative to the calling file, with this priority: - current platform locale folder - common locale folder - current platform root - common root Each directory is scanned for four possible file names, depending on resolution. If we find nothing, we will raise an exception. """ module = os.path.split(caller)[1] module_directory = os.path.split(caller)[0] file_name = image.split(".")[0] names = [image, "*****@*****.**" % file_name] if OSHelper.get_os_version() == "win7": os_version = "win7" else: os_version = OSHelper.get_os().value paths = [] current_locale = Settings.locale platform_directory = os.path.join(module_directory, "images", os_version) if current_locale != "": platform_locale_directory = os.path.join(platform_directory, current_locale) for name in names: paths.append(os.path.join(platform_locale_directory, name)) common_directory = os.path.join(module_directory, "images", "common") if current_locale != "": common_locale_directory = os.path.join(common_directory, current_locale) for name in names: paths.append(os.path.join(common_locale_directory, name)) for name in names: paths.append(os.path.join(platform_directory, name)) for name in names: paths.append(os.path.join(common_directory, name)) found = False image_path = None for path in paths: if os.path.exists(path): found = True image_path = path break logger.debug("Module %s requests image %s" % (module, image)) if found: logger.debug("Found %s" % image_path) return image_path else: raise APIHelperError("Image not found")