Python pytest.exit() Examples

The following are 30 code examples of pytest.exit(). 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 File: async_test.py    From tildemush with 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 #2
Source File: test_chat.py    From pylangacq with 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 #3
Source File: test_main.py    From pytest with 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
Source File: test_unittest.py    From pytest with 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 #5
Source File: __init__.py    From pytest-forked with 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 #6
Source File: async_test.py    From tildemush with 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 #7
Source File: conftest.py    From cassandra-dtest with 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
Source File: test_homework2.py    From sbcw with MIT License 5 votes vote down vote up
def setup_module(module):
    username = pytest.config.getoption('username')
    solution_module = f'homework2_{username}'

    try:
        namespace = __import__(f'solutions.{solution_module}')
    except ImportError:
        pytest.exit(f'{solution_module}.py does not exist')
    else:
        global solution
        solution = getattr(namespace, solution_module) 
Example #9
Source File: test_homework1.py    From sbcw with MIT License 5 votes vote down vote up
def setup_module(module):
    username = pytest.config.getoption('username')
    solution_module = f'homework1_{username}'

    try:
        namespace = __import__(f'solutions.{solution_module}')
    except ImportError:
        pytest.exit(f'{solution_module}.py does not exist')
    else:
        global solution
        solution = getattr(namespace, solution_module) 
Example #10
Source File: __init__.py    From vakt with Apache License 2.0 5 votes vote down vote up
def create_test_sql_engine():
    dsn = os.getenv('DATABASE_DSN')
    if not dsn:
        pytest.exit('Please set DATABASE_DSN env variable with the target database DSN, ex: sqlite:///:memory:')
    engine = create_engine(dsn, encoding='utf-8')
    try:
        engine.execute(text('select 1'))
    except OperationalError as e:
        pytest.exit('DATABASE_DSN is not correct. Error: %s' % e)
    return engine 
Example #11
Source File: conftest.py    From deckard with 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)") 
Example #12
Source File: deckard_pytest.py    From deckard with 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 #13
Source File: test_auth.py    From dart-fss with 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 #14
Source File: common.py    From dcos with 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 #15
Source File: common.py    From dcos with 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 #16
Source File: common.py    From dcos with 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 #17
Source File: postgres.py    From pytest-plugins with 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 #18
Source File: plugin.py    From pytest-cloud with 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 #19
Source File: conftest.py    From nanog77-nrfu-tutorial with 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 #20
Source File: conftest.py    From pennylane with 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 #21
Source File: test_runner.py    From pytest with 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 #22
Source File: conftest.py    From cassandra-dtest with 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 #23
Source File: async_test.py    From tildemush with 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 #24
Source File: tm_test_case.py    From tildemush with 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 #25
Source File: event_loop.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def interrupt_event_loop(self, *args, **kwargs):
        pyglet.app.exit() 
Example #26
Source File: event_loop.py    From pyglet with 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 #27
Source File: abstract_tests.py    From ambassador with 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 #28
Source File: t_envoy_logs.py    From ambassador with 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 #29
Source File: conftest.py    From parsec-cloud with 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 #30
Source File: service.py    From agent-python-pytest with 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