def restore_window_control(window_type): """Click on restore window control. :param window_type: Type of window that need to be restored. :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: if OSHelper.is_linux(): reset_mouse() click(AuxiliaryWindow.ZOOM_RESTORE_BUTTON) 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: if OSHelper.is_linux(): reset_mouse() click(MainWindow.RESIZE_BUTTON)
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 __init__(self): self.root = Tk() self.root.overrideredirect(1) s_width = MULTI_MONITOR_AREA["width"] s_height = MULTI_MONITOR_AREA["height"] self.root.wm_attributes("-topmost", True) canvas = Canvas( self.root, width=s_width, height=s_height, borderwidth=0, highlightthickness=0, bg=Color.BLACK.value, ) canvas.grid() Canvas.draw_circle = _draw_circle Canvas.draw_rectangle = _draw_rectangle if OSHelper.is_mac(): self.root.wm_attributes("-fullscreen", 1) self.root.wm_attributes("-transparent", True) self.root.config(bg="systemTransparent") canvas.config(bg="systemTransparent") canvas.pack() if OSHelper.is_windows(): self.root.wm_attributes("-transparentcolor", Color.BLACK.value) if OSHelper.is_linux(): self.root.wait_visibility(self.root) self.root.attributes("-alpha", 0.7) self.canvas = canvas
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 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 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_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 _region_to_image(region) -> Image or ScreenshotError: if not OSHelper.is_linux(): grabbed_area = _mss_screenshot(region) else: try: grabbed_area = np.array( screenshot(region=(region.x, region.y, region.width, region.height))) except (IOError, OSError): logger.debug( "Call to pyautogui.screnshot failed, using mss instead.") grabbed_area = _mss_screenshot(region) return grabbed_area
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.run( "xset q", shell=True, stdout=subprocess.PIPE, timeout=20 ) 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" stdout = cmd.stdout.decode("utf-8").split("\n") for line in stdout: if processed_lock_key in line: values = re.findall(r"\d*\D+", " ".join(line.split())) for val in values: if processed_lock_key in val and "off" in val: return False return True
def shutdown_process(process_name: str): """Checks if the process name exists in the process list and close it .""" if OSHelper.is_windows(): command_str = "taskkill /IM " + process_name + ".exe" try: subprocess.Popen(command_str, shell=True, stdout=subprocess.PIPE) except subprocess.CalledProcessError: logger.error('Command failed: "%s"' % command_str) raise Exception("Unable to run Command.") elif OSHelper.is_mac() or OSHelper.is_linux(): command_str = "pkill " + process_name try: subprocess.Popen(command_str, shell=True, stdout=subprocess.PIPE) except subprocess.CalledProcessError: logger.error('Command failed: "%s"' % command_str) raise Exception("Unable to run Command.")
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 import_package_by_name(target_name: str, path: str): logger.debug("Adding path %s to sys.path:" % path) sys.path.append(path) logger.debug("Looking for target %s in path %s" % (target_name, path)) try: my_module = importlib.import_module("targets.%s.main" % target_name) logger.info("Successful import!") try: target_plugin = my_module.Target() logger.info("Found target named %s" % target_plugin.target_name) return target_plugin except NameError: raise Exception("Target %s not found in path %s" % (target_name, path)) except ImportError as e: if e.name.__contains__("Xlib") and not OSHelper.is_linux(): pass else: logger.error("Problems importing module:\n%s" % e) raise ImportError
def _region_to_image(region) -> Image or ScreenshotError: # On Linux, try to use pyautogui to take screenshots, and revert to mss if it fails. # On Windows/Mac, do the reverse. try: if OSHelper.is_linux(): try: grabbed_area = _pyautogui_screenshot(region) except ScreenshotError as e: logger.debug(e) grabbed_area = _mss_screenshot(region) else: try: grabbed_area = _mss_screenshot(region) except ScreenshotError as e: logger.debug(e) grabbed_area = _pyautogui_screenshot(region) except ScreenshotError as e: logger.error("Screenshot failed: %s" % e) raise ScreenshotError("Cannot create screenshot: %s" % e) return grabbed_area
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._raw_image = _region_to_image(screen_region) self._gray_array = _convert_image_to_gray(self._raw_image) self._color_array = _convert_image_to_color(self._raw_image) 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._color_array = cv2.resize( self._color_array, dsize=(self.width, self.height), interpolation=cv2.INTER_CUBIC, ) self._gray_array = cv2.resize( self._gray_array, dsize=(self.width, self.height), interpolation=cv2.INTER_CUBIC, )
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
from moziris.api.keyboard.key import Key, KeyModifier from moziris.api.keyboard.keyboard_util import get_active_modifiers, is_shift_character from moziris.api.os_helpers import OSHelper from moziris.api.settings import Settings logger = logging.getLogger(__name__) try: from Xlib.display import Display from Xlib import X from Xlib.ext.xtest import fake_input import Xlib.XK except ImportError: if OSHelper.is_linux(): logger.error("Could not import Xlib modules.") exit(1) pyautogui.FAILSAFE = False use_virtual_keyboard = Settings.virtual_keyboard def key_down(key): """Performs a keyboard key press without the release. This will put that key in a held down state. :param key: The key to be pressed down. :return: None. """ if use_virtual_keyboard: virtual_keyboard.key_down(key)
def get_core_args(): global iris_args log_level_strings = ["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"] def log_level_string_to_int(log_level_string): if log_level_string not in log_level_strings: logger.error( "Invalid choice: %s (choose from %s)", log_level_string, log_level_strings, ) exit(1) log_level_int = getattr(logging, log_level_string, logging.INFO) assert isinstance(log_level_int, int) return log_level_int parser = argparse.ArgumentParser(description="Iris core arguments", prog="iris") parser.add_argument( "target", nargs="?", action="store", type=str, help="Target name" ) parser.add_argument( "-a", "--rerun", help="Rerun last failed tests", action="store_true" ) parser.add_argument( "-b", "--highlight", help="Highlight patterns and click actions", action="store_true", ) parser.add_argument( "-c", "--clear", help="Clear run data", default=False, action="store_true" ) parser.add_argument( "-d", "--directory", help="Directory name containing tests to execute", action="store", default="", ) parser.add_argument( "-e", "--email", help="Submit email report", action="store_true" ) parser.add_argument( "-i", "--level", help="Set the logging output level", type=log_level_string_to_int, dest="level", default="INFO", ) parser.add_argument( "-k", "--control", help="Display control center", action="store_true" ) parser.add_argument( "-l", "--locale", help="Locale to use for pattern search", action="store", default="en-US", ) parser.add_argument( "-m", "--max_tries", help="Maximum times a test can be run before failure", type=int, action="store", default=3, ) parser.add_argument( "-n", "--no_check", help="Skip key lock check on startup", action="store_true" ) parser.add_argument( "-o", "--override", help="Override disabled tests", action="store_true" ) parser.add_argument( "-p", "--port", help="Port to use for local web server", type=int, action="store", default=2000, ) parser.add_argument( "-q", "--code_root", help="Path to code root", type=os.path.abspath, action="store", default=None, ) parser.add_argument( "-t", "--test", help="Partial or full test names or paths to execute", action="store", default="", ) parser.add_argument( "-w", "--workdir", help="Path to working directory", type=os.path.abspath, action="store", default=get_working_dir(), ) parser.add_argument( "-x", "--exclude", help="Partial or full test names or paths to exclude", action="store", default="", ) parser.add_argument( "-z", "--resize", help="Convert hi-res images to normal", action="store_true" ) parser.add_argument( "-vk", "--virtual_keyboard", help="Use the virtual/fake keyboard for virtual environments", action="store_true", default=False, ) global iris_args if iris_args is None: iris_args = parser.parse_known_args()[0] if iris_args.virtual_keyboard and not OSHelper.is_linux(): logger.error("Virtual keyboard is available only on LINUX.") exit(1) return iris_args