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 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 try: wait(library_menu_pattern, 10) region = Region( image_find(library_menu_pattern).x - Screen().width / 4, image_find(library_menu_pattern).y, Screen().width / 4, Screen().height / 4 - 100) 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 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 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, Settings.DEFAULT_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, Settings.DEFAULT_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, Settings.DEFAULT_FIREFOX_TIMEOUT) except FindError: raise APIHelperError( 'Zoom indicator not removed from toolbar, aborting.')
def download_file(file_to_download, accept_download): """ :param file_to_download: File to be downloaded. :param accept_download: Accept download pattern. :return: None. """ file_found = exists(file_to_download, 2) if file_found: click(file_to_download) else: while not file_found: type(Key.PAGE_DOWN) try: click(file_to_download) file_found = True except FindError: file_found = False if exists(DownloadFiles.ABOUT, 2): raise APIHelperError('File to be downloaded not found.') try: wait(DownloadFiles.SAVE_FILE, 90) logger.debug('The \'Save file\' option is present in the page.') click(DownloadFiles.SAVE_FILE) except FindError: raise APIHelperError('The \'Save file\' option is not present in the page, aborting.') try: ok_button = exists(accept_download, 5) if ok_button: logger.debug('The OK button found in the page.') click(accept_download) except FindError: raise APIHelperError('The OK button is not found in the page.')
def create_region_from_image(image): """Create region starting from a pattern. :param image: Pattern used to create a region. :return: None. """ try: from src.core.api.rectangle import Rectangle from src.core.api.enums import Alignment m = image_find(image) if m: sync_pattern = Pattern('sync_hamburger_menu.png') sync_width, sync_height = sync_pattern.get_size() sync_image = image_find(sync_pattern) top_left = Rectangle(sync_image.x, sync_image.y, sync_width, sync_width). \ apply_alignment(Alignment.TOP_RIGHT) if OSHelper.is_mac(): exit_pattern = Pattern('help_hamburger_menu.png') else: exit_pattern = Pattern('exit_hamburger_menu.png') exit_width, exit_height = exit_pattern.get_size() exit_image = image_find(exit_pattern) bottom_left = Rectangle(exit_image.x, exit_image.y, exit_width, exit_height). \ apply_alignment(Alignment.BOTTOM_RIGHT) x0 = top_left.x + 2 y0 = top_left.y height = bottom_left.y - top_left.y width = Screen().width - top_left.x - 2 region = Region(x0, y0, width, height) return region else: raise APIHelperError('No matching found.') except FindError: raise APIHelperError('Image not present.')
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(';'[0])[1] except Exception as e: raise APIHelperError( 'Failed to retrieve preference value.\n{}'.format(e)) close_tab() return value
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) time.sleep(0.5) sign_in_to_sync = Pattern('sign_in_to_sync.png') if OSHelper.is_linux(): quit_menu_pattern = Pattern('quit.png') return RegionUtils.create_region_from_patterns(None, sign_in_to_sync, quit_menu_pattern, None, padding_right=20) elif OSHelper.is_mac(): help_menu_pattern = Pattern('help.png') return RegionUtils.create_region_from_patterns(None, sign_in_to_sync, help_menu_pattern, None, padding_right=20) else: exit_menu_pattern = Pattern('exit.png') return RegionUtils.create_region_from_patterns(None, sign_in_to_sync, exit_menu_pattern, None, padding_right=20) except (FindError, ValueError): raise APIHelperError( 'Can\'t find the hamburger menu 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 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) type(Key.SPACE) time.sleep(Settings.DEFAULT_UI_DELAY) type(Key.ENTER) time.sleep(Settings.DEFAULT_UI_DELAY) paste(pref_name) time.sleep(Settings.DEFAULT_UI_DELAY) type(Key.TAB) 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 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 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 click_cancel_button(): """Click cancel button.""" cancel_button_pattern = Pattern('cancel_button.png') 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 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 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 close_customize_page(): """Close the 'Customize...' page by pressing the 'Done' button.""" customize_done_button_pattern = Pattern('customize_done_button.png') try: wait(customize_done_button_pattern, 10) logger.debug('Done button found.') click(customize_done_button_pattern) except FindError: raise APIHelperError( 'Can\'t find the Done button in the page, aborting.')
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 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 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 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 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 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 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 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) type(Key.ENTER) except Exception: raise APIHelperError( 'No active window found, cannot navigate to page.')
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: click(hamburger_menu_pattern) time.sleep(Settings.DEFAULT_UI_DELAY) try: region = create_region_from_image(hamburger_menu_pattern) region.click(option) return region except FindError: raise APIHelperError( 'Can\'t find the option in the page, aborting test.')
def restore_firefox_focus(): """Restore Firefox focus by clicking the panel near HOME or REFRESH button.""" try: if exists(NavBar.HOME_BUTTON, 1): 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 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 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)