Parse command line arguments and then run the test suite
160756
def main():
  
  parser = argparse.ArgumentParser(description='A distributed test framework')
  parser.add_argument('testfile',
      help='The file that is used to determine the test suite run')
  parser.add_argument('--test-only',
      nargs='*',
      dest='test_list',
      help='run only the named tests to help debug broken tests')
  parser.add_argument('--machine-list',
      nargs='*',
      dest='machine_list',
      help='''mapping of logical host names to physical names allowing the same
              test suite to run on different hardware, each argument is a pair
              of logical name and physical name separated by a =''')
  parser.add_argument('--config-overrides',
      nargs='*',
      dest='config_overrides',
      help='''config overrides at execution time, each argument is a config with
              its value separated by a =. This has the highest priority of all
              configs''')
  parser.add_argument('-d', '--output-dir',
      dest='output_dir',
      help='''Directory to write output files and logs. Defaults to the current
              directory.''')
  parser.add_argument("--log-level", dest="log_level", help="Log level (default INFO)", default="INFO")
  parser.add_argument("--console-log-level", dest="console_level", help="Console Log level (default ERROR)",
                      default="ERROR")
  parser.add_argument("--nopassword", action='store_true', dest="nopassword", help="Disable password prompt")
  parser.add_argument("--user", dest="user", help="user to run the test as (defaults to current user)")
  args = parser.parse_args()
  try:
    call_main(args)
  except ValueError:
    #We only sys.exit here, as call_main is used as part of a unit test
    #and should not exit the system
    sys.exit(1)
374055
def run():
	
	parser = argparse.ArgumentParser()
	parser.add_argument(
		'--deps-def',
		default=data_lines_from_file("system deps.txt")
		+ data_lines_from_file("build deps.txt"),
		help="A file specifying the dependencies (one per line)",
		type=data_lines_from_file, dest="spec_deps")
	parser.add_argument(
		'--dep', action="append", default=[],
		help="A specific dependency (multiple allowed)", dest="deps")
	parser.add_argument(
		'command', type=shlex.split,
		default=shlex.split("python2.7 setup.py test"),
		help="Command to invoke in the context of the dependencies")
	parser.add_argument(
		'--do-not-remove', default=False, action="store_true",
		help="Keep any installed packages")
	parser.add_argument(
		'--aggressively-remove', default=False,
		action="store_true",
		help="When removing packages, also remove those automatically installed"
		" as dependencies")
	parser.add_argument(
		'-l', '--log-level', default=logging.INFO,
		type=log_level, help="Set log level (DEBUG, INFO, WARNING, ERROR)")
	args = parser.parse_args()
	logging.basicConfig(level=args.log_level)
	context = dependency_context(
		args.spec_deps + args.deps,
		aggressively_remove=args.aggressively_remove)
	with context as to_remove:
		if args.do_not_remove:
			del to_remove[:]
		raise SystemExit(subprocess.Popen(args.command).wait())
1115555
def add_arguments(self, parser):
        """"""
        # Add the underlying test command arguments first
        test_command = TestCommand()
        test_command.add_arguments(parser)

        for option in OPTIONS:
            parser.add_argument(*option[0], **option[1])
1191026
def parse_arguments():
    
    max_procs = MAX_PROCS
    dry_run = DRY_RUN
    logging.basicConfig(level=logging.INFO, stream=sys.stdout,
                        format='%(asctime)s * %(levelname)s * %(message)s')

    parser = argparse.ArgumentParser(description="""nestrun - substitute values
            into a template and run commands in parallel.""")
    parser.add_argument('-j', '--processes', '--local', dest='local_procs',
            type=int, help="""Run a maximum of N processes in parallel locally
            (default: %(default)s)""", metavar='N', default=MAX_PROCS)
    parser.add_argument('--template', dest='template',
            metavar="'template text'", help="""Command-execution template, e.g.
            bash {infile}. By default, nestrun executes the templatefile.""")
    parser.add_argument('--stop-on-error', action='store_true',
            default=False, help="""Terminate remaining processes if any process
            returns non-zero exit status (default: %(default)s)""")
    parser.add_argument('--template-file', dest='template_file', metavar="FILE",
            help='Command-execution template file path.')
    parser.add_argument('--save-cmd-file', dest='savecmd_file',
            help="""Name of the file that will contain the command that was
            executed.""")
    log_group = parser.add_mutually_exclusive_group()
    log_group.add_argument('--log-file', dest='log_file', default='log.txt',
            help="""Name of the file that will contain output of the executed
            command.""")
    log_group.add_argument('--no-log', dest="log_file", action="store_const",
            default='log.txt', const=os.devnull, help="""Don't create a log
            file""")
    parser.add_argument('--dry-run', action='store_true', help="""Dry run mode,
            does not execute commands.""", default=False)
    parser.add_argument('--summary-file', type=argparse.FileType('w'),
            help="""Write a summary of the run to the specified file""")

    ctrl_group = parser.add_argument_group('Control files')
    ctrl_group.add_argument('json_files', metavar='control_files', type=extant_file,
            nargs='*', help="""Nestly control dictionaries""")
    ctrl_group.add_argument('-d', '--directory', help="""Run on all control
            files under %(metavar)s. May be used in place of specifying control
            files.""", metavar='DIR')
    arguments = parser.parse_args()


    # Load controls
    if bool(arguments.directory) == bool(arguments.json_files):
        parser.error('Exactly one of `-d` and control_files must be specified.')
    elif arguments.directory:
        arguments.json_files.extend(control_iter(arguments.directory))

    template = arguments.template

    # Make sure that either a template or a template file was given
    if arguments.template_file:
        # if given a template file, the default is to run the input
        if not arguments.template:
            template = os.path.join('.',
                    os.path.basename(arguments.template_file))

            # If using the default argument, the template must be executable:
            if (not os.access(arguments.template_file, os.X_OK) and not
                    arguments.dry_run):
                parser.error(
                        "{0} is not executable. Specify a template.".format(
                    arguments.template_file))

    if not (arguments.template or arguments.template_file):
        parser.exit("Error: Please specify either a template "
                "or a template file")

    logging.info('Template: %s', template)

    if arguments.local_procs is not None:
        max_procs = arguments.local_procs

    # Create a dictionary that will be shared amongst all forked processes.
    data = {}
    data['dry_run'] = arguments.dry_run
    data['start_directory'] = os.getcwd()
    data['template'] = template
    data['template_file'] = arguments.template_file
    data['savecmd_file'] = arguments.savecmd_file
    data['log_file'] = arguments.log_file
    data['stop_on_error'] = arguments.stop_on_error
    data['summary_file'] = arguments.summary_file

    return data, max_procs, arguments.json_files
1290510
def run(**kwargs):
    """"""
    paths = kwargs.pop('paths', ())
    action = kwargs.pop('action')
    plugin = kwargs.pop('plugin')
    junit_xml = kwargs.pop('junit_xml')
    use_tracked_files = kwargs.pop('use_tracked_files')
    quiet = kwargs.pop('quiet')

    colorama.init(strip=kwargs.pop('no_color'))

    git_dir = current_git_dir()

    if git_dir is None:
        output(NOT_GIT_REPO_MSG)
        exit(1)

    repo_root = os.path.dirname(git_dir)

    files = []
    if paths:
        # We want to look at files in their current state if paths are passed through
        kwargs['include_unstaged_changes'] = True

        # If paths were provided get all the files for each path
        for path in paths:
            for f in list_files(path):
                f = os.path.relpath(f, repo_root)
                if not f.startswith('..'):  # Don't include files outside the repo root.
                    files.append(f)
    elif use_tracked_files:
        # If the use tracked files flag was passed, get a list of all the tracked files
        out, err, code = git.ls_files()
        files = out.splitlines()

        if kwargs.get('include_untracked'):
            out, err, code = git.ls_files(o=True, exclude_standard=True)
            files += out.splitlines()

    if files or paths:
        kwargs['files'] = files

    config = get_config(repo_root)
    runner = Runner(config.cwd, **kwargs)
    results = ResultCollection()

    if runner.unstaged_changes and not quiet:
        output(UNSTAGED_CHANGES_MSG, end='\n\n')

    processes = list(config.actions) + list(config.plugins)
    processes.sort(key=lambda x: x.name)  # Sort the list of processes for consistent results

    if plugin:
        try:
            processes = [config.plugins.get(plugin)]
        except config.plugins.DoesNotExist as e:
            output('{}\nAvailable plugins:'.format(e.message))

            for p in config.plugins:
                output(p.name)
            exit(1)

    if action:
        try:
            processes = [config.actions.get(action)]
        except config.actions.DoesNotExist as e:
            output('{}\nAvailable actions:'.format(e.message))

            for a in config.actions:
                output(a.name)
            exit(1)

    for process in processes:
        result, message = runner.run_process(process)
        results.append(result)

        if not quiet:
            output(message)

    if junit_xml:
        with open(junit_xml, 'w+') as f:
            f.write('{}'.format(results.dump_junit()))

    if not quiet:
        output(results.dump())
        output('#{{bright}}{}\nCompleted in: {}s'.format(''.ljust(79, '-'), round(results.execution_time, 2)))

    if results.has_error:
        exit(1)
    elif results.has_failure:
        exit(2)
1113588
def parse_args(args, default_server_definitions_path,
               default_profile_definitions_path):
    
    prog = os.path.basename(sys.argv[0])
    usage = '%(prog)s [options] server'
    desc = """
Test script for testing get_central_instances method. This script executes
a number of tests and displays against a set of servers defined in the
test file

"""
    epilog = """
Examples:
  %s Fujitsu -v 3

  %s -v 1`
""" % (prog, prog)

    argparser = _argparse.ArgumentParser(
        prog=prog, usage=usage, description=desc, epilog=epilog,
        add_help=False, formatter_class=_WbemcliCustomFormatter)

    pos_arggroup = argparser.add_argument_group(
        'Positional arguments')
    pos_arggroup.add_argument(
        'servers', metavar='servers', nargs='*', type=str,
        default=['default'],
        help='R|Define by nickname zero or more specific servers to\n'
             'test. If  no servers are specified, the default\n'
             'group is tested. If there is no default group defined,\n'
             'all servers are tested.')

    general_arggroup = argparser.add_argument_group(
        'General options')

    general_arggroup.add_argument(
        '-l', '--list_servers', dest='list_servers',
        action='store_true',
        default=False,
        help='List servers nicknames defined by the servers arguement. If '
             'there are no servers defined by the servers argument, list '
             'the servers defined by the group "default". If there is no '
             'default group. list all servers')

    general_arggroup.add_argument(
        '--tests', dest='tests', default=None, nargs='*',
        choices=['overview', 'tree', 'profiles', 'insts', 'centralinsts'],
        help='List the tests to be executed. Default  is all tests')

    general_arggroup.add_argument(
        '-d', '--direction', dest='direction', default=None,
        choices=['dmtf', 'snia'],
        help='Define a particular reference direction for the test. If this '
             'is not specified, the direction algorithm is used, all of them.')

    general_arggroup.add_argument(
        '--serversfile', dest='servers_file', metavar='serversfile',
        default=default_server_definitions_path,
        help='R|The file path for the JSON file that defines the servers\n'
             'to be tested\n'
             'Default: %(default)s')

    general_arggroup.add_argument(
        '--profilesfile', dest='profiles_file', metavar='profilesfile',
        default=default_profile_definitions_path,
        help='R|The file path for the file that defines the\n'
             'characteristics of known profiles.\n'
             'Default: %(default)s')

    general_arggroup.add_argument(
        '-v', '--verbosity', dest='verbosity', type=int,
        default=0,
        help='Increment the output verbosity as integer from 0 t0 3')
    general_arggroup.add_argument(
        '-V', '--version', action='version', version='%(prog)s ' + __version__,
        help='Display script version and exit.')

    general_arggroup.add_argument(
        '-h', '--help', action='help',
        help='Show this help message and exit')

    args = argparser.parse_args()

    return args
48024
def main(manual_args=None):
    """"""
    parser = argparse.ArgumentParser(description=main.__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.set_defaults(func=parser.print_help)
    add_debug(parser)
    parser.add_argument(
        '-s',
        '--short-log',
        action='store_const',
        const=SHORT_LOGGING_FORMAT,
        default=LOGGING_FORMAT,
        help='Truncated logging format')
    parser.add_argument('-v', '--version', action='store_true', help=print_version.__doc__)

    subparsers = parser.add_subparsers(title='Commands', description='Available activies')

    add_infra(subparsers)
    add_pipeline(subparsers)
    add_rebuild(subparsers)
    add_autoscaling(subparsers)
    add_validate(subparsers)

    CliArgs = collections.namedtuple('CliArgs', ['parsed', 'extra'])

    parsed, extra = parser.parse_known_args(args=manual_args)
    args = CliArgs(parsed, extra)

    logging.basicConfig(format=args.parsed.short_log)

    package, *_ = __package__.split('.')
    logging.getLogger(package).setLevel(args.parsed.debug)

    LOG.debug('Arguments: %s', args)

    if args.parsed.version:
        args.parsed.func = print_version

    try:
        args.parsed.func(args)
    except (AttributeError, TypeError):
        args.parsed.func()
303256
def main():
    """"""
    # Initialize logging to the terminal.
    coloredlogs.install()
    # Prepare for command line argument parsing.
    action = show_matching_entry
    program_opts = dict(exclude_list=[])
    show_opts = dict(filters=[], use_clipboard=is_clipboard_supported())
    verbosity = 0
    # Parse the command line arguments.
    try:
        options, arguments = getopt.gnu_getopt(
            sys.argv[1:],
            "elnp:f:x:vqh",
            ["edit", "list", "no-clipboard", "password-store=", "filter=", "exclude=", "verbose", "quiet", "help"],
        )
        for option, value in options:
            if option in ("-e", "--edit"):
                action = edit_matching_entry
            elif option in ("-l", "--list"):
                action = list_matching_entries
            elif option in ("-n", "--no-clipboard"):
                show_opts["use_clipboard"] = False
            elif option in ("-p", "--password-store"):
                stores = program_opts.setdefault("stores", [])
                stores.append(PasswordStore(directory=value))
            elif option in ("-f", "--filter"):
                show_opts["filters"].append(value)
            elif option in ("-x", "--exclude"):
                program_opts["exclude_list"].append(value)
            elif option in ("-v", "--verbose"):
                coloredlogs.increase_verbosity()
                verbosity += 1
            elif option in ("-q", "--quiet"):
                coloredlogs.decrease_verbosity()
                verbosity -= 1
            elif option in ("-h", "--help"):
                usage(__doc__)
                return
            else:
                raise Exception("Unhandled option! (programming error)")
        if not (arguments or action == list_matching_entries):
            usage(__doc__)
            return
    except Exception as e:
        warning("Error: %s", e)
        sys.exit(1)
    # Execute the requested action.
    try:
        show_opts["quiet"] = verbosity < 0
        kw = show_opts if action == show_matching_entry else {}
        action(QuickPass(**program_opts), arguments, **kw)
    except PasswordStoreError as e:
        # Known issues don't get a traceback.
        logger.error("%s", e)
        sys.exit(1)
    except KeyboardInterrupt:
        # If the user interrupted an interactive prompt they most likely did so
        # intentionally, so there's no point in generating more output here.
        sys.exit(1)
633298
def main(**kwargs):
    """"""

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--version', action='version',
                        version='%(prog)s {}'.format(DATABENCH_VERSION))
    parser.add_argument('--log', dest='loglevel', default="INFO",
                        type=str.upper,
                        help=('log level (info, warning, error, critical or '
                              'debug, default info)'))
    parser.add_argument('--no-watch', dest='watch', default=True,
                        action='store_false',
                        help='do not watch and restart when files change')
    parser.add_argument('--host', dest='host',
                        default=os.environ.get('HOST', '127.0.0.1'),
                        help='host address for webserver (default 127.0.0.1)')
    parser.add_argument('--port', dest='port',
                        type=int, default=int(os.environ.get('PORT', 5000)),
                        help='port for webserver')
    if not kwargs:
        parser.add_argument('--analyses', default=None,
                            help='import path for analyses')
    parser.add_argument('--build', default=False, action='store_true',
                        help='run the build command and exit')
    parser.add_argument('--coverage', default=False,
                        help=argparse.SUPPRESS)

    ssl_args = parser.add_argument_group('SSL')
    ssl_args.add_argument('--ssl-certfile', dest='ssl_certfile',
                          default=os.environ.get('SSLCERTFILE'),
                          help='SSL certificate file')
    ssl_args.add_argument('--ssl-keyfile', dest='ssl_keyfile',
                          default=os.environ.get('SSLKEYFILE'),
                          help='SSL key file')
    ssl_args.add_argument('--ssl-port', dest='ssl_port', type=int,
                          default=int(os.environ.get('SSLPORT', 0)),
                          help='SSL port for webserver')

    args, analyses_args = parser.parse_known_args()

    # coverage
    cov = None
    if args.coverage:
        import coverage
        cov = coverage.Coverage(data_file=args.coverage, data_suffix=True)
        cov.start()

    # this is included here so that is included in coverage
    from .app import App, SingleApp

    # log
    logging.basicConfig(level=getattr(logging, args.loglevel))
    if args.loglevel != 'INFO':
        logging.info('Set loglevel to {}.'.format(args.loglevel))

    # show versions and setup
    logging.info('Databench {}'.format(DATABENCH_VERSION))
    if args.host in ('localhost', '127.0.0.1'):
        logging.info('Open http://{}:{} in a web browser.'
                     ''.format(args.host, args.port))
    logging.debug('host={}, port={}'.format(args.host, args.port))
    logging.debug('Python {}'.format(sys.version))

    if analyses_args:
        logging.debug('Arguments passed to analyses: {}'.format(analyses_args))

    if not kwargs:
        app = App(args.analyses, cli_args=analyses_args, debug=args.watch)
    else:
        app = SingleApp(cli_args=analyses_args, debug=args.watch, **kwargs)

    # check whether this is just a quick build
    if args.build:
        logging.info('Build mode: only run build command and exit.')
        app.build()
        if cov:
            cov.stop()
            cov.save()
        return

    # HTTP server
    tornado_app = app.tornado_app()
    tornado_app.listen(args.port, args.host)

    # HTTPS server
    if args.ssl_port:
        if args.ssl_certfile and args.ssl_keyfile:
            ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
            ssl_ctx.load_cert_chain(args.ssl_certfile, args.ssl_keyfile)
        else:
            # use Tornado's self signed certificates
            module_dir = os.path.dirname(tornado.__file__)
            ssl_ctx = {
                'certfile': os.path.join(module_dir, 'test', 'test.crt'),
                'keyfile': os.path.join(module_dir, 'test', 'test.key'),
            }

        logging.info('Open https://{}:{} in a web browser.'
                     ''.format(args.host, args.ssl_port))
        tornado_app.listen(args.ssl_port, ssl_options=ssl_ctx)

    try:
        tornado.ioloop.IOLoop.current().start()
    except KeyboardInterrupt:
        tornado.ioloop.IOLoop.current().stop()
        if cov:
            cov.stop()
            cov.save()
1345705
def run_from_command_line():
    
    for commands_conf in firenado.conf.management['commands']:
        logger.debug("Loading %s commands from %s." % (
            commands_conf['name'],
            commands_conf['module']
        ))
        exec('import %s' % commands_conf['module'])
    command_index = 1
    for arg in sys.argv[1:]:
        command_index += 1
        if arg[0] != "-":
            break
    parser = FirenadoArgumentParser(prog=os.path.split(sys.argv[0])[1],
                                    add_help=False)
    parser.add_argument("-h", "--help", default=argparse.SUPPRESS)
    parser.add_argument("command", default="help", help="Command to executed")

    try:
        namespace = parser.parse_args(sys.argv[1:command_index])
        if not command_exists(namespace.command):
            show_command_line_usage(parser)
        else:
            run_command(namespace.command, sys.argv[command_index-1:])
    except FirenadoArgumentError:
        show_command_line_usage(parser, True)
237538
def main():
    
    parser = argparse.ArgumentParser()
    parser.add_argument("--log-level", default="INFO",
                        choices=logging._nameToLevel,
                        help="Logging verbosity.")
    subparsers = parser.add_subparsers(help="Commands", dest="command")

    def add_backend_args(p):
        p.add_argument("--backend", default=None, help="Backend to use.")
        p.add_argument("--args", default=None, help="Backend's arguments.")

    def add_index_args(p):
        p.add_argument("--username", default="",
                       help="Username for the Git repository with the index.")
        p.add_argument("--password", default="",
                       help="Password for the Git repository with the index.")
        p.add_argument("--index-repo", default=None,
                       help="Url of the remote Git repository.")
        p.add_argument("--cache", default=None,
                       help="Path to the folder where the Git repository will be cached.")
        p.add_argument("-s", "--signoff", action="store_true",
                       help="Add Signed-off-by line by the committer at the end of the commit log "
                            "message. The meaning of a signoff depends on the project, but it "
                            "typically certifies that committer has the rights to submit this work"
                            " under the same license and agrees to a Developer Certificate of "
                            "Origin (see http://developercertificate.org/ for more information).")

    def add_templates_args(p):
        p.add_argument(
            "--template-model",
            default=os.path.join(os.path.dirname(__file__), "templates/template_model.md.jinja2"),
            help="Path to the jinja2 template used in the index for the model.")
        p.add_argument(
            "--template-readme",
            default=os.path.join(os.path.dirname(__file__), "templates/template_readme.md.jinja2"),
            help="Path to the jinja2 template used in the index for the readme.")

    # ------------------------------------------------------------------------
    init_parser = subparsers.add_parser("init", help="Initialize the registry.")
    init_parser.set_defaults(handler=initialize_registry)
    init_parser.add_argument("-f", "--force", action="store_true",
                             help="Destructively initialize the registry.")
    add_index_args(init_parser)
    add_backend_args(init_parser)
    # ------------------------------------------------------------------------
    dump_parser = subparsers.add_parser(
        "dump", help="Print a brief information about the model to stdout.")
    dump_parser.set_defaults(handler=dump_model)
    dump_parser.add_argument(
        "input", help="Path to the model file, URL or UUID.")
    add_index_args(dump_parser)
    add_backend_args(dump_parser)
    # ------------------------------------------------------------------------
    install_parser = subparsers.add_parser(
        "install", help="Install the environment to run the model.")
    install_parser.set_defaults(handler=install_environment)
    install_parser.add_argument(
        "input", help="Path to the model file, URL or UUID.")
    install_parser.add_argument(
        "--reproduce", action="store_true",
        help="Ensure that training the model is possible.")
    install_parser.add_argument(
        "--pip", nargs="*", help="Additional arguments to pass to pip.")
    add_index_args(install_parser)
    add_backend_args(install_parser)
    # ------------------------------------------------------------------------
    publish_parser = subparsers.add_parser(
        "publish", help="Upload the model and update the registry.")
    publish_parser.set_defaults(handler=publish_model)
    publish_parser.add_argument(
        "model", help="The path to the model to publish.")
    publish_parser.add_argument(
        "--meta", default=os.path.join(os.path.dirname(__file__), "templates/template_meta.json"),
        help="Path to the JSON file which contains the additional metadata of the model.")
    publish_parser.add_argument("-d", "--update-default", action="store_true",
                                help="Set this model as the default one.")
    publish_parser.add_argument("-f", "--force", action="store_true",
                                help="Overwrite existing models.")
    add_index_args(publish_parser)
    add_backend_args(publish_parser)
    add_templates_args(publish_parser)
    # ------------------------------------------------------------------------
    list_parser = subparsers.add_parser(
        "list", help="Lists all the models in the registry.")
    list_parser.set_defaults(handler=list_models)
    add_index_args(list_parser)
    # ------------------------------------------------------------------------
    delete_parser = subparsers.add_parser("delete", help="Delete a model.")
    delete_parser.set_defaults(handler=delete_model)
    delete_parser.add_argument(
        "input", help="UUID of the model to be deleted.")
    add_index_args(delete_parser)
    add_backend_args(delete_parser)
    add_templates_args(delete_parser)
    # ------------------------------------------------------------------------
    args = parser.parse_args()
    args.log_level = logging._nameToLevel[args.log_level]
    slogging.setup(args.log_level, False)
    try:
        handler = args.handler
    except AttributeError:
        def print_usage(_):
            parser.print_usage()

        handler = print_usage
    return handler(args)
626361
def parse_command_line(self, argv=None):
        
        if self.config:
            parser = argparse.ArgumentParser(add_help=False)
            self.settings['config'].add_argument(parser)
            opts, _ = parser.parse_known_args(argv)
            if opts.config is not None:
                self.set('config', opts.config)

            self.params.update(self.import_from_module())

        parser = self.parser()
        opts = parser.parse_args(argv)
        for k, v in opts.__dict__.items():
            if v is None:
                continue
            self.set(k.lower(), v)
2669
def parseArguments(argv=None):  # pragma: no cover
    
    store_opt = StoreOpt()
    parser = argparse.ArgumentParser(
            prog='green',
            usage='%(prog)s [options] [target [target2 ...]]',
            add_help=False,
            description=dedent(
                """
                Green is a clean, colorful, fast test runner for Python unit tests.
                """.rstrip()),
            epilog=dedent(
                """
                ENABLING SHELL COMPLETION

                  To enable bash- or zsh-completion, add the line below to the end of your
                  .bashrc or .zshrc file (or equivalent config file):

                    which green >& /dev/null && source "$( green --completion-file )"

                  Warning!  Generating a completion list actually discovers and loads tests
                  -- this can be very slow if you run it in huge directories!

                SETUP.PY RUNNER

                  To run green as a setup.py command, simply add green to the 'setup_requires'
                  section in the setup.py file, and specify a target as the 'test_suite'
                  parameter if you do not want green to load all the tests:

                     setup(
                         setup_requires = ['green'],
                         install_requires = 'myproject.tests'
                     )

                  Then simply run green as any other setup.py command (it accepts the same
                  parameters as the 'green' executable):

                     python setup.py green
                     python setup.py green -r   # to run with coverage, etc.


                CONFIG FILES

                  For documentation on config files, please see
                  https://github.com/CleanCut/green#config-files
                """.rstrip()),
            formatter_class=argparse.RawDescriptionHelpFormatter)

    target_args = parser.add_argument_group("Target Specification")
    target_args.add_argument('targets', action='store', nargs='*',
        metavar='target',
        help=("""Targets to test.  Any number of targets may be specified.  If
        blank, then discover all testcases in the current directory tree.  Can
        be a directory (or package), file (or module), or fully-qualified
        'dotted name' like proj.tests.test_things.TestStuff.  If a directory
        (or package) is specified, then we will attempt to discover all tests
        under the directory (even if the directory is a package and the tests
        would not be accessible through the package's scope).  In all other
        cases, only tests accessible from introspection of the object will
        be loaded."""),
        default=argparse.SUPPRESS)

    concurrency_args = parser.add_argument_group("Concurrency Options")
    store_opt(
        concurrency_args.add_argument('-s', '--processes', action='store',
            type=int, metavar='NUM',
            help="Number of processes to use to run tests.  Note that your "
            "tests need to be written to avoid using the same resources (temp "
            "files, sockets, ports, etc.) for the multi-process mode to work "
            "well (--initializer and --finalizer can help provision "
            "per-process resources). Default is to run the same number of "
            "processes as your machine has logical CPUs. Note that for a "
            "small number of trivial tests, running everything in a single "
            "process may be faster than the overhead of initializing all the "
            "processes.",
            default=argparse.SUPPRESS))
    store_opt(
        concurrency_args.add_argument('-i', '--initializer', action='store',
            metavar='DOTTED_FUNCTION',
            help="Python function to run inside of a single worker process "
            "before it starts running tests.  This is the way to provision "
            "external resources that each concurrent worker process needs to "
            "have exclusive access to. Specify the function in dotted "
            "notation in a way that will be importable from the location you "
            "are running green from.",
            default=argparse.SUPPRESS))
    store_opt(
        concurrency_args.add_argument('-z', '--finalizer', action='store',
            metavar='DOTTED_FUNCTION',
            help="Same as --initializer, only run at the end of a worker "
            "process's lifetime.  Used to unprovision resources provisioned by "
            "the initializer.",
            default=argparse.SUPPRESS))

    format_args = parser.add_argument_group("Format Options")
    store_opt(format_args.add_argument('-t', '--termcolor', action='store_true',
        help="Force terminal colors on.  Default is to autodetect.",
        default=argparse.SUPPRESS))
    store_opt(
        format_args.add_argument('-T', '--notermcolor', action='store_true',
        help="Force terminal colors off.  Default is to autodetect.",
        default=argparse.SUPPRESS))
    store_opt(
        format_args.add_argument('-W', '--disable-windows', action='store_true',
        help="Disable Windows support by turning off Colorama",
        default=argparse.SUPPRESS))

    out_args = parser.add_argument_group("Output Options")
    store_opt(out_args.add_argument('-a', '--allow-stdout', action='store_true',
        help=("Instead of capturing the stdout and stderr and presenting it "
        "in the summary of results, let it come through."),
        default=argparse.SUPPRESS))
    store_opt(out_args.add_argument('-q', '--quiet-stdout', action='store_true',
        help=("Instead of capturing the stdout and stderr and presenting it "
        "in the summary of results, discard it completly for successful "
        "tests. --allow-stdout option overrides it."),
        default=argparse.SUPPRESS))
    store_opt(out_args.add_argument('-k', '--no-skip-report',
        action='store_true', help=("Don't print the report of skipped tests "
        "after testing is done.  Skips will still show up in the progress "
        "report and summary count."),
        default=argparse.SUPPRESS))
    store_opt(out_args.add_argument('-e', '--no-tracebacks',
        action='store_true', help=("Don't print tracebacks for failures and "
        "errors."),
        default=argparse.SUPPRESS))
    store_opt(out_args.add_argument('-h', '--help', action='store_true',
        help="Show this help message and exit.",
        default=argparse.SUPPRESS))
    store_opt(out_args.add_argument('-V', '--version', action='store_true',
        help="Print the version of Green and Python and exit.",
        default=argparse.SUPPRESS))
    store_opt(out_args.add_argument('-l', '--logging', action='store_true',
        help="Don't configure the root logger to redirect to /dev/null, "
        "enabling internal debugging output, as well as any output test (or "
        "tested) code may be sending via the root logger.",
        default=argparse.SUPPRESS))
    store_opt(out_args.add_argument('-d', '--debug', action='count',
        help=("Enable internal debugging statements.  Implies --logging.  Can "
        "be specified up to three times for more debug output."),
        default=argparse.SUPPRESS))
    store_opt(out_args.add_argument('-v', '--verbose', action='count',
        help=("Verbose. Can be specified up to three times for more "
        "verbosity. Recommended levels are -v and -vv."),
        default=argparse.SUPPRESS))
    store_opt(out_args.add_argument('-U', '--disable-unidecode', action='store_true',
        help=("Disable unidecode which converts test output from unicode to"
            "ascii by default on Windows to avoid hard-to-debug crashes."),
        default=argparse.SUPPRESS))

    other_args = parser.add_argument_group("Other Options")
    store_opt(other_args.add_argument('-f', '--failfast', action='store_true',
        help=("Stop execution at the first test that fails or errors."),
        default=argparse.SUPPRESS))
    store_opt(other_args.add_argument('-c', '--config', action='store',
        metavar='FILE', help="Use this config file to override any values from "
        "the config file specified by environment variable GREEN_CONFIG, "
        "~/.green, and .green in the current working directory.",
        default=argparse.SUPPRESS))
    store_opt(other_args.add_argument('-p', '--file-pattern', action='store',
        metavar='PATTERN',
        help="Pattern to match test files. Default is test*.py",
        default=argparse.SUPPRESS))
    store_opt(other_args.add_argument('-n', '--test-pattern', action='store',
        metavar='PATTERN', help="Pattern to match test method names after "
        "'test'.  Default is '*', meaning match methods named 'test*'.",
        default=argparse.SUPPRESS))
    store_opt(other_args.add_argument('-j', '--junit-report',
                                      action='store',
                                      metavar="FILENAME",
                                      help=("Generate a JUnit XML report."),
                                      default=argparse.SUPPRESS))

    cov_args = parser.add_argument_group(
        "Coverage Options ({})".format(coverage_version))
    store_opt(cov_args.add_argument('-r', '--run-coverage', action='store_true',
        help=("Produce coverage output."), default=argparse.SUPPRESS))
    store_opt(cov_args.add_argument('-g', '--cov-config-file',
        action='store', metavar='FILE', help=("Specify a coverage config file. "
            "Implies --run-coverage See the coverage documentation "
            "at https://coverage.readthedocs.io/en/v4.5.x/config.html "
            "for coverage config file syntax. The [run] and [report] sections "
            "are most relevant."),
        default=argparse.SUPPRESS)),
    store_opt(cov_args.add_argument('-R', '--quiet-coverage', action='store_true',
        help=("Do not print coverage report to stdout (coverage files will "
            "still be created). Implies --run-coverage"),
        default=argparse.SUPPRESS))
    store_opt(cov_args.add_argument('-O', '--clear-omit', action='store_true',
        help=("Green tries really hard to set up a good list of patterns of "
            "files to omit from coverage reports.  If the default list "
            "catches files that you DO want to cover you can specify this "
            "flag to leave the default list empty to start with.  You can "
            "then add patterns back in with --omit-add. The default list is "
            "something like '*/test*,*/mock*,*(temp dir)*,*(python system "
            "packages)*' -- only longer."),
        default=argparse.SUPPRESS))
    store_opt(cov_args.add_argument('-u', '--include-patterns', action='store',
        metavar='PATTERN',
        help=("Comma-separated file-patterns to include in coverage.  This "
            "implies that anything that does not match the include pattern is "
            "omitted from coverage reporting."),
        default=argparse.SUPPRESS))
    store_opt(cov_args.add_argument('-o', '--omit-patterns', action='store',
        metavar='PATTERN',
        help=("Comma-separated file-patterns to omit from coverage.  For "
            "example, if coverage reported a file mypackage/foo/bar you could "
            "omit it from coverage with 'mypackage*', '*/foo/*', or '*bar'"),
        default=argparse.SUPPRESS))
    store_opt(cov_args.add_argument('-m', '--minimum-coverage', action='store',
        metavar='X', type=int, help=("Integer. A minimum coverage value.  If "
            "not met, then we will print a message and exit with a nonzero "
            "status. Implies --run-coverage"),
        default=argparse.SUPPRESS))

    integration_args = parser.add_argument_group("Integration Options")
    store_opt(integration_args.add_argument('--completion-file',
        action='store_true', help=("Location of the bash- and zsh-completion "
            "file.  To enable bash- or zsh-completion, see ENABLING SHELL "
            "COMPLETION below."), default=argparse.SUPPRESS))
    store_opt(integration_args.add_argument('--completions',
        action='store_true',
        help=("Output possible completions of the given target.  Used by "
        "bash- and zsh-completion."), default=argparse.SUPPRESS))
    store_opt(integration_args.add_argument('--options', action='store_true',
        help="Output all options.  Used by bash- and zsh-completion.",
        default=argparse.SUPPRESS))

    args = parser.parse_args(argv)

    # Add additional members
    args.parser    = parser
    args.store_opt = store_opt

    return args
1024133
def main(argv=None):
    """"""

    parser = argparse.ArgumentParser(
        description='Commands as arguments'
    )
    command_help = 'optional command to run, if no command given, enter an interactive shell'
    parser.add_argument('command', nargs='?',
                        help=command_help)
    arg_help = 'optional arguments for command'
    parser.add_argument('command_args', nargs=argparse.REMAINDER,
                        help=arg_help)

    args = parser.parse_args(argv)

    c = CmdLineApp()

    if args.command:
        # we have a command, run it and then exit
        c.onecmd_plus_hooks('{} {}'.format(args.command, ' '.join(args.command_args)))
    else:
        # we have no command, drop into interactive mode
        c.cmdloop()
603887
def parse_input(command_input=None):
    """"""
    parser = argparse.ArgumentParser(
        prog='python3 ok',
        description=__doc__,
        usage='%(prog)s [--help] [options]',
        formatter_class=argparse.RawDescriptionHelpFormatter)

    testing = parser.add_argument_group('running tests')
    testing.add_argument('-q', '--question', type=str, action='append',
                        help="run tests for a specific question")
    testing.add_argument('--suite', type=str, default=None,
                        help="run cases from a specific suite")
    testing.add_argument('--case', type=str, action='append',
                        help="run specific cases")
    testing.add_argument('-u', '--unlock', action='store_true',
                        help="unlock tests interactively")
    testing.add_argument('-i', '--interactive', action='store_true',
                        help="start the Python interpreter after a failed test")
    testing.add_argument('-v', '--verbose', action='store_true',
                        help="show all tests, not just passing tests")
    testing.add_argument('-t', '--testing', nargs='?', type=str, const='mytests.rst', 
                        help='run tests from rst file (default: mytests.rst)')
    testing.add_argument('--all', action='store_true',
                        help="run tests for all questions in config file")
    testing.add_argument('--submit', action='store_true',
                        help="submit the assignment")
    testing.add_argument('--backup', action='store_true',
                        help="attempt to reliably backup your work")
    testing.add_argument('--revise', action='store_true',
                        help="submit composition revision")
    testing.add_argument('--timeout', type=int, default=10,
                        help="set the timeout duration (in seconds) for running tests")
    testing.add_argument('-cov', '--coverage', action='store_true',
                        help="get suggestions on what lines to add tests for")

    # Experiments
    experiment = parser.add_argument_group('experiment options')
    experiment.add_argument('--no-experiments', action='store_true',
                        help="do not run experimental features")
    experiment.add_argument('--hint', action='store_true',
                        help="give a hint (if available)")
    experiment.add_argument('--style', action='store_true',
                        help="run AutoStyle feedback system")
    experiment.add_argument('--collab', action='store_true',
                        help="launch collaborative programming environment")

    # Debug information
    debug = parser.add_argument_group('debugging options')
    debug.add_argument('--version', action='store_true',
                        help="print the version number and exit")
    debug.add_argument('--tests', action='store_true',
                        help="display a list of all available tests")
    debug.add_argument('--debug', action='store_true',
                        help="show debugging output")

    # Grading
    grading = parser.add_argument_group('grading options')
    grading.add_argument('--lock', action='store_true',
                        help="lock the tests in a directory")
    grading.add_argument('--score', action='store_true',
                        help="score the assignment")
    grading.add_argument('--score-out', type=str,
                        nargs='?', const=None, default=None,
                        help="write scores to a file")
    grading.add_argument('--config', type=str,
                        help="use a specific configuration file")

    # Server parameters
    server = parser.add_argument_group('server options')
    server.add_argument('--local', action='store_true',
                        help="disable any network activity")
    server.add_argument('--server', type=str,
                        default='okpy.org',
                        help="set the server address")
    server.add_argument('--authenticate', action='store_true',
                        help="authenticate, ignoring previous authentication")
    server.add_argument('--no-browser', action='store_true',
                        help="do not use a web browser for authentication")
    server.add_argument('--get-token', action='store_true',
                        help="get ok access token")
    server.add_argument('--insecure', action='store_true',
                        help="use http instead of https")
    server.add_argument('--no-update', action='store_true',
                        help="do not check for ok updates")
    server.add_argument('--update', action='store_true',
                        help="update ok and exit")

    return parser.parse_args(command_input)
118209
def main(argv=None):
    """"""
    parser = ArgumentParser(prog="pygenstub")
    parser.add_argument("--version", action="version", version="%(prog)s " + __version__)
    parser.add_argument("files", nargs="*", help="generate stubs for given files")
    parser.add_argument(
        "-m",
        "--module",
        action="append",
        metavar="MODULE",
        dest="modules",
        default=[],
        help="generate stubs for given modules",
    )
    parser.add_argument(
        "-o", "--output", metavar="PATH", dest="out_dir", help="change the output directory"
    )
    parser.add_argument(
        "--generic", action="store_true", default=False, help="generate generic stubs"
    )
    parser.add_argument("--debug", action="store_true", help="enable debug messages")

    argv = argv if argv is not None else sys.argv
    arguments = parser.parse_args(argv[1:])

    # set debug mode
    if arguments.debug:
        logging.basicConfig(level=logging.DEBUG)
        _logger.debug("running in debug mode")

    out_dir = arguments.out_dir if arguments.out_dir is not None else ""
    if (out_dir == "") and (len(arguments.modules) > 0):
        print("Output directory must be given when generating stubs for modules.")
        sys.exit(1)

    modules = []
    for path in arguments.files:
        paths = Path(path).glob("**/*.py") if Path(path).is_dir() else [Path(path)]
        for source in paths:
            if str(source).startswith(os.path.pardir):
                source = source.absolute().resolve()
            if (out_dir != "") and source.is_absolute():
                source = source.relative_to(source.root)
            destination = Path(out_dir, source.with_suffix(".pyi"))
            modules.append((source, destination))

    for mod_name in arguments.modules:
        modules.extend(get_pkg_paths(mod_name, out_dir))

    for source, destination in modules:
        _logger.info("generating stub for %s to path %s", source, destination)
        with source.open() as f:
            code = f.read()
        try:
            stub = get_stub(code, generic=arguments.generic)
        except Exception as e:
            print(source, "-", e, file=sys.stderr)
            continue

        if stub != "":
            if not destination.parent.exists():
                destination.parent.mkdir(parents=True)
            with destination.open("w") as f:
                f.write("# " + EDIT_WARNING + "\n\n" + stub)
779817
def main():
    
    # Parse command line arguments
    args = get_args()

    # Instantiate the TestRail client
    # Use the CLI argument to identify which project to work with
    tr = TestRail(project_dict[args.project])

    # Get a reference to the current project
    project = tr.project(project_dict[args.project])

    # To create a new run in TestRail, first create a new, blank run
    # Update the new run with a name and project reference
    new_run = tr.run()
    new_run.name = "Creating a new Run through the API"
    new_run.project = project
    new_run.include_all = True  # All Cases in the Suite will be added as Tests

    # Add the run in TestRail. This creates the run, and returns a run object
    run = tr.add(new_run)

    print("Created new run: {0}".format(run.name))

    # Before starting the tests, lets pull in the Status objects for later
    PASSED = tr.status('passed')
    FAILED = tr.status('failed')
    BLOCKED = tr.status('blocked')

    # Get a list of tests associated with the new run
    tests = list(tr.tests(run))

    print("Found {0} tests".format(len(tests)))

    # Execute the tests, marking as passed, failed, or blocked
    for test_num, test in enumerate(tests):
        print("Executing test #{0}".format(test_num))
        # Run your tests here, reaching some sort of pass/fail criteria
        # This example will pick results at random and update the tests as such

        test_status = random.choice([PASSED, FAILED, BLOCKED])

        print("Updating test  #{0} with a status of {1}".format(test_num,
                                                               test_status.name))

        # Create a blank result, and associate it with a test and a status
        result = tr.result()
        result.test = test
        result.status = test_status
        result.comment = "The test case was udpated via a script"

        # Add the result to TestRail
        tr.add(result)

    # All tests have been executed. Close this test run
    print("Finished, closing the run")
    tr.close(run)