Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create decorator compatible with pytest.mark.parametrize

I want to create a decorator for my test written with pytest. My problem, when calling decorator, pytest raises an exception that decorator hasn't got parameters "test_params".

Decorator example:

def decorator_example(fn):

    def create(*args, **kwargs):
        # any code here
        return fn(*args, **kwargs)

return create

Test example:

@pytest.mark.parametrize(
    "test_params",
    [
        pytest.param("own_parameters")
    ])
@decorator_example
def test_1(self, fixture1, fixture2, test_params):
    pass

And caught exception:

ValueError: <function create at address> uses no argument 'test_params'

How can I create a decorator which will be compatible with pytest's parametrized test?

like image 740
Артем Лебаков Avatar asked Aug 10 '26 19:08

Артем Лебаков


1 Answers

That's because decorator_example replaces the test_1 function with the wrapper function create that has a completely different signature, breaking pytest introspection (e.g. checking whether create has an argument test_params fails because there are only *args and **kwargs available). You need to use functools.wraps to mimic the wrapped function's signature:

import functools


def decorator_example(fn):

    @functools.wraps(fn)    
    def create(*args, **kwargs):
        # any code here
        return fn(*args, **kwargs)

    return create

Python 2.7 compatibility

You can make use of the decorator package. Install it with the usual

$ pip install decorator

The above example will be:

import decorator


def decorator_example(fn):
    def create(fn, *args, **kwargs):
        return fn(*args, **kwargs)
    return decorator.decorator(create, fn)

Or using six:

import six


def decorator_example(fn):

    @six.wraps(fn)    
    def create(*args, **kwargs):
        # any code here
        return fn(*args, **kwargs)

    return create
like image 79
hoefling Avatar answered Aug 12 '26 10:08

hoefling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!