Python pytest.exit() Examples

The following are 30 code examples for showing how to use pytest.exit(). 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: pytest-forked   Author: pytest-dev   File: __init__.py    License: MIT License 6 votes vote down vote up
def forked_run_report(item):
    # for now, we run setup/teardown in the subprocess
    # XXX optionally allow sharing of setup/teardown
    from _pytest.runner import runtestprotocol
    EXITSTATUS_TESTEXIT = 4
    import marshal

    def runforked():
        try:
            reports = runtestprotocol(item, log=False)
        except KeyboardInterrupt:
            os._exit(EXITSTATUS_TESTEXIT)
        return marshal.dumps([serialize_report(x) for x in reports])

    ff = py.process.ForkedFunc(runforked)
    result = ff.waitfinish()
    if result.retval is not None:
        report_dumps = marshal.loads(result.retval)
        return [runner.TestReport(**x) for x in report_dumps]
    else:
        if result.exitstatus == EXITSTATUS_TESTEXIT:
            pytest.exit("forked test item %s raised Exit" % (item,))
        return [report_process_crash(item, result)] 
Example 2
Project: pytest   Author: pytest-dev   File: test_unittest.py    License: MIT License 6 votes vote down vote up
def test_exit_outcome(testdir):
    testdir.makepyfile(
        test_foo="""
        import pytest
        import unittest

        class MyTestCase(unittest.TestCase):
            def test_exit_outcome(self):
                pytest.exit("pytest_exit called")

            def test_should_not_run(self):
                pass
    """
    )
    result = testdir.runpytest()
    result.stdout.fnmatch_lines(["*Exit: pytest_exit called*", "*= no tests ran in *"]) 
Example 3
Project: pytest   Author: pytest-dev   File: test_main.py    License: MIT License 6 votes vote down vote up
def test_wrap_session_exit_sessionfinish(
    returncode: Optional[int], testdir: Testdir
) -> None:
    testdir.makeconftest(
        """
        import pytest
        def pytest_sessionfinish():
            pytest.exit(msg="exit_pytest_sessionfinish", returncode={returncode})
    """.format(
            returncode=returncode
        )
    )
    result = testdir.runpytest()
    if returncode:
        assert result.ret == returncode
    else:
        assert result.ret == ExitCode.NO_TESTS_COLLECTED
    assert result.stdout.lines[-1] == "collected 0 items"
    assert result.stderr.lines == ["Exit: exit_pytest_sessionfinish"] 
Example 4
Project: tildemush   Author: vilmibm   File: async_test.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_create_oneway_exit(client):
    vil = await client.setup_user('vilmibm')
    await client.assert_next('STATE', 'STATE')
    sanctum = GameObject.get(
        GameObject.author==vil,
        GameObject.is_sanctum==True)
    GameWorld.put_into(sanctum, vil.player_obj)

    await client.assert_next('STATE', 'STATE', 'STATE')

    await client.send('COMMAND create exit "Rusty Door" east god/foyer A rusted, metal door', [
        'COMMAND OK',
        'STATE',
        'STATE',
        'You breathed light into a whole new exit'])
    await client.send('COMMAND go east', [
        'STATE',
        'COMMAND OK',
        'STATE',
        'STATE',
        'STATE',
        'You materialize'])

    foyer = GameObject.get(GameObject.shortname=='god/foyer')
    assert vil.player_obj in foyer.contains 
Example 5
Project: pylangacq   Author: jacksonllee   File: test_chat.py    License: MIT License 6 votes vote down vote up
def test_download_and_extract_brown_zip_file():  # pragma: no cover
    """pytest runs tests in the same order they are defined in the test
    module, and so this test for downloading and unzipping the Brown zip
    data file runs first. If download fails, abort all tests."""
    try:
        with open(REMOTE_BROWN_ZIP_PATH, "wb") as f:
            with requests.get(REMOTE_BROWN_URL) as r:
                f.write(r.content)
    except Exception as e:
        msg = (
            "Error in downloading {}: "
            "network problems or invalid URL for Brown zip? "
            "If URL needs updating, tutorial.rst in docs "
            "has to be updated as well.".format(REMOTE_BROWN_URL)
        )
        try:
            raise e
        finally:
            pytest.exit(msg)
    else:
        # If download succeeds, unzip the Brown zip file.
        with zipfile.ZipFile(REMOTE_BROWN_ZIP_PATH) as zip_file:
            zip_file.extractall()
        # TODO compare the local eve.cha and CHILDES's 010600a.cha
        # if there are differences, CHILDES has updated data and may break us 
Example 6
Project: cassandra-dtest   Author: apache   File: conftest.py    License: Apache License 2.0 5 votes vote down vote up
def check_required_loopback_interfaces_available():
    """
    We need at least 3 loopback interfaces configured to run almost all dtests. On Linux, loopback
    interfaces are automatically created as they are used, but on Mac they need to be explicitly
    created. Check if we're running on Mac (Darwin), and if so check we have at least 3 loopback
    interfaces available, otherwise bail out so we don't run the tests in a known bad config and
    give the user some helpful advice on how to get their machine into a good known config
    """
    if platform.system() == "Darwin":
        if len(ni.ifaddresses('lo0')[AF_INET]) < 9:
            pytest.exit("At least 9 loopback interfaces are required to run dtests. "
                            "On Mac you can create the required loopback interfaces by running "
                            "'for i in {1..9}; do sudo ifconfig lo0 alias 127.0.0.$i up; done;'") 
Example 7
Project: cassandra-dtest   Author: apache   File: conftest.py    License: Apache License 2.0 5 votes vote down vote up
def dtest_config(request):
    dtest_config = DTestConfig()
    dtest_config.setup(request)

    # if we're on mac, check that we have the required loopback interfaces before doing anything!
    check_required_loopback_interfaces_available()

    try:
        if dtest_config.cassandra_dir is not None:
            validate_install_dir(dtest_config.cassandra_dir)
    except Exception as e:
        pytest.exit("{}. Did you remember to build C*? ('ant clean jar')".format(e))

    yield dtest_config 
Example 8
Project: pytest   Author: pytest-dev   File: test_runner.py    License: MIT License 5 votes vote down vote up
def test_exit_propagates(self, testdir) -> None:
        try:
            testdir.runitem(
                """
                import pytest
                def test_func():
                    raise pytest.exit.Exception()
            """
            )
        except pytest.exit.Exception:
            pass
        else:
            assert False, "did not raise" 
Example 9
Project: pytest   Author: pytest-dev   File: test_runner.py    License: MIT License 5 votes vote down vote up
def test_pytest_exit() -> None:
    with pytest.raises(pytest.exit.Exception) as excinfo:
        pytest.exit("hello")
    assert excinfo.errisinstance(pytest.exit.Exception) 
Example 10
Project: pytest   Author: pytest-dev   File: test_runner.py    License: MIT License 5 votes vote down vote up
def test_pytest_exit_msg(testdir) -> None:
    testdir.makeconftest(
        """
    import pytest

    def pytest_configure(config):
        pytest.exit('oh noes')
    """
    )
    result = testdir.runpytest()
    result.stderr.fnmatch_lines(["Exit: oh noes"]) 
Example 11
Project: pytest   Author: pytest-dev   File: test_runner.py    License: MIT License 5 votes vote down vote up
def test_pytest_exit_returncode(testdir) -> None:
    testdir.makepyfile(
        """\
        import pytest
        def test_foo():
            pytest.exit("some exit msg", 99)
    """
    )
    result = testdir.runpytest()
    result.stdout.fnmatch_lines(["*! *Exit: some exit msg !*"])

    assert _strip_resource_warnings(result.stderr.lines) == []
    assert result.ret == 99

    # It prints to stderr also in case of exit during pytest_sessionstart.
    testdir.makeconftest(
        """\
        import pytest

        def pytest_sessionstart():
            pytest.exit("during_sessionstart", 98)
        """
    )
    result = testdir.runpytest()
    result.stdout.fnmatch_lines(["*! *Exit: during_sessionstart !*"])
    assert _strip_resource_warnings(result.stderr.lines) == [
        "Exit: during_sessionstart"
    ]
    assert result.ret == 98 
Example 12
Project: agent-python-pytest   Author: reportportal   File: service.py    License: Apache License 2.0 5 votes vote down vote up
def _stop_if_necessary(self):
        """
        Stop tests if any error occurs.

        :return: None
        """
        try:
            exc, msg, tb = self._errors.get(False)
            traceback.print_exception(exc, msg, tb)
            sys.stderr.flush()
            if not self.ignore_errors:
                pytest.exit(msg)
        except queue.Empty:
            pass 
Example 13
Project: parsec-cloud   Author: Scille   File: conftest.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def pytest_configure(config):
    # Patch pytest-trio
    patch_pytest_trio()
    # Configure structlog to redirect everything in logging
    structlog.configure(
        logger_factory=structlog.stdlib.LoggerFactory(),
        processors=[
            structlog.processors.StackInfoRenderer(),
            structlog.processors.format_exc_info,
            structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S"),
            structlog.stdlib.add_logger_name,
            structlog.stdlib.add_log_level,
            structlog.dev.ConsoleRenderer(),
        ],
    )
    # Lock configuration
    structlog.configure = lambda *args, **kwargs: None
    # Add helper to caplog
    patch_caplog()
    if config.getoption("--run-postgresql-cluster"):
        pgurl = bootstrap_postgresql_testbed()
        capturemanager = config.pluginmanager.getplugin("capturemanager")
        if capturemanager:
            capturemanager.suspend(in_=True)
        print(f"usage: PG_URL={pgurl} py.test --postgresql tests")
        input("Press enter when you're done with...")
        pytest.exit("bye")
    elif config.getoption("--postgresql") and not is_xdist_master(config):
        bootstrap_postgresql_testbed() 
Example 14
Project: ambassador   Author: datawire   File: t_envoy_logs.py    License: Apache License 2.0 5 votes vote down vote up
def check(self):
        cmd = ShellCommand("kubectl", "exec", self.path.k8s, "cat", self.log_path)
        if not cmd.check("check envoy access log"):
            pytest.exit("envoy access log does not exist")

        for line in cmd.stdout.splitlines():
            assert access_log_entry_regex.match(line), f"{line} does not match {access_log_entry_regex}" 
Example 15
Project: ambassador   Author: datawire   File: abstract_tests.py    License: Apache License 2.0 5 votes vote down vote up
def queries(self):
        if DEV:
            cmd = ShellCommand("docker", "ps", "-qf", "name=%s" % self.path.k8s)

            if not cmd.check(f'docker check for {self.path.k8s}'):
                if not cmd.stdout.strip():
                    log_cmd = ShellCommand("docker", "logs", self.path.k8s, stderr=subprocess.STDOUT)

                    if log_cmd.check(f'docker logs for {self.path.k8s}'):
                        print(cmd.stdout)

                    pytest.exit(f'container failed to start for {self.path.k8s}')

        return () 
Example 16
Project: pyglet   Author: pyglet   File: event_loop.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def handle_answer(self):
        if self.answer is None:
            raise Exception('Did not receive valid input in question window')
        elif self.answer == self.key_fail:
            # TODO: Ask input
            pytest.fail('Tester marked test failed')
        elif self.answer == self.key_skip:
            pytest.skip('Tester marked test skipped')
        elif self.answer == self.key_quit:
            pytest.exit('Tester requested to quit') 
Example 17
Project: pyglet   Author: pyglet   File: event_loop.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def interrupt_event_loop(self, *args, **kwargs):
        pyglet.app.exit() 
Example 18
Project: tildemush   Author: vilmibm   File: tm_test_case.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        if os.environ.get('TILDEMUSH_ENV') != 'test':
            pytest.exit('Run tildemush tests with TILDEMUSH_ENV=test') 
Example 19
Project: tildemush   Author: vilmibm   File: async_test.py    License: GNU General Public License v3.0 5 votes vote down vote up
def state(event_loop):
    if os.environ.get('TILDEMUSH_ENV') != 'test':
        pytest.exit('Run tildemush tests with TILDEMUSH_ENV=test')
    reset_db()
    GameWorld.reset()
    gs = GameServer(GameWorld, loop=event_loop, logger=mock.Mock(), port=5555)
    server_future = gs._get_ws_server()
    asyncio.ensure_future(server_future, loop=event_loop)
    yield
    server_future.ws_server.server.close() 
Example 20
Project: tildemush   Author: vilmibm   File: async_test.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_create_twoway_exit_via_world_perms(client):
    vil = await client.setup_user('vilmibm')
    await client.assert_next('STATE', 'STATE')
    vil = UserAccount.get(UserAccount.username=='vilmibm')
    foyer = GameObject.get(GameObject.shortname=='god/foyer')
    foyer.set_perm('write', 'world')

    await client.send('COMMAND create room "Crystal Cube" a cube-shaped room made entirely of crystal.', [
        'COMMAND OK',
        'You breathed light into a whole new room'])

    cube = GameObject.get(GameObject.shortname.startswith('vilmibm/crystal-cube'))

    await client.send(
        'COMMAND create exit "Rusty Door" east {} A rusted, metal door'.format(cube.shortname), [
            'STATE',
            'COMMAND OK',
            'STATE',
            'STATE',
            'You breathed light into a whole new exit'])

    await client.send('COMMAND go east', [
        'STATE',
        'COMMAND OK',
        'STATE',
        'STATE',
        'STATE',
        'You materialize'])

    assert vil.player_obj in cube.contains
    assert vil.player_obj not in foyer.contains

    await client.send('COMMAND go west', [
        'COMMAND OK',
        'STATE',
        'STATE',
        'STATE',
        'You materialize'])

    assert vil.player_obj not in cube.contains
    assert vil.player_obj in foyer.contains 
Example 21
Project: pennylane   Author: XanaduAI   File: conftest.py    License: Apache License 2.0 5 votes vote down vote up
def device(device_kwargs):
    """Fixture to create a device."""

    __tracebackhide__ = True

    def _device(n_wires):
        device_kwargs["wires"] = n_wires

        try:
            dev = qml.device(**device_kwargs)
        except qml.DeviceError:
            # exit the tests if the device cannot be created
            pytest.exit(
                "Device {} cannot be created. To run the device tests on an external device, the "
                "plugin and all of its dependencies must be installed.".format(
                    device_kwargs["name"]
                )
            )

        capabilities = dev.capabilities()
        if "model" not in capabilities or not capabilities["model"] == "qubit":
            # exit the tests if device based on cv model (currently not supported)
            pytest.exit("The device test suite currently only runs on qubit-based devices.")

        return dev

    return _device 
Example 22
Project: nanog77-nrfu-tutorial   Author: jeremyschulman   File: conftest.py    License: Apache License 2.0 5 votes vote down vote up
def pytest_sessionstart(session):
    config = session.config

    # Store the instance of the Path to the test-case dir since we'll be using
    # it many times in each of the test function modules.

    config._nrfu = NRFUconfig()
    config._nrfu.testcases_dir = Path(config.option.nrfu_testcasedir).absolute()

    device_name = config.getoption("--nrfu-device")
    ssh_config_file = config.getoption('--ssh-config')
    dev = Device(device_name, ssh_config_file=ssh_config_file)

    # first probe IP/hostname of the device to ensure it is reachable.

    if not dev.probe():
        pytest.exit(f"Device unreachable, check --nrfu-device value: {device_name}.")

    # next try to run a show command to ensure the credentials are valid.

    try:
        dev.execute('show version')

    except Exception as exc:
        if isinstance(exc, ConnectionError):
            pytest.exit("Unable to access device.\nCheck you $EOS_USER and $EOS_PASSWORD env")

        pytest.exit(f"Unable to access device {device_name}: {str(exc)}")

    # I am now going to attach this device object to the session config data
    # since we have it, and we can then reference it for use by the device
    # fixture so we don't need to re-connect to the device a second time. ;-)

    config._nrfu.device = dev 
Example 23
Project: pytest-cloud   Author: pytest-dev   File: plugin.py    License: MIT License 5 votes vote down vote up
def check_options(config):
    """Process options to manipulate (produce other options) important for pytest-cloud."""
    if getattr(config, 'slaveinput', {}).get('slaveid', 'local') == 'local' and config.option.cloud_nodes:
        patches.apply_patches()
        mem_per_process = config.option.cloud_mem_per_process
        if mem_per_process:
            mem_per_process = mem_per_process * 1024 * 1024
        virtualenv_path = config.option.cloud_virtualenv_path
        chdir = config.option.cloud_chdir
        python = config.option.cloud_python
        node_specs = get_nodes_specs(
            config.option.cloud_nodes,
            chdir=chdir,
            python=python,
            virtualenv_path=virtualenv_path,
            rsync_max_processes=config.option.cloud_rsync_max_processes,
            rsync_bandwidth_limit=config.option.cloud_rsync_bandwidth_limit,
            max_processes=config.option.cloud_max_processes,
            mem_per_process=mem_per_process,
            rsync_cipher=config.option.cloud_rsync_cipher,
            config=config)
        if node_specs:
            print('Scheduling with {0} parallel test sessions'.format(len(node_specs)))
        if not node_specs:
            pytest.exit('None of the given test nodes are able to serve as a test node due to capabilities')
        config.option.tx += node_specs
        config.option.dist = 'load' 
Example 24
Project: pytest-plugins   Author: man-group   File: postgres.py    License: MIT License 5 votes vote down vote up
def __init__(self, database_name="integration", skip_on_missing_postgres=False, **kwargs):
        self.database_name = database_name
        # TODO make skip configurable with a pytest flag
        self._fail = pytest.skip if skip_on_missing_postgres else pytest.exit
        super(PostgresServer, self).__init__(workspace=None, delete=True, preserve_sys_path=False, **kwargs) 
Example 25
Project: dcos   Author: dcos   File: common.py    License: Apache License 2.0 5 votes vote down vote up
def stop(self):
        """Stop the LogCatcher instance and perform resource cleanup."""
        self._termination_flag.set()

        while self._logger_thread.is_alive():
            self._logger_thread.join(timeout=0.5)
            log.info("Waiting for LogCatcher thread to exit")

        log.info("LogCatcher thread has terminated, bye!") 
Example 26
Project: dcos   Author: dcos   File: common.py    License: Apache License 2.0 5 votes vote down vote up
def start(self):
        """Start a subprocess

        This method makes python actually spawn the subprocess and wait for it
        to finish initializing.
        """
        self._start_subprocess()

        self._register_stdout_stderr_to_logcatcher()

        if not self._wait_for_subprocess_to_finish_init():
            self.stop()
            pytest.exit("Failed to start `{}` process".format(self.id)) 
Example 27
Project: dcos   Author: dcos   File: common.py    License: Apache License 2.0 5 votes vote down vote up
def stop(self):
        """Stop ManagedSubprocess instance and perform a cleanup

        This method makes sure that there are no child processes left after
        the object destruction finalizes. In case when a process cannot stop
        on it's own, it's forced to using SIGTERM/SIGKILL.
        """
        self._process.poll()
        if self._process.returncode is not None:
            msg_fmt = "`%s` process has already terminated with code `%s`"
            pytest.exit(msg_fmt % (self.id, self._process.returncode))
            return

        log.info("Send SIGINT to `%s` session leader", self.id)
        self._process.send_signal(signal.SIGINT)
        try:
            self._process.wait(self._EXIT_TIMEOUT / 2.0)
        except subprocess.TimeoutExpired:
            log.info("Send SIGTERM to `%s` session leader", self.id)
            self._process.send_signal(signal.SIGTERM)
            try:
                self._process.wait(self._EXIT_TIMEOUT / 2.0)
            except subprocess.TimeoutExpired:
                log.info("Send SIGKILL to all `%s` processess", self.id)
                os.killpg(os.getpgid(self._process.pid), signal.SIGKILL)
                log.info("wait() for `%s` session leader to die", self.id)
                self._process.wait()

        log.info("`%s` session leader has terminated", self.id) 
Example 28
Project: dart-fss   Author: josw123   File: test_auth.py    License: MIT License 5 votes vote down vote up
def dart_api_key():
    api_key = os.getenv("DART_API_KEY")
    if api_key is None:
        pytest.exit('DART_API_KEY not set')
    else:
        return get_api_key() 
Example 29
Project: deckard   Author: CZ-NIC   File: deckard_pytest.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def check_platform():
    if sys.platform == 'windows':
        pytest.exit('Not supported at all on Windows')


# Suppress extensive Augeas logging 
Example 30
Project: deckard   Author: CZ-NIC   File: conftest.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def check_log_level_xdist(level):
    if level < logging.ERROR:
        pytest.exit("Advanced logging not available while running with xdist "
                    "(try ommiting -n option)")