本文整理汇总了Python中coverage.Coverage.report方法的典型用法代码示例。如果您正苦于以下问题:Python Coverage.report方法的具体用法?Python Coverage.report怎么用?Python Coverage.report使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类coverage.Coverage
的用法示例。
在下文中一共展示了Coverage.report方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_tests
# 需要导入模块: from coverage import Coverage [as 别名]
# 或者: from coverage.Coverage import report [as 别名]
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)
示例2: with_coverage
# 需要导入模块: from coverage import Coverage [as 别名]
# 或者: from coverage.Coverage import report [as 别名]
def with_coverage(f, source, *, report=True, data=False):
cov = Coverage(source=[source])
cov.start()
try:
exit_code = f()
finally:
cov.stop()
if not exit_code:
if report:
print() # Print blank line.
cov.report(show_missing=False)
cov.html_report()
if data:
cov.save()
return exit_code
示例3: run_unit_tests
# 需要导入模块: from coverage import Coverage [as 别名]
# 或者: from coverage.Coverage import report [as 别名]
def run_unit_tests():
from datetime import datetime
from coverage import Coverage
from io import StringIO
import unittest
from tests import testModels
w = StringIO()
cov = Coverage(omit=["/usr/*", "*/venv/*", "*-packages*"])
cov.start()
runner = unittest.TextTestRunner(stream=w)
runner.run(unittest.makeSuite(testModels))
cov.stop()
cov.report(file=w)
output = w.getvalue()
db.app = app
return ("You ran the tests on: " + datetime.now().strftime("%I:%M%p on %B %d, %Y") + " GMT\n" + output)
示例4: run_test_suite
# 需要导入模块: from coverage import Coverage [as 别名]
# 或者: from coverage.Coverage import report [as 别名]
def run_test_suite():
cov = Coverage(config_file=True)
cov.erase()
cov.start()
# Announce the test suite
sys.stdout.write(colored(text="\nWelcome to the ", color="magenta", attrs=["bold"]))
sys.stdout.write(colored(text="python-doc-inherit", color="green", attrs=["bold"]))
sys.stdout.write(colored(text=" test suite.\n\n", color="magenta", attrs=["bold"]))
# Announce test run
print(colored(text="Step 1: Running unit tests.\n", color="yellow", attrs=["bold"]))
test_suite = TestLoader().discover(str(Path("tests").absolute()))
result = TextTestRunner(verbosity=1).run(test_suite)
if not result.wasSuccessful():
sys.exit(len(result.failures) + len(result.errors))
# Announce coverage run
print(colored(text="\nStep 2: Generating coverage results.\n", color="yellow", attrs=["bold"]))
cov.stop()
percentage = round(cov.report(show_missing=True), 2)
cov.html_report(directory='cover')
cov.save()
if percentage < TESTS_THRESHOLD:
print(colored(text="YOUR CHANGES HAVE CAUSED TEST COVERAGE TO DROP. " +
"WAS {old}%, IS NOW {new}%.\n".format(old=TESTS_THRESHOLD, new=percentage),
color="red", attrs=["bold"]))
sys.exit(1)
# Announce flake8 run
sys.stdout.write(colored(text="\nStep 3: Checking for pep8 errors.\n\n", color="yellow", attrs=["bold"]))
print("pep8 errors:")
print("----------------------------------------------------------------------")
from subprocess import call
flake_result = call(["flake8", ".", "--count"])
if flake_result != 0:
print("pep8 errors detected.")
print(colored(text="\nYOUR CHANGES HAVE INTRODUCED PEP8 ERRORS!\n", color="red", attrs=["bold"]))
sys.exit(flake_result)
else:
print("None")
# Announce success
print(colored(text="\nTests completed successfully with no errors. Congrats!", color="green", attrs=["bold"]))
示例5: CodeCoverage
# 需要导入模块: from coverage import Coverage [as 别名]
# 或者: from coverage.Coverage import report [as 别名]
class CodeCoverage(object):
"""
Code Coverage radish extension
"""
OPTIONS = [
("--with-coverage", "enable code coverage"),
("--cover-packages=<cover_packages>", "specify source code package")
]
LOAD_IF = staticmethod(lambda config: config.with_coverage)
LOAD_PRIORITY = 70
def __init__(self):
before.all(self.coverage_start)
after.all(self.coverage_stop)
if world.config.cover_packages:
cover_packages = world.config.cover_packages.split(",")
else:
cover_packages = []
self.coverage = Coverage(source=cover_packages)
def coverage_start(self, features, marker):
"""
Start the coverage measurement
"""
self.coverage.load()
self.coverage.start()
def coverage_stop(self, features, marker):
"""
Stop the coverage measurement
and create report
"""
self.coverage.stop()
self.coverage.save()
self.coverage.report(file=sys.stdout)
示例6: main
# 需要导入模块: from coverage import Coverage [as 别名]
# 或者: from coverage.Coverage import report [as 别名]
def main():
""" The main function, mainly functioning to do the main functional work
(thanks pylint)
"""
if len(sys.argv) > 1 and sys.argv[1] == 'cover':
# FIXME - there are enough args now to need an arg parser
cover = Coverage(branch=True, auto_data=True)
min_percent = 0
if len(sys.argv) > 2:
min_percent = float(sys.argv[2])
else:
cover = False
loader = unittest.defaultTestLoader
runner = unittest.TextTestRunner(verbosity=2)
if cover:
cover.erase()
cover.start()
tests = loader.discover('.')
tests_lib = loader.discover('lib', top_level_dir='lib')
tests.addTests(tests_lib)
result = runner.run(tests)
if cover:
cover.stop()
# the debian coverage package didnt include jquery.debounce.min.js
# (and additionally, that thing is not packaged for debian elsewhere)
try:
cover.html_report()
except:
pass
percent = cover.report(show_missing=True)
if min_percent > percent:
print("The coverage ({:.1f}% reached) fails to reach the "
"minimum required ({}%)\n".format(percent, min_percent))
exit(1)
if not result.wasSuccessful():
exit(1)
示例7: Coverage
# 需要导入模块: from coverage import Coverage [as 别名]
# 或者: from coverage.Coverage import report [as 别名]
#!/usr/bin/env python
import os
import sys
from django.core import management
# Point to the correct settings for testing
os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
if __name__ == "__main__":
testing = 'test' in sys.argv
if testing:
from coverage import Coverage
cov = Coverage()
cov.erase()
cov.start()
management.execute_from_command_line()
if testing:
cov.stop()
cov.save()
cov.report()
示例8: run_test_suite
# 需要导入模块: from coverage import Coverage [as 别名]
# 或者: from coverage.Coverage import report [as 别名]
#.........这里部分代码省略.........
},
DJSTRIPE_PLAN_HIERARCHY = {
"bronze": {
"level": 1,
"plans": [
"test0",
"test",
]
},
"silver": {
"level": 2,
"plans": [
"test2",
"test_deletion",
]
},
"gold": {
"level": 3,
"plans": [
"test_trial",
"unidentified_test_plan",
]
},
},
DJSTRIPE_SUBSCRIPTION_REQUIRED_EXCEPTION_URLS=(
"(admin)",
"test_url_name",
"testapp_namespaced:test_url_namespaced",
),
)
# Avoid AppRegistryNotReady exception
# http://stackoverflow.com/questions/24793351/django-appregistrynotready
if hasattr(django, "setup"):
django.setup()
# Announce the test suite
sys.stdout.write(colored(text="\nWelcome to the ", color="magenta", attrs=["bold"]))
sys.stdout.write(colored(text="dj-stripe", color="green", attrs=["bold"]))
sys.stdout.write(colored(text=" test suite.\n\n", color="magenta", attrs=["bold"]))
# Announce test run
sys.stdout.write(colored(text="Step 1: Running unit tests.\n\n", color="yellow", attrs=["bold"]))
# Hack to reset the global argv before nose has a chance to grab it
# http://stackoverflow.com/a/1718407/1834570
args = sys.argv[1:]
sys.argv = sys.argv[0:1]
from django_nose import NoseTestSuiteRunner
test_runner = NoseTestSuiteRunner(verbosity=1)
failures = test_runner.run_tests(["."])
if failures:
sys.exit(failures)
if enable_coverage:
# Announce coverage run
sys.stdout.write(colored(text="\nStep 2: Generating coverage results.\n\n", color="yellow", attrs=["bold"]))
cov.stop()
percentage = round(cov.report(show_missing=True), 2)
cov.html_report(directory='cover')
cov.save()
if percentage < TESTS_THRESHOLD:
sys.stderr.write(colored(text="YOUR CHANGES HAVE CAUSED TEST COVERAGE TO DROP. " +
"WAS {old}%, IS NOW {new}%.\n\n".format(old=TESTS_THRESHOLD, new=percentage),
color="red", attrs=["bold"]))
sys.exit(1)
else:
# Announce disabled coverage run
sys.stdout.write(colored(text="\nStep 2: Generating coverage results [SKIPPED].", color="yellow", attrs=["bold"]))
if enable_pep8:
# Announce flake8 run
sys.stdout.write(colored(text="\nStep 3: Checking for pep8 errors.\n\n", color="yellow", attrs=["bold"]))
print("pep8 errors:")
print("----------------------------------------------------------------------")
from subprocess import call
flake_result = call(["flake8", ".", "--count"])
if flake_result != 0:
sys.stderr.write("pep8 errors detected.\n")
sys.stderr.write(colored(text="\nYOUR CHANGES HAVE INTRODUCED PEP8 ERRORS!\n\n", color="red", attrs=["bold"]))
sys.exit(flake_result)
else:
print("None")
else:
# Announce disabled coverage run
sys.stdout.write(colored(text="\nStep 3: Checking for pep8 errors [SKIPPED].\n", color="yellow", attrs=["bold"]))
# Announce success
if enable_coverage and enable_pep8:
sys.stdout.write(colored(text="\nTests completed successfully with no errors. Congrats!\n", color="green", attrs=["bold"]))
else:
sys.stdout.write(colored(text="\nTests completed successfully, but some step(s) were skipped!\n", color="green", attrs=["bold"]))
sys.stdout.write(colored(text="Don't push without running the skipped step(s).\n", color="red", attrs=["bold"]))
示例9: run_test_suite
# 需要导入模块: from coverage import Coverage [as 别名]
# 或者: from coverage.Coverage import report [as 别名]
#.........这里部分代码省略.........
"price": 2500, # $25.00
"currency": "usd",
"interval": "month"
},
"test2": {
"stripe_plan_id": "test_id_2",
"name": "Test Plan 2",
"description": "Yet Another test plan",
"price": 5000, # $50.00
"currency": "usd",
"interval": "month"
},
"test_deletion": {
"stripe_plan_id": "test_id_3",
"name": "Test Plan 3",
"description": "Test plan for deletion.",
"price": 5000, # $50.00
"currency": "usd",
"interval": "month"
},
"test_trial": {
"stripe_plan_id": "test_id_4",
"name": "Test Plan 4",
"description": "Test plan for trails.",
"price": 7000, # $70.00
"currency": "usd",
"interval": "month",
"trial_period_days": 7
},
"unidentified_test_plan": {
"name": "Unidentified Test Plan",
"description": "A test plan with no ID.",
"price": 2500, # $25.00
"currency": "usd",
"interval": "month"
}
},
DJSTRIPE_SUBSCRIPTION_REQUIRED_EXCEPTION_URLS=(
"(admin)",
"test_url_name",
"testapp_namespaced:test_url_namespaced",
"fn:/test_fnmatch*"
),
DJSTRIPE_USE_NATIVE_JSONFIELD=os.environ.get("USE_NATIVE_JSONFIELD", "") == "1",
)
# Avoid AppRegistryNotReady exception
# http://stackoverflow.com/questions/24793351/django-appregistrynotready
if hasattr(django, "setup"):
django.setup()
# Announce the test suite
sys.stdout.write(colored(text="\nWelcome to the ", color="magenta", attrs=["bold"]))
sys.stdout.write(colored(text="dj-stripe", color="green", attrs=["bold"]))
sys.stdout.write(colored(text=" test suite.\n\n", color="magenta", attrs=["bold"]))
# Announce test run
sys.stdout.write(colored(text="Step 1: Running unit tests.\n\n", color="yellow", attrs=["bold"]))
# Hack to reset the global argv before nose has a chance to grab it
# http://stackoverflow.com/a/1718407/1834570
args = sys.argv[1:]
sys.argv = sys.argv[0:1]
from django_nose import NoseTestSuiteRunner
test_runner = NoseTestSuiteRunner(verbosity=1, keepdb=True, failfast=True)
failures = test_runner.run_tests(tests)
if failures:
sys.exit(failures)
if enable_coverage:
# Announce coverage run
sys.stdout.write(colored(text="\nStep 2: Generating coverage results.\n\n", color="yellow", attrs=["bold"]))
cov.stop()
percentage = round(cov.report(show_missing=True), 2)
cov.html_report(directory='cover')
cov.save()
if percentage < TESTS_THRESHOLD:
sys.stderr.write(colored(text="YOUR CHANGES HAVE CAUSED TEST COVERAGE TO DROP. " +
"WAS {old}%, IS NOW {new}%.\n\n".format(old=TESTS_THRESHOLD, new=percentage),
color="red", attrs=["bold"]))
sys.exit(1)
else:
# Announce disabled coverage run
sys.stdout.write(colored(text="\nStep 2: Generating coverage results [SKIPPED].",
color="yellow", attrs=["bold"]))
# Announce success
if enable_coverage:
sys.stdout.write(colored(text="\nTests completed successfully with no errors. Congrats!\n",
color="green", attrs=["bold"]))
else:
sys.stdout.write(colored(text="\nTests completed successfully, but some step(s) were skipped!\n",
color="green", attrs=["bold"]))
sys.stdout.write(colored(text="Don't push without running the skipped step(s).\n",
color="red", attrs=["bold"]))
示例10: suite
# 需要导入模块: from coverage import Coverage [as 别名]
# 或者: from coverage.Coverage import report [as 别名]
# If the module defines a suite() function, call it to get the suite.
mod = __import__(t, globals(), locals(), ['suite'])
suitefn = getattr(mod, 'suite')
suite.addTest(suitefn())
except (ImportError, AttributeError):
# else, just load all the test cases from the module.
suite.addTest(unittest.defaultTestLoader.loadTestsFromName(t))
runner = unittest.TextTestRunner()
cov.start()
result = runner.run(suite)
cov.stop()
if not result.wasSuccessful():
exit(3)
percent = round(cov.report(), 4)
cov.html_report()
if os.path.isfile('min_cov.txt'):
file = open('min_cov.txt', 'r')
min_coverage = float(file.read())
file.close()
if percent < min_coverage:
exit(2)
else:
file = open('min_cov.txt', 'w')
file.write(str(percent))
file.close()
else:
file = open('min_cov.txt', 'w')
file.write(str(percent))
file.close()
示例11: test
# 需要导入模块: from coverage import Coverage [as 别名]
# 或者: from coverage.Coverage import report [as 别名]
def test(config, tests=(), fail_fast=False, verbosity=1, with_coverage=False, with_lint=False):
from coverage import Coverage
from django import setup
from django.conf import settings
from django.conf.urls import url
from django.http import HttpResponse
from django.test.runner import DiscoverRunner
with_coverage = with_coverage and not tests
with_lint = with_lint and not tests
settings.configure(
DEBUG=True,
ALLOWED_HOSTS=['*'],
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
ROOT_URLCONF=(
url(r'^test$', lambda request: HttpResponse('test'), name='test'),
),
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'arcutils',
),
MIDDLEWARE_CLASSES=[],
LDAP={
'default': {
'host': 'ldap://ldap-login.oit.pdx.edu',
'username': '',
'password': '',
'search_base': 'ou=people,dc=pdx,dc=edu',
}
},
TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
]
}
}],
)
setup()
runner = DiscoverRunner(failfast=fail_fast, verbosity=verbosity)
if with_coverage:
coverage = Coverage(source=['arcutils'])
coverage.start()
if tests:
num_errors = runner.run_tests(tests)
else:
num_errors = runner.run_tests(['arcutils'])
if num_errors:
abort(code=num_errors, message='Test failure(s) encountered; aborting')
if with_coverage:
coverage.stop()
coverage.report()
if with_lint:
lint(config)
示例12: Coverage
# 需要导入模块: from coverage import Coverage [as 别名]
# 或者: from coverage.Coverage import report [as 别名]
# usage:
# run_tests.py [PYTEST_ARGS]
import os
import subprocess
import sys
from coverage import Coverage
SHELL = sys.platform == 'win32'
if __name__ == '__main__':
command = ['py.test']
if os.environ.get('WITH_COVERAGE') == '1':
command.extend(['--cov=rinoh', '--cov-report='])
if os.environ.get('BASETEMP'):
command.append('--basetemp={}'.format(os.environ['BASETEMP']))
command.extend(sys.argv[1:])
rc = subprocess.call(command, shell=SHELL)
if os.environ.get('WITH_COVERAGE') == '1':
cov = Coverage()
cov.load()
cov.combine()
cov.report(skip_covered=True)
cov.xml_report()
raise SystemExit(rc)
示例13: CoverageScript
# 需要导入模块: from coverage import Coverage [as 别名]
# 或者: from coverage.Coverage import report [as 别名]
class CoverageScript(object):
"""The command-line interface to coverage.py."""
def __init__(self):
self.global_option = False
self.coverage = None
def command_line(self, argv):
"""The bulk of the command line interface to coverage.py.
`argv` is the argument list to process.
Returns 0 if all is well, 1 if something went wrong.
"""
# Collect the command-line options.
if not argv:
show_help(topic='minimum_help')
return OK
# The command syntax we parse depends on the first argument. Global
# switch syntax always starts with an option.
self.global_option = argv[0].startswith('-')
if self.global_option:
parser = GlobalOptionParser()
else:
parser = CMDS.get(argv[0])
if not parser:
show_help("Unknown command: '%s'" % argv[0])
return ERR
argv = argv[1:]
ok, options, args = parser.parse_args_ok(argv)
if not ok:
return ERR
# Handle help and version.
if self.do_help(options, args, parser):
return OK
# Listify the list options.
source = unshell_list(options.source)
omit = unshell_list(options.omit)
include = unshell_list(options.include)
debug = unshell_list(options.debug)
# Do something.
self.coverage = Coverage(
data_suffix=options.parallel_mode,
cover_pylib=options.pylib,
timid=options.timid,
branch=options.branch,
config_file=options.rcfile,
source=source,
omit=omit,
include=include,
debug=debug,
concurrency=options.concurrency,
check_preimported=True,
context=options.context,
)
if options.action == "debug":
return self.do_debug(args)
elif options.action == "erase":
self.coverage.erase()
return OK
elif options.action == "run":
return self.do_run(options, args)
elif options.action == "combine":
if options.append:
self.coverage.load()
data_dirs = args or None
self.coverage.combine(data_dirs, strict=True)
self.coverage.save()
return OK
# Remaining actions are reporting, with some common options.
report_args = dict(
morfs=unglob_args(args),
ignore_errors=options.ignore_errors,
omit=omit,
include=include,
)
# We need to be able to import from the current directory, because
# plugins may try to, for example, to read Django settings.
sys.path.insert(0, '')
self.coverage.load()
total = None
if options.action == "report":
total = self.coverage.report(
show_missing=options.show_missing,
skip_covered=options.skip_covered,
**report_args
#.........这里部分代码省略.........