[py-dev] Using funcargs with decorators

Sebastian Rahlf basti at redtoad.de
Thu Oct 11 14:44:15 CEST 2012


Hi Holger!

>> At work we use a decorator @rollback on selected test functions which
>> will rollback any db changes made during that test.
>>
>> I've recently started using pytest's dependency injection for a few
>> use cases, both with @pytest.mark.parametrize(...) and the
>> pytest_funcarg__XXX hook.
>> Unfortunately, this clashes with our decorated test functions.
>>
>> How can I make this work?
>>
>> My first idea was using a custom marker, say @pytest.mark.rollback and
>> do something like:
>>
>> def rollback(meth):
>>     """Original rollback function"""
>>     ...
>>
>> def pytest_runtest_setup(item):
>>     if not isinstance(item, pytest.Function):
>>         return
>>     if hasattr(item.obj, 'rollback'):
>>         item = rollback(item)
>>
>> Would an approach like this actually work?
>
> I think so - probably you need to call "rollback(item.obj") though.

Thanks for your feedback. I've tried it again with the following code:

# conftest.py
import pytest
from unittests import rollback

def pytest_configure(config):
    # register an additional marker
    config.addinivalue_line("markers",
        "rollback: rollback any db changes after test")

def pytest_runtest_setup(item):
    if not isinstance(item, pytest.Function):
        return
    if hasattr(item.obj, 'rollback'):
        item.obj = rollback(item.obj)

# test_my_tests.py

import pytest

@pytest.mark.rollback
def test_rollback(monkepatch):
    # ...
    assert True

What I get is a "TypeError: test_rollback() takes exactly 1 argument (0 given)".
How can I make this work?

Cheers,
Seb.



More information about the Pytest-dev mailing list