Пример #1
0
    def activate(self, app_args):
        def app_using_human_output(app_args):
            for key in app_args.__dict__:
                if key.endswith('output'):
                    if app_args.__dict__[key] == '-':
                        return False
            return True

        view = output.View(app_args=app_args)
        if (hasattr(app_args, 'disable_restore_image_test')
                and getattr(app_args, 'disable_restore_image_test')):
            if (hasattr(app_args, 'disable_restore_image_job')
                    and not getattr(app_args, 'disable_restore_image_job')):
                if app_args.guest_image_path:
                    drive_file = app_args.guest_image_path
                else:
                    drive_file = defaults.guest_image_path
                compressed_drive_file = drive_file + '.7z'
                if os.path.isfile(compressed_drive_file):
                    if app_using_human_output(app_args):
                        msg = ("Plugin setup (Restoring guest image backup). "
                               "Please wait...")
                        view.notify(event='minor', msg=msg)
                    cwd = os.getcwd()
                    os.chdir(os.path.dirname(compressed_drive_file))
                    process.run('7za -y e %s' %
                                os.path.basename(compressed_drive_file))
                    os.chdir(cwd)
Пример #2
0
    def run(self, args):
        wraps = getattr(args, "wrapper", None)
        if wraps:
            view = output.View(app_args=args)
            if getattr(args, 'gdb_run_bin', None):
                view.notify(event='error',
                            msg='Command line option --wrapper is incompatible'
                                ' with option --gdb-run-bin.')
                sys.exit(exit_codes.AVOCADO_FAIL)

            for wrap in args.wrapper:
                if ':' not in wrap:
                    if process.WRAP_PROCESS is None:
                        script = os.path.abspath(wrap)
                        process.WRAP_PROCESS = os.path.abspath(script)
                    else:
                        view.notify(event='error',
                                    msg="You can't have multiple global"
                                        " wrappers at once.")
                        sys.exit(exit_codes.AVOCADO_FAIL)
                else:
                    script, cmd = wrap.split(':', 1)
                    script = os.path.abspath(script)
                    process.WRAP_PROCESS_NAMES_EXPR.append((script, cmd))
                if not os.path.exists(script):
                    view.notify(event='error',
                                msg="Wrapper '%s' not found!" % script)
                    sys.exit(exit_codes.AVOCADO_FAIL)
Пример #3
0
 def activate(self, app_args):
     try:
         if not app_args.wrapper:  # Not enabled
             return
         view = output.View(app_args=app_args)
         for wrap in app_args.wrapper:
             if ':' not in wrap:
                 if runtime.WRAP_PROCESS is None:
                     script = os.path.abspath(wrap)
                     runtime.WRAP_PROCESS = os.path.abspath(script)
                 else:
                     view.notify(event='error',
                                 msg="You can't have multiple global"
                                 " wrappers at once.")
                     sys.exit(exit_codes.AVOCADO_FAIL)
             else:
                 script, cmd = wrap.split(':', 1)
                 script = os.path.abspath(script)
                 runtime.WRAP_PROCESS_NAMES_EXPR.append((script, cmd))
             if not os.path.exists(script):
                 view.notify(event='error',
                             msg="Wrapper '%s' not found!" % script)
                 sys.exit(exit_codes.AVOCADO_FAIL)
         if app_args.gdb_run_bin:
             view.notify(event='error',
                         msg='Command line option --wrapper is incompatible'
                         ' with option --gdb-run-bin.')
             sys.exit(exit_codes.AVOCADO_FAIL)
     except AttributeError:
         pass
Пример #4
0
def download_assets():
    view = output.View()
    all_assets = asset.get_all_assets()
    if all_assets:
        view.notify(msg="Available download assets:")
        view.notify(msg="")
        for asset_info in all_assets:
            asset_keys = asset_info.keys()
            view.notify(
                event='minor',
                msg="%d - %s" %
                (all_assets.index(asset_info) + 1, asset_info['title']))
            asset_keys.pop(asset_keys.index('title'))
            asset_keys.sort()
            for k in asset_keys:
                view.notify(event='minor',
                            msg="    %s = %s" % (k, asset_info[k]))
            view.notify(msg="")
    indexes = raw_input("Type the index for the assets you want to "
                        "download (comma separated, leave empty to abort): ")

    index_list = []

    for idx in indexes.split(","):
        try:
            index = int(idx) - 1
            index_list.append(index)
            all_assets[index]
        except (ValueError, IndexError):
            logging.error("Invalid index(es), aborting...")
            sys.exit(1)

    for idx in index_list:
        asset_info = all_assets[idx]
        asset.download_file(asset_info, interactive=True)
Пример #5
0
    def activate(self, app_args):
        def app_using_human_output(app_args):
            for key in app_args.__dict__:
                if key.endswith('output'):
                    if app_args.__dict__[key] == '-':
                        return False
            return True

        self.__add_default_values(app_args)

        view = output.View(app_args=app_args)
        if (not defaults.disable_restore_image_job
                and defaults.disable_restore_image_test):
            # Don't restore the image when also restoring image per-test
            drive_file = getattr(app_args, 'guest_image_path', None)
            compressed_drive_file = drive_file + '.7z'
            if os.path.isfile(compressed_drive_file):
                if app_using_human_output(app_args):
                    msg = ("Plugin setup (Restoring guest image backup). "
                           "Please wait...")
                    view.notify(event='minor', msg=msg)
                cwd = os.getcwd()
                os.chdir(os.path.dirname(compressed_drive_file))
                process.run('7za -y e %s' %
                            os.path.basename(compressed_drive_file))
                os.chdir(cwd)
Пример #6
0
    def run(self, args):
        fail = False
        view = output.View(app_args=args)
        view.notify(event='message',
                    msg='Probing your system for test requirements')
        try:
            utils_path.find_command('7za')
            view.notify(event='minor', msg='7zip present')
        except utils_path.CmdNotFoundError:
            view.notify(event='warning',
                        msg=("7za not installed. You may "
                             "install 'p7zip' (or the "
                             "equivalent on your distro) to "
                             "fix the problem"))
            fail = True

        jeos_sha1_url = 'https://lmr.fedorapeople.org/jeos/SHA1SUM_JEOS20'
        try:
            view.notify(event='minor',
                        msg=('Verifying expected SHA1 '
                             'sum from %s' % jeos_sha1_url))
            sha1_file = urllib2.urlopen(jeos_sha1_url)
            sha1_contents = sha1_file.read()
            sha1 = sha1_contents.split(" ")[0]
            view.notify(event='minor', msg='Expected SHA1 sum: %s' % sha1)
        except Exception, e:
            view.notify(event='error',
                        msg='Failed to get SHA1 from file: %s' % e)
            fail = True
Пример #7
0
    def run(self, args):
        """
        Print libexec path and finish

        :param args: Command line args received from the run subparser.
        """
        self.view = output.View(app_args=args, use_paginator=False)
        if 'VIRTUAL_ENV' in os.environ:
            self.view.notify(event='minor', msg='libexec')
        elif os.path.exists('/usr/libexec/avocado'):
            self.view.notify(event='minor', msg='/usr/libexec/avocado')
        elif os.path.exists('/usr/lib/avocado'):
            self.view.notify(event='minor', msg='/usr/lib/avocado')
        else:
            for path in os.environ.get('PATH').split(':'):
                if (os.path.exists(os.path.join(path, 'avocado'))
                        and os.path.exists(
                            os.path.join(os.path.dirname(path), 'libexec'))):
                    self.view.notify(event='minor',
                                     msg=os.path.join(os.path.dirname(path),
                                                      'libexec'))
                    break
            else:
                self.view.notify(event='error',
                                 msg="Can't locate avocado libexec path")
                sys.exit(exit_codes.AVOCADO_FAIL)
        return sys.exit(exit_codes.AVOCADO_ALL_OK)
Пример #8
0
 def get_extra_listing(self):
     if self.args.vt_list_guests:
         use_paginator = self.args.paginator == 'on'
         view = output.View(use_paginator=use_paginator)
         try:
             guest_listing(self.args, view)
         finally:
             view.cleanup()
         sys.exit(0)
Пример #9
0
 def __init__(self, args):
     use_paginator = args.paginator == 'on'
     self.view = output.View(app_args=args, use_paginator=use_paginator)
     self.term_support = output.TermSupport()
     try:
         loader.loader.load_plugins(args)
     except loader.LoaderError, details:
         sys.stderr.write(str(details))
         sys.stderr.write('\n')
         sys.exit(exit_codes.AVOCADO_FAIL)
Пример #10
0
    def __init__(self, args=None, standalone=False):
        """
        Creates an instance of Job class.

        :param args: an instance of :class:`argparse.Namespace`.
        :param standalone: do not create any content and present the job log
                           on the output.
        """
        self.args = args
        self.standalone = standalone
        if args is not None:
            self.unique_id = args.unique_job_id or job_id.create_unique_job_id(
            )
        else:
            self.unique_id = job_id.create_unique_job_id()
        self.view = output.View(app_args=self.args)
        self.logdir = None
        if self.args is not None:
            raw_log_level = args.job_log_level
            mapping = {
                'info': logging.INFO,
                'debug': logging.DEBUG,
                'warning': logging.WARNING,
                'error': logging.ERROR,
                'critical': logging.CRITICAL
            }
            if raw_log_level is not None and raw_log_level in mapping:
                self.loglevel = mapping[raw_log_level]
            else:
                self.loglevel = logging.DEBUG
            if multiplexer.MULTIPLEX_CAPABLE:
                self.multiplex_files = args.multiplex_files
            self.show_job_log = args.show_job_log
            self.silent = args.silent
        else:
            self.loglevel = logging.DEBUG
            self.multiplex_files = None
            self.show_job_log = False
            self.silent = False

        if standalone:
            self.show_job_log = True
            if self.args is not None:
                setattr(self.args, 'show_job_log', True)

        if self.show_job_log:
            if not self.silent:
                test_logger = logging.getLogger('avocado.test')
                output.add_console_handler(test_logger)
                test_logger.setLevel(self.loglevel)
        self.test_dir = data_dir.get_test_dir()
        self.test_index = 1
        self.status = "RUNNING"
        self.result_proxy = result.TestResultProxy()
        self.sysinfo = None
Пример #11
0
    def __init__(self, stream=None, args=None):
        """
        Creates an instance of xUnitTestResult.

        :param stream: an instance of :class:`avocado.core.output.View`.
        :param args: an instance of :class:`argparse.Namespace`.
        """
        TestResult.__init__(self, stream, args)
        self.output = getattr(self.args, 'xunit_output', '-')
        self.stream = output.View(app_args=args)
        self.xml = XmlResult()
Пример #12
0
    def run(self, args):
        if 'html_output' in args and args.html_output == '-':
            view = output.View(app_args=args)
            view.notify(event='error',
                        msg='HTML to stdout not supported '
                        '(not all HTML resources can be embedded '
                        'on a single file)')
            sys.exit(exit_codes.AVOCADO_JOB_FAIL)

        if 'html_output' in args and args.html_output is not None:
            args.html_result = HTMLTestResult
Пример #13
0
    def run(self, args):
        view = output.View(use_paginator=(args.paginator == 'on'))
        try:
            view.notify(event="message", msg='Config files read (in order):')
            for cfg_path in settings.config_paths:
                view.notify(event="message", msg='    %s' % cfg_path)
            if settings.config_paths_failed:
                view.notify(event="minor", msg='')
                view.notify(event="error",
                            msg='Config files that failed to read:')
                for cfg_path in settings.config_paths_failed:
                    view.notify(event="error", msg='    %s' % cfg_path)
            view.notify(event="minor", msg='')
            if not args.datadir:
                blength = 0
                for section in settings.config.sections():
                    for value in settings.config.items(section):
                        clength = len('%s.%s' % (section, value[0]))
                        if clength > blength:
                            blength = clength

                format_str = "    %-" + str(blength) + "s %s"

                view.notify(event="minor",
                            msg=format_str % ('Section.Key', 'Value'))
                for section in settings.config.sections():
                    for value in settings.config.items(section):
                        config_key = ".".join((section, value[0]))
                        view.notify(event="minor",
                                    msg=format_str % (config_key, value[1]))
            else:
                view.notify(
                    event="minor",
                    msg="Avocado replaces config dirs that can't be accessed")
                view.notify(
                    event="minor",
                    msg="with sensible defaults. Please edit your local config"
                )
                view.notify(event="minor", msg="file to customize values")
                view.notify(event="message", msg='')
                view.notify(event="message", msg='Avocado Data Directories:')
                view.notify(event="minor",
                            msg='    base     ' + data_dir.get_base_dir())
                view.notify(event="minor",
                            msg='    tests    ' + data_dir.get_test_dir())
                view.notify(event="minor",
                            msg='    data     ' + data_dir.get_data_dir())
                view.notify(event="minor",
                            msg='    logs     ' + data_dir.get_logs_dir())
        finally:
            view.cleanup()
Пример #14
0
 def activate(self, app_args):
     try:
         if app_args.html_output:
             if app_args.html_output == '-':
                 view = output.View(app_args=app_args)
                 view.notify(event='error',
                             msg='HTML to stdout not supported '
                             '(not all HTML resources can be embedded '
                             'on a single file)')
                 sys.exit(exit_codes.AVOCADO_JOB_FAIL)
             else:
                 self.parser.application.set_defaults(
                     html_result=HTMLTestResult)
     except AttributeError:
         pass
Пример #15
0
Файл: app.py Проект: ypu/avocado
    def __init__(self):
        """
        Initializes a new app instance.

        This class is intended both to be used by the stock client application
        and also to be reused by custom applications. If you want, say, to
        limit the amount of command line actions and its arguments, you can
        simply supply another argument parser class to this constructor. Of
        course another way to customize it is to inherit from this and modify
        its members at will.
        """
        self.connection = None
        self.parser = parser.Parser()
        self.parser.add_arguments_on_all_modules()
        self.view = output.View()
Пример #16
0
Файл: job.py Проект: ypu/avocado
    def __init__(self, args=None):
        """
        Creates an instance of Job class.

        :param args: an instance of :class:`argparse.Namespace`.
        """
        if args is None:
            args = argparse.Namespace()
        self.args = args
        self.standalone = getattr(self.args, 'standalone', False)
        unique_id = getattr(self.args, 'unique_job_id', None)
        if unique_id is None:
            unique_id = job_id.create_unique_job_id()
        self.unique_id = unique_id
        self.view = output.View(app_args=self.args)
        self.logdir = None
        raw_log_level = settings.get_value('job.output',
                                           'loglevel',
                                           default='debug')
        mapping = {
            'info': logging.INFO,
            'debug': logging.DEBUG,
            'warning': logging.WARNING,
            'error': logging.ERROR,
            'critical': logging.CRITICAL
        }
        if raw_log_level in mapping:
            self.loglevel = mapping[raw_log_level]
        else:
            self.loglevel = logging.DEBUG
        self.show_job_log = getattr(self.args, 'show_job_log', False)
        self.silent = getattr(self.args, 'silent', False)

        if self.standalone:
            self.show_job_log = True
            if self.args is not None:
                setattr(self.args, 'show_job_log', True)

        if self.show_job_log:
            if not self.silent:
                output.add_console_handler(_TEST_LOGGER)
                _TEST_LOGGER.setLevel(self.loglevel)

        self.test_dir = data_dir.get_test_dir()
        self.test_index = 1
        self.status = "RUNNING"
        self.result_proxy = result.TestResultProxy()
        self.sysinfo = None
Пример #17
0
    def run(self, args):
        view = output.View(app_args=args, use_paginator=True)
        pm = get_plugin_manager()
        view.notify(event='message', msg='Plugins loaded:')
        blength = 0
        for plug in pm.plugins:
            clength = len(plug.name)
            if clength > blength:
                blength = clength

        format_str = "    %-" + str(blength) + "s %s %s"
        for plug in sorted(pm.plugins):
            if plug.enabled:
                status = "(Enabled)"
            else:
                status = "(Disabled)"
            view.notify(event='minor', msg=format_str % (plug.name, plug.description, status))
        view.cleanup()
Пример #18
0
 def run(self, args):
     self._activate(args)
     view = output.View(app_args=args)
     err = None
     if args.tree and args.debug:
         err = "Option --tree is incompatible with --debug."
     elif not args.tree and args.inherit:
         err = "Option --inherit can be only used with --tree"
     if err:
         view.notify(event="minor", msg=self.parser.format_help())
         view.notify(event="error", msg=err)
         sys.exit(exit_codes.AVOCADO_FAIL)
     try:
         mux_tree = multiplexer.yaml2tree(args.multiplex_files,
                                          args.filter_only, args.filter_out,
                                          args.debug)
     except IOError, details:
         view.notify(event='error', msg=details.strerror)
         sys.exit(exit_codes.AVOCADO_JOB_FAIL)
Пример #19
0
    def run(self, args):
        """
        Run test modules or simple tests.

        :param args: Command line args received from the run subparser.
        """
        self._activate(args)
        self.view = output.View(app_args=args)
        if args.unique_job_id is not None:
            try:
                int(args.unique_job_id, 16)
                if len(args.unique_job_id) != 40:
                    raise ValueError
            except ValueError:
                self.view.notify(event='error', msg='Unique Job ID needs to be a 40 digit hex number')
                sys.exit(exit_codes.AVOCADO_FAIL)
        args.job_timeout = self._validate_job_timeout(args.job_timeout)
        job_instance = job.Job(args)
        return job_instance.run()
Пример #20
0
    def run(self, args):
        view = output.View(app_args=args)
        multiplex_files = args.multiplex_files
        if args.tree:
            view.notify(event='message', msg='Config file tree structure:')
            t = tree.create_from_yaml(multiplex_files)
            t = tree.apply_filters(t, args.filter_only, args.filter_out)
            view.notify(event='minor',
                        msg=t.get_ascii(attributes=args.attr))
            sys.exit(exit_codes.AVOCADO_ALL_OK)

        try:
            variants = multiplexer.multiplex_yamls(multiplex_files,
                                                   args.filter_only,
                                                   args.filter_out,
                                                   args.debug)
        except IOError, details:
            view.notify(event='error',
                        msg="%s: '%s'" % (details.strerror, details.filename))
            sys.exit(exit_codes.AVOCADO_JOB_FAIL)
Пример #21
0
    def _check_required_args(args, enable_arg, required_args):
        """
        :return: True when enable_arg enabled and all required args are set
        :raise sys.exit: When missing required argument.
        """
        if (not hasattr(args, enable_arg) or not getattr(args, enable_arg)):
            return False
        missing = []
        for arg in required_args:
            if not getattr(args, arg):
                missing.append(arg)
        if missing:
            view = output.View(app_args=args)
            e_msg = (
                'Use of %s requires %s arguments to be set. Please set %s'
                '.' %
                (enable_arg, ', '.join(required_args), ', '.join(missing)))

            view.notify(event='error', msg=e_msg)
            return sys.exit(exit_codes.AVOCADO_FAIL)
        return True
Пример #22
0
    def run(self, args):
        view = output.View(app_args=args)
        multiplex_files = tuple(
            os.path.abspath(_) for _ in args.multiplex_files)
        for path in multiplex_files:
            if not os.path.isfile(path):
                view.notify(event='error',
                            msg='Invalid multiplex file %s' % path)
                sys.exit(exit_codes.AVOCADO_JOB_FAIL)

        if args.tree:
            view.notify(event='message', msg='Config file tree structure:')
            t = tree.create_from_yaml(multiplex_files)
            t = tree.apply_filters(t, args.filter_only, args.filter_out)
            view.notify(event='minor', msg=t.get_ascii())
            sys.exit(exit_codes.AVOCADO_ALL_OK)

        variants = multiplexer.multiplex_yamls(multiplex_files,
                                               args.filter_only,
                                               args.filter_out, args.debug)

        view.notify(event='message', msg='Variants generated:')
        for (index, tpl) in enumerate(variants):
            if not args.debug:
                paths = ', '.join([x.path for x in tpl])
            else:
                color = output.term_support.LOWLIGHT
                cend = output.term_support.ENDC
                paths = ', '.join(
                    ["%s%s@%s%s" % (_.name, color, _.yaml, cend) for _ in tpl])
            view.notify(event='minor',
                        msg='\nVariant %s:    %s' % (index + 1, paths))
            if args.contents:
                env = {}
                for node in tpl:
                    env.update(node.environment)
                for k in sorted(env.keys()):
                    view.notify(event='minor', msg='    %s: %s' % (k, env[k]))

        sys.exit(exit_codes.AVOCADO_ALL_OK)
Пример #23
0
    def run(self, args):
        view = output.View(app_args=args, use_paginator=args.paginator == 'on')

        cli_cmds = dispatcher.CLICmdDispatcher()
        msg = 'Plugins that add new commands (avocado.plugins.cli.cmd):'
        view.notify(event='message', msg=msg)
        plugin_matrix = []
        for plugin in sorted(cli_cmds):
            plugin_matrix.append((plugin.name, plugin.obj.description))

        for line in astring.iter_tabular_output(plugin_matrix):
            view.notify(event='minor', msg=line)

        msg = 'Plugins that add new options to commands (avocado.plugins.cli):'
        cli = dispatcher.CLIDispatcher()
        view.notify(event='message', msg=msg)
        plugin_matrix = []
        for plugin in sorted(cli):
            plugin_matrix.append((plugin.name, plugin.obj.description))

        for line in astring.iter_tabular_output(plugin_matrix):
            view.notify(event='minor', msg=line)
Пример #24
0
    def run(self, args):
        """
        Run test modules or simple tests.

        :param args: Command line args received from the run subparser.
        """
        view = output.View(app_args=args)
        if args.unique_job_id is not None:
            try:
                int(args.unique_job_id, 16)
                if len(args.unique_job_id) != 40:
                    raise ValueError
            except ValueError:
                view.notify(event='error', msg='Unique Job ID needs to be a 40 digit hex number')
                return sys.exit(exit_codes.AVOCADO_FAIL)

        job_instance = job.Job(args)
        rc = job_instance.run()
        if not args.url:
            self.parser.print_help()

        return rc
Пример #25
0
    def run(self, args):
        view = output.View()
        if args.distro_def_create:
            if not (args.distro_def_name and args.distro_def_version and
                    args.distro_def_arch and args.distro_def_type and
                    args.distro_def_path):
                error_msg = ('Required arguments: name, version, arch, type '
                             'and path')
                view.notify(event="error", msg=error_msg)
                sys.exit(exit_codes.AVOCADO_FAIL)

            output_file_name = self.get_output_file_name(args)
            if os.path.exists(output_file_name):
                error_msg = ('Output file "%s" already exists, will not '
                             'overwrite it' % output_file_name)
                view.notify(event="error", msg=error_msg)
            else:
                view.notify(event="message",
                            msg=("Loading distro information from tree... "
                                 "Please wait..."))
                distro = load_from_tree(args.distro_def_name,
                                        args.distro_def_version,
                                        args.distro_def_release,
                                        args.distro_def_arch,
                                        args.distro_def_type,
                                        args.distro_def_path)
                save_distro(distro, output_file_name)
                view.notify(event="message",
                            msg=('Distro information saved '
                                 'to "%s"' % output_file_name))
        else:
            detected = distro_utils.detect()
            msg = 'Detected distribution: %s (%s) version %s release %s' % (
                detected.name,
                detected.arch,
                detected.version,
                detected.release)
            view.notify(event="message", msg=msg)
Пример #26
0
    def run(self, args):
        if getattr(args, 'replay_jobid', None) is None:
            return

        view = output.View()

        if args.remote_hostname is not None:
            msg = "Currently we don't replay jobs in remote hosts."
            view.notify(event='error', msg=(msg))
            sys.exit(exit_codes.AVOCADO_JOB_FAIL)

        if args.replay_datadir is not None:
            resultsdir = args.replay_datadir
        else:
            logs_dir = settings.get_value('datadir.paths', 'logs_dir',
                                          default=None)
            self.logdir = os.path.expanduser(logs_dir)
            resultsdir = replay.get_resultsdir(self.logdir, args.replay_jobid)

        if resultsdir is None:
            msg = "can't find job results directory in '%s'" % self.logdir
            view.notify(event='error', msg=(msg))
            sys.exit(exit_codes.AVOCADO_JOB_FAIL)

        sourcejob = replay.get_id(os.path.join(resultsdir, 'id'),
                                  args.replay_jobid)
        if sourcejob is None:
            msg = "can't find matching job id '%s' in '%s' directory." % \
                  (args.replay_jobid, resultsdir)
            view.notify(event='error', msg=(msg))
            sys.exit(exit_codes.AVOCADO_JOB_FAIL)

        setattr(args, 'replay_sourcejob', sourcejob)

        if getattr(args, 'url', None):
            msg = 'Overriding the replay urls with urls provided in '\
                  'command line.'
            view.notify(event='warning', msg=(msg))
        else:
            urls = replay.retrieve_urls(resultsdir)
            if urls is None:
                msg = 'Source job urls data not found. Aborting.'
                view.notify(event='error', msg=(msg))
                sys.exit(exit_codes.AVOCADO_JOB_FAIL)
            else:
                setattr(args, 'url', urls)

        if args.replay_ignore and 'config' in args.replay_ignore:
            msg = "Ignoring configuration from source job with " \
                  "--replay-ignore."
            view.notify(event='warning', msg=(msg))
        else:
            self.load_config(resultsdir)

        if args.replay_ignore and 'mux' in args.replay_ignore:
            msg = "Ignoring multiplex from source job with --replay-ignore."
            view.notify(event='warning', msg=(msg))
        else:
            if getattr(args, 'multiplex_files', None) is not None:
                msg = 'Overriding the replay multiplex with '\
                      '--multiplex-file.'
                view.notify(event='warning', msg=(msg))
                # Use absolute paths to avoid problems with os.chdir
                args.multiplex_files = [os.path.abspath(_)
                                        for _ in args.multiplex_files]
            else:
                mux = replay.retrieve_mux(resultsdir)
                if mux is None:
                    msg = 'Source job multiplex data not found. Aborting.'
                    view.notify(event='error', msg=(msg))
                    sys.exit(exit_codes.AVOCADO_JOB_FAIL)
                else:
                    setattr(args, "multiplex_files", mux)

        if args.replay_teststatus:
            replay_map = replay.retrieve_replay_map(resultsdir,
                                                    args.replay_teststatus)
            setattr(args, 'replay_map', replay_map)

        # Use the original directory to discover test urls properly
        pwd = replay.retrieve_pwd(resultsdir)
        if pwd is not None:
            if os.path.exists(pwd):
                os.chdir(pwd)
            else:
                view.notify(event="warning", msg="Directory used in the replay"
                            " source job '%s' does not exist, using '.' "
                            "instead" % pwd)
Пример #27
0
"""

import os
import sys
import optparse

from avocado.utils import crypto
from avocado.core import output
from avocado.core import log

if __name__ == "__main__":
    parser = optparse.OptionParser("usage: %prog [options] [filenames]")
    options, args = parser.parse_args()

    log.configure()
    view = output.View()

    if args:
        filenames = args
    else:
        parser.print_help()
        sys.exit(1)

    for filename in filenames:
        filename = os.path.abspath(filename)

        file_exists = os.path.isfile(filename)
        can_read_file = os.access(filename, os.R_OK)
        if not file_exists:
            view.notify(event='error',
                        msg="File %s does not exist!" % filename)
Пример #28
0
    def _run(self, args):
        """
        List available test modules.

        :param args: Command line args received from the list subparser.
        """
        self.view = output.View(app_args=args,
                                use_paginator=args.paginator == 'on')

        paths = [data_dir.get_test_dir()]
        if args.paths:
            paths = args.paths
        params_list = self.test_loader.discover_urls(paths)
        for params in params_list:
            params['omit_non_tests'] = False
        test_suite = self.test_loader.discover(params_list)
        error_msg_parts = self.test_loader.validate_ui(test_suite,
                                                       ignore_not_test=True,
                                                       ignore_access_denied=True,
                                                       ignore_broken_symlinks=True)
        if error_msg_parts:
            for error_msg in error_msg_parts:
                self.view.notify(event='error', msg=error_msg)
            self.view.cleanup()
            sys.exit(exit_codes.AVOCADO_FAIL)

        test_matrix = []
        stats = {'simple': 0,
                 'instrumented': 0,
                 'buggy': 0,
                 'missing': 0,
                 'not_a_test': 0,
                 'broken_symlink': 0,
                 'access_denied': 0}
        for cls, params in test_suite:
            id_label = ''
            type_label = cls.__name__

            if 'params' in params:
                id_label = params['params']['id']
            else:
                if 'name' in params:
                    id_label = params['name']
                elif 'path' in params:
                    id_label = params['path']

            if cls == test.SimpleTest:
                stats['simple'] += 1
                type_label = self.term_support.healthy_str('SIMPLE')
            elif cls == test.BuggyTest:
                stats['buggy'] += 1
                type_label = self.term_support.fail_header_str('BUGGY')
            elif cls == test.NotATest:
                if not args.verbose:
                    continue
                stats['not_a_test'] += 1
                type_label = self.term_support.warn_header_str('NOT_A_TEST')
            elif cls == test.MissingTest:
                stats['missing'] += 1
                type_label = self.term_support.fail_header_str('MISSING')
            elif cls == loader.BrokenSymlink:
                stats['broken_symlink'] += 1
                type_label = self.term_support.fail_header_str('BROKEN_SYMLINK')
            elif cls == loader.AccessDeniedPath:
                stats['access_denied'] += 1
                type_label = self.term_support.fail_header_str('ACCESS_DENIED')
            else:
                if issubclass(cls, test.Test):
                    stats['instrumented'] += 1
                    type_label = self.term_support.healthy_str('INSTRUMENTED')

            test_matrix.append((type_label, id_label))

        header = None
        if args.verbose:
            header = (self.term_support.header_str('Type'),
                      self.term_support.header_str('file'))
        for line in astring.tabular_output(test_matrix,
                                           header=header).splitlines():
            self.view.notify(event='minor', msg="%s" % line)

        if args.verbose:
            self.view.notify(event='minor', msg='')

            self.view.notify(event='message', msg=("SIMPLE: %s" %
                                                   stats['simple']))
            self.view.notify(event='message', msg=("INSTRUMENTED: %s" %
                                                   stats['instrumented']))
            self.view.notify(event='message', msg=("BUGGY: %s" %
                                                   stats['buggy']))
            self.view.notify(event='message', msg=("MISSING: %s" %
                                                   stats['missing']))
            self.view.notify(event='message', msg=("NOT_A_TEST: %s" %
                                                   stats['not_a_test']))
            self.view.notify(event='message', msg=("ACCESS_DENIED: %s" %
                                                   stats['access_denied']))
            self.view.notify(event='message', msg=("BROKEN_SYMLINK: %s" %
                                                   stats['broken_symlink']))
Пример #29
0
 def __init__(self, stream=None, args=None):
     TestResult.__init__(self, stream, args)
     self.output = getattr(self.args, 'html_output')
     self.args = args
     self.view = output.View(app_args=args)
     self.json = None