def run_tests_if_main(show_coverage=False):
""" Run tests in a given file if it is run as a script
Coverage is reported for running this single test. Set show_coverage to
launch the report in the web browser.
"""
local_vars = inspect.currentframe().f_back.f_locals
if not local_vars.get('__name__', '') == '__main__':
return
# we are in a "__main__"
os.chdir(ROOT_DIR)
fname = str(local_vars['__file__'])
_clear_imageio()
_enable_faulthandler()
pytest.main('-v -x --color=yes --cov imageio '
'--cov-config .coveragerc --cov-report html %s' % repr(fname))
if show_coverage:
import webbrowser
fname = os.path.join(ROOT_DIR, 'htmlcov', 'index.html')
webbrowser.open_new_tab(fname)
python类main()的实例源码
def run_tests(self, test_labels):
"""Run pytest and return the exitcode.
It translates some of Django's test command option to pytest's.
"""
import pytest
argv = []
if self.verbosity == 0:
argv.append('--quiet')
if self.verbosity == 2:
argv.append('--verbose')
if self.failfast:
argv.append('--exitfirst')
if self.keepdb:
argv.append('--reuse-db')
argv.extend(test_labels)
return pytest.main(argv)
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)
def inline_runsource(self, source, *cmdlineargs):
"""Run a test module in process using ``pytest.main()``.
This run writes "source" into a temporary file and runs
``pytest.main()`` on it, returning a :py:class:`HookRecorder`
instance for the result.
:param source: The source code of the test module.
:param cmdlineargs: Any extra command line arguments to use.
:return: :py:class:`HookRecorder` instance of the result.
"""
p = self.makepyfile(source)
l = list(cmdlineargs) + [p]
return self.inline_run(*l)
def run(self):
import pytest
import _pytest.main
# Customize messages for pytest exit codes...
msg = {_pytest.main.EXIT_OK: 'OK',
_pytest.main.EXIT_TESTSFAILED: 'Tests failed',
_pytest.main.EXIT_INTERRUPTED: 'Interrupted',
_pytest.main.EXIT_INTERNALERROR: 'Internal error',
_pytest.main.EXIT_USAGEERROR: 'Usage error',
_pytest.main.EXIT_NOTESTSCOLLECTED: 'No tests collected'}
bldobj = self.distribution.get_command_obj('build')
bldobj.run()
exitcode = pytest.main(self.pytest_opts)
print(msg[exitcode])
sys.exit(exitcode)
def _test_style(filename, ignore):
""" Test style for a certain file.
"""
if isinstance(ignore, (list, tuple)):
ignore = ','.join(ignore)
orig_dir = os.getcwd()
orig_argv = sys.argv
os.chdir(ROOT_DIR)
sys.argv[1:] = [filename]
sys.argv.append('--ignore=' + ignore)
try:
from flake8.main import main
main()
except SystemExit as ex:
if ex.code in (None, 0):
return False
else:
return True
finally:
os.chdir(orig_dir)
sys.argv[:] = orig_argv
def main(args=None):
"""
Called with ``python -m jarvis.tests``: run main test suite.
"""
parser = get_parser()
args = parser.parse_args(args)
# Check if pytest is available
try:
import pytest
except ImportError:
raise SystemExit(
'You need py.test to run the test suite.\n'
'You can install it using your distribution package manager or\n'
' $ python -m pip install pytest --user'
)
# Get data from test_module
import pentest.tests as test_module
test_path = os.path.abspath(os.path.dirname(test_module.__file__))
pytest.main([test_path, '-m', 'not documentation'])
def main(args=None):
"""
Called with ``python -m lazyutils.tests``: run main test suite.
"""
parser = get_parser()
args = parser.parse_args(args)
# Check if pytest is available
try:
import pytest
except ImportError:
raise SystemExit(
'You need py.test to run the test suite.\n'
'You can install it using your distribution package manager or\n'
' $ python -m pip install pytest --user'
)
# Get data from test_module
import lazyutils.tests as test_module
test_path = os.path.abspath(os.path.dirname(test_module.__file__))
pytest.main([test_path, '-m', 'not documentation'])
def run_tests(self, test_labels):
argv = []
if self.failfast:
argv.append('-x')
if self.verbosity == 0:
argv.append('-q')
elif self.verbosity == 1:
argv.append('-s')
argv.append('-v')
elif self.verbosity == 2:
argv.append('-s')
argv.append('-vv')
argv.extend(test_labels)
return pytest.main(argv)
def start_backtesting(args) -> None:
"""
Exports all args as environment variables and starts backtesting via pytest.
:param args: arguments namespace
:return:
"""
import pytest
os.environ.update({
'BACKTEST': 'true',
'BACKTEST_LIVE': 'true' if args.live else '',
'BACKTEST_CONFIG': args.config,
'BACKTEST_TICKER_INTERVAL': str(args.ticker_interval),
})
path = os.path.join(os.path.dirname(__file__), 'tests', 'test_backtesting.py')
pytest.main(['-s', path])
# Required json-schema for user specified config
def main(args=None):
"""
Called with ``python -m beeswax_api.tests``: run main test suite.
"""
parser = get_parser()
args = parser.parse_args(args)
# Check if pytest is available
try:
import pytest
except ImportError:
raise SystemExit(
'You need py.test to run the test suite.\n'
'You can install it using your distribution package manager or\n'
' $ python -m pip install pytest --user'
)
# Get data from test_module
import beeswax_api.tests as test_module
test_path = os.path.abspath(os.path.dirname(test_module.__file__))
pytest.main([test_path, '-m', 'not documentation'])
def inline_runsource(self, source, *cmdlineargs):
"""Run a test module in process using ``pytest.main()``.
This run writes "source" into a temporary file and runs
``pytest.main()`` on it, returning a :py:class:`HookRecorder`
instance for the result.
:param source: The source code of the test module.
:param cmdlineargs: Any extra command line arguments to use.
:return: :py:class:`HookRecorder` instance of the result.
"""
p = self.makepyfile(source)
l = list(cmdlineargs) + [p]
return self.inline_run(*l)
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
def run_tests(self):
import pytest
pytest.main(self.test_args)
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
def run_tests(self):
# import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno)
def execute(*args):
import pytest
return pytest.main(['-x', 'tests', '-m', 'not slow']) == 0
def run_tests(self):
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno)
def test_output():
out = io.BytesIO()
segno.make_qr('Good Times', error='M').save(out, kind='png', scale=10, color='red')
f = tempfile.NamedTemporaryFile('w', suffix='.png', delete=False)
f.close()
cli.main(['-e=M', '--scale=10', '--color=red', '--output={0}'.format(f.name), 'Good Times'])
f = open(f.name, 'rb')
content = f.read()
f.close()
os.unlink(f.name)
assert out.getvalue() == content
def test_output2():
out = io.BytesIO()
segno.make_qr('Good Times', error='M').save(out, kind='png', scale=10, color='red')
f = tempfile.NamedTemporaryFile('w', suffix='.png', delete=False)
f.close()
cli.main(['-e=M', '--scale=10', '--color=red', '--output={0}'.format(f.name), 'Good', 'Times'])
f = open(f.name, 'rb')
content = f.read()
f.close()
os.unlink(f.name)
assert out.getvalue() == content
def test_sequence_output():
directory = tempfile.mkdtemp()
assert 0 == len(os.listdir(directory))
cli.main(['--seq', '-v=1', '-e=m', '-o=' + os.path.join(directory, 'test.svg'), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'])
number_of_files = len(os.listdir(directory))
shutil.rmtree(directory)
assert 4 == number_of_files
def test_output(arg, ext, expected, mode):
f = tempfile.NamedTemporaryFile('w', suffix='.{0}'.format(ext), delete=False)
f.close()
try:
cli.main(['test', arg, f.name])
f = open(f.name, mode=mode)
val = f.read(len(expected))
f.close()
assert expected == val
finally:
os.unlink(f.name)
def test_terminal(capsys):
cli.main(['test'])
out, err = capsys.readouterr()
assert out
# -- PNG
def main(): # pragma: no cover
print('Checking requirements...')
# Forces quiet output and overrides pytest.ini
os.environ['PYTEST_ADDOPTS'] = '-q -s --tb=short'
return pytest.main([__file__.replace('pyc', 'py')] + sys.argv[1:])
def run_tests(self):
import shlex
#import here, cause outside the eggs aren't loaded
import pytest
if not self.pytest_args:
targs = []
else:
targs = shlex.split(self.pytest_args)
errno = pytest.main(targs)
sys.exit(errno)
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
def test_sqlalchemy(self):
pytest.main(["-n", "4", "-q"])
def run_tests(self):
# import here because outside the eggs aren't loaded
import pytest
errno = pytest.main(["-v"])
sys.exit(errno)
def run(self):
import pytest
errno = pytest.main(self.pytest_args)
if errno != 0:
sys.exit(errno)
def main():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.testing")
sys.path.insert(0, "src")
sys.path.insert(0, "examples/simple")
return pytest.main()