예제 #1
0
파일: finder.py 프로젝트: leshibily/iris2
def wait(ps, timeout=None, region=None) -> bool or FindError:
    """Verify that a Pattern or str appears.

    :param ps: String or Pattern.
    :param timeout: Number as maximum waiting time in seconds.
    :param region: Rectangle object in order to minimize the area.
    :return: True if found, otherwise raise FindError.
    """
    if isinstance(ps, Pattern):
        if timeout is None:
            timeout = Settings.auto_wait_timeout

        image_found = image_find(ps, timeout, region)
        if image_found is not None:
            if get_core_args().highlight:
                highlight(region=region, ps=ps, location=[image_found])
            return True
        else:
            raise FindError('Unable to find image %s' % ps.get_filename())
    elif isinstance(ps, str):
        text_found = text_find(ps, region)
        if len(text_found) > 0:
            if get_core_args().highlight:
                highlight(region=region, ps=ps, text_location=text_found)
            return Location(text_found[0].x, text_found[0].y)
        else:
            raise FindError('Unable to find text %s' % ps)
    else:
        raise ValueError('Invalid input')
예제 #2
0
파일: finder.py 프로젝트: leshibily/iris2
def find_all(ps: Pattern or str, region: Rectangle = None):
    """Look for all matches of a Pattern or image.

    :param ps: Pattern or String.
    :param region: Rectangle object in order to minimize the area.
    :return: Location object or FindError.
    """
    if isinstance(ps, Pattern):
        images_found = match_template(ps, region, MatchTemplateType.MULTIPLE)
        if len(images_found) > 0:
            if get_core_args().highlight:
                highlight(region=region, ps=ps, location=images_found)
            return images_found
        else:
            raise FindError('Unable to find image %s' % ps.get_filename())
    elif isinstance(ps, str):
        locations = []
        text_found = text_find_all(ps, region)
        if len(text_found) > 0:
            if get_core_args().highlight:
                highlight(region=region, ps=ps, text_location=text_found)
            for text in text_found:
                locations.append(Location(text.x, text.y))
                return locations
        else:
            raise FindError('Unable to find text %s' % ps)
예제 #3
0
파일: __main__.py 프로젝트: m8ttyB/iris
def get_test_params():
    tests_to_execute = collect_tests()
    pytest_args = []
    if get_core_args().rerun:
        failed_tests_file = os.path.join(PathManager.get_working_dir(),
                                         'lastfail.txt')
        tests_dir = os.path.join(PathManager.get_tests_dir(),
                                 get_core_args().target)
        failed_tests = []
        with open(failed_tests_file, 'r') as f:
            for line in f:
                failed_tests.append(line.rstrip('\n'))
        f.close()
        # Read first line to see if these tests apply to current target.
        if tests_dir in failed_tests[0]:
            pytest_args = failed_tests
        else:
            logging.error(
                'The -a flag cannot be used now because the last failed tests don\'t match current target.'
            )
    else:
        if len(tests_to_execute) > 0:
            for running in tests_to_execute:
                pytest_args.append(running)
        else:
            exit_iris('No tests to execute.', status=1)
    return pytest_args
예제 #4
0
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
예제 #5
0
def show_control_center():
    if get_core_args().control:
        return True
    elif get_core_args().target is None:
        exit_iris(
            'No target specified, e.g.: \n\niris your_target\n\nClosing Iris.',
            status=1)
        return False
    else:
        return False
예제 #6
0
파일: __main__.py 프로젝트: m8ttyB/iris
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
예제 #7
0
def main():
    args = get_core_args()
    initialize_logger()
    validate_config_ini(args)
    if verify_config(args):
        pytest_args = None
        settings = None
        if show_control_center():
            init_control_center()
            user_result = launch_control_center()
            logger.debug(user_result)
            if user_result is not 'cancel':
                # Extract list of tests
                if not 'tests' in user_result:
                    logger.info('No tests chosen, closing Iris.')
                    delete(PathManager.get_run_id(), update_run_file=False)
                    ShutdownTasks.at_exit()
                    exit(0)

                pytest_args = user_result['tests']

                # Extract target from response and update core arg for application/target
                set_core_arg('application', user_result['target'])

                # Extract settings from response
                args = get_core_args()
                settings = user_result['args']
            else:
                # User cancelled or otherwise failed to select tests,
                # so we will shut down Iris.
                delete(PathManager.get_run_id(), update_run_file=False)
                ShutdownTasks.at_exit()
                exit(0)

        try:
            target_plugin = get_target(args.application)
            if settings is not None:
                logger.debug('Passing settings to target: %s' % settings)
                target_plugin.update_settings(settings)
            if pytest_args is None:
                pytest_args = get_test_params()
            pytest_args.append('-vs')
            pytest_args.append('-r ')
            pytest_args.append('-s')
            initialize_platform(args)
            pytest.main(pytest_args, plugins=[target_plugin])
        except ImportError:
            logger.error('Could not load plugin for {} application'.format(
                args.application))
            exit(1)
    else:
        logger.error('Failed platform verification.')
        exit(1)
예제 #8
0
파일: __main__.py 프로젝트: m8ttyB/iris
def main():
    args = get_core_args()
    initialize_logger()
    migrate_data()
    validate_config_ini(args)
    if verify_config(args):
        pytest_args = None
        settings = None
        if show_control_center():
            init_control_center()
            user_result = launch_control_center()
            logger.debug(user_result)
            if user_result is not 'cancel':
                # Extract list of tests
                if not 'tests' in user_result:
                    exit_iris('No tests chosen, closing Iris.', status=0)

                pytest_args = user_result['tests']

                # Extract target from response and update core arg for target
                set_core_arg('target', user_result['target'])

                # Extract settings from response
                args = get_core_args()
                settings = user_result['args']
            else:
                # User cancelled or otherwise failed to select tests,
                # so we will shut down Iris.
                exit_iris('User cancelled run, closing Iris.', status=0)

        try:
            if pytest_args is None:
                pytest_args = get_test_params()
            if len(pytest_args) == 0:
                exit_iris('No tests found.', status=1)

            pytest_args.append('-vs')
            pytest_args.append('-r ')
            pytest_args.append('-s')
            target_plugin = get_target(args.target)
            if settings is not None:
                logger.debug('Passing settings to target: %s' % settings)
                target_plugin.update_settings(settings)
            initialize_platform(args)
            pytest.main(pytest_args, plugins=[target_plugin])
        except ImportError as e:
            exit_iris('Could not load plugin for %s target, error: %s' %
                      (args.target, e),
                      status=1)
    else:
        logger.error('Failed platform verification.')
        exit(1)
예제 #9
0
    def pytest_sessionstart(self, session):
        global core_args
        core_args = get_core_args()
        global target_args
        BaseTarget.pytest_sessionstart(self, session)
        self.validate_config()
        try:
            port = core_args.port

            logger.info('Starting local web server on port %s for directory %s' % (port, self.local_web_root))
            web_server_process = Process(target=LocalWebServer, args=(self.local_web_root, port,))
            self.process_list.append(web_server_process)
            web_server_process.start()

            fx = self.args.firefox
            locale = core_args.locale
            app = FX_Collection.get(fx, locale)

            if not app:
                FX_Collection.add(fx, locale)
                app = FX_Collection.get(fx, locale)
            self.values = {'fx_version': app.version, 'fx_build_id': app.build_id, 'channel': app.channel}
        except IOError:
            logger.critical('Unable to launch local web server, aborting Iris.')
            exit(1)
        logger.info('Loading more test images...')
예제 #10
0
def show_control_center():
    # TODO
    # expand logic to display Control Center only when no target specified,
    # or if -k argument is explicitly used
    if get_core_args().control:
        return True
    else:
        return False
예제 #11
0
    def __init__(self, app: FirefoxApp, profile: FirefoxProfile = None):

        if profile is None:
            profile = FirefoxProfile.make_profile()
        self.application = app
        self.url = 'http://127.0.0.1:{}'.format(get_core_args().port)
        self.profile = profile
        self.runner = self.launch()
예제 #12
0
파일: __main__.py 프로젝트: m8ttyB/iris
def init_control_center():
    copy_tree(
        os.path.join(PathManager.get_module_dir(), 'src', 'control_center',
                     'assets'),
        get_core_args().workdir)
    targets_dir = os.path.join(PathManager.get_module_dir(), 'targets')

    exclude_dirs = {'__pycache__'}
    for path, dirs, files in PathManager.sorted_walk(targets_dir):
        [dirs.remove(d) for d in list(dirs) if d in exclude_dirs]
        for target in dirs:
            src = os.path.join(targets_dir, target, 'icon.png')
            dest = os.path.join(get_core_args().workdir, 'images',
                                '%s.png' % target)
            try:
                shutil.copyfile(src, dest)
            except FileNotFoundError:
                logger.warning('Could not find icon file for target: %s' %
                               target)
        break
    create_target_json()
예제 #13
0
    def __init__(self, app: FirefoxApp, profile: FirefoxProfile = None, args = None):

        if profile is None:
            profile = FirefoxProfile()
        self.application = app
        self.url = 'http://127.0.0.1:{}'.format(get_core_args().port)
        self.profile = profile
        if args is not None:
            query_string = '?'
            for arg in args:
                value_pair = '%s=%s&' % (arg, args[arg])
                query_string += value_pair
            self.url += query_string[:-1]
예제 #14
0
파일: pattern.py 프로젝트: leshibily/iris2
def _load_all_patterns(application: str) -> list:
    """Function returns a list with all the project's Patterns."""
    if get_core_args().resize:
        _convert_hi_res_images()
    result_list = []
    for root, dirs, files in os.walk(PathManager.get_module_dir()):
        for file_name in files:
            if file_name.endswith('.png'):
                if application in root and (PathManager.get_images_path() in root or 'common' in root):
                    pattern_name, pattern_scale = _parse_name(file_name)
                    pattern_path = os.path.join(root, file_name)
                    pattern = {'name': pattern_name, 'path': pattern_path, 'scale': pattern_scale}
                    result_list.append(pattern)
    return result_list
예제 #15
0
파일: finder.py 프로젝트: leshibily/iris2
def find(ps: Pattern or str,
         region: Rectangle = None) -> Location or FindError:
    """Look for a single match of a Pattern or image.

    :param ps: Pattern or String.
    :param region: Rectangle object in order to minimize the area.
    :return: Location object.
    """
    if isinstance(ps, Pattern):
        image_found = match_template(ps, region, MatchTemplateType.SINGLE)
        if len(image_found) > 0:
            if get_core_args().highlight:
                highlight(region=region, ps=ps, location=image_found)
            return image_found[0]
        else:
            raise FindError('Unable to find image %s' % ps.get_filename())
    elif isinstance(ps, str):
        text_found = text_find(ps, region)
        if len(text_found) > 0:
            if get_core_args().highlight:
                highlight(region=region, ps=ps, text_location=text_found)
            return Location(text_found[0].x, text_found[0].y)
        else:
            raise FindError('Unable to find text %s' % ps)
예제 #16
0
파일: app.py 프로젝트: leshibily/iris2
    def firefox(self, request):
        profile_type = request.node.own_markers[0].kwargs.get('profile')
        preferences = request.node.own_markers[0].kwargs.get('preferences')
        profile = FirefoxProfile.make_profile(profile_type, preferences)

        fx = target_args.firefox
        locale = get_core_args().locale
        app = FX_Collection.get(fx, locale)

        if not app:
            FX_Collection.add(fx, locale)
            app = FX_Collection.get(fx, locale)

        if target_args.update_channel:
            FirefoxUtils.set_update_channel_pref(app.path,
                                                 target_args.update_channel)
        return FXRunner(app, profile)
예제 #17
0
파일: pattern.py 프로젝트: leshibily/iris2
    def __init__(self, image_name: str, from_path: str = None, application: str = get_core_args().application):

        if from_path is None:
            path = _get_image_path(inspect.stack()[1][1], image_name, application)
        else:
            path = from_path
        name, scale = _parse_name(os.path.split(path)[1])

        image = cv2.imread(path)

        self.image_name = name
        self.image_path = path
        self.scale_factor = scale
        self.similarity = Settings.min_similarity
        self._target_offset = None
        self._size = _get_pattern_size(image, scale)
        self.rgb_array = _get_array_from_image(image)
        self.color_image = _get_image_from_array(scale, self.rgb_array)
        self.gray_image = _get_gray_image(self.color_image)
        self.gray_array = _get_array_from_image(self.gray_image)
예제 #18
0
    def firefox(self, request):
        profile_type = request.node.own_markers[0].kwargs.get('profile')
        preferences = request.node.own_markers[0].kwargs.get('preferences')
        profile = FirefoxProfile.make_profile(profile_type, preferences)

        fx = target_args.firefox
        locale = get_core_args().locale
        app = FX_Collection.get(fx, locale)

        if not app:
            FX_Collection.add(fx, locale)
            app = FX_Collection.get(fx, locale)

        if target_args.update_channel:
            FirefoxUtils.set_update_channel_pref(app.path, target_args.update_channel)

        args = {'total': len(request.node.session.items), 'current': Target.index,
                'title': os.path.basename(request.node.fspath)}

        return  FXRunner(app, profile, args)
예제 #19
0
class Test(FirefoxTest):
    # Set the region from command line flag, if given.
    # Command line flag is for testing en-US locale in IN, ID and CA regions, de locale in RU and ru locale in DE.
    # Otherwise, we'll automatically set the region based on the Firefox locale under test.
    global fx_region_code
    region_arg = Target().get_target_args().region
    if region_arg != '':
        fx_region_code = region_arg
    else:
        regions_by_locales = {
            'en-US': 'US',
            'de': 'DE',
            'fr': 'FR',
            'pl': 'PL',
            'it': 'IT',
            'pt-BR': 'BR',
            'ja': 'JA',
            'es-ES': 'ES',
            'en-GB': 'GB',
            'ru': 'DE'
        }
        fx_locale_code = get_core_args().locale
        fx_region_code = regions_by_locales[fx_locale_code]

    @pytest.mark.details(description='Default Search Code: Google.',
                         locale=[
                             'en-US', 'de', 'fr', 'pl', 'it', 'pt-BR', 'ja',
                             'es-ES', 'en-GB', 'ru'
                         ],
                         test_case_id='218333',
                         test_suite_id='83',
                         profile=Profiles.BRAND_NEW,
                         preferences={
                             'browser.search.region': fx_region_code,
                             'browser.search.cohort': 'nov17-1'
                         })
    def run(self, firefox):
        url = LocalWeb.FOCUS_TEST_SITE
        text_pattern = Pattern('focus_text.png')
        text_pattern_selected = Pattern('focus_text_selected.png')

        change_preference('browser.search.widget.inNavBar', True)
        change_preference('browser.tabs.warnOnClose', True)

        default_search_engine_google_pattern = Pattern(
            'default_search_engine_google.png')
        google_logo_content_search_field_pattern = Pattern(
            'google_logo_content_search_field.png')

        navigate('about:preferences#search')

        default_search_engine_check = exists(
            default_search_engine_google_pattern,
            FirefoxSettings.FIREFOX_TIMEOUT)
        assert default_search_engine_check, 'Google is the default search engine.'

        # Perform a search using the awesome bar and then clear the content from it.
        select_location_bar()
        paste('test')
        time.sleep(FirefoxSettings.TINY_FIREFOX_TIMEOUT)
        type(Key.ENTER)
        time.sleep(FirefoxSettings.TINY_FIREFOX_TIMEOUT)
        select_location_bar()
        url_text = copy_to_clipboard()

        if FirefoxUtils.get_firefox_channel(firefox.application.path) == 'beta' \
                or FirefoxUtils.get_firefox_channel(firefox.application.path) == 'release':
            if fx_region_code != 'US':
                assert url_text == 'https://www.google.com/search?client=firefox-b-d&q=test', \
                    'Client search code is correct for searches from awesome bar, region ' + fx_region_code + '.'
            else:
                assert url_text == 'https://www.google.com/search?client=firefox-b-1-d&q=test', \
                    'Client search code is correct for searches from awesome bar, region ' + fx_region_code + '.'
        elif FirefoxUtils.get_firefox_channel(
                firefox.application.path) == 'esr':
            if fx_region_code != 'US':
                assert url_text == 'https://www.google.com/search?client=firefox-b-e&q=test', \
                    'Client search code is correct for searches from awesome bar, region ' + fx_region_code + '.'
            else:
                assert url_text == 'https://www.google.com/search?client=firefox-b-1-e&q=test', \
                    'Client search code is correct for searches from awesome bar, region ' + fx_region_code + '.'

        select_location_bar()
        type(Key.DELETE)

        # Perform a search using the search bar.
        select_search_bar()
        paste('test')
        time.sleep(FirefoxSettings.TINY_FIREFOX_TIMEOUT)
        type(Key.ENTER)
        time.sleep(FirefoxSettings.TINY_FIREFOX_TIMEOUT)
        select_location_bar()
        url_text = copy_to_clipboard()

        if FirefoxUtils.get_firefox_channel(firefox.application.path) == 'beta' or \
                FirefoxUtils.get_firefox_channel(firefox.application.path) == 'release':
            if fx_region_code != 'US':
                assert url_text == 'https://www.google.com/search?client=firefox-b-d&q=test', \
                                   'Client search code is correct for searches from search bar, region ' + \
                                   fx_region_code + '.'
            else:
                assert url_text == 'https://www.google.com/search?client=firefox-b-1-d&q=test',\
                    'Client search code is correct for searches from search bar, region ' + fx_region_code + '.'

        elif FirefoxUtils.get_firefox_channel(
                firefox.application.path) == 'esr':
            if fx_region_code != 'US':
                assert url_text == 'https://www.google.com/search?client=firefox-b-e&q=test', \
                    'Client search code is correct for searches from search bar, region ' + fx_region_code + '.'
            else:
                assert url_text == 'https://www.google.com/search?client=firefox-b-1-e&q=test', \
                    'Client search code is correct for searches from search bar, region ' + fx_region_code + '.'

        # Highlight some text and right click it.
        new_tab()

        navigate(url)

        focus_page_loaded = exists(text_pattern,
                                   FirefoxSettings.HEAVY_SITE_LOAD_TIMEOUT)
        assert focus_page_loaded, 'Page successfully loaded, focus text found.'

        double_click(text_pattern)
        time.sleep(FirefoxSettings.TINY_FIREFOX_TIMEOUT)
        right_click(text_pattern_selected)
        time.sleep(FirefoxSettings.TINY_FIREFOX_TIMEOUT)
        repeat_key_down(3)
        type(Key.ENTER)
        time.sleep(FirefoxSettings.TINY_FIREFOX_TIMEOUT)
        select_location_bar()
        url_text = copy_to_clipboard()

        if FirefoxUtils.get_firefox_channel(firefox.application.path) == 'beta' or \
                FirefoxUtils.get_firefox_channel(firefox.application.path) == 'release':
            if fx_region_code != 'US':
                assert url_text == 'https://www.google.com/search?client=firefox-b-d&q=Focus', \
                    'Client search code is correct, region ' + fx_region_code + '.'
            else:
                assert url_text == 'https://www.google.com/search?client=firefox-b-1-d&q=Focus', \
                    'Client search code is correct, region ' + fx_region_code + '.'
        elif FirefoxUtils.get_firefox_channel(
                firefox.application.path) == 'esr':
            if fx_region_code != 'US':
                assert url_text == 'https://www.google.com/search?client=firefox-b-e&q=Focus', \
                    'Client search code is correct, region ' + fx_region_code + '.'
            else:
                assert url_text == 'https://www.google.com/search?client=firefox-b-1-e&q=Focus', \
                    'Client search code is correct, region ' + fx_region_code + '.'

        # Perform a search from about:newtab page, content search field.
        new_tab()

        google_logo_found = exists(google_logo_content_search_field_pattern,
                                   FirefoxSettings.FIREFOX_TIMEOUT)
        assert google_logo_found, 'Google logo from content search field found.'

        click(google_logo_content_search_field_pattern)
        time.sleep(FirefoxSettings.TINY_FIREFOX_TIMEOUT)
        paste('beats')
        time.sleep(FirefoxSettings.TINY_FIREFOX_TIMEOUT)
        type(Key.ENTER)
        time.sleep(FirefoxSettings.TINY_FIREFOX_TIMEOUT)
        select_location_bar()
        url_text = copy_to_clipboard()

        if FirefoxUtils.get_firefox_channel(firefox.application.path) == 'beta' or \
                FirefoxUtils.get_firefox_channel(firefox.application.path) == 'release':
            if fx_region_code != 'US':
                assert url_text == 'https://www.google.com/search?client=firefox-b-d&q=beats',\
                    'Client search code is correct for searches from about:newtab page, content search field, ' \
                    'region ' + fx_region_code + '.'
            else:
                assert url_text == 'https://www.google.com/search?client=firefox-b-1-d&q=beats',\
                    'Client search code is correct for searches from about:newtab page, content search field, ' \
                    'region ' + fx_region_code + '.'
        elif FirefoxUtils.get_firefox_channel(
                firefox.application.path) == 'esr':
            if fx_region_code != 'US':
                assert url_text == 'https://www.google.com/search?client=firefox-b-e&q=beats', \
                    'Client search code is correct for searches from about:newtab pageq, region ' + fx_region_code + '.'
            else:
                assert url_text == 'https://www.google.com/search?client=firefox-b-1-e&q=beats', \
                    'Client search code is correct for searches from about:newtab page, region ' + fx_region_code + '.'
예제 #20
0
from src.core.util.arg_parser import get_core_args

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 = get_core_args().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)
    else:
        _Keyboard.key_down(key)


def key_up(key):
예제 #21
0
class Test(FirefoxTest):
    # Set the region from command line argument, if given. Otherwise, set the region based on Firefox locale.
    # Use -g <region> for testing the English locales of Firefox in the four Yandex regions; RU, BY, KZ and TR.
    global fx_region_code
    region_arg = Target().get_target_args().region
    if region_arg != '':
        fx_region_code = region_arg
    else:
        regions_by_locales = {
            'ru': 'RU',
            'be': 'BY',
            'kk': 'KZ',
            'tr': 'TR',
            'en-US': 'RU',
            'en-GB': 'RU',
            'en-CA': 'RU'
        }
        fx_locale_code = get_core_args().locale
        fx_region_code = regions_by_locales[fx_locale_code]

    @pytest.mark.details(
        description='Default Search Code: Yandex: Russia.',
        locale=['ru', 'be', 'kk', 'tr', 'en-US', 'en-GB', 'en-CA'],
        test_case_id='218336',
        test_suite_id='83',
        profile=Profiles.BRAND_NEW,
        preferences={
            'browser.search.region': fx_region_code,
            'browser.search.cohort': 'jan18-1'
        })
    def run(self, firefox):
        url = LocalWeb.FOCUS_TEST_SITE
        text_pattern = Pattern('focus_text.png')

        change_preference('browser.search.widget.inNavBar', True)
        change_preference('browser.tabs.warnOnClose', True)

        default_search_engine_yandex_pattern = Pattern(
            'default_search_engine_yandex.png')
        yandex_logo_content_search_field_pattern = Pattern(
            'yandex_logo_content_search_field.png')

        navigate('about:preferences#search')

        expected = exists(default_search_engine_yandex_pattern,
                          FirefoxSettings.FIREFOX_TIMEOUT)
        assert expected, 'Yandex is the default search engine.'

        # Perform a search using the awesome bar and then clear the content from it.
        select_location_bar()
        paste('test')
        type(Key.ENTER)
        time.sleep(Settings.DEFAULT_UI_DELAY_LONG)
        select_location_bar()
        url_text = copy_to_clipboard()

        assert '/search/?text=test&clid=2186621' in url_text, 'Client search code is correct for searches from' \
                                                              'awesomebar, region ' + fx_region_code + '.'

        select_location_bar()
        type(Key.DELETE)

        # Perform a search using the search bar.
        select_search_bar()
        paste('test')
        type(Key.ENTER)
        time.sleep(Settings.DEFAULT_UI_DELAY_LONG)
        select_location_bar()
        url_text = copy_to_clipboard()

        assert '/search/?text=test&clid=2186618' in url_text, 'Client search code is correct for searches from ' \
                                                              'search bar, region ' + fx_region_code + '.'

        # Highlight some text and right click it.
        new_tab()
        navigate(url)
        expected = exists(LocalWeb.FOCUS_LOGO, 10)
        assert expected, 'Page successfully loaded, Focus logo found.'

        double_click(text_pattern)
        time.sleep(Settings.DEFAULT_UI_DELAY_SHORT)
        right_click(text_pattern)
        time.sleep(Settings.DEFAULT_UI_DELAY_SHORT)
        repeat_key_down(3)
        type(Key.ENTER)
        time.sleep(Settings.DEFAULT_UI_DELAY_LONG)
        select_location_bar()
        url_text = copy_to_clipboard()

        assert '/search/?text=Focus&clid=2186623' in url_text, 'Client search code is correct for searches ' \
                                                               'with context menu, region ' + fx_region_code + '.'

        # Perform a search from about:newtab page, content search field.
        new_tab()
        expected = exists(yandex_logo_content_search_field_pattern,
                          FirefoxSettings.FIREFOX_TIMEOUT)
        assert expected, 'Yandex logo from content search field found.'

        click(yandex_logo_content_search_field_pattern)

        paste('beats')
        type(Key.ENTER)
        time.sleep(Settings.DEFAULT_UI_DELAY_LONG)
        select_location_bar()
        url_text = copy_to_clipboard()

        assert '/search/?text=beats&clid=2186620' in url_text, 'Client search code is correct for searches ' \
                                                               'from content search field, region ' \
                                                               + fx_region_code + '.'
예제 #22
0
파일: settings.py 프로젝트: leshibily/iris2
class _Settings:
    """Class that holds general Iris settings.

    wait_scan_rate              -   The number of times actual pattern search operations are performed per second.
                                    (default - 3)
    type_delay                  -   The number of seconds between each keyboard press. (default - 0)
    move_mouse_delay            -   duration of mouse movement from current location to target location. (default - 0.5
                                    or value selected from Control Center)
    click_delay                 -   The number of seconds a click event is executed after the mouse moves to the target
                                    location. (default - 0)
    min_similarity              -   The default minimum similarity of find operations. While using a Region.find()
                                    operation. Iris searches the region using a default minimum similarity of 0.8.
    auto_wait_timeout           -   The maximum waiting time for all subsequent find operations. (default - 3)
    delay_before_mouse_down     -   Delay before the mouse is put in a held down state.
    delay_before_drag           -   Delay before the drag operation takes place.
    delay_before_drop           -   Delay before the drop operation takes place.
    slow_motion_delay           -   Controls the duration of the visual effect (seconds).
    observe_scan_rate           -   The number of times actual search operations are performed per second while waiting
                                    for a pattern to appear or vanish.
    observe_min_changed_pixels  -   The minimum size in pixels of a change to trigger a change event.
    highlight_duration          -   The duration of the highlight effect.
    highlight_color             -   The rectangle/circle border color for the highlight effect.
    highlight_thickness         -   The rectangle/circle border thickness for the highlight effect.
    mouse_scroll_step           -   The number of pixels for a vertical/horizontal scroll event.
    """

    DEFAULT_MIN_SIMILARITY = 0.8
    DEFAULT_SLOW_MOTION_DELAY = 2
    DEFAULT_OBSERVE_MIN_CHANGED_PIXELS = 50
    DEFAULT_TYPE_DELAY = 0
    DEFAULT_MOVE_MOUSE_DELAY = get_core_args().mouse
    DEFAULT_CLICK_DELAY = 0
    DEFAULT_WAIT_SCAN_RATE = 3
    DEFAULT_OBSERVE_SCAN_RATE = 3
    DEFAULT_AUTO_WAIT_TIMEOUT = 3
    DEFAULT_DELAY_BEFORE_MOUSE_DOWN = 0.3
    DEFAULT_DELAY_BEFORE_DRAG = 0.3
    DEFAULT_DELAY_BEFORE_DROP = 0.3
    DEFAULT_HIGHLIGHT_DURATION = 2
    DEFAULT_HIGHLIGHT_COLOR = Color.RED
    DEFAULT_HIGHLIGHT_THICKNESS = 2
    DEFAULT_MOUSE_SCROLL_STEP = 100
    DEFAULT_SITE_LOAD_TIMEOUT = 30
    DEFAULT_HEAVY_SITE_LOAD_TIMEOUT = 90
    DEFAULT_KEY_SHORTCUT_DELAY = 0.1
    DEFAULT_UI_DELAY = 1
    DEFAULT_UI_DELAY_SHORT = 0.5
    DEFAULT_UI_DELAY_LONG = 2.5
    DEFAULT_SYSTEM_DELAY = 5
    DEFAULT_FIREFOX_TIMEOUT = 10
    DEFAULT_FX_PREFS = {
        # Don't automatically update the application
        'app.update.disabledForTesting': True,
        # Don't restore the last open set of tabs if the browser has crashed
        'browser.sessionstore.resume_from_crash': False,
        # Don't check for the default web browser during startup
        'browser.shell.checkDefaultBrowser': False,
        # Don't warn on exit when multiple tabs are open
        'browser.tabs.warnOnClose': False,
        # Don't warn when exiting the browser
        'browser.warnOnQuit': False,
        # Don't send Firefox health reports to the production server
        'datareporting.healthreport.documentServerURI':
        'http://%(server)s/healthreport/',
        # Skip data reporting policy notifications
        'datareporting.policy.dataSubmissionPolicyBypassNotification': False,
        # Only install add-ons from the profile and the application scope
        # Also ensure that those are not getting disabled.
        # see: https://developer.mozilla.org/en/Installing_extensions
        'extensions.enabledScopes': 5,
        'extensions.autoDisableScopes': 10,
        # Don't send the list of installed addons to AMO
        'extensions.getAddons.cache.enabled': False,
        # Don't install distribution add-ons from the app folder
        'extensions.installDistroAddons': False,
        # Don't automatically update add-ons
        'extensions.update.enabled': False,
        # Don't open a dialog to show available add-on updates
        'extensions.update.notifyUser': False,
        # Enable test mode to run multiple tests in parallel
        'focusmanager.testmode': True,
        # Enable test mode to not raise an OS level dialog for location sharing
        'geo.provider.testing': True,
        # Suppress delay for main action in popup notifications
        'security.notification_enable_delay': 0,
        # Suppress automatic safe mode after crashes
        'toolkit.startup.max_resumed_crashes': -1,
        # Don't send Telemetry reports to the production server. This is
        # needed as Telemetry sends pings also if FHR upload is enabled.
        'toolkit.telemetry.server': 'http://%(server)s/telemetry-dummy/',
    }

    def __init__(self,
                 wait_scan_rate=DEFAULT_WAIT_SCAN_RATE,
                 type_delay=DEFAULT_TYPE_DELAY,
                 move_mouse_delay=DEFAULT_MOVE_MOUSE_DELAY,
                 click_delay=DEFAULT_CLICK_DELAY,
                 min_similarity=DEFAULT_MIN_SIMILARITY,
                 auto_wait_timeout=DEFAULT_AUTO_WAIT_TIMEOUT,
                 delay_before_mouse_down=DEFAULT_DELAY_BEFORE_MOUSE_DOWN,
                 delay_before_drag=DEFAULT_DELAY_BEFORE_DRAG,
                 delay_before_drop=DEFAULT_DELAY_BEFORE_DROP,
                 slow_motion_delay=DEFAULT_SLOW_MOTION_DELAY,
                 observe_scan_rate=DEFAULT_OBSERVE_SCAN_RATE,
                 observe_min_changed_pixels=DEFAULT_OBSERVE_MIN_CHANGED_PIXELS,
                 system_delay=DEFAULT_SYSTEM_DELAY,
                 highlight_duration=DEFAULT_HIGHLIGHT_DURATION,
                 highlight_color=DEFAULT_HIGHLIGHT_COLOR,
                 highlight_thickness=DEFAULT_HIGHLIGHT_THICKNESS,
                 mouse_scroll_step=DEFAULT_MOUSE_SCROLL_STEP,
                 firefox_timeout=DEFAULT_FIREFOX_TIMEOUT,
                 key_shortcut_delay=DEFAULT_KEY_SHORTCUT_DELAY,
                 default_fx_prefs=DEFAULT_FX_PREFS):

        self.wait_scan_rate = wait_scan_rate
        self._type_delay = type_delay
        self.move_mouse_delay = move_mouse_delay
        self._click_delay = click_delay
        self._min_similarity = min_similarity
        self.auto_wait_timeout = auto_wait_timeout
        self.delay_before_mouse_down = delay_before_mouse_down
        self.delay_before_drag = delay_before_drag
        self.delay_before_drop = delay_before_drop
        self.slow_motion_delay = slow_motion_delay
        self.system_delay = system_delay
        self.observe_scan_rate = observe_scan_rate
        self.observe_min_changed_pixels = observe_min_changed_pixels
        self.highlight_duration = highlight_duration
        self.highlight_color = highlight_color.value
        self.highlight_thickness = highlight_thickness
        self.mouse_scroll_step = mouse_scroll_step
        self.key_shortcut_delay = key_shortcut_delay
        self.firefox_timeout = firefox_timeout
        self.default_fx_prefs = default_fx_prefs

    @property
    def type_delay(self):
        return self._type_delay

    @property
    def FIREFOX_TIMEOUT(self):
        return self.firefox_timeout

    @property
    def SYSTEM_DELAY(self):
        return self.system_delay

    @type_delay.setter
    def type_delay(self, value):
        if value > 1:
            self._type_delay = 1
        else:
            self._type_delay = value

    @property
    def click_delay(self):
        return self._click_delay

    @click_delay.setter
    def click_delay(self, value):
        if value > 1:
            self._click_delay = 1
        else:
            self._click_delay = value

    @property
    def min_similarity(self):
        return self._min_similarity

    @min_similarity.setter
    def min_similarity(self, value):
        if value > 1:
            self._min_similarity = 1
        else:
            self._min_similarity = value
예제 #23
0
import json
import logging
import os
import sys
import time

import git
import pytest

from src.core.api.os_helpers import OSHelper
from src.core.util.arg_parser import get_core_args
from src.core.util.path_manager import PathManager
from src.core.util.system import get_python_version

logger = logging.getLogger(__name__)
args = get_core_args()


def create_target_json():
    if not use_cached_target_file():
        logging.info('Preparing data for the Control Center.')
        logging.info('This may take a minute.')
        master_target_dir = os.path.join(PathManager.get_module_dir(),
                                         'targets')
        target_list = [
            f for f in os.listdir(master_target_dir)
            if not f.startswith('__') and not f.startswith('.')
        ]

        targets = []
        for item in target_list:
예제 #24
0
파일: __main__.py 프로젝트: m8ttyB/iris
def show_control_center():
    if get_core_args().control or get_core_args().target is None:
        return True
    else:
        return False
예제 #25
0
def _get_image_path(caller, image: str, target: 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 the above fails, we will look up the file name in the list of project-wide images,
    and return whatever we find, with a warning message.
    If we find nothing, we will raise an exception.
    """

    module = os.path.split(caller)[1]
    module_directory = os.path.split(caller)[0]
    parent_directory = os.path.basename(module_directory)
    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 = ''
    try:
        current_locale = get_core_args().locale
    except AttributeError:
        pass

    platform_directory = os.path.join(module_directory, 'images', os_version)
    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')
    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

    if found:
        logger.debug('Module %s requests image %s' % (module, image))
        logger.debug('Found %s' % image_path)
        return image_path
    else:
        result_list = [
            x for x in _load_all_patterns(target) if x['name'] == image
        ]
        if len(result_list) > 0:
            res = result_list[0]
            logger.warning(
                'Failed to find image %s in default locations for module %s.' %
                (image, module))
            logger.warning('Using this one instead: %s' % res['path'])
            logger.warning(
                'Please move image to correct location relative to caller.')
            location_1 = os.path.join(parent_directory, 'images', 'common')
            location_2 = os.path.join(parent_directory,
                                      PathManager.get_images_path())
            logger.warning('Suggested locations: %s, %s' %
                           (location_1, location_2))
            return res['path']
        else:
            logger.error('Pattern creation for %s failed for caller %s.' %
                         (image, caller))
            logger.error(
                'Image not found. Either it is in the wrong platform folder, or it does not exist.'
            )
            logger.debug('Paths searched:')
            logger.debug('\n'.join(paths))
            raise FindError('Pattern not found.')
예제 #26
0
class _Settings:
    """Class that holds general Iris settings.

    wait_scan_rate              -   The number of times actual pattern search operations are performed per second.
                                    (default - 3)
    type_delay                  -   The number of seconds between each keyboard press. (default - 0)
    move_mouse_delay            -   duration of mouse movement from current location to target location. (default - 0.5
                                    or value selected from Control Center)
    click_delay                 -   The number of seconds a click event is executed after the mouse moves to the target
                                    location. (default - 0)
    min_similarity              -   The default minimum similarity of find operations. While using a Region.find()
                                    operation. Iris searches the region using a default minimum similarity of 0.8.
    auto_wait_timeout           -   The maximum waiting time for all subsequent find operations. (default - 3)
    delay_before_mouse_down     -   Delay before the mouse is put in a held down state.
    delay_before_drag           -   Delay before the drag operation takes place.
    delay_before_drop           -   Delay before the drop operation takes place.
    slow_motion_delay           -   Controls the duration of the visual effect (seconds).
    observe_scan_rate           -   The number of times actual search operations are performed per second while waiting
                                    for a pattern to appear or vanish.
    observe_min_changed_pixels  -   The minimum size in pixels of a change to trigger a change event.
    highlight_duration          -   The duration of the highlight effect.
    highlight_color             -   The rectangle/circle border color for the highlight effect.
    highlight_thickness         -   The rectangle/circle border thickness for the highlight effect.
    mouse_scroll_step           -   The number of pixels for a vertical/horizontal scroll event.
    """

    DEFAULT_MIN_SIMILARITY = 0.8
    DEFAULT_SLOW_MOTION_DELAY = 2
    DEFAULT_OBSERVE_MIN_CHANGED_PIXELS = 50
    DEFAULT_TYPE_DELAY = 0
    DEFAULT_MOVE_MOUSE_DELAY = get_core_args().mouse
    DEFAULT_CLICK_DELAY = 0
    DEFAULT_WAIT_SCAN_RATE = 3
    DEFAULT_OBSERVE_SCAN_RATE = 3
    DEFAULT_AUTO_WAIT_TIMEOUT = 3
    DEFAULT_DELAY_BEFORE_MOUSE_DOWN = 0.3
    DEFAULT_DELAY_BEFORE_DRAG = 0.3
    DEFAULT_DELAY_BEFORE_DROP = 0.3
    DEFAULT_HIGHLIGHT_DURATION = 2
    DEFAULT_HIGHLIGHT_COLOR = Color.RED
    DEFAULT_HIGHLIGHT_THICKNESS = 2
    DEFAULT_MOUSE_SCROLL_STEP = 100
    DEFAULT_SITE_LOAD_TIMEOUT = 30
    DEFAULT_HEAVY_SITE_LOAD_TIMEOUT = 90
    DEFAULT_KEY_SHORTCUT_DELAY = 0.1
    DEFAULT_UI_DELAY = 1
    DEFAULT_UI_DELAY_SHORT = 0.5
    DEFAULT_UI_DELAY_LONG = 2.5
    DEFAULT_SYSTEM_DELAY = 5

    def __init__(self,
                 wait_scan_rate=DEFAULT_WAIT_SCAN_RATE,
                 type_delay=DEFAULT_TYPE_DELAY,
                 move_mouse_delay=DEFAULT_MOVE_MOUSE_DELAY,
                 click_delay=DEFAULT_CLICK_DELAY,
                 min_similarity=DEFAULT_MIN_SIMILARITY,
                 auto_wait_timeout=DEFAULT_AUTO_WAIT_TIMEOUT,
                 delay_before_mouse_down=DEFAULT_DELAY_BEFORE_MOUSE_DOWN,
                 delay_before_drag=DEFAULT_DELAY_BEFORE_DRAG,
                 delay_before_drop=DEFAULT_DELAY_BEFORE_DROP,
                 slow_motion_delay=DEFAULT_SLOW_MOTION_DELAY,
                 observe_scan_rate=DEFAULT_OBSERVE_SCAN_RATE,
                 observe_min_changed_pixels=DEFAULT_OBSERVE_MIN_CHANGED_PIXELS,
                 system_delay=DEFAULT_SYSTEM_DELAY,
                 highlight_duration=DEFAULT_HIGHLIGHT_DURATION,
                 highlight_color=DEFAULT_HIGHLIGHT_COLOR,
                 highlight_thickness=DEFAULT_HIGHLIGHT_THICKNESS,
                 mouse_scroll_step=DEFAULT_MOUSE_SCROLL_STEP,
                 key_shortcut_delay=DEFAULT_KEY_SHORTCUT_DELAY,
                 site_load_timeout=DEFAULT_SITE_LOAD_TIMEOUT):

        self.wait_scan_rate = wait_scan_rate
        self._type_delay = type_delay
        self.move_mouse_delay = move_mouse_delay
        self._click_delay = click_delay
        self._min_similarity = min_similarity
        self.auto_wait_timeout = auto_wait_timeout
        self.delay_before_mouse_down = delay_before_mouse_down
        self.delay_before_drag = delay_before_drag
        self.delay_before_drop = delay_before_drop
        self.slow_motion_delay = slow_motion_delay
        self.system_delay = system_delay
        self.observe_scan_rate = observe_scan_rate
        self.observe_min_changed_pixels = observe_min_changed_pixels
        self.highlight_duration = highlight_duration
        self.highlight_color = highlight_color.value
        self.highlight_thickness = highlight_thickness
        self.mouse_scroll_step = mouse_scroll_step
        self.key_shortcut_delay = key_shortcut_delay
        self.site_load_timeout = site_load_timeout

    @property
    def type_delay(self):
        return self._type_delay

    @property
    def SYSTEM_DELAY(self):
        return self.system_delay

    @type_delay.setter
    def type_delay(self, value):
        if value > 1:
            self._type_delay = 1
        else:
            self._type_delay = value

    @property
    def click_delay(self):
        return self._click_delay

    @property
    def SITE_LOAD_TIMEOUT(self):
        return self.site_load_timeout

    @click_delay.setter
    def click_delay(self, value):
        if value > 1:
            self._click_delay = 1
        else:
            self._click_delay = value

    @property
    def min_similarity(self):
        return self._min_similarity

    @min_similarity.setter
    def min_similarity(self, value):
        if value > 1:
            self._min_similarity = 1
        else:
            self._min_similarity = value
예제 #27
0
class LocalWeb(object):
    """Constants that represent URLs and images for local content. """

    _ip_host = '127.0.0.1'
    _domain_host = 'localhost.allizom.org'
    _port = get_core_args().port
    """Simple blank HTML page."""
    BLANK_PAGE = 'http://%s:%s/blank.htm' % (_ip_host, _port)
    BLANK_PAGE_2 = 'http://%s:%s/blank.htm' % (_domain_host, _port)
    """Local Firefox site."""
    FIREFOX_TEST_SITE = 'http://%s:%s/firefox/' % (_ip_host, _port)
    FIREFOX_TEST_SITE_2 = 'http://%s:%s/firefox/' % (_domain_host, _port)
    FIREFOX_LOGO = Pattern('firefox_logo.png')
    FIREFOX_IMAGE = Pattern('firefox_full.png')
    FIREFOX_BOOKMARK = Pattern('firefox_bookmark.png')
    FIREFOX_BOOKMARK_SMALL = Pattern('firefox_bookmark_small.png')
    """Local Firefox Focus site."""
    FOCUS_TEST_SITE = 'http://%s:%s/focus/' % (_ip_host, _port)
    FOCUS_TEST_SITE_2 = 'http://%s:%s/focus/' % (_domain_host, _port)
    FOCUS_LOGO = Pattern('focus_logo.png')
    FOCUS_IMAGE = Pattern('focus_full.png')
    FOCUS_BOOKMARK = Pattern('focus_bookmark.png')
    FOCUS_BOOKMARK_SMALL = Pattern('focus_bookmark_small.png')
    """Local Mozilla site."""
    MOZILLA_TEST_SITE = 'http://%s:%s/mozilla/' % (_ip_host, _port)
    MOZILLA_TEST_SITE_2 = 'http://%s:%s/mozilla/' % (_domain_host, _port)
    MOZILLA_LOGO = Pattern('mozilla_logo.png')
    MOZILLA_IMAGE = Pattern('mozilla_full.png')
    MOZILLA_BOOKMARK = Pattern('mozilla_bookmark.png')
    MOZILLA_BOOKMARK_SMALL = Pattern('mozilla_bookmark_small.png')
    """Local Pocket site."""
    POCKET_TEST_SITE = 'http://%s:%s/pocket/' % (_ip_host, _port)
    POCKET_TEST_SITE_2 = 'http://%s:%s/pocket/' % (_domain_host, _port)
    POCKET_LOGO = Pattern('pocket_logo.png')
    POCKET_IMAGE = Pattern('pocket_full.png')
    POCKET_BOOKMARK = Pattern('pocket_bookmark.png')
    POCKET_BOOKMARK_SMALL = Pattern('pocket_bookmark_small.png')
    """Soap Wiki Test Site"""
    SOAP_WIKI_TEST_SITE = 'http://%s:%s/soap_wiki_test_site/' % (_ip_host,
                                                                 _port)
    SOAP_WIKI_1_OF_2_MATCHES = Pattern('1_of_2_matches.png')
    SOAP_WIKI_2_OF_2_MATCHES = Pattern('2_of_2_matches.png')
    SOAP_WIKI_CLEANING_SEE_SELECTED_LABEL = Pattern(
        'cleaning_see_selected_label.png')
    SOAP_WIKI_OPERATING_ALL = Pattern('operating_all.png')
    SOAP_WIKI_OPERATING_ALL_HIGHLIGHTED = Pattern(
        'operating_all_highlighted.png')
    SOAP_WIKI_OPERATING_DISPARATE = Pattern('operating_disparate.png')
    SOAP_WIKI_OPERATING_DISPARATE_HIGHLIGHTED = Pattern(
        'operating_disparate_highlighted.png')
    SOAP_WIKI_SEE_LABEL = Pattern('see_label.png')
    SOAP_WIKI_SEE_LABEL_UNHIGHLITED = Pattern('see_label_unhighlited.png')
    SOAP_WIKI_SOAP_ENVELOPE_LABEL_SELECTED = Pattern(
        'soap_envelope_label_selected.png')
    SOAP_WIKI_SOAP_LABEL = Pattern('soap_label.png')
    SOAP_WIKI_SOAP_LINK_HIGHLIGHTED = Pattern('soap_link_highlighted.png')
    SOAP_WIKI_SOAP_XML_LABEL = Pattern('soap_xml_label.png')
    SOAP_WIKI_TEST_LABEL_PATTERN = Pattern('test_label_pattern.png')
    """Local files samples."""
    SAMPLE_FILES = 'http://%s:%s/files/' % (_ip_host, _port)
    """about:preferences#privacy"""
    ABOUT_PREFERENCES_PRIVACY_ADDRESS = Pattern(
        'about_preferences_privacy_address.png')
    """CNN Site"""
    CNN_LOGO = Pattern('cnn_logo.png')
    CNN_BLOCKED_CONTENT_ADV = Pattern('cnn_blocked_content.png')
    """Iris Core elements"""
    IRIS_LOGO = Pattern('iris_logo.png')
    IRIS_LOGO_ACTIVE_TAB = Pattern('iris_logo_active_tab.png')
    IRIS_LOGO_INACTIVE_TAB = Pattern('iris_logo_inactive_tab.png')
    """Thinkbroadband site"""
    THINKBROADBAND_TEST_SITE = 'http://%s:%s/thinkbroadband/' % (_ip_host,
                                                                 _port)
예제 #28
0
def create_run_log(app):
    args = get_core_args()
    meta = {
        'run_id':
        PathManager.get_run_id(),
        'platform':
        OSHelper.get_os().value,
        'config':
        '%s, %s-bit, %s' % (OSHelper.get_os().value, OSHelper.get_os_bits(),
                            OSHelper.get_processor()),
        'locale':
        args.locale,
        'args':
        ' '.join(sys.argv),
        'params':
        vars(args),
        'log':
        os.path.join(PathManager.get_current_run_dir(), 'iris_log.log')
    }
    values = {}
    for i in app.values:
        values[i] = app.values[i]
    meta['values'] = values

    repo = git.Repo(PathManager.get_module_dir())
    meta['iris_version'] = 2.0
    meta['iris_repo'] = repo.working_tree_dir
    meta['iris_branch'] = repo.active_branch.name
    meta['iris_branch_head'] = repo.head.object.hexsha
    meta['python_version'] = get_python_version()

    failed = 0
    passed = 0
    skipped = 0
    errors = 0

    for test in app.completed_tests:
        if test.outcome == 'FAILED':
            failed = failed + 1
        if test.outcome == 'PASSED':
            passed = passed + 1
        if test.outcome == 'SKIPPED':
            skipped = skipped + 1
        if test.outcome == 'ERROR':
            errors = errors + 1

    logger.debug('Updating runs.json with completed run data.')
    meta['total'] = len(app.completed_tests)
    meta['passed'] = passed
    meta['failed'] = failed
    meta['skipped'] = skipped
    meta['errors'] = errors
    meta['start_time'] = app.start_time
    meta['end_time'] = app.end_time
    meta['total_time'] = app.end_time - app.start_time

    tests = {
        'all_tests': convert_test_list(app.completed_tests),
        'failed_tests': convert_test_list(app.completed_tests,
                                          only_failures=True)
    }

    run_file = os.path.join(PathManager.get_current_run_dir(), 'run.json')
    run_file_data = {'meta': meta, 'tests': tests}

    with open(run_file, 'w') as f:
        json.dump(run_file_data, f, sort_keys=True, indent=True)
예제 #29
0
 def get_web_asset_dir(asset_file_name):
     resource = '/tests/{}'.format(asset_file_name)
     return 'http://127.0.0.1:%s' % get_core_args().port + resource