我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用pytest.main()。
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)
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 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 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 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()
def run(self): import pytest rcode = pytest.main(self.test_args) sys.exit(rcode)
def run_tests(self): """Customized run""" # deferred import import pytest # run pytest with empty array so pytest.ini takes complete control # need to use [] because of https://github.com/pytest-dev/pytest/issues/1110 errno = pytest.main([]) sys.exit(errno) # # Main logic #
def run_tests(self): import pytest sys.exit(pytest.main(self.pytest_args))
def run_tests(self): # Import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) # Read the long description from readme.rst
def run_tests(self): import pytest exit_code = pytest.main(self.pytest_args) sys.exit(exit_code)
def run_tests(self): import shlex #import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(shlex.split(self.pytest_args)) sys.exit(errno)
def pytest_addoption(parser): # group = parser.getgroup("pytester", "pytester (self-tests) options") parser.addoption('--lsof', action="store_true", dest="lsof", default=False, help=("run FD checks if lsof is available")) parser.addoption('--runpytest', default="inprocess", dest="runpytest", choices=("inprocess", "subprocess", ), help=("run pytest sub runs in tests using an 'inprocess' " "or 'subprocess' (python -m main) method"))
def inline_genitems(self, *args): """Run ``pytest.main(['--collectonly'])`` in-process. Retuns a tuple of the collected items and a :py:class:`HookRecorder` instance. This runs the :py:func:`pytest.main` function to run all of pytest inside the test process itself like :py:meth:`inline_run`. However the return value is a tuple of the collection items and a :py:class:`HookRecorder` instance. """ rec = self.inline_run("--collect-only", *args) items = [x.item for x in rec.getcalls("pytest_itemcollected")] return items, rec
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 run_tests(self): # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.test_args) sys.exit(errno)
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)
def run_tests(): import pytest pytest.main(tests_directory_path) create_database()
def main(): import os import sys from ptvsd.visualstudio_py_debugger import DONT_DEBUG, DEBUG_ENTRYPOINTS, get_code from ptvsd.attach_server import DEFAULT_PORT, enable_attach, wait_for_attach sys.path[0] = os.getcwd() os.chdir(sys.argv[1]) secret = sys.argv[2] port = int(sys.argv[3]) testFx = sys.argv[4] args = sys.argv[5:] DONT_DEBUG.append(os.path.normcase(__file__)) DEBUG_ENTRYPOINTS.add(get_code(main)) enable_attach(secret, ('127.0.0.1', port), redirect_output = False) sys.stdout.flush() print('READY') sys.stdout.flush() wait_for_attach() try: if testFx == 'pytest': import pytest pytest.main(args) else: import nose nose.run(argv=args) sys.exit() finally: pass
def test(ctx, watch=False, last_failing=False): """Run the tests. Note: --watch requires pytest-xdist to be installed. """ import pytest flake(ctx) args = [] if watch: args.append('-f') if last_failing: args.append('--lf') retcode = pytest.main(args) sys.exit(retcode)