0

I'm using pytest bdd to execute bdd scenarios. Example:

Scenario Outline: entry with special character
Given I am an authenticated user
When I request entry information with <entryName> name
Then I expect a 200 response code
And I check the output list contains valid data
Examples:
  | entryName     |
  | #@            |

During the scenario, I create the entry, that I then query for and validate response code/output. I want to be able to cleanup the entry I created regardless of the scenario success (so inserting another row of "Then I clean up my data" won't achieve my goal).

According to https://pytest-bdd.readthedocs.io/en/latest/ - there's a pytest_bdd_after_scenario(request, feature, scenario) hook that should allow me to execute the cleanup regardless of the scenario success.

  1. Where should I implement it? (I tried putting it in test_my_scenario.py but it didn't get executed, and according to https://github.com/pytest-dev/pytest-bdd/issues/174 it looks like it should be in conftest?)
  2. How can I pass a scenario specific argument to the hook? Unlike pytest_bdd_step_error it doesn't have func_args in the signature. So how can I clean up the specific entry I created during the scenario?
user3698979
  • 103
  • 1
  • 9

1 Answers1

1
  1. Yes, you should put the pytest_bdd_after_scenario(request, feature, scenario) hook in the conftest.py, so that it will be executed for all test cases.

  2. You can create a pytest fixture and store all data you need for cleanup in there and then retrieve that fixture in pytest_bdd_after_scenario(request, feature, scenario) by calling request.getfixturevalue(name_of_fixture)

Example:

@pytest.fixture
def context():
    return {'entryName': None}

@when("I request entry information with <entryName> name")
def do_post(context, entryName):
    # Do stuff here ...
    context['entryName'] = entryName

def pytest_bdd_after_scenario(request, feature, scenario):
    context = request.getfixturevalue('context')
    entry_name = context['entryName']
    # Clean up entry ...

mattefrank
  • 231
  • 1
  • 9