Default unit test session.

    This is intended to be run **without** an interpreter set, so
    that the current ``python`` (on the ``PATH``) or the version of
    Python corresponding to the ``nox`` binary the ``PATH`` can
    run the tests.
180320
def default(session):
    
    # Install all test dependencies, then install local packages in-place.
    session.install('mock', 'pytest', 'pytest-cov')
    for local_dep in LOCAL_DEPS:
        session.install('-e', local_dep)
    session.install('-e', '.')

    # Run py.test against the unit tests.
    session.run(
        'py.test',
        '--quiet',
        '--cov=google.cloud.storage',
        '--cov=tests.unit',
        '--cov-append',
        '--cov-config=.coveragerc',
        '--cov-report=',
        '--cov-fail-under=97',
        'tests/unit',
        *session.posargs
    )
922284
def suites
      # Since we're not using `ruby -Itest -Ilib` to run the tests, we need to add this directory to the `LOAD_PATH`
      $:.unshift "./test", "./spec", "./lib"

      begin
        # Fire up this Ruby file. Let's hope it actually has tests.
        require "./#{testable.file}"
      rescue LoadError => e
        # Fail with a happier error message instead of spitting out a backtrace from this gem
        STDERR.puts "Failed loading test file:\n#{e.message}"
        return []
      end

      suites = runner.suites

      # Use some janky internal APIs to group test methods by test suite.
      suites.each_with_object({}) do |suite_class, test_suites|
        # End up with a hash of suite class name to an array of test methods, so we can later find them and ignore empty test suites
        if runner.test_methods(suite_class).any?
          test_suites[suite_class] = runner.test_methods(suite_class)
        end
      end
    end
915069
def start(self):
        
        self.check_dependencies()
        self.args = self.parser.parse_args()

        # Python 3 doesn't set the cmd if no args are given
        if not hasattr(self.args, 'cmd'):
            self.parser.print_help()
            return

        cmd = self.args.cmd
        try:
            if cmd.app_dir_required and not self.in_app_directory:
                raise EnvironmentError(
                    "'enaml-native {}' must be run within an app root "
                    "directory not: {}".format(cmd.title, os.getcwd()))
            cmd.run(self.args)
        except sh.ErrorReturnCode as e:
            raise
1034645
def main(argv=None):
    
    import getopt

    # default values
    test_read = None
    test_write = None
    n = 3       # number of repeat

    if argv is None:
        argv = sys.argv[1:]

    try:
        opts, args = getopt.getopt(argv, 'hn:rw', [])

        for o,a in opts:
            if o == '-h':
                print(HELP)
                return 0
            elif o == '-n':
                n = int(a)
            elif o == '-r':
                test_read = True
            elif o == '-w':
                test_write = True

        if args:
            raise getopt.GetoptError('Arguments are not used.')
    except getopt.GetoptError:
        msg = sys.exc_info()[1]     # current exception
        txt = str(msg)
        print(txt)
        return 1

    if (test_read, test_write) == (None, None):
        test_read = test_write = True

    m = Measure(n, test_read, test_write)
    m.measure_all()
    m.print_report()

    return 0
1180207
def find_compatible_interpreters(pex_python_path=None, compatibility_constraints=None):
  
  if pex_python_path:
    interpreters = []
    for binary in pex_python_path.split(os.pathsep):
      try:
        interpreters.append(PythonInterpreter.from_binary(binary))
      except Executor.ExecutionError:
        print("Python interpreter %s in PEX_PYTHON_PATH failed to load properly." % binary,
          file=sys.stderr)
    if not interpreters:
      die('PEX_PYTHON_PATH was defined, but no valid interpreters could be identified. Exiting.')
  else:
    # We may have been invoked with a specific interpreter not on the $PATH, make sure our
    # sys.executable is included as a candidate in this case.
    interpreters = OrderedSet([PythonInterpreter.get()])

    # Add all qualifying interpreters found in $PATH.
    interpreters.update(PythonInterpreter.all())

  return list(
    matched_interpreters(interpreters, compatibility_constraints)
    if compatibility_constraints
    else interpreters
  )
928098
def system(session):
    """"""

    # Sanity check: Only run system tests if the environment variable is set.
    if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''):
        session.skip('Credentials must be set via environment variable.')

    # Use pre-release gRPC for system tests.
    session.install('--pre', 'grpcio')

    # Install all test dependencies, then install this package into the
    # virtualenv's dist-packages.
    session.install('mock', 'pytest')
    for local_dep in LOCAL_DEPS:
        session.install('-e', local_dep)
    systest_deps = [
        '../bigquery/',
        '../pubsub/',
        '../storage/',
        '../test_utils/',
    ]
    for systest_dep in systest_deps:
        session.install('-e', systest_dep)
    session.install('-e', '.')

    # Run py.test against the system tests.
    session.run(
        'py.test',
        '-vvv',
        '-s',
        'tests/system',
        *session.posargs)
913780
def _run_with_different_python(executable):
    
    args = [arg for arg in sys.argv if arg != VIRTUALENV_OPTION]
    args.insert(0, executable)
    print("Running bootstrap.py with {0}".format(executable))
    exit(subprocess.call(args))
379714
def run(self):
        ""
        arguments = self.argument_parser.parse_args()
        argspec = inspect.getargspec(arguments.func)
        vargs = []
        for arg in argspec.args:
            vargs.append(getattr(arguments, arg))
        if argspec.varargs:
            vargs.extend(getattr(arguments, argspec.varargs))
        output = arguments.func(*vargs)
        if getattr(arguments.func, '_cli_test_command', False):
            self.exit_code = 0 if output else 1
            output = ''
        if getattr(arguments.func, '_cli_no_output', False):
            output = ''
        self.formatter.format_output(output, arguments.format)
        if charmhelpers.core.unitdata._KV:
            charmhelpers.core.unitdata._KV.flush()
804505
def unit(session):
    """"""

    # Testing multiple version of django
    # See https://www.djangoproject.com/download/ for supported version
    django_deps_27 = [
        ('django==1.8.19',),
        ('django >= 1.11.0, < 2.0.0dev',),
    ]

    if session.virtualenv.interpreter == '2.7':
        [default(session, django_dep=django) for django in django_deps_27]
    else:
        default(session)
543650
def check_session(self):
        
        if self.session is None:
            if self.autosession:
                self.open_session()
            else:
                msg = "must open a session before modifying %s" % self
                raise RuntimeError(msg)
724907
def init(opts=None):
    '''
    
    '''
    global CONNECTION
    if __opts__.get('proxy').get('connection') is not None:
        CONNECTION = __opts__.get('proxy').get('connection')

    if CONNECTION == 'ssh':
        log.info('NXOS PROXY: Initialize ssh proxy connection')
        return _init_ssh(opts)
    elif CONNECTION == 'nxapi':
        log.info('NXOS PROXY: Initialize nxapi proxy connection')
        return _init_nxapi(opts)
    else:
        log.error('Unknown Connection Type: %s', CONNECTION)
        return False
760099
def run(self):
        
        venv = "virtualenv {:s}"
        if self.python:
            venv += " -p {:s}"
        pip = "{0:s}/bin/pip install -r {2:s}" if self.requirements else None
        args = self.name, self.python, self.requirements
        try:
            check_call(venv.format(*args).split())
            if pip:
                log.info("installing requirements")
                check_call(pip.format(*args).split())
        except CalledProcessError:
            raise SystemExit(1)
        return
1120557
def main(argv=None):
    
    @contextmanager
    def tmpdir():
        """ Create a self-deleting temporary directory. """
        path = mkdtemp()
        try:
            yield path
        finally:
            rmtree(path)
        return

    def test():
        """ Execute the test suite. """
        install = "{:s} install -r requirements-test.txt"
        check_call(install.format(pip).split())
        pytest = join(path, "bin", "py.test")
        test = "{:s} test/".format(pytest)
        check_call(test.split())
        uninstall = "{:s} uninstall -y -r requirements-test.txt"
        check_call(uninstall.format(pip).split())
        return

    args = _cmdline(argv)
    path = join(abspath(args.root), args.name)
    with tmpdir() as tmp:
        clone = "git clone {:s} {:s}".format(args.repo, tmp)
        check_call(clone.split())
        chdir(tmp)
        checkout = "git checkout {:s}".format(args.checkout)
        check_call(checkout.split())
        virtualenv = "virtualenv {:s}".format(path)
        check_call(virtualenv.split())
        pip = join(path, "bin", "pip")
        install = "{:s} install -U -r requirements.txt .".format(pip)
        check_call(install.split())
        if args.test:
            test()
    return 0
486453
def main(raw_args=None):
    """"""
    parser = argparse.ArgumentParser(
        description="poor man's integration testing")
    parser.add_argument(
        'cmds', metavar='cmd', default=['test'], nargs='*',
        help='Run command(s) defined in the configuration file. Each command '
             'is run on each package before proceeding with the next command. '
             '(default: "test")')
    parser.add_argument(
        '-c', '--config', dest='file', type=argparse.FileType('r'),
        default='toll.ini',
        help='ini-style file to read the configuration from')
    parser.add_argument(
        '--start-at', dest='start_at', type=str, default='',
        help='Skip over the packages in the config file listed before this'
             ' one. (It does a substring match to find the first package.)')

    args = parser.parse_args(raw_args)
    config_file = config.parsed_file(args.file)
    commands = config.commands(config_file, args.cmds)
    packages = config.packages(config_file)
    runner = Runner(commands, packages, start_at=args.start_at)
    return runner()
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)
531768
def main():
    
    # Define Parser object and add to Toil
    if mock_mode():
        usage_msg = 'You have the TOIL_SCRIPTS_MOCK_MODE environment variable set, so this pipeline ' \
                    'will run in mock mode. To disable mock mode, set TOIL_SCRIPTS_MOCK_MODE=0'
    else:
        usage_msg = None

    parser = argparse.ArgumentParser(usage=usage_msg)
    subparsers = parser.add_subparsers(dest='command')
    subparsers.add_parser('generate-config', help='Generates an editable config in the current working directory.')
    subparsers.add_parser('generate-manifest', help='Generates an editable manifest in the current working directory.')
    subparsers.add_parser('generate', help='Generates a config and manifest in the current working directory.')
    # Run subparser                                                                                                              
    parser_run = subparsers.add_parser('run', help='Runs the ADAM/GATK pipeline')
    default_config = 'adam-gatk-mock.config' if mock_mode() else 'adam-gatk.config'
    default_manifest = 'adam-gatk-mock-manifest.csv' if mock_mode() else 'adam-gatk-manifest.csv'
    parser_run.add_argument('--config', default=default_config, type=str,
                            help='Path to the (filled in) config file, generated with "generate-config".')
    parser_run.add_argument('--manifest', default=default_manifest,
                            type=str, help='Path to the (filled in) manifest file, generated with "generate-manifest". '
                                           '\nDefault value: "%(default)s".')
    Job.Runner.addToilOptions(parser_run)
    args = parser.parse_args()

    cwd = os.getcwd()
    if args.command == 'generate-config' or args.command == 'generate':
        generate_file(os.path.join(cwd, default_config), generate_config)
    if args.command == 'generate-manifest' or args.command == 'generate':
        generate_file(os.path.join(cwd, default_manifest), generate_manifest)
    # Pipeline execution
    elif args.command == 'run':
        require(os.path.exists(args.config), '{} not found. Please run '
                                             'generate-config'.format(args.config))
        if not hasattr(args, 'sample'):
            require(os.path.exists(args.manifest), '{} not found and no samples provided. Please '
                                                   'run "generate-manifest"'.format(args.manifest))
        # Parse config
        parsed_config = {x.replace('-', '_'): y for x, y in yaml.load(open(args.config).read()).iteritems()}
        inputs = argparse.Namespace(**parsed_config)

        # Parse manifest file
        uuid_list = []
        with open(args.manifest) as f_manifest:
            for line in f_manifest:
                if not line.isspace() and not line.startswith('#'):
                    uuid_list.append(line.strip())

        inputs.sort = False
        if not inputs.dir_suffix:
            inputs.dir_suffix = ''
        if not inputs.s3_bucket:
            inputs.s3_bucket = ''

        if inputs.master_ip and inputs.num_nodes:
            raise ValueError("Exactly one of master_ip (%s) and num_nodes (%d) must be provided." %
                             (inputs.master_ip, inputs.num_nodes))

        if not hasattr(inputs, 'master_ip') and inputs.num_nodes <= 1:
            raise ValueError('num_nodes allocates one Spark/HDFS master and n-1 workers, and thus must be greater '
                             'than 1. %d was passed.' % inputs.num_nodes)

        if (inputs.pipeline_to_run != "adam" and
            inputs.pipeline_to_run != "gatk" and
            inputs.pipeline_to_run != "both"):
            raise ValueError("pipeline_to_run must be either 'adam', 'gatk', or 'both'. %s was passed." % inputs.pipeline_to_run)

        Job.Runner.startToil(Job.wrapJobFn(sample_loop, uuid_list, inputs), args)
1757
def system(session):
    """"""

    # Sanity check: Only run system tests if the environment variable is set.
    if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''):
        session.skip('Credentials must be set via environment variable.')

    # Install all test dependencies, then install this package into the
    # virtualenv's dist-packages.
    session.install('pytest')
    session.install('-e', os.path.join('..', 'test_utils'))
    for local_dep in LOCAL_DEPS:
        session.install('-e', local_dep)
    session.install('-e', '.[pandas,fastavro]')

    # Run py.test against the system tests.
    session.run('py.test', '--quiet', 'tests/system/')