pytest.yield_fixture

Here are the examples of the python api pytest.yield_fixture taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

196 Examples 7

Example 1

Project: dumb-init Source File: conftest.py
@pytest.yield_fixture(autouse=True, scope='function')
def clean_environment():
    """Ensure all tests start with a clean environment.

    Even if tests properly clean up after themselves, we still need this in
    case the user runs tests with an already-polluted environment.
    """
    with mock.patch.dict(
        os.environ,
        {'DUMB_INIT_DEBUG': '', 'DUMB_INIT_SETSID': ''},
    ):
        yield

Example 2

Project: trans Source File: tests.py
@pytest.yield_fixture(scope='function')
def complex_table():
    yield ({u'4 5': u'45'},
           {u'1': u'11', u'2': u'22', u'4': u'4', u'5': u'5', None: u'-'})

    trans_module.trans.tables.pop('my_simple', None)

Example 3

Project: cookiecutter-webapp Source File: conftest.py
Function: api_app
@pytest.yield_fixture(scope='function', params=['classy', 'restful'])
def apiapp(request):
    _app = api.create_app(test_settings)
    if request.param == 'classy':
        classy_api(_app)
    else:
        restful_api(_app)
    ctx = _app.test_request_context()
    ctx.push()
    yield _app
    ctx.pop()

Example 4

Project: tchannel-python Source File: test_vcr.py
@pytest.yield_fixture
def tracer():
    reporter = InMemoryReporter()
    tracer = Tracer(
        service_name='test-tracer',
        sampler=ConstSampler(True),
        reporter=reporter,
    )
    try:
        yield tracer
    finally:
        tracer.close()

Example 5

Project: flaskbb Source File: app.py
Function: application
@pytest.yield_fixture(autouse=True)
def application():
    """application with context."""
    app = create_app(Config)

    ctx = app.app_context()
    ctx.push()

    yield app

    ctx.pop()

Example 6

Project: qtile Source File: conftest.py
@pytest.yield_fixture(scope="function")
def qtile(request, xephyr):
    config = getattr(request, "param", BareConfig)

    with tempfile.NamedTemporaryFile() as f:
        sockfile = f.name
        q = Qtile(sockfile, xephyr.display)
        try:
            q.start(config)

            yield q
        finally:
            q.terminate()

Example 7

Project: pgctl Source File: dirty_tests.py
Function: clean_up
    @pytest.yield_fixture(autouse=True)
    def cleanup(self, in_example_dir):
        try:
            yield in_example_dir
        finally:
            for service in in_example_dir.join('playground').listdir():
                clean_service(str(service))

Example 8

Project: pip Source File: conftest.py
@pytest.yield_fixture
def tmpdir(tmpdir):
    """
    Return a temporary directory path object which is unique to each test
    function invocation, created as a sub directory of the base temporary
    directory. The returned object is a ``tests.lib.path.Path`` object.

    This uses the built-in tmpdir fixture from pytest itself but modified
    to return our typical path object instead of py.path.local as well as
    deleting the temporary directories at the end of each test case.
    """
    assert tmpdir.isdir()
    yield Path(str(tmpdir))
    # Clear out the temporary directory after the test has finished using it.
    # This should prevent us from needing a multiple gigabyte temporary
    # directory while running the tests.
    tmpdir.remove(ignore_errors=True)

Example 9

Project: odo Source File: test_csv.py
@pytest.yield_fixture
def multibyte_csv():
    header = random_multibyte_string(nrows=2, string_length=3)
    single_column = random_multibyte_string(nrows=10, string_length=4)
    numbers = np.random.randint(4, size=10)
    with tmpfile('.csv') as fn:
        with open(fn, 'wb') as f:
            f.write((','.join(header) + '\n').encode('utf8'))
            f.write('\n'.join(','.join(map(unicode, row))
                              for row in zip(single_column, numbers)).encode('utf8'))
        yield fn

Example 10

Project: pytest Source File: recwarn.py
@pytest.yield_fixture
def recwarn(request):
    """Return a WarningsRecorder instance that provides these methods:

    * ``pop(category=None)``: return last warning matching the category.
    * ``clear()``: clear list of warnings

    See http://docs.python.org/library/warnings.html for information
    on warning categories.
    """
    wrec = WarningsRecorder()
    with wrec:
        warnings.simplefilter('default')
        yield wrec

Example 11

Project: flask-boilerplate Source File: conftest.py
Function: app
@pytest.yield_fixture(scope='session')
def app():
    app = create_app(config_file='config/testing.py')
    app.response_class = ApiTestingResponse
    ctx = app.app_context()
    ctx.push()

    yield app

    ctx.pop()

Example 12

Project: webargs Source File: test_core.py
Function: web_request
@pytest.yield_fixture(scope='function')
def web_request():
    req = mock.Mock()
    req.query = {}
    yield req
    req.query = {}

Example 13

Project: pytest-mock Source File: pytest_mock.py
@pytest.yield_fixture
def mocker(pytestconfig):
    """
    return an object that has the same interface to the `mock` module, but
    takes care of automatically undoing all patches after each test method.
    """
    result = MockFixture(pytestconfig)
    yield result
    result.stopall()

Example 14

Project: backy2 Source File: test_main.py
Function: argv
@pytest.yield_fixture
def argv():
    original = sys.argv
    new = original[:1]
    sys.argv = new
    yield new
    sys.argv = original

Example 15

Project: hamster-lib Source File: conftest.py
Function: controller
@pytest.yield_fixture
def controller(base_config):
    """Provide a basic controller."""
    # [TODO] Parametrize over all available stores.
    controller = HamsterControl(base_config)
    yield controller
    controller.store.cleanup()

Example 16

Project: kafka-utils Source File: test_delete_group.py
Function: client
    @pytest.yield_fixture
    def client(self):
        with mock.patch(
                'kafka_utils.kafka_consumer_manager.'
                'commands.delete_group.KafkaToolClient',
                autospec=True,
        ) as mock_client:
            yield mock_client

Example 17

Project: puzzle Source File: conftest.py
@pytest.yield_fixture(scope='session')
def ped_lines():
    """Return an unformatted list of ped lines."""
    _ped_lines = [
        "636808\tADM1059A1\t0\t0\t1\t1",
        "636808\tADM1059A2\tADM1059A1\tADM1059A3\t1\t2",
        "636808\tADM1059A3\t0\t0\t2\t1"
    ]
    yield _ped_lines

Example 18

Project: venv-update Source File: conftest.py
Function: tmp_dir
@pytest.yield_fixture
def tmpdir(tmpdir):
    """override tmpdir to provide a $HOME and $TMPDIR"""
    home = tmpdir.ensure('home', dir=True)
    tmp = tmpdir.ensure('tmp', dir=True)

    orig_environ = os.environ.copy()
    os.environ['HOME'] = str(home)
    os.environ['TMPDIR'] = str(tmp)

    with tmpdir.as_cwd():  # TODO: remove all the tmpdir.chdir()
        yield tmpdir

    os.environ.clear()
    os.environ.update(orig_environ)

Example 19

Project: web3.py Source File: conftest.py
@pytest.yield_fixture()
def web3_ipc_empty():
    from web3 import (
        Web3, IPCProvider,
    )

    with setup_testing_geth() as geth:
        provider = IPCProvider(ipc_path=geth.ipc_path)
        provider._geth = geth
        web3 = Web3(provider)
        yield web3

Example 20

Project: castra Source File: test_core.py
Function: base
@pytest.yield_fixture
def base():
    d = tempfile.mkdtemp(prefix='castra-')
    try:
        yield d
    finally:
        shutil.rmtree(d)

Example 21

Project: aiohttp-devtools Source File: conftest.py
@pytest.yield_fixture
def tmpworkdir(tmpdir):
    """
    Create a temporary working working directory.
    """
    cwd = os.getcwd()
    os.chdir(tmpdir.strpath)

    yield tmpdir

    os.chdir(cwd)

Example 22

Project: graypy Source File: test_gelf_datagram.py
Function: logger
@pytest.yield_fixture
def logger(handler):
    logger = logging.getLogger('test')
    logger.addHandler(handler)
    yield logger
    logger.removeHandler(handler)

Example 23

Project: ploy Source File: conftest.py
Function: temp_dir
@pytest.yield_fixture
def tempdir():
    """ Returns an object for easy use of a temporary directory which is
        cleaned up afterwards.

        Use tempdir[filepath] to access files.
        Use .fill(lines) on the returned object to write content to the file.
    """
    directory = tempfile.mkdtemp()
    yield Directory(directory)
    shutil.rmtree(directory)

Example 24

Project: flaskbb Source File: app.py
Function: database
@pytest.yield_fixture()
def database():
    """database setup."""
    db.create_all()  # Maybe use migration instead?

    yield db

    db.drop_all()

Example 25

Project: pytest-asyncio Source File: plugin.py
Function: event_loop
@pytest.yield_fixture
def event_loop(request):
    """Create an instance of the default event loop for each test case."""
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()

Example 26

Project: sqlalchemy-redshift Source File: conftest.py
@pytest.yield_fixture(scope='function')
def redshift_session(_session_scoped_redshift_engine):
    """
    A redshift session that rolls back all operations.

    The engine and db is maintained for the entire test session for efficiency.
    """
    conn = _session_scoped_redshift_engine.connect()
    tx = conn.begin()

    RedshiftSession = sa.orm.sessionmaker()
    session = RedshiftSession(bind=conn)
    try:
        yield session
    finally:
        session.close()
        tx.rollback()
        conn.close()

Example 27

Project: DockCI Source File: conftest.py
@pytest.yield_fixture
def tmpgitdir(tmpdir):
    """ Get a new ``tmpdir``, make it the cwd, and set git config """
    with tmpdir.as_cwd():
        subprocess.check_call(['git', 'init'])
        for name, val in (
            ('user.name', 'DockCI Test'),
            ('user.email', '[email protected]'),
        ):
            subprocess.check_call(['git', 'config', name, val])

        yield tmpdir

Example 28

Project: pytest-flask Source File: fixtures.py
Function: client
@pytest.yield_fixture
def client(app):
    """A Flask test client. An instance of :class:`flask.testing.TestClient`
    by default.
    """
    with app.test_client() as client:
        yield client

Example 29

Project: bepasty-server Source File: conftest.py
Function: app
@pytest.yield_fixture(scope='module')
def app(request):
    """
    creates a bepasty App-Instance
    """
    app = create_app()
    yield app
    unlink(app.config['DATABASE'])

Example 30

Project: pre-commit Source File: autoupdate_test.py
@pytest.yield_fixture
def hook_disappearing_repo(tempdir_factory):
    path = make_repo(tempdir_factory, 'python_hooks_repo')
    original_sha = get_head_sha(path)

    with cwd(path):
        shutil.copy(
            get_resource_path('manifest_without_foo.yaml'),
            C.MANIFEST_FILE,
        )
        cmd_output('git', 'add', '.')
        cmd_output('git', 'commit', '-m', 'Remove foo')

    yield auto_namedtuple(path=path, original_sha=original_sha)

Example 31

Project: telegram-uz-bot Source File: conftest.py
@pytest.yield_fixture
def patch_sleep_resolution():
    orig = utils.RESOLUTION
    utils.RESOLUTION = 0.1
    yield
    utils.RESOLUTION = orig

Example 32

Project: pytest-services Source File: folders.py
Function: base_dir
@pytest.yield_fixture(scope='session')
def base_dir(request, session_id, root_dir, services_log):
    """The directory where test run artifacts should be stored.

    It is responsibility of fixtures and tests that depend on it to clean up
    after themselves.

    """
    path = os.path.join(root_dir, 'sr-{0}'.format(session_id))
    services_log.debug('creating base dir: {0}'.format(path))
    if not os.path.exists(path):
        os.mkdir(path)

    yield path

    services_log.debug('finalizing base dir: {0}'.format(path))
    shutil.rmtree(path, ignore_errors=True)

Example 33

Project: pyramid_sqlalchemy Source File: fixtures.py
Function: transaction
@pytest.yield_fixture
def transaction():
    """Create a new transaction for a test. The transaction is automatically
    marked as doomed to prevent it from being committed accidentily. At the end
    of the test it will be rolled back.
    """
    import transaction
    tx = transaction.begin()
    tx.doom()  # Make sure a transaction can never be commited.
    # Mock out transaction.get so code can call abort
    with mock.patch('transaction.get'):
        yield
    tx.abort()

Example 34

Project: populus Source File: plugin.py
@pytest.yield_fixture()
def unmigrated_chain(request, project):
    # This should probably allow you to specify the test chain to be used based
    # on the `request` object.  It's unclear what the best way to do this is
    # so... punt!
    chain = project.get_chain('testrpc')

    # TODO: this should run migrations.  If `testrpc` it should be snapshotted.
    # In the future we should be able to snapshot the `geth` chains too and
    # save them for faster test runs.

    with chain:
        yield chain

Example 35

Project: git-code-debt Source File: conftest.py
@pytest.yield_fixture
def cloneable(tempdir_factory):
    repo_path = tempdir_factory.get()
    with cwd(repo_path):
        subprocess.check_call(('git', 'init', '.'))
        subprocess.check_call(('git', 'commit', '-m', 'foo', '--allow-empty'))

    yield repo_path

Example 36

Project: qtile Source File: conftest.py
@pytest.yield_fixture(scope="function")
def qtile_nospawn(request, xephyr):
    with tempfile.NamedTemporaryFile() as f:
        sockfile = f.name
        q = Qtile(sockfile, xephyr.display)

        try:
            yield q
        finally:
            q.terminate()

Example 37

Project: mycroft Source File: test_worker.py
@pytest.yield_fixture(params=['et'])  # noqa
def get_worker(request, scheduled_jobs, etl_records):
    with staticconf.testing.MockConfiguration(MOCK_CONFIG):
        with mock.patch(
                'mycroft.models.aws_connections.TableConnection.get_connection'
                ) as mocked_tc:
            scheduled_jobs.put(**SAMPLE_RECORD_ET_STATUS_SCHEDULED)
            mocked_tc.side_effect = lambda x: {
                'ScheduledJobs': scheduled_jobs, 'ETLRecords': etl_records
            }[x]
            workers = {
                'et':   ImdWorker(CONFIG_LOC, CONFIG_OVERRIDE_LOC, True, Mailer(True)),
            }
            yield workers[request.param]

Example 38

Project: pydocstyle Source File: test_integration.py
Function: install_package
@pytest.yield_fixture(scope="module")
def install_package(request):
    cwd = os.path.join(os.path.dirname(__file__), '..', '..')
    install_cmd = "python setup.py develop"
    uninstall_cmd = install_cmd + ' --uninstall'
    subprocess.check_call(shlex.split(install_cmd), cwd=cwd)
    yield
    subprocess.check_call(shlex.split(uninstall_cmd), cwd=cwd)

Example 39

Project: uwsgi_metrics Source File: meter_test.py
@pytest.yield_fixture
def meter_and_clock():
    with mock.patch('time.time', Clock(0.0)) as clock:
        clock = clock
        meter = Meter()
        yield (meter, clock)

Example 40

Project: szurubooru Source File: conftest.py
Function: session
@pytest.yield_fixture(scope='function', autouse=True)
def session(query_logger):  # pylint: disable=unused-argument
    db.sessionmaker = sqlalchemy.orm.sessionmaker(
        bind=_engine, autoflush=False)
    db.session = sqlalchemy.orm.scoped_session(db.sessionmaker)
    try:
        yield db.session
    finally:
        db.session.remove()
        for table in reversed(db.Base.metadata.sorted_tables):
            db.session.execute(table.delete())
        db.session.commit()

Example 41

Project: zenodo Source File: conftest.py
Function: app
@pytest.yield_fixture(scope='session')
def app(env_config, default_config):
    """Flask application fixture."""
    app = create_app(**default_config)

    with app.app_context():
        yield app

Example 42

Project: rawkit Source File: util_test.py
Function: libraw
@pytest.yield_fixture
def libraw():
    with mock.patch('rawkit.util.LibRaw') as libraw:
        # TODO: There must be a better way...
        libraw.return_value = libraw
        yield libraw

Example 43

Project: blaze Source File: test_h5py.py
Function: file
@pytest.yield_fixture
def file():
    with tmpfile('.h5') as filename:
        f = h5py.File(filename)
        d = f.create_dataset('/x', shape=x.shape, dtype=x.dtype,
                             fillvalue=0.0, chunks=(4, 6))
        d[:] = x
        yield f
        f.close()

Example 44

Project: s3ql Source File: t3_verify.py
Function: db
@pytest.yield_fixture()
def db():
    dbfile = tempfile.NamedTemporaryFile()
    db = Connection(dbfile.name)
    create_tables(db)
    init_tables(db)
    try:
        yield db
    finally:
        db.close()
        dbfile.close()

Example 45

Project: setuptools Source File: test_easy_install.py
@pytest.yield_fixture
def distutils_package():
    distutils_setup_py = SETUP_PY.replace(
        'from setuptools import setup',
        'from distutils.core import setup',
    )
    with contexts.tempdir(cd=os.chdir):
        with open('setup.py', 'w') as f:
            f.write(distutils_setup_py)
        yield

Example 46

Project: CorpusTools Source File: conftest.py
Function: qapp
@pytest.yield_fixture(scope='session')
def qapp():
    """
    fixture that instantiates the QApplication instance that will be used by
    the tests.
    """
    app = QApplicationMessaging.instance()
    if app is None:
        app = QApplicationMessaging([])
        yield app
        app.exit()
    else:
        yield app # pragma: no cover

Example 47

Project: eth-testrpc Source File: conftest.py
@pytest.yield_fixture()
def rpc_server():
    from testrpc.server import application
    from testrpc.testrpc import full_reset

    full_reset()

    port = get_open_port()

    server = WSGIServer(
        ('127.0.0.1', port),
        application,
    )
    gevent.spawn(server.serve_forever)

    yield server

    server.stop()

Example 48

Project: pre-commit Source File: autoupdate_test.py
@pytest.yield_fixture
def out_of_date_repo(tempdir_factory):
    path = make_repo(tempdir_factory, 'python_hooks_repo')
    original_sha = get_head_sha(path)

    # Make a commit
    with cwd(path):
        cmd_output('git', 'commit', '--allow-empty', '-m', 'foo')
    head_sha = get_head_sha(path)

    yield auto_namedtuple(
        path=path, original_sha=original_sha, head_sha=head_sha,
    )

Example 49

Project: pytest-django Source File: fixtures.py
Function: settings
@pytest.yield_fixture()
def settings():
    """A Django settings object which restores changes after the testrun"""
    skip_if_no_django()

    wrapper = SettingsWrapper()
    yield wrapper
    wrapper.finalize()

Example 50

Project: sqlalchemy-redshift Source File: conftest.py
@pytest.yield_fixture(scope='session')
def _session_scoped_redshift_engine(_redshift_database_tool):
    """
    Private fixture to maintain a db for the entire test session.
    """
    with _redshift_database_tool.migrated_database() as egs:
        yield egs['engine']
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4