Python coverage 模块,Coverage() 实例源码

我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用coverage.Coverage()

项目:rancher-gen    作者:pitrho    | 项目源码 | 文件源码
def run_tests(self):
        import coverage
        import pytest

        if self.pytest_args and len(self.pytest_args) > 0:
            self.test_args.extend(self.pytest_args.strip().split(' '))
            self.test_args.append('tests/')

        cov = coverage.Coverage()
        cov.start()
        errno = pytest.main(self.test_args)
        cov.stop()
        cov.report()
        cov.html_report()
        print("Wrote coverage report to htmlcov directory")
        sys.exit(errno)
项目:Vector-Tiles-Reader-QGIS-Plugin    作者:geometalab    | 项目源码 | 文件源码
def run_all():
    cov = coverage.Coverage(omit=['*/usr/*',
                                  '*__init__.py',
                                  '*global_map_tiles*',
                                  '/vector-tiles-reader/tests/*',
                                  '/vector-tiles-reader/util/*',
                                  '/vector-tiles-reader/ext-libs/*',
                                  '/vector-tiles-reader/vtr_plugin.py'  # todo: remove from here when tests exist
                                  ])
    cov.start()
    complete_suite = unittest.TestSuite(get_tests())
    print("")
    unittest.TextTestRunner(verbosity=3, stream=sys.stdout).run(complete_suite)
    print("")
    cov.stop()
    cov.save()
    cov.html_report(directory='tests/htmlcov')
    print cov.report()
项目:flack    作者:miguelgrinberg    | 项目源码 | 文件源码
def run():
    os.environ['FLACK_CONFIG'] = 'testing'

    # start coverage engine
    cov = coverage.Coverage(branch=True)
    cov.start()

    # run tests
    tests = unittest.TestLoader().discover('.')
    ok = unittest.TextTestRunner(verbosity=2).run(tests).wasSuccessful()

    # print coverage report
    cov.stop()
    print('')
    cov.report(omit=['manage.py', 'tests/*', 'venv*/*'])

    sys.exit(0 if ok else 1)
项目:cuvner    作者:meejah    | 项目源码 | 文件源码
def diff_coverage_files(file_a, file_b, cfg):
    """
    This shows the difference in lines covered between two coverage files
    """

    data_a = coverage.Coverage(data_file=file_a)
    data_a.load()

    data_b = coverage.Coverage(data_file=file_b)
    data_b.load()

    click.echo(
        "Comparing {} vs {}".format(
            click.style(file_a, fg='red'),
            click.style(file_b, fg='green'),
        )
    )

    diff_coverage_data(data_a, data_b, cfg)
项目:kobin-todo    作者:kobinpy    | 项目源码 | 文件源码
def run():
    os.environ['KOBIN_SETTINGS_FILE'] = 'config/tests.py'

    # start coverage engine
    cov = coverage.Coverage(branch=True)
    cov.start()

    # run tests
    tests = unittest.TestLoader().discover('.')
    ok = unittest.TextTestRunner(verbosity=2).run(tests).wasSuccessful()

    # print coverage report
    cov.stop()
    print('')
    cov.report(omit=['manage.py', 'tests/*', 'venv/*', 'config/*'])

    sys.exit(0 if ok else 1)
项目:livetv_mining    作者:taogeT    | 项目源码 | 文件源码
def test(coverage=False):
    """Run the unit tests."""
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    testresult = TextTestRunner(verbosity=2).run(TestLoader().discover('tests'))
    if cov:
        cov.stop()
        cov.save()
        print('Coverage Summary:')
        cov.report()
        covdir = app.config.get('COVERAGE_DIRECTORY', '')
        if covdir:
            covdir = os.path.join(covdir, datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S'))
            if not os.path.exists(covdir):
                os.makedirs(covdir)
            cov.html_report(directory=covdir)
            print('Coverage HTML version: file://{}/index.html'.format(covdir))
        cov.erase()
    if len(testresult.failures) + len(testresult.errors) > 0:
        sys.exit(1)
项目:runcommands    作者:wylee    | 项目源码 | 文件源码
def test(config, tests=(), fail_fast=False, with_coverage=True, with_lint=True):
    if tests:
        num_tests = len(tests)
        s = '' if num_tests == 1 else 's'
        printer.header('Running {num_tests} test{s}...'.format_map(locals()))
    else:
        coverage_message = ' with coverage' if with_coverage else ''
        printer.header('Running tests{coverage_message}...'.format_map(locals()))

    runner = unittest.TextTestRunner(failfast=fail_fast)
    loader = unittest.TestLoader()

    if with_coverage:
        from coverage import Coverage
        coverage = Coverage(source=['runcommands'])
        coverage.start()

    if tests:
        for name in tests:
            runner.run(loader.loadTestsFromName(name))
    else:
        tests = loader.discover('.')
        result = runner.run(tests)
        if not result.errors:
            if with_coverage:
                coverage.stop()
                coverage.report()
            if with_lint:
                printer.header('Checking for lint...')
                lint(config)
项目:bencoder.pyx    作者:whtsky    | 项目源码 | 文件源码
def run_tests(self):
        #import here, cause outside the eggs aren't loaded
        import coverage
        cov = coverage.Coverage()
        cov.start()

        import pytest
        errno = pytest.main(self.pytest_args)

        cov.stop()
        cov.save()
        sys.exit(errno)
项目:django-readonly-field    作者:peopledoc    | 项目源码 | 文件源码
def cover():
    do_coverage = "COVERAGE" in os.environ

    if do_coverage:
        import coverage
        cov = coverage.Coverage(source=["django_readonly_field"])
        cov.start()
        print("Coverage will be generated")

    try:
        yield
    finally:
        if do_coverage:
            cov.stop()
            cov.save()
项目:hdlcc    作者:suoto    | 项目源码 | 文件源码
def _noseRunner(args):
    "Runs nose2 with coverage"
    _logger.info("nose2 args: %s", repr(args))
    cov = coverage.Coverage(config_file='.coveragerc')
    cov.start()

    try:
        result = nose2.discover(exit=False, argv=args)
    finally:
        cov.stop()
        cov.save()

    return result
项目:coverage2sql    作者:openstack    | 项目源码 | 文件源码
def __init__(self, coverage_file=None):
        self.cov = coverage.Coverage(data_file=coverage_file)
        self.cov.load()
        xmlfile = tempfile.NamedTemporaryFile(suffix='.xml')
        self.cov_pct = self.cov.xml_report(outfile=xmlfile.name)
        self.covdoc = xmltodict.parse(xmlfile.read())
        xmlfile.close()
项目:smother    作者:ChrisBeaumont    | 项目源码 | 文件源码
def combine(ctx, src, dst):
    """
    Combine several smother reports.
    """
    c = coverage.Coverage(config_file=ctx.obj['rcfile'])
    result = Smother(c)

    for infile in src:
        result |= Smother.load(infile)

    result.write(dst)
项目:azure-cli    作者:Azure    | 项目源码 | 文件源码
def __init__(self):
        from coverage import Coverage
        self._cov = Coverage(cover_pylib=False)
        self._cov.start()
项目:pymm    作者:aRkadeFR    | 项目源码 | 文件源码
def run_tests(self):
        " Run coverage on unit test "
        # need to import here cause we are in a venv
        import six
        from coverage import Coverage

        coverage = Coverage()
        coverage.start()

        # Purge modules under test from sys.modules. The test loader will
        # re-import them from the build location. Required when 2to3 is used
        # with namespace packages.
        if six.PY3 and getattr(self.distribution, 'use_2to3', False):
            module = self.test_suite.split('.')[0]
            if module in _namespace_packages:
                del_modules = []
                if module in sys.modules:
                    del_modules.append(module)
                module += '.'
                for name in sys.modules:
                    if name.startswith(module):
                        del_modules.append(name)
                list(map(sys.modules.__delitem__, del_modules))

        unittest_main(
            None, None, self._argv,
            testLoader=self._resolve_as_ep(self.test_loader),
            testRunner=self._resolve_as_ep(self.test_runner),
            exit=False,
        )

        coverage.stop()
        coverage.save()
        coverage.report(show_missing=False)
项目:cuvner    作者:meejah    | 项目源码 | 文件源码
def cuv(ctx, coverage_fname, exclude, branch):
    """
    Cuv'ner provides ways to visualize your project's coverage data.

    Everything works on the console and assumes a unicode and
    256-color capable terminal. There must be a .coverage file which
    is loaded for coverage data; it is assumed to be in the top level
    of your source code checkout.
    """
    if coverage_fname is None:
        coverage_fname = find_coverage_data('.')
        # coverage_fname still could be None

    cfg = Config()
    ctx.obj = cfg

    cfg.nice_width = min(80, click.get_terminal_size()[0])
    cfg.exclude = exclude

    cfg.branch = branch
    if coverage_fname is not None:
        cfg.data = coverage.Coverage(data_file=coverage_fname)
        cfg.data.load()
    else:
        raise click.UsageError(
            "No coverage data. Do you have a .coverage file?"
        )
项目:azure-batch-cli-extensions    作者:Azure    | 项目源码 | 文件源码
def __init__(self):
        from coverage import Coverage
        self._cov = Coverage(cover_pylib=False)
        self._cov.start()
项目:memgraph    作者:technige    | 项目源码 | 文件源码
def run_tests(*here):
    if Coverage is None:
        for x in here:
            _run_tests(x)
    else:
        coverage = Coverage()
        coverage.start()
        for x in here:
            _run_tests(x)
        coverage.stop()
        coverage.save()
项目:Hawkeye    作者:tozhengxq    | 项目源码 | 文件源码
def patch_multiprocessing():
    """Monkey-patch the multiprocessing module.

    This enables coverage measurement of processes started by multiprocessing.
    This is wildly experimental!

    """
    if hasattr(multiprocessing, PATCHED_MARKER):
        return

    if sys.version_info >= (3, 4):
        klass = multiprocessing.process.BaseProcess
    else:
        klass = multiprocessing.Process

    original_bootstrap = klass._bootstrap

    class ProcessWithCoverage(klass):
        """A replacement for multiprocess.Process that starts coverage."""
        def _bootstrap(self):
            """Wrapper around _bootstrap to start coverage."""
            from coverage import Coverage
            cov = Coverage(data_suffix=True)
            cov.start()
            try:
                return original_bootstrap(self)
            finally:
                cov.stop()
                cov.save()

    if sys.version_info >= (3, 4):
        klass._bootstrap = ProcessWithCoverage._bootstrap
    else:
        multiprocessing.Process = ProcessWithCoverage

    setattr(multiprocessing, PATCHED_MARKER, True)
项目:python-zulip-api    作者:zulip    | 项目源码 | 文件源码
def handle_input_and_run_tests_for_package(package_name):
    parser = argparse.ArgumentParser(description="Run tests for the {} package.".format(package_name))
    parser.add_argument('--coverage',
                        nargs='?',
                        const=True,
                        default=False,
                        help='compute test coverage (--coverage combine to combine with previous reports)')
    options = parser.parse_args()

    if options.coverage:
        import coverage
        cov = coverage.Coverage(config_file="tools/.coveragerc")
        if options.coverage == 'combine':
            cov.load()
        cov.start()

    # Codecov seems to work only when using loader.discover. It failed to capture line executions
    # for functions like loader.loadTestFromModule or loader.loadTestFromNames.
    test_suites = unittest.defaultTestLoader.discover(package_name)
    suite = unittest.TestSuite(test_suites)
    runner = unittest.TextTestRunner(verbosity=2)
    result = runner.run(suite)
    if result.failures or result.errors:
        sys.exit(1)

    if not result.failures and options.coverage:
        cov.stop()
        cov.data_suffix = False  # Disable suffix so that filename is .coverage
        cov.save()
        cov.html_report()
        print("HTML report saved in directory 'htmlcov'.")
项目:hdlcc    作者:suoto    | 项目源码 | 文件源码
def main():
    args = _parseArguments()
    _setupLogging(args.log_stream, args.log_level)
    _setupPaths()
    #  _clear()

    _logger.info("Arguments: %s", args)

    logging.getLogger('nose2').setLevel(logging.FATAL)
    logging.getLogger('vunit').setLevel(logging.ERROR)
    logging.getLogger('requests').setLevel(logging.WARNING)
    file_handler = logging.FileHandler(args.log_file)
    log_format = "[%(asctime)s] %(levelname)-8s || %(name)-30s || %(message)s"
    file_handler.formatter = logging.Formatter(log_format)
    logging.root.addHandler(file_handler)

    _logger.info("Environment info:")
    _logger.info(" - CI:       %s", _CI)
    _logger.info(" - APPVEYOR: %s", _APPVEYOR)
    _logger.info(" - TRAVIS:   %s", _TRAVIS)
    _logger.info(" - LOG:      %s", args.log_file)

    cov = coverage.Coverage(config_file='.coveragerc')
    cov.start()

    passed = True
    for env in ('ghdl', 'msim', 'xvhdl', 'fallback', 'standalone'):
        if getattr(args, env):
            _logger.info("Running env '%s'", env)

            if not runTestsForEnv(env, args):
                if passed:
                    _logger.warning("Some tests failed while running '%s'", env)
                passed = False

            if not passed and args.fail_fast:
                break
        else:
            _logger.info("Skipping env '%s'", env)

    cov.stop()
    cov.save()
    for cmd in ('coverage combine',
                'coverage html'):
        _shell(cmd)

    if not passed:
        _logger.warning("Some tests failed!")
        print("Some tests failed!")

    return 0 if passed else 1
项目:cuvner    作者:meejah    | 项目源码 | 文件源码
def measured_filenames(self, keywords=None):
        """
        returns an iterator that yields filenames, one for each file found
        in the coverage data we've currently loaded.

        This also handles filtering; if any filters were configured,
        you'll only get instances which get past the filter.
        """

        # XXX should probably move to a helper function that takes a
        # Coverage instance?

        # XXX said helper can take a filter-function too

        # FIXME passing keywords is stupid

        def filter(fname):
            if not fname.endswith('.py'):
                return True
            if [x for x in fname.split(os.path.sep) if x.startswith('test')]:
                return True
            if self.exclude:
                for ex in self.exclude:
                    if ex in fname:
                        print("excluding:", fname)
                        return True
            if keywords:
                found = False
                for k in keywords:
                    if k in fname:
                        found = True
                if not found:
                    return True
            return False

        if self.data is None:
            click.echo("No coverage data foud.")
            raise click.Abort

        for fname in self.data.data.measured_files():
            if not filter(fname):
                yield fname
项目:cuvner    作者:meejah    | 项目源码 | 文件源码
def watch_coverage(keywords, cfg):
    file_coverage = []

    file_coverage = list(cfg.measured_filenames(keywords))
    file_coverage.sort()

    common = util.common_root_path(file_coverage)

    existing_data = cfg.data
    coverage_fname = cfg.data.data_files.filename

    # ugh
    class Handler(FileSystemEventHandler):
        def __init__(self):
            # a real closure!
            self._existing_data = existing_data

        def on_modified(self, event):
            if event.src_path == coverage_fname:
                click.echo("New coverage data:")
                new_data = coverage.Coverage(data_file=coverage_fname)
                new_data.load()
                diff_coverage_data(self._existing_data, new_data, cfg)
                newly_covered = _new_covered_lines(self._existing_data, new_data, cfg)
                self._existing_data = new_data
                click.echo('----')
                click.echo("newly covered:")
                for k, v in newly_covered.items():
                    click.echo("  {}: {}".format(k, v))
                click.echo('----')
                show_missing(self._existing_data, file_coverage, len(common))

    handler = Handler()
    observer = Observer()
    print("Watching: {}".format(coverage_fname))
    observer.schedule(handler, split(coverage_fname)[0])
    observer.start()
    show_missing(existing_data, file_coverage, len(common))
    try:
        while True:
            sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()