[py-dev] optionally considering setup (needsdb usecase)

Floris Bruynooghe flub at devork.be
Sun Aug 5 17:14:33 CEST 2012


Hello Holger,

On 4 August 2012 14:13, holger krekel <holger at merlinux.eu> wrote:
> On Sat, Jun 30, 2012 at 12:26 +0100, Floris Bruynooghe wrote:
>> As an aside however, one of my usecases for merged request/item
>> objects was so I could put setup in a session-wide scoped funcarg but
>> also automatically request this funcarg based on a mark::
>>
>>    def pytest_runtest_setup(item):
>>        if 'needsdb' in item.keywords:  # or a more explicit API
>>           item.getresource('db')
>>
>> I understand that this will still be possible via::
>>
>>    def pytest_runtest_setup(item):
>>        if 'needsdb' in item.keywords:
>>            item.session.getresource('db')
>>
>> Or something similar to that.
>
> With the current @setup API this is not possible but it should be.  I'd like
> to understand the exact use case a bit.  What do you do with the "db"
> object here?  I guess you cause side effects because you would otherwise
> just request a funcarg in the tests, right?

Actually there is no side effect here.  This was born out of Andreas
Pelme's desire to be able to mark tests with a marker while trying to
re-use the session-wide caching that funcargs gave us.  But the new
@setup already covers this case completely since it can handle the
caching just fine.  But I still think this is a nice use-case, since
it would allow being able to use the same setup and request it with
either a funcargs or a mark.

> If so, then i can imagine the following solution:
>
>     @pytest.setup(enabled=myhelper)
>     def perform_side_effect_with(db):
>         ...
>
> The "enabled" helper would be called during collection so that
> pytest gets to know which tests will actually execute the setup
> function and its (potentially parametrized) required resources.
> It could look like this::
>
>     def myhelper(collectioncontext):
>         return "needsdb" in collectioncontext.markers:
>
> and collectioncontext also carries module/class/function (depending on
> the scope specified with the setup).  If the helper returns True then
> the setup is considered and thus receives the DB object.  Do you
> think this would solve your use case? (Collectioncontext would not
> have a addfinalizer() and might in the future offer more collection-specific
> things).

This does sound like a very neat solution indeed, I think this would
be a good addition.


Regards,
Floris



More information about the Pytest-dev mailing list