pytest-dev / pytest-bdd

BDD library for the py.test runner
https://pytest-bdd.readthedocs.io/en/latest/
MIT License
1.28k stars 214 forks source link

Function argument default values are not overridden by parameterized steps #198

Open mctwynne opened 7 years ago

mctwynne commented 7 years ago

For example:

@given('I have {count:w} apples')
@given('I have apples')
def given_i_have_apples(count=1):
    return count

The step Given I have 5 apples will always return 1. Is there no way to provide default values for such arguments?

mctwynne commented 7 years ago

Does anyone have anything to add to this?

wren commented 3 years ago

I'm in the process of migrating from Behave to Pytest-BDD, I've been trying to figure out how to do the same thing described.

What I've found works is something like this:

from pytest import fixture
from pytest_bdd import given
from pytest_bdd.parsers import parse

@fixture
def count():
    return 1

@given(parse('I have {count:d} apples'), target_fixture="count_apples")
@given('I have apples', target_fixture="count_apples")
def given_i_have_apples(count):
    return count

The downside is that you'll end up with lots of small fixtures all over the place even if they're only used in the one step.

Is there any chance that pytest-bdd can support default parameter values?

youtux commented 3 years ago

I'm afraid this is more a question for pytest itself, not really pytest-bdd. pytest-bdd only injects the fixture value for the "count" fixture in case it was able to parse it, otherwise it falls back to whatever pytest would do.

You can also make 2 explicit different steps to emphasize which one handles the default case, and which one handles the parameter:

from pytest import fixture
from pytest_bdd import given
from pytest_bdd.parsers import parse

@given(parsers.parse('I have {count:d} apples'), target_fixture="count_apples")
def given_i_have_apples(count):
    return count

@given('I have apples', target_fixture="count_apples")
def given_i_have_default_apples():
    return 1

This way you also don't have to define a fixture "count" that can potentially be evaluated by some step later on without being set up by your "given" steps (but that also has pros and cons).