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 init_tesseract_path(): """Initialize Tesseract path.""" which_tesseract = subprocess.Popen('which tesseract', stdout=subprocess.PIPE, shell=True).communicate()[ 0].rstrip().decode("utf-8") path_not_found = False if OSHelper.is_windows(): win_default_tesseract_path = 'C:\\Program Files (x86)\\Tesseract-OCR' if '/c/' in str(which_tesseract): win_which_tesseract_path = which_tesseract.replace('/c/', 'C:\\').replace('/', '\\') + '.exe' else: win_which_tesseract_path = which_tesseract.replace('\\', '\\\\') if _check_path(win_default_tesseract_path): pytesseract.pytesseract.tesseract_cmd = win_default_tesseract_path + '\\tesseract' elif _check_path(win_which_tesseract_path): pytesseract.pytesseract.tesseract_cmd = win_which_tesseract_path else: path_not_found = True elif OSHelper.is_linux() or OSHelper.is_mac(): if _check_path(which_tesseract): pytesseract.pytesseract.tesseract_cmd = which_tesseract else: path_not_found = True else: path_not_found = True if path_not_found: logger.critical('Unable to find Tesseract.') logger.critical('Please consult wiki for complete setup instructions.') return False return True
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 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 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 zoom_with_mouse_wheel(nr_of_times=1, zoom_type=None): """Zoom in/Zoom out using the mouse wheel. :param nr_of_times: Number of times the 'zoom in'/'zoom out' action should take place. :param zoom_type: Type of the zoom action('zoom in'/'zoom out') intended to be performed. :return: None. """ # MAC needs doubled number of mouse wheels to zoom in correctly. if OSHelper.is_mac(): nr_of_times *= 2 # Move focus in the middle of the page to be able to use the scroll. Mouse().move(Location(Screen.SCREEN_WIDTH // 4, Screen.SCREEN_HEIGHT // 2)) for i in range(nr_of_times): if OSHelper.is_mac(): key_down('command') else: key_down('ctrl') Mouse().scroll(dy=zoom_type, dx=0) if OSHelper.is_mac(): key_up('command') else: key_up('ctrl') time.sleep(Settings.DEFAULT_UI_DELAY) Mouse().move(Location(0, 0))
def open_directory(directory): if OSHelper.is_windows(): os.startfile(directory) elif OSHelper.is_linux(): os.system('xdg-open \"' + directory + '\"') else: os.system('open \"' + directory + '\"')
def is_blocked(bug_id): """Checks if a Github issue/Bugzilla bug is blocked or not.""" try: if 'issue_' in bug_id: bug = get_github_issue(bug_id) if bug is None: return True if bug.state == 'closed': return False else: if OSHelper.get_os() in bug.title: return True return False else: bug = get_bugzilla_bug(bug_id) if bug is None: return True if bug.status in ['CLOSED', 'RESOLVED']: return False else: if bugzilla_os[OSHelper.get_os(). value] == bug.op_sys or bug.platform in [ 'All', 'Unspecified' ]: return True return False except BugManagerError as e: logger.error(str(e)) return True
def get_local_firefox_path() -> str or None: """Checks if Firefox is installed on your machine.""" paths = { 'osx': [ '/Applications/Firefox.app/Contents/MacOS/firefox', '/Applications/Firefox Developer Edition.app/Contents/MacOS/firefox', '/Applications/Firefox Nightly.app/Contents/MacOS/firefox' ], 'win': [ 'C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe', 'C:\\Program Files (x86)\\Firefox Developer Edition\\firefox.exe', 'C:\\Program Files (x86)\\Nightly\\firefox.exe', 'C:\\Program Files\\Mozilla Firefox\\firefox.exe', 'C:\\Program Files\\Firefox Developer Edition\\firefox.exe', 'C:\\Program Files\\Nightly\\firefox.exe' ], 'linux': ['/usr/bin/firefox', '/usr/lib/firefox/firefox'] } if OSHelper.is_windows(): paths['win'].append(PathManager.get_win_environment_path()) for path in paths[OSHelper.get_os().value]: if os.path.exists(path): return path return None
def launch_control_center(): profile_path = os.path.join(get_core_args().workdir, 'cc_profile') fx_path = PathManager.get_local_firefox_path() if fx_path is None: logger.error( 'Can\'t find local Firefox installation, aborting Iris run.') return False, None args = ['http://127.0.0.1:%s' % get_core_args().port] process_args = {'stream': None} profile = MozProfile(profile=profile_path, preferences=Settings.default_fx_prefs) fx_runner = FirefoxRunner(binary=fx_path, profile=profile, cmdargs=args, process_args=process_args) fx_runner.start() server = LocalWebServer(get_core_args().workdir, get_core_args().port) server.stop() time.sleep(Settings.DEFAULT_UI_DELAY) if OSHelper.is_mac(): type(text='q', modifier=KeyModifier.CMD) elif OSHelper.is_windows(): type(text='w', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT]) else: type(text='q', modifier=KeyModifier.CTRL) try: fx_runner.stop() except Exception as e: logger.debug('Error stopping fx_runner') logger.debug(e) return server.result
def get_active_modifiers(key): """Gets all the active modifiers depending on the used OS. :param key: Key modifier. :return: Returns an array with all the active modifiers. """ all_modifiers = [Key.SHIFT, Key.CTRL] if OSHelper.is_mac(): all_modifiers.append(Key.CMD) elif OSHelper.is_windows(): all_modifiers.append(Key.WIN) else: all_modifiers.append(Key.META) all_modifiers.append(Key.ALT) active_modifiers = [] for item in all_modifiers: try: for key_value in key: if item == key_value.value: active_modifiers.append(item) except TypeError: if item == key.value: active_modifiers.append(item) return active_modifiers
def open_about_firefox(): """Open the 'About Firefox' window.""" if OSHelper.get_os() == OSPlatform.MAC: type(Key.F3, modifier=KeyModifier.CTRL) type(Key.F2, modifier=KeyModifier.CTRL) time.sleep(0.5) type(Key.RIGHT) type(Key.DOWN) type(Key.DOWN) type(Key.ENTER) elif OSHelper.get_os() == OSPlatform.WINDOWS: type(Key.ALT) if args.locale != 'ar': type(Key.LEFT) else: type(Key.RIGHT) type(Key.ENTER) type(Key.UP) type(Key.ENTER) else: type(Key.F10) if args.locale != 'ar': type(Key.LEFT) else: type(Key.RIGHT) type(Key.UP) type(Key.ENTER)
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 select_last_tab(): """Select the last tab.""" if OSHelper.is_mac(): type(text='9', modifier=KeyModifier.CMD) elif OSHelper.is_windows(): type(text='9', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT]) else: type(text='9', modifier=KeyModifier.CTRL)
def open_library(): """Open the Library window.""" if OSHelper.is_mac(): type(text='b', modifier=[KeyModifier.CMD, KeyModifier.SHIFT]) elif OSHelper.is_windows(): type(text='b', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT]) else: type(text='o', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT])
def open_downloads(): """Open the Downloads dialog.""" if OSHelper.is_mac(): type(text='j', modifier=KeyModifier.CMD) elif OSHelper.is_windows(): type(text='j', modifier=KeyModifier.CTRL) else: type(text='y', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT])
def pytest_runtest_setup(self, item): BaseTarget.pytest_runtest_setup(self, item) if OSHelper.is_mac(): mouse_reset() if item.name == 'test_run': skip_reason_list = [] values = item.own_markers[0].kwargs is_disabled = 'enabled' in values and not values.get( 'enabled') and not core_args.override is_excluded = 'exclude' in values and OSHelper.get_os( ) in values.get('exclude') incorrect_locale = 'locale' in values and core_args.locale not in values.get( 'locale') incorrect_platform = 'platform' in values and OSHelper.get_os( ) not in values.get('platform') fx_version = self.values.get('fx_version') incorrect_fx_version = 'fx_version' in values and not check_version( fx_version, values.get('fx_version')) if is_disabled: skip_reason_list.append('Test is disabled') if is_excluded: skip_reason_list.append('Test is excluded for {}'.format( OSHelper.get_os())) if 'blocked_by' in values: bug_id = values.get('blocked_by') if is_blocked(bug_id): skip_reason_list.append( 'Test is blocked by [{}]'.format(bug_id)) if incorrect_locale: skip_reason_list.append( 'Test doesn\'t support locale [{}]'.format( core_args.locale)) if incorrect_platform: skip_reason_list.append( 'Test doesn\'t support platform [{}]'.format( OSHelper.get_os())) if incorrect_fx_version: skip_reason_list.append( 'Test doesn\'t support Firefox version [{}]'.format( fx_version)) if len(skip_reason_list) > 0: logger.info('Test skipped: - [{}]: {} Reason(s): {}'.format( item.nodeid.split(':')[0], values.get('description'), ', '.join(skip_reason_list))) test_instance = (item, 'SKIPPED', None) test_result = create_result_object(test_instance, 0, 0) self.completed_tests.append(test_result) pytest.skip(item)
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 minimize_window(): """Minimize the browser window to the application launch bar.""" if OSHelper.is_mac(): type(text='m', modifier=KeyModifier.CMD) elif OSHelper.is_windows(): type(text=Key.DOWN, modifier=KeyModifier.WIN) else: type(text=Key.DOWN, modifier=[KeyModifier.CTRL, KeyModifier.META]) time.sleep(Settings.DEFAULT_UI_DELAY)
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 select_tab(num): """Select a given tab (only 1-8). param: num is a string 1-8. example: '4'. """ if OSHelper.is_mac(): type(text=str(num), modifier=KeyModifier.CMD) elif OSHelper.is_windows(): type(text=str(num), modifier=KeyModifier.CTRL) else: type(text=str(num), modifier=KeyModifier.ALT)
def quit_firefox(): """Quit the browser.""" # Wait before quiting Firefox to avoid concurrency. time.sleep(1) if OSHelper.is_mac(): type(text='q', modifier=KeyModifier.CMD) elif OSHelper.is_windows(): type(text='w', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT]) else: type(text='q', modifier=KeyModifier.CTRL)
def launch_control_center(): profile_path = os.path.join(get_core_args().workdir, 'cc_profile') fx_path = PathManager.get_local_firefox_path() if fx_path is None: logger.error( 'Can\'t find local Firefox installation, aborting Iris run.') return False, None args = ['http://127.0.0.1:%s' % get_core_args().port] process_args = {'stream': None} profile = MozProfile(profile=profile_path, preferences=Settings.default_fx_prefs) if OSHelper.is_windows(): process = subprocess.Popen([ fx_path, '-no-remote', '-new-tab', args, '--wait-for-browser', '-foreground', '-profile', profile.profile ], shell=False) else: fx_runner = FirefoxRunner(binary=fx_path, profile=profile, cmdargs=args, process_args=process_args) fx_runner.start() server = LocalWebServer(get_core_args().workdir, get_core_args().port) server.stop() time.sleep(Settings.DEFAULT_UI_DELAY) if OSHelper.is_mac(): type(text='q', modifier=KeyModifier.CMD) elif OSHelper.is_windows(): type(text='w', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT]) else: type(text='q', modifier=KeyModifier.CTRL) if OSHelper.is_windows(): if process.pid is not None: try: logger.debug('Closing Firefox process ID: %s' % process.pid) process = psutil.Process(process.pid) for proc in process.children(recursive=True): proc.kill() process.kill() except psutil.NoSuchProcess: pass else: try: fx_runner.stop() except Exception as e: logger.debug('Error stopping fx_runner') logger.debug(e) return server.result
def quit_firefox(): """Quit the browser.""" # Press the ESC key to exit any modal dialogs that might prevent key capture. type(text=Key.ESC) # Wait before quitting Firefox to avoid concurrency. time.sleep(1) if OSHelper.is_mac(): type(text='q', modifier=KeyModifier.CMD) elif OSHelper.is_windows(): type(text='q', modifier=[KeyModifier.CTRL, KeyModifier.SHIFT]) else: type(text='q', modifier=KeyModifier.CTRL)
def is_lock_on(key): """Determines if a keyboard key(CAPS LOCK, NUM LOCK or SCROLL LOCK) is ON. :param key: Keyboard key(CAPS LOCK, NUM LOCK or SCROLL LOCK). :return: TRUE if keyboard_key state is ON or FALSE if keyboard_key state is OFF. """ if OSHelper.is_windows(): hll_dll = ctypes.WinDLL("User32.dll") keyboard_code = 0 if key == Key.CAPS_LOCK: keyboard_code = 0x14 elif key == Key.NUM_LOCK: keyboard_code = 0x90 elif key == Key.SCROLL_LOCK: keyboard_code = 0x91 try: key_state = hll_dll.GetKeyState(keyboard_code) & 1 except Exception: raise Exception('Unable to run Command.') if key_state == 1: return True return False elif OSHelper.is_linux() or OSHelper.is_mac(): try: cmd = subprocess.Popen('xset q', shell=True, stdout=subprocess.PIPE) shutdown_process('Xquartz') except subprocess.CalledProcessError as e: logger.error('Command failed: %s' % repr(e.cmd)) raise Exception('Unable to run Command.') else: processed_lock_key = key.value.label if 'caps' in processed_lock_key: processed_lock_key = 'Caps' elif 'num' in processed_lock_key: processed_lock_key = 'Num' elif 'scroll' in processed_lock_key: processed_lock_key = 'Scroll' for line in cmd.stdout: line = line.decode("utf-8") if processed_lock_key in line: values = re.findall('\d*\D+', ' '.join(line.split())) for val in values: if processed_lock_key in val and 'off' in val: return False return True
def __init__(self, region: Rectangle = None, screen_id: int = None): if screen_id is None: screen_id = 0 if region is None: region = DisplayCollection[screen_id].bounds if OSHelper.is_linux(): screen_region = region else: screen_region = {'top': int(region.y), 'left': int(region.x), 'width': int(region.width), 'height': int(region.height)} self._gray_array = _region_to_image(screen_region) height, width = self._gray_array.shape self.width = width self.height = height scale = DisplayCollection[screen_id].scale if scale != 1: self.width = int(width / scale) self.height = int(height / scale) self._gray_array = cv2.resize(self._gray_array, dsize=(self.width, self.height), interpolation=cv2.INTER_CUBIC)
def pytest_runtest_teardown(self, item): BaseTarget.pytest_runtest_teardown(self, item) try: if not OSHelper.is_windows(): if item.funcargs['firefox'].runner and item.funcargs[ 'firefox'].runner.process_handler: quit_firefox() status = item.funcargs[ 'firefox'].runner.process_handler.wait(10) if status is None: item.funcargs['firefox'].browser.runner.stop() else: item.funcargs['firefox'].stop() if not target_args.save: profile_instance = item.funcargs['firefox'].profile if os.path.exists(profile_instance.profile): try: shutil.rmtree(profile_instance.profile) except OSError as e: logger.error('Error: %s - %s.' % (e.filename, e.strerror)) else: logger.error('Invalid Path: %s' % profile_instance.profile) except (AttributeError, KeyError): pass
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 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 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('')