我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用coverage.coverage()。
def cov(): """Runs the unit tests with coverage.""" tests = unittest.TestLoader().discover('project/tests') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): COV.stop() COV.save() print('Coverage Summary:') COV.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'tmp/coverage') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase() return 0 return 1
def test(coverage=False): """Run the unit tests.""" if coverage and not os.environ.get('FLASK_COVERAGE'): import sys os.environ['FLASK_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest import xmlrunner tests = unittest.TestLoader().discover('tests') # run tests with unittest-xml-reporting and output to $CIRCLE_TEST_REPORTS on CircleCI or test-reports locally xmlrunner.XMLTestRunner(output=os.environ.get('CIRCLE_TEST_REPORTS','test-reports')).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'tmp/coverage') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase()
def test(coverage=False): """Run the unit tests.""" if coverage and not os.environ.get('FLASK_COVERAGE'): import sys os.environ['FLASK_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'tmp/coverage') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase()
def test(coverage=False): """ ?? :param coverage ???????? :return: """ if coverage and not os.environ.get('PG_COVERAGE'): import sys os.environ['PG_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'tests/coverage') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase()
def test(coverage): """Run the unit tests.""" if coverage and not os.environ.get('FLASK_COVERAGE'): import subprocess os.environ['FLASK_COVERAGE'] = '1' sys.exit(subprocess.call(sys.argv)) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'tmp/coverage') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase()
def test(coverage=False): # run the test unit if coverage and not os.environ.get('FLASK_COVERAGE'): import sys os.environ['FLASK_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'tmp/coverage') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase()
def pytest_addoption(parser): """Add options to control coverage.""" group = parser.getgroup( 'smother', 'smother reporting') group.addoption('--smother', action='append', default=[], metavar='path', nargs='?', const=True, dest='smother_source', help='measure coverage for filesystem path ' '(multi-allowed)') group.addoption('--smother-config', action='store', default='.coveragerc', help='config file for coverage, default: .coveragerc') group.addoption('--smother-append', action='store_true', default=False, help='append to existing smother report, ' 'default: False') group.addoption('--smother-output', action='store', default='.smother', help='output file for smother data. ' 'default: .smother') group.addoption('--smother-cover', action='store_true', default=False, help='Create a vanilla coverage file in addition to ' 'the smother output')
def __init__(self, options): self.coverage = coverage.coverage( source=options.smother_source, config_file=options.smother_config, ) # The unusual import statement placement is so that # smother's own test suite can measure coverage of # smother import statements self.coverage.start() from smother.control import Smother self.smother = Smother(self.coverage) self.output = options.smother_output self.append = options.smother_append self.cover_report = options.smother_cover self.first_test = True
def cli(cov): """ Runs all the tests. :param cov: bool Set to True to get coverage report """ if cov and not os.environ.get('FLASK_COVERAGE'): import sys os.environ['FLASK_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) tests = unittest.TestLoader().discover('app.tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() basedir = os.path.abspath(os.path.dirname('__file__')) covdir = os.path.join(basedir, 'tmp/coverage') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase()
def test(coverage=False): """Runs the unit tests.""" if coverage and not os.environ.get('FLASK_COVERAGE'): import sys os.environ['FLASK_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'tmp/coverage') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase()
def test(coverage=False): import unittest2 import os import coverage as _coverage cov = None if coverage: cov = _coverage.coverage(branch=True, include='./*') cov.start() tests = unittest2.TestLoader().discover('tests') unittest2.TextTestRunner(verbosity=2).run(tests) if cov: cov.stop() cov.save() print('Coverage Summary:') cov.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'tmp/coverage') cov.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) cov.erase() # TODO: Implement options
def test(coverage=False): """Run the unit tests.""" import sys if coverage and not os.environ.get('FLASK_COVERAGE'): os.environ['FLASK_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest import xmlrunner tests = unittest.TestLoader().discover('tests') results = xmlrunner.XMLTestRunner(output='test-reports').run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'test-reports/coverage') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase() if (len(results.failures) > 0 or len(results.errors) > 0): sys.exit(1)
def test(coverage = False): """Run the unit tests""" if coverage and not os.environ.get('FLASK_COVERAGE'): import sys os.environ['FLASK_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity = 2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'tmp/coverage') COV.html_report(directory = covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase()
def cov(): """Runs the unit tests with coverage.""" cov = coverage.coverage( branch=True, include='minitweet_app/*', omit="*/__init__.py" ) cov.start() tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) cov.stop() cov.save() print('Coverage Summary:') cov.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'coverage') cov.html_report(directory=covdir) cov.erase()
def runTest(self): print(self.id()) kernel = 'python%d' % sys.version_info[0] cur_dir = os.path.dirname(self.nbfile) with open(self.nbfile) as f: nb = nbformat.read(f, as_version=4) if self.cov: covdict = {'cell_type': 'code', 'execution_count': 1, 'metadata': {'collapsed': True}, 'outputs': [], 'nbsphinx': 'hidden', 'source': 'import coverage\n' 'coverage.process_startup()\n' 'import sys\n' 'sys.path.append("{0}")\n'.format(cur_dir) } nb['cells'].insert(0, nbformat.from_dict(covdict)) exproc = ExecutePreprocessor(kernel_name=kernel, timeout=500) try: run_dir = os.getenv('WRADLIB_BUILD_DIR', cur_dir) exproc.preprocess(nb, {'metadata': {'path': run_dir}}) except CellExecutionError as e: raise e if self.cov: nb['cells'].pop(0) with io.open(self.nbfile, 'wt') as f: nbformat.write(nb, f) self.assertTrue(True)
def print_banner(fname, percent, fill): print(colors.color('-' * fill, bg=226, fg=236)) maxsize = fill - len('coverage: ') - 3 truncfname = fname[-maxsize:] if len(truncfname) != len(fname): truncfname = '...' + truncfname print(colors.color(('coverage: ' + truncfname).ljust(fill), bg=226, fg=236)) grsize = int(fill * percent) if grsize >= 5: prcnt_formatted = '%3d%%' % int(percent * 100.0) gr = colors.color(prcnt_formatted + (' ' * (grsize - 4)), fg=255, bg=22) else: gr = colors.color(' ' * grsize, bg=22) red = colors.color(' ' * int(math.ceil(fill * (1.0 - percent))), bg=52) #print(colors.color('{}%'.format(int(percent * 100.0)).ljust(fill), bg=226, fg=236)) print(gr + red) print(colors.color('-' * fill, bg=226, fg=236))
def test(coverage=False): """Run the unit tests.""" if coverage and not os.environ.get('FLASK_COVERAGE'): import sys os.environ['FLASK_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'tmp/coverage') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase() # source code profile
def pkg_verify(self, command, exit=0, comment="", prefix="", su_wrap=None, out=False, stderr=False, cmd_path=None, use_img_root=True, debug_smf=True, env_arg=None, coverage=True): """Wraps self.pkg(..) and checks that the 'verify' command run does not contain the string 'Unexpected Exception', indicating something has gone wrong during package verification.""" cmd = "verify {0}".format(command) res = self.pkg(command=cmd, exit=exit, comment=comment, prefix=prefix, su_wrap=su_wrap, out=out, stderr=stderr, cmd_path=cmd_path, use_img_root=use_img_root, debug_smf=debug_smf, env_arg=env_arg, coverage=coverage) if "Unexpected Exception" in self.output: raise TracebackException(cmd, self.output, "Unexpected errors encountered while verifying.") return res
def validate_html_file(self, fname, exit=0, comment="", options="--doctype strict -utf8 -quiet", drop_prop_attrs=False): """ Run a html file specified by fname through a html validator (tidy). The drop_prop_attrs parameter can be used to ignore proprietary attributes which would otherwise make tidy fail. """ if drop_prop_attrs: tfname = fname + ".tmp" os.rename(fname, tfname) moptions = options + " --drop-proprietary-attributes y" cmdline = "tidy {0} {1} > {2}".format(moptions, tfname, fname) self.cmdline_run(cmdline, comment=comment, coverage=False, exit=exit, raise_error=False) os.unlink(tfname) cmdline = "tidy {0} {1}".format(options, fname) return self.cmdline_run(cmdline, comment=comment, coverage=False, exit=exit)
def usage(exitcode=2): print("Usage: {0} [-dfghlpqtvx] [-a dir] [-b filename] [-c format]\n"\ " [-j jobs] [-o regexp] [-s regexp]\n"\ " [-z port] ".format(sys.argv[0]), file=sys.stderr) print("""\ -a <dir> Archive failed test cases to <dir>/$pid/$testcasename -b <filename> Baseline filename -c <format> Collect code coverage data in xml or html format -d Show debug output, including commands run, and outputs -f Show fail/error information even when test is expected to fail -g Generate result baseline -h This help message -j <jobs> Parallelism -l Run tests against live system -o <regexp> Run only tests that match regexp -p Parseable output format -q Quiet output -s <regexp> Run tests starting at regexp -t Generate timing info file -v Verbose output -x Stop after the first baseline mismatch -z <port> Lowest port the test suite should use """, file=sys.stderr) sys.exit(exitcode)
def cov(): tests = unittest.TestLoader().discover('tests') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): COV.stop() COV.save() print('Coverage Summary:') COV.report() COV.html_report() COV.erase() return 0 else: return 1 # Enter 'docker-compose run --rm flask python manage.py test' to run all the # tests in the 'tests' directory, but provides no coverage report.
def test(coverage=False): """Run the unit tests""" if coverage and not os.environ.get('FLASK_COVERAGE'): import sys os.environ['FLASK_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'tmp/coverage') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase()
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) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'tmp/coverage') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase()
def test(): """Runs the unit tests without test coverage.""" tests = unittest.TestLoader().discover('project/tests', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 return 1
def run(self): try: from coverage import coverage except ImportError: raise SystemExit( "Missing 'coverage' module. See " "https://pypi.python.org/pypi/coverage or try " "`apt-get install python-coverage python3-coverage`") for key in list(sys.modules.keys()): if key.startswith('senf'): del(sys.modules[key]) cov = coverage() cov.start() cmd = self.reinitialize_command("test") cmd.ensure_finalized() cmd.run() dest = os.path.join(os.getcwd(), "coverage") cov.stop() cov.html_report( directory=dest, ignore_errors=True, include=["senf/*"]) print("Coverage summary: file://%s/index.html" % dest)
def beforeTest(self, *args, **kwargs): """ Begin recording coverage information. """ if self.coverInstance.is_worker: self.coverInstance.load() self.coverInstance.start()
def afterTest(self, *args, **kwargs): """ Stop recording coverage information. """ if self.coverInstance.is_worker: self.coverInstance.stop() self.coverInstance.save()
def wantModuleCoverage(self, name, module): if not hasattr(module, '__file__'): log.debug("no coverage of %s: no __file__", name) return False module_file = src(module.__file__) if not module_file or not module_file.endswith('.py'): log.debug("no coverage of %s: not a python file", name) return False if self.coverPackages: for package in self.coverPackages: if (re.findall(r'^%s\b' % re.escape(package), name) and (self.coverTests or not self.conf.testMatch.search(name))): log.debug("coverage for %s", name) return True if name in self.skipModules: log.debug("no coverage for %s: loaded before coverage start", name) return False if self.conf.testMatch.search(name) and not self.coverTests: log.debug("no coverage for %s: is a test", name) return False # accept any package that passed the previous tests, unless # coverPackages is on -- in that case, if we wanted this # module, we would have already returned True return not self.coverPackages
def cov(): """Runs the unit tests with coverage.""" tests = unittest.TestLoader().discover('project/tests') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): COV.stop() COV.save() print('Coverage Summary:') COV.report() COV.html_report() COV.erase() return 0 return 1
def test(): """Runs the unit tests without coverage.""" tests = unittest.TestLoader().discover('tests') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 else: return 1
def cov(): """Runs the unit tests with coverage.""" tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) COV.stop() COV.save() print('Coverage Summary:') COV.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, 'tmp/coverage') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase()
def __init__(self, source, with_coverage=False, html_cov=False, config_file=None, root='', comm=None): """ Parameters ---------- source : str the name of the package module which we are reporting coverage for with_coverage : bool, optional whether to record the coverage html_cov : bool, optional whether to save a html coverage report; in 'build/coverage' config_file : str, optional a coveragerc file to load root : str, optional this specifies the root of the package comm : MPI communicator, optional the MPI communicator """ self.comm = comm self.source = source self.root = root # options self.with_coverage = with_coverage self.config_file = os.path.join(root, config_file) self.html_cov = html_cov # check if coverage file exists if not os.path.exists(self.config_file): self.config_file = None
def __enter__(self): if not self.with_coverage: self.cov = None return else: self.cov = coverage.coverage(source=[self.source], config_file=self.config_file) self.cov.start()
def __exit__(self, type, value, tb): if not self.with_coverage: return self.cov.stop() # with only one rank, just write out the coverage if self.comm is None or self.comm.size == 1: self.cov.get_data().write_file(os.path.join(self.root, self.cov.config.data_file)) self.report(self.cov) # parallel -- combine coverage from all ranks else: # write to a single temporary directory, then have root combine them if self.comm.rank == 0: tmpdir = tempfile.mkdtemp() else: tmpdir = None tmpdir = self.comm.bcast(tmpdir) try: # write coverage data file filename = os.path.join(tmpdir, '.coverage.%d' % os.getpid()) self.cov.get_data().write_file(filename) # now combine from each rank and save self.comm.barrier() if self.comm.rank == 0: # write out combined data combined_cov = coverage.coverage(config_file=self.config_file, data_file='.coverage') combined_cov.combine(data_paths=[tmpdir]) combined_cov.get_data().write_file(os.path.join(self.root, self.cov.config.data_file)) # and report self.report(combined_cov) finally: self.comm.barrier() if self.comm.rank == 0: shutil.rmtree(tmpdir)
def report(self, cov): """ Report the coverage """ # and report (to screen) cov.report() # write html if self.html_cov: html_dir = os.path.join(self.root, 'build', 'coverage') if not os.path.exists(html_dir): os.makedirs(html_dir) cov.html_report(directory=html_dir)
def test(): """ Run tests without coverage :return: """ tests = unittest.TestLoader().discover('tests', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 return 1
def __enter__(self): self.cov = coverage() os.environ['COVERAGE_PROCESS_START'] = '.coveragerc' self.cov.start()
def run(): cov = coverage(source=['flask_testing']) cov.start() from tests import suite result = unittest.TextTestRunner(verbosity=2).run(suite()) if not result.wasSuccessful(): sys.exit(1) cov.stop() print("\nCode Coverage") cov.report() cov.html_report(directory='cover')
def coverage(A,B,z=False): """Takes two PyGL objects and returns a PyGL object resulting from the coverage operation""" if _cs(A)!=0: print "A is not sorted. Please use a pyglSort." return if _cs(B)!=0: print "B is not sorted. Please use a pyglSort." return args={'z':z} return _cov.coverage(A,B,"",args) # In[8]:
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)
def csv(ctx, dst): """ Flatten a coverage file into a CSV of source_context, testname """ sm = Smother.load(ctx.obj['report']) semantic = ctx.obj['semantic'] writer = _csv.writer(dst, lineterminator='\n') dst.write("source_context, test_context\n") writer.writerows(sm.iter_records(semantic=semantic))
def to_coverage(ctx): """ Produce a .coverage file from a smother file """ sm = Smother.load(ctx.obj['report']) sm.coverage = coverage.coverage() sm.write_coverage()
def pytest_runtest_teardown(self, item, nextitem): self.coverage.stop() self.smother.save_context(item.nodeid)
def native_error(msg, version): print textwrap.dedent("""\ ERROR: Native python-coverage (version: %s) is required to be installed on your PYTHONPATH to run this test. Recommendation: sudo apt-get install pip sudo pip install --upgrade coverage %s""") % (version, msg) sys.exit(1)