Python pytest.main() Examples

The following are 30 code examples of pytest.main(). 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 also want to check out all available functions/classes of the module pytest , or try the search function .
Example #1
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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
Source 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)