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 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 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 select_throttling(option): network_pattern = Pattern("network.png").similar(0.6) throttling_menu_pattern = Pattern("no_throttling.png").similar(0.6) region_ll = Screen.LOWER_LEFT_CORNER region_lr = Region.screen_regions(Screen.LOWER_RIGHT_CORNER, "RIGHT_THIRD") open_web_console() try: region_ll.wait(network_pattern, 30) region_ll.click(network_pattern) except FindError: raise APIHelperError( "Can't find the network menu in the page, aborting test.") try: region_lr.wait(throttling_menu_pattern, 10) region_lr.click(throttling_menu_pattern) 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 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 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 launch(self, args=None): """Launch the app with optional args for profile, windows, URI, etc. :param url: URL to be loaded. :param args: Optional list of arguments. :return: List of Firefox flags. """ if args is None: args = [] args.append('-foreground') args.append('-no-remote') args.append('-new-tab') args.append(self.url) process_args = {'stream': None} logger.debug('Creating Firefox runner ...') try: runner = FirefoxRunner(binary=self.application.path, profile=self.profile, cmdargs=args, process_args=process_args) logger.debug('Firefox runner successfully created.') logger.debug('Running Firefox with command: "%s"' % ','.join(runner.command)) except run_errors.RunnerNotStartedError: raise APIHelperError('Error creating Firefox runner.') else: return runner
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 get_pref_value(pref_name): """Returns the value of a provided preference from 'about:config' page. :param pref_name: Preference's name. :return: Preference's value. """ new_tab() select_location_bar() paste("about:config") 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: value = copy_to_clipboard().split("\t")[1] except Exception as e: raise APIHelperError( "Failed to retrieve preference value.\n{}".format(e)) close_tab() return value
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 find_in_region_from_pattern( outer_pattern: Pattern, inner_pattern: Pattern, outer_pattern_timeout=Settings.auto_wait_timeout, inner_pattern_timeout=Settings.auto_wait_timeout, ): """ Finds pattern in region created from another pattern :param outer_pattern: Pattern for region creation :param inner_pattern: Pattern to find in region :param outer_pattern_timeout: Time to finding outer_pattern :param inner_pattern_timeout: Time to finding inner_pattern, :return: Boolean. True if inner_pattern found in outer_pattern region :raises: ValueError and APIHelperError """ if not isinstance(outer_pattern, Pattern) or not isinstance( inner_pattern, Pattern): raise ValueError(INVALID_GENERIC_INPUT) try: wait(outer_pattern, outer_pattern_timeout) logger.debug("Outer pattern found.") except FindError: raise APIHelperError("Can't find the outer pattern.") width, height = outer_pattern.get_size() region = Region( image_find(outer_pattern).x, image_find(outer_pattern).y, width, height) pattern_found = exists(inner_pattern, inner_pattern_timeout, region=region) return pattern_found
def delete_file(path): try: os.remove(path) except FileNotFoundError: logger.debug(f"File {path} not found. Skipping deleting.") return except OSError: raise APIHelperError(f"Cannot remove {path} file")
def get_firefox_channel_from_about_config(): """Returns the Firefox channel from 'about:config' page.""" try: return get_pref_value("app.update.channel") except APIHelperError: raise APIHelperError( "Could not retrieve firefox channel information from about:config page." )
def get_firefox_version_from_about_config(): """Returns the Firefox version from 'about:config' page.""" try: return get_pref_value("extensions.lastAppVersion") except APIHelperError: raise APIHelperError( "Could not retrieve firefox version information from about:config page." )
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 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 find_window_controls(window_type): """Find window controls for main and auxiliary windows. :param window_type: Controls for a specific window type. :return: None. """ if window_type == "auxiliary": Mouse().move(Location(1, 300)) if OSHelper.is_mac(): try: wait(AuxiliaryWindow.RED_BUTTON_PATTERN.similar(0.9), 5) logger.debug("Auxiliary window control found.") except FindError: raise APIHelperError( "Can't find the auxiliary window controls, aborting.") else: if OSHelper.is_linux(): Mouse().move(Location(80, 0)) try: wait(AuxiliaryWindow.CLOSE_BUTTON, 5) logger.debug("Auxiliary window control found.") except FindError: raise APIHelperError( "Can't find the auxiliary window controls, aborting.") elif window_type == "main": if OSHelper.is_mac(): try: wait(MainWindow.MAIN_WINDOW_CONTROLS.similar(0.9), 5) logger.debug("Main window controls found.") except FindError: raise APIHelperError( "Can't find the Main window controls, aborting.") else: try: if OSHelper.is_linux(): reset_mouse() wait(MainWindow.CLOSE_BUTTON, 5) logger.debug("Main window control found.") except FindError: raise APIHelperError( "Can't find the Main window controls, aborting.") else: raise APIHelperError("Window Type not supported.")
def change_preference(pref_name, value): """Change the value for a specific preference. :param pref_name: Preference to be changed. :param value: Preference's value after the change. :return: None. """ if not isinstance(value, str): value = str(value).lower() try: new_tab() navigate("about:config") time.sleep(Settings.DEFAULT_UI_DELAY_LONG) type(Key.SPACE) time.sleep(Settings.DEFAULT_UI_DELAY) paste(pref_name) time.sleep(Settings.DEFAULT_UI_DELAY) type(Key.TAB) time.sleep(Settings.DEFAULT_UI_DELAY) try: retrieved_value = copy_to_clipboard().split("\t")[1] except Exception: raise APIHelperError("Failed to retrieve preference value.") if retrieved_value == value: logger.debug("Flag is already set to value:" + value) return None else: type(Key.ENTER) if not (value == "true" or value == "false"): try: paste(value) type(Key.ENTER) except FindError: pass close_tab() except Exception: raise APIHelperError( "Could not set value: %s to preference: %s" % (value, pref_name) )
def change_preference(pref_name, value): """Change the value for a specific preference. :param pref_name: Preference to be changed. :param value: Preference's value after the change. :return: None. """ try: new_tab() navigate("about:config") time.sleep(Settings.DEFAULT_UI_DELAY_LONG) type(Key.SPACE) time.sleep(Settings.DEFAULT_UI_DELAY) paste(pref_name) time.sleep(Settings.DEFAULT_UI_DELAY) type(Key.TAB) time.sleep(Settings.DEFAULT_UI_DELAY) try: retrieved_value = copy_to_clipboard() except Exception: raise APIHelperError("Failed to retrieve preference value.") if retrieved_value == value: logger.debug("Flag is already set to value:" + value) return None else: type(Key.ENTER) dialog_box_pattern = Pattern("preference_dialog_icon.png") try: wait(dialog_box_pattern, 3) paste(value) type(Key.ENTER) except FindError: pass close_tab() except Exception: raise APIHelperError( "Could not set value: %s to preference: %s" % (value, pref_name) )
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 create_region_for_awesome_bar(): """Create region for the awesome bar.""" try: identity_icon_pattern = LocationBar.IDENTITY_ICON page_action_pattern = LocationBar.PAGE_ACTION_BUTTON return RegionUtils.create_region_from_patterns( left=page_action_pattern, right=identity_icon_pattern) except FindError: raise APIHelperError("Could not create region for awesome bar.")
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.")
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 get_firefox_locale_from_about_config(): """Returns the Firefox locale from 'about:config' page.""" try: value_str = get_pref_value( "browser.newtabpage.activity-stream.feeds.section.topstories.options" ) logger.debug(value_str) temp = json.loads(value_str) return str(temp["stories_endpoint"]).split("&locale_lang=")[1].split("&")[0] except (APIHelperError, KeyError): raise APIHelperError("Pref format to determine locale has changed.")
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 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, 5) logger.debug("Hamburger menu found.") except FindError: raise APIHelperError( 'Can\'t find the "hamburger menu" in the page, aborting test.' ) else: try: region = create_region_for_hamburger_menu() region.click(option) return region except FindError: raise APIHelperError("Can't find the option in the page, aborting test.")
def get_os(): """Get the type of the operating system your script is running on.""" if OS_NAME == "win": return OSPlatform.WINDOWS elif OS_NAME == "linux": return OSPlatform.LINUX elif OS_NAME == "mac": return OSPlatform.MAC else: raise APIHelperError( "Iris does not yet support your current environment: %s" % OS_NAME )
def confirm_firefox_launch(image=None): """Waits for firefox to exist by waiting for the iris logo to be present. :param image: Pattern to confirm Firefox launch :return: None. """ if image is None: image = Pattern("iris_logo.png") try: wait(image, 60) except Exception: raise APIHelperError("Can't launch Firefox - aborting test run.")
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()