Load a test suite with test lines from the TAP stream on STDIN.

        :returns: A ``unittest.TestSuite`` instance
176229
def load_suite_from_stdin(self):
        
        suite = unittest.TestSuite()
        rules = Rules("stream", suite)
        line_generator = self._parser.parse_stdin()
        return self._load_lines("stream", line_generator, suite, rules)
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()
242418
def main(argv=sys.argv, stream=sys.stderr):
    """"""
    args = parse_args(argv)
    suite = build_suite(args)
    runner = unittest.TextTestRunner(verbosity=args.verbose, stream=stream)
    result = runner.run(suite)

    return get_status(result)
322281
def write_unitth(suites, out_dir):
        
        if not os.path.isdir(out_dir):
            os.mkdir(out_dir)

        for classname, cases in suites.items():
            doc_xml = minidom.Document()

            suite_xml = doc_xml.createElement('testsuite')
            suite_xml.setAttribute('name', classname)
            suite_xml.setAttribute('tests', str(len(cases)))
            suite_xml.setAttribute('errors', str(sum('error' in case for case in cases)))
            suite_xml.setAttribute('failures', str(sum('failure' in case for case in cases)))
            suite_xml.setAttribute('skipped', str(sum('skipped' in case for case in cases)))
            suite_xml.setAttribute('time', '{:.3f}'.format(sum(case['time'] for case in cases)))
            doc_xml.appendChild(suite_xml)

            for case in cases:
                case_xml = doc_xml.createElement('testcase')
                case_xml.setAttribute('classname', classname)
                case_xml.setAttribute('name', case['name'])
                case_xml.setAttribute('time', '{:.3f}'.format(case['time']))
                suite_xml.appendChild(case_xml)

                if 'skipped' in case:
                    skipped_xml = doc_xml.createElement('skipped')
                    skipped_xml.setAttribute('type', case['skipped']['type'])
                    skipped_xml.setAttribute('message', case['skipped']['message'])
                    case_xml.appendChild(skipped_xml)

                    skipped_text_xml = doc_xml.createCDATASection(case['skipped']['text'])
                    skipped_xml.appendChild(skipped_text_xml)

                if 'failure' in case:
                    failure_xml = doc_xml.createElement('failure')
                    failure_xml.setAttribute('type', case['failure']['type'])
                    failure_xml.setAttribute('message', case['failure']['message'])
                    case_xml.appendChild(failure_xml)

                    failure_text_xml = doc_xml.createCDATASection(case['failure']['text'])
                    failure_xml.appendChild(failure_text_xml)

                if 'error' in case:
                    error_xml = doc_xml.createElement('error')
                    error_xml.setAttribute('type', case['error']['type'])
                    error_xml.setAttribute('message', case['error']['message'])
                    case_xml.appendChild(error_xml)

                    error_text_xml = doc_xml.createCDATASection(case['error']['text'])
                    error_xml.appendChild(error_text_xml)

            with open(os.path.join(out_dir, '{}.xml'.format(classname)), 'w') as output:
                doc_xml.writexml(output, encoding='utf-8', addindent='', newl="")
            doc_xml.unlink()
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
960740
def run(self):
        """"""
        if self.auto_clear:
            os.system('cls' if os.name == 'nt' else 'auto_clear')
        else:
            print
        print 'Running unit tests...'
        if self.auto_clear:
            print
        subprocess.call('nosetests', cwd=self.directory)
994984
def prepare_suite(self, suite):
        """"""
        all_tests = {}
        for s in suite:
            m = re.match(r'(\w+)\s+\(.+\)', str(s))
            if m:
                name = m.group(1)
            else:
                name = str(s).split('.')[-1]
            all_tests[name] = s

        return self.orderTests(all_tests, suite)
525204
public void afterSuite(String suiteName, String ... testGroups) {
        testSuiteListener.onFinish();

        if (!CollectionUtils.isEmpty(afterSuite)) {
            for (SequenceAfterSuite sequenceAfterSuite : afterSuite) {
                try {
                    if (sequenceAfterSuite.shouldExecute(suiteName, testGroups)) {
                        sequenceAfterSuite.execute(createTestContext());
                    }
                } catch (Exception e) {
                    testSuiteListener.onFinishFailure(e);
                    throw new AssertionError("After suite failed with errors", e);
                }
            }

            testSuiteListener.onFinishSuccess();
        } else {
            testSuiteListener.onFinishSuccess();
        }
    }
556694
def _input_file_as_lines(cls, session: AppSession):
        ''''''
        if session.args.input_file == sys.stdin:
            input_file = session.args.input_file
        else:
            reader = codecs.getreader(session.args.local_encoding or 'utf-8')
            input_file = reader(session.args.input_file)

        return input_file
269078
def main():
    
    parser = argparse.ArgumentParser(description='Github-based load test')

    parser.add_argument('--version', action='store_true', default=False,
                        help='Displays version and exits.')

    parser.add_argument('--virtualenv', type=str, default='virtualenv',
                        help='Virtualenv executable.')

    parser.add_argument('--python', type=str, default=sys.executable,
                        help='Python executable.')

    parser.add_argument('--config', type=str, default='molotov.json',
                        help='Path of the configuration file.')

    parser.add_argument('repo', help='Github repo', type=str, nargs="?")
    parser.add_argument('run', help='Test to run', nargs="?")

    args = parser.parse_args()

    if args.version:
        print(__version__)
        sys.exit(0)

    tempdir = tempfile.mkdtemp()
    curdir = os.getcwd()
    os.chdir(tempdir)
    print('Working directory is %s' % tempdir)
    try:
        clone_repo(args.repo)
        config_file = os.path.join(tempdir, args.config)

        with open(config_file) as f:
            config = json.loads(f.read())

        # creating the virtualenv
        create_virtualenv(args.virtualenv, args.python)

        # install deps
        if 'requirements' in config['molotov']:
            install_reqs(config['molotov']['requirements'])

        # load deps into sys.path
        pyver = '%d.%d' % (sys.version_info.major, sys.version_info.minor)
        site_pkg = os.path.join(tempdir, 'venv', 'lib', 'python' + pyver,
                                'site-packages')
        site.addsitedir(site_pkg)
        pkg_resources.working_set.add_entry(site_pkg)

        # environment
        if 'env' in config['molotov']:
            for key, value in config['molotov']['env'].items():
                os.environ[key] = value

        run_test(**config['molotov']['tests'][args.run])
    except Exception:
        os.chdir(curdir)
        shutil.rmtree(tempdir, ignore_errors=True)
        raise
54746
def run(suite, stream, args, testing=False):
    
    if not issubclass(GreenStream, type(stream)):
        stream = GreenStream(stream, disable_windows=args.disable_windows,
                disable_unidecode=args.disable_unidecode)
    result = GreenTestResult(args, stream)

    # Note: Catching SIGINT isn't supported by Python on windows (python
    # "WONTFIX" issue 18040)
    installHandler()
    registerResult(result)

    with warnings.catch_warnings():
        if args.warnings:  # pragma: no cover
            # if args.warnings is set, use it to filter all the warnings
            warnings.simplefilter(args.warnings)
            # if the filter is 'default' or 'always', special-case the
            # warnings from the deprecated unittest methods to show them
            # no more than once per module, because they can be fairly
            # noisy.  The -Wd and -Wa flags can be used to bypass this
            # only when args.warnings is None.
            if args.warnings in ['default', 'always']:
                warnings.filterwarnings('module',
                                        category=DeprecationWarning,
                                        message='Please use assert\w+ instead.')

        result.startTestRun()

        pool = LoggingDaemonlessPool(processes=args.processes or None,
                                     initializer=InitializerOrFinalizer(args.initializer),
                                     finalizer=InitializerOrFinalizer(args.finalizer))
        manager = multiprocessing.Manager()
        targets = [(target, manager.Queue())
                   for target in toParallelTargets(suite, args.targets)]
        if targets:
            for index, (target, queue) in enumerate(targets):
                if args.run_coverage:
                    coverage_number = index + 1
                else:
                    coverage_number = None
                debug("Sending {} to runner {}".format(target, poolRunner))
                pool.apply_async(
                    poolRunner,
                    (target, queue, coverage_number, args.omit_patterns, args.cov_config_file))
            pool.close()
            for target, queue in targets:
                abort = False

                while True:
                    msg = queue.get()

                    # Sentinel value, we're done
                    if not msg:
                        break
                    else:
                        # Result guaranteed after this message, we're
                        # currently waiting on this test, so print out
                        # the white 'processing...' version of the output
                        result.startTest(msg)
                        proto_test_result = queue.get()
                        result.addProtoTestResult(proto_test_result)

                    if result.shouldStop:
                        abort = True
                        break

                if abort:
                    break

        pool.close()
        pool.join()

        result.stopTestRun()

    removeResult(result)

    return result
766311
def run(config, path=None, stop_on_error=True, just_tests=False):
    """"""
    if path is None:
        path = os.getcwd()
    prep(config, path=path)

    models = __import__('models')
    tests = __import__('tests')
    suites = __import__('suites')

    print('\n')
    for x in ['models', 'tests', 'suites']:
        module = __import__(x)
        assert hasattr(module, x), "'%s' module requires attribute '%s'" %\
                                   (x, x)

    if just_tests:
        for test in tests.tests:
            _run(test, models, stop_on_error)

    else:
        for suite in suites.suites:
            _run(suite, models, stop_on_error)
1141479
def get_logger(name, file_name=None, stream=None, template=None, propagate=False, level=None):
    

    logger = logging.getLogger(name)
    running_tests = (
        'test' in sys.argv  # running with setup.py
        or sys.argv[0].endswith('py.test'))  # running with py.test
    if running_tests and not level:
        # testing without level, this means tester does not want to see any log messages.
        level = logging.CRITICAL

    if not level:
        level = logging.INFO
    logger.setLevel(level)
    logger.propagate = propagate

    formatter = logging.Formatter(template)

    if not stream:
        stream = sys.stdout

    logger.handlers = []
    handler = logging.StreamHandler(stream=stream)
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    if file_name:
        handler = logging.FileHandler(file_name)
        handler.setFormatter(logging.Formatter('%(asctime)s '+template))
        logger.addHandler(handler)

    return logger
1002606
def _read_stdin():
    
    line = sys.stdin.readline()
    while line:
        yield line
        line = sys.stdin.readline()
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
927501
def run():
    

    print('Python ' + sys.version.replace('\n', ''))

    try:
        oscrypto_tests_module_info = imp.find_module('tests', [os.path.join(build_root, 'oscrypto')])
        oscrypto_tests = imp.load_module('oscrypto.tests', *oscrypto_tests_module_info)
        oscrypto = oscrypto_tests.local_oscrypto()
        print('\noscrypto backend: %s' % oscrypto.backend())
    except (ImportError):
        pass

    if run_lint:
        print('')
        lint_result = run_lint()
    else:
        lint_result = True

    if run_coverage:
        print('\nRunning tests (via coverage.py)')
        sys.stdout.flush()
        tests_result = run_coverage(ci=True)
    else:
        print('\nRunning tests')
        sys.stdout.flush()
        tests_result = run_tests()
    sys.stdout.flush()

    return lint_result and tests_result
672050
def _setup_py_run_from_dir(root_dir, py_interpreter):
    """"""
    data = {}
    with _enter_single_subdir(root_dir) as single_subdir:
        if not os.path.exists("setup.py"):
            raise Exception("'setup.py' does not exist in '%s'" % (
                single_subdir))
        # generate a temporary json file which contains the metadata
        output_json = tempfile.NamedTemporaryFile()
        cmd = "%s setup.py -q --command-packages metaextract " \
              "metaextract -o %s " % (py_interpreter, output_json.name)
        try:
            subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
        except subprocess.CalledProcessError:
            # try again with a encoding in setup.py
            _set_file_encoding_utf8("setup.py")
            subprocess.check_output(cmd, shell=True)

        # read json file and return data
        with open(output_json.name, "r") as f:
            data = json.loads(f.read())

        # sort some of the keys if the dict values are lists
        for key in ['data_files', 'entry_points', 'extras_require',
                    'install_requires', 'setup_requires', 'scripts',
                    'tests_require', 'tests_suite']:
            if key in data['data'] and isinstance(data['data'][key], list):
                data['data'][key] = sorted(data['data'][key])
    return data