[pytest-dev] fixtures as context managers

holger krekel holger at merlinux.eu
Sun May 5 15:05:35 CEST 2013


Hi all,

after having been asked by Andreas Pelme and Vladimir Keleshev, repeatedly,
i finally tried to allow fixture functions to be context managers like this:

    @pytest.fixture
    def myfixture():
        print "setup"
        yield val
        print "teardown"

With this, you don't need to use "request.addfinalizer" - pytest does
this by detecting your yield.  I checked this into trunk to allow
experimentation - it seems to work fine with scopes and parametrization.
For pytest, it's really just a slightly different "fixture function calling"
protocol, contained in this commit:

https://bitbucket.org/hpk42/pytest/commits/b93ac0cdae02effaa3c136a681cc45bba757fe46

Note that i don't plan to extend this yield mechanism to parametrization
as that would meanparametrization at test execution time, rather than at
collection time.  It would be both conceptually and implementation wise
hard to do i think.

The change is committed to trunk, and you can also do:

    pip install -i http://pypi.testrun.org -U pytest

to get pytest-2.3.6.dev2 at least.

feedback welcome, actually without people actively 
wanting it, it might be thrown out again ;)

holger




More information about the Pytest-dev mailing list