Exemple #1
0
def init_control_center():
    cc_assets_path = os.path.join(
        os.path.realpath(os.path.split(__file__)[0] + '/..'), 'control_center',
        'assets')
    logger.debug('Copying Control Center assets from %s to %s' %
                 (cc_assets_path, get_core_args().workdir))
    copy_tree(cc_assets_path, get_core_args().workdir)
    if os.path.exists(os.path.join(PathManager.get_module_dir(), 'targets')):
        logger.debug('Looking for CC files in module directory.')
        targets_dir = os.path.join(PathManager.get_module_dir(), 'targets')
    else:
        logger.debug('Looking for CC files in package directory.')
        targets_dir = os.path.join(Settings.PACKAGE_ROOT, 'mattapi', '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()
Exemple #2
0
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
Exemple #3
0
def main():
    args = get_core_args()
    set_code_paths(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:
            try:
                target_plugin = get_target(args.target)
            except Exception as e:
                exit_iris('Problems getting target %s:\n%s' % (args.target, e),
                          status=1)
            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()
            if len(pytest_args) == 0:
                exit_iris('No tests found.', status=1)

            pytest_args.append('-vs')
            pytest_args.append('-r ')
            pytest_args.append('-s')

            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)
Exemple #4
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
Exemple #5
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={})
    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
Exemple #6
0
def main():
    args = get_core_args()
    set_code_paths(args)
    if args.control:
        exit_iris('Can\'t use Control Center with lite command, exiting Iris.', 1)
    else:
        initialize_logger()
        validate_config_ini(args)
        if verify_config(args):
            pytest_args = None
            settings = None
            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:
            exit_iris('Failed platform verification.', status=1)
Exemple #7
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]
Exemple #8
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...')
Exemple #9
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)
Exemple #10
0
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.

import importlib
import logging
import os
import sys

from mattapi.api.os_helpers import OSHelper
from mattapi.api.settings import Settings
from mattapi.util.arg_parser import get_core_args
from mattapi.util.path_manager import PathManager

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


def check_target(target: str = None):
    """Checks if provided target exists."""
    # Currently not in use, but maintaining for possible future use.

    if target is None:
        logger.warning('No target provided.')

    local_target_path = os.path.join(PathManager.get_module_dir(), 'targets')
    package_target_path = os.path.join(PathManager.get_module_dir(), 'mattapi', 'targets')

    if os.path.exists(os.path.join(local_target_path, target)):
        return True
    if os.path.exists(os.path.join(package_target_path, target)):
Exemple #11
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
Exemple #12
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')
    MOZILLA_BOOKMARK_HISTORY_SIDEBAR = Pattern('mozilla_bookmark_history_sidebar.png')
    MOZILLA_BOOKMARK_LIBRARY_HISTORY_LIST = Pattern('mozilla_bookmark_library_history_list.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)