Python pytest.main() Examples

The following are 30 code examples for showing how to use pytest.main(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module pytest , or try the search function .

Example 1
Project: python-netsurv   Author: sofia-netsurv   File: pytester.py    License: MIT License 7 votes vote down vote up
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)
        values = list(cmdlineargs) + [p]
        return self.inline_run(*values) 
Example 2
Project: recruit   Author: Frank-qlu   File: _tester.py    License: Apache License 2.0 6 votes vote down vote up
def test(extra_args=None):
    try:
        import pytest
    except ImportError:
        raise ImportError("Need pytest>=3.0 to run tests")
    try:
        import hypothesis  # noqa
    except ImportError:
        raise ImportError("Need hypothesis>=3.58 to run tests")
    cmd = ['--skip-slow', '--skip-network', '--skip-db']
    if extra_args:
        if not isinstance(extra_args, list):
            extra_args = [extra_args]
        cmd = extra_args
    cmd += [PKG]
    print("running: pytest {}".format(' '.join(cmd)))
    sys.exit(pytest.main(cmd)) 
Example 3
Project: sea   Author: shanbay   File: cmds.py    License: MIT License 6 votes vote down vote up
def generate(proto_path, protos):
    from grpc_tools import protoc
    well_known_path = os.path.join(os.path.dirname(protoc.__file__), '_proto')

    proto_out = os.path.join(os.getcwd(), 'protos')
    proto_path.append(well_known_path)
    proto_path_args = []
    for protop in proto_path:
        proto_path_args += ['--proto_path', protop]
    cmd = [
        'grpc_tools.protoc',
        *proto_path_args,
        '--python_out', proto_out,
        '--grpc_python_out', proto_out,
        *protos
    ]
    return protoc.main(cmd) 
Example 4
Project: pysaxon   Author: ajelenak   File: setup.py    License: Creative Commons Zero v1.0 Universal 6 votes vote down vote up
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) 
Example 5
Project: python-netsurv   Author: sofia-netsurv   File: pytester.py    License: MIT License 6 votes vote down vote up
def pytest_addoption(parser):
    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"
        ),
    )

    parser.addini(
        "pytester_example_dir", help="directory to take the pytester example files from"
    ) 
Example 6
Project: python-netsurv   Author: sofia-netsurv   File: pytester.py    License: MIT License 6 votes vote down vote up
def pytest_addoption(parser):
    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"
        ),
    )

    parser.addini(
        "pytester_example_dir", help="directory to take the pytester example files from"
    ) 
Example 7
Project: python-netsurv   Author: sofia-netsurv   File: pytester.py    License: MIT License 6 votes vote down vote up
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)
        values = list(cmdlineargs) + [p]
        return self.inline_run(*values) 
Example 8
Project: ciocheck   Author: ContinuumIO   File: tools.py    License: MIT License 5 votes vote down vote up
def run(self, paths):
        """Run pytest test suite."""
        cmd = paths + self.pytest_args
        print(cmd)

        try:
            with ShortOutput(self.cmd_root) as so:
                errno = pytest.main(cmd)
            output_lines = ''.join(so.output).lower()

            if 'FAIL Required test coverage'.lower() in output_lines:
                self.coverage_fail = True

            if errno != 0:
                print("pytest failed, code {errno}".format(errno=errno))
        except CoverageError as e:
            print("Test coverage failure: " + str(e))
            self.coverage_fail = True

        covered_lines = self.parse_coverage()
        pytest_report = self.parse_pytest_report()

        results = {'coverage': covered_lines}
        if pytest_report is not None:
            results['pytest'] = pytest_report
        return results 
Example 9
Project: invana-bot   Author: invanalabs   File: runtests.py    License: MIT License 5 votes vote down vote up
def run_tests_coverage():
    if __name__ == "__main__":
        pytest.main(PYTEST_ARGS) 
Example 10
Project: comport   Author: codeforamerica   File: manage.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test():
    """Run the tests."""
    import pytest
    exit_code = pytest.main([TEST_PATH, '-x', '--verbose'])
    return exit_code 
Example 11
Project: pysm4   Author: yang3yen   File: setup.py    License: MIT License 5 votes vote down vote up
def run_tests(self):
        import pytest

        errno = pytest.main(self.pytest_args)
        sys.exit(errno) 
Example 12
Project: pyspectator   Author: it-geeks-club   File: setup.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run_tests(self):
        # import here, cause outside the eggs aren't loaded
        import pytest
        err_no = pytest.main(self.pytest_args)
        sys.exit(err_no) 
Example 13
Project: sanic   Author: huge-success   File: setup.py    License: MIT License 5 votes vote down vote up
def run_tests(self):
        import shlex
        import pytest

        errno = pytest.main(shlex.split(self.pytest_args))
        sys.exit(errno) 
Example 14
Project: python-consul2   Author: poppyred   File: setup.py    License: MIT License 5 votes vote down vote up
def run_tests(self):
        import pytest
        errno = pytest.main(self.test_args)
        sys.exit(errno) 
Example 15
Project: eqllib   Author: endgameinc   File: setup.py    License: MIT License 5 votes vote down vote up
def run(self):
        """Run the flake8 linter."""
        self.distribution.fetch_build_eggs(test_requires)
        self.distribution.packages.append('tests')

        from flake8.main import Flake8Command
        flake8cmd = Flake8Command(self.distribution)
        flake8cmd.options_dict = {}
        flake8cmd.run() 
Example 16
Project: eqllib   Author: endgameinc   File: setup.py    License: MIT License 5 votes vote down vote up
def run_tests(self):
        """Run pytest."""
        self.distribution.fetch_build_eggs(test_requires)
        self.distribution.packages.append('tests')

        import pytest
        sys.exit(pytest.main(self.pytest_args)) 
Example 17
Project: indy-anoncreds   Author: hyperledger-archives   File: run_tests_multiple_times.py    License: Apache License 2.0 5 votes vote down vote up
def run():
    runs = 40
    fails = 0
    for x in range(runs):
        itr = x + 1
        print('running {}'.format(itr))
        # tst = 'test_greater_eq_predicate.py::testPredicateGreaterEqMultiIssuers'
        # result = pytest.main('-x --tb=long -n 7 {}'.format(tst))
        result = pytest.main('-x')
        failed = bool(result)
        fails += int(failed)
    print("{} runs, {} failures".format(runs, fails)) 
Example 18
Project: indy-anoncreds   Author: hyperledger-archives   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def run():
    import pytest
    pytest.main() 
Example 19
Project: pwnypack   Author: edibledinos   File: setup.py    License: MIT License 5 votes vote down vote up
def run_tests(self):
        import pytest
        errno = pytest.main(self.pytest_args)
        sys.exit(errno) 
Example 20
Project: symspellpy   Author: mammothb   File: setup.py    License: MIT License 5 votes vote down vote up
def run_tests(self):
        import shlex

        import pytest

        errno = pytest.main(shlex.split(self.pytest_args))
        sys.exit(errno)

# "setup.py publish" shortcut. 
Example 21
Project: simnibs   Author: simnibs   File: postinstall_simnibs.py    License: GNU General Public License v3.0 5 votes vote down vote up
def run_tests(args):
    ''' run tests on pytest '''
    import pytest
    exitcode = pytest.main(args)
    return exitcode 
Example 22
Project: respy   Author: OpenSourceEconomics   File: __init__.py    License: MIT License 5 votes vote down vote up
def test(*args, **kwargs):
    """Run basic tests of the package."""
    pytest.main([str(ROOT_DIR), *args], **kwargs) 
Example 23
Project: ds_store   Author: al45tair   File: setup.py    License: MIT License 5 votes vote down vote up
def run_tests(self):
        import pytest
        errno = pytest.main(self.test_args)
        sys.exit(errno) 
Example 24
Project: qutebrowser   Author: qutebrowser   File: run_profile.py    License: GNU General Public License v3.0 5 votes vote down vote up
def main():
    args, remaining = parse_args()
    tempdir = tempfile.mkdtemp()

    if args.profile_tool == 'none':
        profilefile = os.path.join(os.getcwd(), args.profile_file)
    else:
        profilefile = os.path.join(tempdir, 'profile')

    sys.argv = [sys.argv[0]] + remaining

    profiler = cProfile.Profile()

    if args.profile_test:
        import pytest
        profiler.runcall(pytest.main)
    else:
        profiler.runcall(qutebrowser.qutebrowser.main)

    # If we have an exception after here, we don't want the qutebrowser
    # exception hook to take over.
    sys.excepthook = sys.__excepthook__
    profiler.dump_stats(profilefile)

    if args.profile_tool == 'none':
        print("Profile data written to {}".format(profilefile))
    elif args.profile_tool == 'gprof2dot':
        # yep, shell=True. I know what I'm doing.
        subprocess.run(
            'gprof2dot -f pstats {} | dot -Tpng | feh -F -'.format(
                shlex.quote(profilefile)), shell=True, check=True)
    elif args.profile_tool == 'kcachegrind':
        callgraphfile = os.path.join(tempdir, 'callgraph')
        subprocess.run(['pyprof2calltree', '-k', '-i', profilefile,
                        '-o', callgraphfile], check=True)
    elif args.profile_tool == 'snakeviz':
        subprocess.run(['snakeviz', profilefile], check=True)
    elif args.profile_tool == 'tuna':
        subprocess.run(['tuna', profilefile], check=True)

    shutil.rmtree(tempdir) 
Example 25
Project: activitywatch   Author: ActivityWatch   File: integration_tests.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def test_integration(server_process):
    # This is just here so that the server_process fixture is initialized
    pass

    # exit_code = pytest.main(["./aw-server/tests", "-v"])
    # if exit_code != 0:
    #     pytest.fail("Tests exited with non-zero code: " + str(exit_code)) 
Example 26
Project: ipymd   Author: rossant   File: setup.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run_tests(self):
        #import here, cause outside the eggs aren't loaded
        import pytest
        errno = pytest.main(self.pytest_args)
        sys.exit(errno) 
Example 27
Project: beavy   Author: beavyHQ   File: manager.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def pytest(path=None, no_coverage=False, maxfail=0,  # noqa
           debug=False, verbose=False):
    import pytest

    arguments = []

    def add_path_with_coverage(x):
        arguments.append("--cov={}".format(x))
        arguments.append(x)

    def simple_add(x):
        arguments.append(x)

    if maxfail:
        arguments.append("--maxfail={}".format(maxfail))

    if verbose:
        arguments.append("-vv")

    if debug:
        arguments.append("--pdb")

    if no_coverage:
        add_path = simple_add
    else:
        arguments.extend(["--cov-config", ".coveragerc"])
        add_path = add_path_with_coverage

    if path:
        add_path(path)
    else:
        add_path("beavy")
        get_all_beavy_paths(add_path)

    exit(pytest.main(arguments)) 
Example 28
Project: coala-quickstart   Author: coala   File: setup.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def run_tests(self):
        # import here, cause outside the eggs aren't loaded
        import pytest
        errno = pytest.main(self.pytest_args)
        sys.exit(errno) 
Example 29
Project: NURBS-Python   Author: orbingol   File: setup.py    License: MIT License 5 votes vote down vote up
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) 
Example 30
Project: brownie   Author: eth-brownie   File: test.py    License: MIT License 5 votes vote down vote up
def main():
    args = docopt(__doc__)

    project_path = project.check_for_project(".")
    if project_path is None:
        raise ProjectNotFound

    # ensure imports are possible from anywhere in the project
    project.main._add_to_sys_path(project_path)

    if args["<path>"] is None:
        structure_config = _load_project_structure_config(project_path)
        args["<path>"] = project_path.joinpath(structure_config["tests"]).as_posix()

    pytest_args = [args["<path>"]]
    for opt, value in [(i, args[i]) for i in sorted(args) if i.startswith("-") and args[i]]:
        if value is True:
            pytest_args.append(opt)
        elif isinstance(value, str):
            pytest_args.extend([opt, value])

    return_code = pytest.main(pytest_args, ["pytest-brownie"])

    if return_code:
        # only exit with non-zero status to make testing easier
        sys.exit(return_code)