Skip to main content
Python Software Foundation 20th Year Anniversary Fundraiser  Donate today!

Define pytest fixtures as context managers.

Project description

pytest-contextfixture makes it possible to define pytest fixtures as context managers.

A contextfixture works like a standard fixture, but it allows the definition to be written as a generator. This simplifies the teardown code and allows for other context managers to be used within a fixture.


pip install pytest-contextfixture


Consider this example, using the standard pytest.fixture:

import pytest

def dependency(request)
    def teardown():
        # fixture teardown code goes here

    return 1234

def test_foo(dependency):
    assert fn_under_test(dependency) == 'expected'

With pytest.contextfixture, this is equivalent:

import pytest

def dependency(request):
    # fixture setup code goes here
    yield 1234
    # fixture teardown code goes here

def test_foo(dependency):
    assert fn_under_test(dependency) == 'expected'

While this is a slightly nicer syntax, when using other context managers to get a dependency for a fixture, this becomes more useful:

def dependency(request):
    with setup_something():
        with setup_something_else() as d:
            yield d

def test_foo(dependency):
    assert fn_under_test(dependency) == 'expected'

test_foo will then run in the context of setup_something and setup_something_else.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for pytest-contextfixture, version 0.1.1
Filename, size File type Python version Upload date Hashes
Filename, size pytest-contextfixture-0.1.1.tar.gz (3.2 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page