pytest-dev / pytest-bdd

BDD library for the pytest runner
https://pytest-bdd.readthedocs.io/en/latest/
MIT License
1.32k stars 221 forks source link

Decorator with arguments does not stack with pytest bdd given when then #520

Closed ShedPlant closed 2 years ago

ShedPlant commented 2 years ago
import functools

from pytest_bdd import when, scenario

def repeat_no_args(func):
    @functools.wraps(func)
    def wrapper_repeat(*args, **kwargs):
        for _ in range(2):
            value = func(*args, **kwargs)
        return value
    return wrapper_repeat

def repeat_with_args(num_times):
    def decorator_repeat(func):
        @functools.wraps(func)
        def wrapper_repeat(*args, **kwargs):
            for _ in range(num_times):
                value = func(*args, **kwargs)
            return value
        return wrapper_repeat
    return decorator_repeat

@scenario("decorator demo")
def repro_decorator_with_args_bug():
    pass

@when("something")
@repeat_no_args
def something():
    # This works
    pass

@when("something else")
@repeat_with_args
def something_else():
    # This fails with
    # fixture 'func' not found
    pass

As a workaround:

repeat_with_args_5 = repeat_with_args(5)

@when("something else")
@repeat_with_args_5
def something_else():
    # This works
    pass
elchupanebrej commented 2 years ago

It's not an issue of pytest-bdd. Your usage of the repeat_with_args decorator is wrong. It expects num_times as argument but gets function

ShedPlant commented 2 years ago

My simplified example above was a bit wrong, should have said there was a default value.

def repeat_with_args(num_times=5):
    # then as above

I expected @repeat_with_args decorator without specifying the num_times argument to work, but it results in the error. @repeat_with_args() works fine.

Thanks for the help @elchupanebrej !