How do I make pytest fixtures work with decorated functions?

jck picture jck · Oct 27, 2013 · Viewed 11.2k times · Source

py.test seems to fail when I decorate test functions which has a fixture as an argument.

def deco(func):

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)

    return wrapper


@pytest.fixture
def x():
    return 0

@deco
def test_something(x):
    assert x == 0

In this simple example, I get the following error:

TypeError: test_something() takes exactly 1 argument (0 given).

Is there a way to fix this, preferably without modifying the decorator too much? (Since the decorator is used outside testing code too.)

Answer

jck picture jck · Oct 27, 2013

It looks like functools.wraps does not do the job well enough, so it breaks py.test's introspection.

Creating the decorator using the decorator package seems to do the trick.

import decorator

def deco(func):
    def wrapper(func, *args, **kwargs):
        return func(*args, **kwargs)
    return decorator.decorator(wrapper, func)