gherkin - pytest-bdd . Step definitions for any of whenthengivenand - Stack Overflow

admin2025-05-01  1

Is there a way to use Then steps for When definitions with pytest-bdd?

Example,

I have the step in my scenario

Then User downloads the file "test_file.txt"

But my definitions is

@when(parsers.parse('User downloads the file "{file_name}"'))
def step_user_downloads_file(bdd_context, file_name):
    pass

There is the error about step is not found. I have scenarios where same step is used with "When" keyword. I would like to use with both. But more globally, i would like to use any step definitions with any of keywords When/Then/Given/And . is it possible?

Is there a way to use Then steps for When definitions with pytest-bdd?

Example,

I have the step in my scenario

Then User downloads the file "test_file.txt"

But my definitions is

@when(parsers.parse('User downloads the file "{file_name}"'))
def step_user_downloads_file(bdd_context, file_name):
    pass

There is the error about step is not found. I have scenarios where same step is used with "When" keyword. I would like to use with both. But more globally, i would like to use any step definitions with any of keywords When/Then/Given/And . is it possible?

Share Improve this question asked Jan 2 at 16:47 Roman GelembjukRoman Gelembjuk 2,0453 gold badges29 silver badges57 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Unfortunately, there are no pytest annotations that allow you to bind a step definition to any keyword. It would be pretty neat if there was an annotation like @step(parsers.parse(...)) that would allow you to use that step with Given, When, or Then. However, there are still several workarounds that can get the job done for your example:

  1. In place of using "When User downloads the file..." in your feature file, you could use the wildcard symbol which will work with any step, regardless of which keyword the step definition was bound to. See https://pytest-bdd.readthedocs.io/en/stable/#using-asterisks-in-place-of-keywords for reference.
* User downloads the file "test_file.txt"
  1. You could also bind each step definition to all keywords in the step definition file using step aliases with the format given below. This could also be applied to attach multiple names to the same step. See https://pytest-bdd.readthedocs.io/en/stable/#step-aliases for reference.
@given(parsers.parse('User downloads the file "{file_name}"'))
@when(parsers.parse('User downloads the file "{file_name}"'))
@then(parsers.parse('User downloads the file "{file_name}"'))
def step_user_downloads_file(bdd_context, file_name):
    pass
转载请注明原文地址:http://www.anycun.com/QandA/1746106523a91761.html