Sam Hooke

pytest and functools decorator

If using a decorator created using functools.wraps with pytest, it will give an error similar to the following if you attempt to use fixtures:

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

The solution is to use the decorator package instead of functools to create the decorator.

A comment on the above stackoverflow answer (which is over 4 years old) states that pytest depends upon the decorator package. However as far as I can tell from looking at the current setup.py for pytest, it does not depend upon decorator. However using decorator still fixed the issue.

# Uses functools - *not* compatible with pytest :(
import functools

def my_decorator(some_arg):
    def deco(func):
        @functools.wraps(*args, **kwargs)
        def wrapper(*args, **kwargs)
            # do something with some_arg?
            ret = func(*args, **kwargs)
            # do something else?
            return ret
        return wrapper
    return deco
# Uses decorator - compatible with pytest :)
import decorator

def my_decorator(some_arg):
    def deco(func):
        def wrapper(func, *args, **kwargs):
            # do stuff with some_arg?
            ret = func(*args, **kwargs)
            # do something else?
            return ret
        return decorator.decorator(wrapper, func)
    return deco
from my_module.decorators import my_decorator

@my_decorator(1234)
def test_something(my_fixture):
    # do test

These are rough notes from whatever I was working on, interested in or thinking about at the time. They vary greatly in quality and length, but prove useful to me, and hopefully to you too!

← Previous: normalize-scss with hugo
Next: Using a non-pk as a foreign key in a Tastypie endpoint →