Python pytest 模块,main() 实例源码

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

项目:radar    作者:amoose136    | 项目源码 | 文件源码
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)
项目:django-strict    作者:kyle-eshares    | 项目源码 | 文件源码
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)
项目: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)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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)
项目:pysaxon    作者:ajelenak    | 项目源码 | 文件源码
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)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
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
项目:jarvis    作者:BastienFaure    | 项目源码 | 文件源码
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'])
项目:lazyutils    作者:fabiommendes    | 项目源码 | 文件源码
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'])
项目:2017.1-PlataformaJogosUnB    作者:fga-gpp-mds    | 项目源码 | 文件源码
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)
项目:freqtrade    作者:gcarq    | 项目源码 | 文件源码
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
项目:beeswax-api    作者:hbmartin    | 项目源码 | 文件源码
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'])
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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)
项目:flash_services    作者:textbook    | 项目源码 | 文件源码
def run_tests(self):
        import pytest
        errcode = pytest.main(self.test_args)
        sys.exit(errcode)
项目:nidaqmx-python    作者:ni    | 项目源码 | 文件源码
def run_tests(self):
        import pytest
        pytest.main(self.test_args)
项目:polyaxon-cli    作者:polyaxon    | 项目源码 | 文件源码
def run_tests(self):
        import pytest
        errcode = pytest.main(self.test_args)
        sys.exit(errcode)
项目:django-asset-definitions    作者:andreyfedoseev    | 项目源码 | 文件源码
def run_tests(self):
        # import here, cause outside the eggs aren't loaded
        import pytest
        errno = pytest.main(self.pytest_args)
        sys.exit(errno)
项目:wiki-to-doc    作者:serra    | 项目源码 | 文件源码
def execute(*args):
    import pytest
    return pytest.main(['-x', 'tests', '-m', 'not slow']) == 0
项目:pymarsys    作者:transcovo    | 项目源码 | 文件源码
def run_tests(self):
        import pytest

        errno = pytest.main(self.pytest_args)
        sys.exit(errno)
项目:segno    作者:heuer    | 项目源码 | 文件源码
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
项目:segno    作者:heuer    | 项目源码 | 文件源码
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
项目:segno    作者:heuer    | 项目源码 | 文件源码
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
项目:segno    作者:heuer    | 项目源码 | 文件源码
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)
项目:segno    作者:heuer    | 项目源码 | 文件源码
def test_terminal(capsys):
    cli.main(['test'])
    out, err = capsys.readouterr()
    assert out


# -- PNG
项目:requirements-tools    作者:Yelp    | 项目源码 | 文件源码
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:])
项目:astrobase    作者:waqasbhatti    | 项目源码 | 文件源码
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)
项目:graphene-custom-directives    作者:ekampf    | 项目源码 | 文件源码
def run_tests(self):
        import pytest
        errcode = pytest.main(self.test_args)
        sys.exit(errcode)
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def test_sqlalchemy(self):
        pytest.main(["-n", "4", "-q"])
项目:pybluetooth    作者:pebble    | 项目源码 | 文件源码
def run_tests(self):
        # import here because outside the eggs aren't loaded
        import pytest
        errno = pytest.main(["-v"])
        sys.exit(errno)
项目:senf    作者:quodlibet    | 项目源码 | 文件源码
def run(self):
        import pytest
        errno = pytest.main(self.pytest_args)
        if errno != 0:
            sys.exit(errno)
项目:django-elasticsearch-dsl-drf    作者:barseghyanartur    | 项目源码 | 文件源码
def main():
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.testing")
    sys.path.insert(0, "src")
    sys.path.insert(0, "examples/simple")
    return pytest.main()
项目:poco    作者:shiwaforce    | 项目源码 | 文件源码
def run(self):
        import pytest
        rcode = pytest.main(self.test_args)
        sys.exit(rcode)
项目:h1-python    作者:uber-common    | 项目源码 | 文件源码
def run_tests(self):
        import pytest
        errcode = pytest.main(self.test_args)
        sys.exit(errcode)
项目:dractor    作者:VerizonDigital    | 项目源码 | 文件源码
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
#
项目:errcron    作者:attakei    | 项目源码 | 文件源码
def run_tests(self):
        # import here, cause outside the eggs aren't loaded
        import pytest
        errno = pytest.main(self.pytest_args)
        sys.exit(errno)
项目:wsstat    作者:Fitblip    | 项目源码 | 文件源码
def run_tests(self):
        import pytest
        errcode = pytest.main(self.test_args)
        sys.exit(errcode)
项目:thorn    作者:robinhood    | 项目源码 | 文件源码
def run_tests(self):
        import pytest
        sys.exit(pytest.main(self.pytest_args))
项目:formatizer    作者:fgimian    | 项目源码 | 文件源码
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
项目:octoconf    作者:andras-tim    | 项目源码 | 文件源码
def run_tests(self):
        import pytest
        exit_code = pytest.main(self.pytest_args)
        sys.exit(exit_code)
项目:python-ceph-cfg    作者:oms4suse    | 项目源码 | 文件源码
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)
项目:chrome-prerender    作者:bosondata    | 项目源码 | 文件源码
def run_tests(self):
        import pytest
        errno = pytest.main(self.pytest_args)
        sys.exit(errno)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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"))
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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
项目:uniq    作者:CiscoDevNet    | 项目源码 | 文件源码
def run_tests(self):
        #import here, cause outside the eggs aren't loaded
        import pytest
        errno = pytest.main(self.pytest_args)
        sys.exit(errno)
项目:http    作者:grappa-py    | 项目源码 | 文件源码
def run_tests(self):
        # import here, cause outside the eggs aren't loaded
        import pytest
        errno = pytest.main(self.test_args)
        sys.exit(errno)
项目: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)
项目:pyprometheus    作者:Lispython    | 项目源码 | 文件源码
def run_tests(self):
        # import here, cause outside the eggs aren't loaded
        import pytest
        errno = pytest.main(self.pytest_args)
        sys.exit(errno)
项目:pushkin    作者:Nordeus    | 项目源码 | 文件源码
def run_tests():
    import pytest
    pytest.main(tests_directory_path)
    create_database()
项目:pythonVSCode    作者:DonJayamanne    | 项目源码 | 文件源码
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
项目:django-include    作者:chrisseto    | 项目源码 | 文件源码
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)