1

Background I need to run some specific method after a scenario run for a specific test scenario

What I tried

Scenario is as below

Scenario: Test Fixture
    Given I am a mechanic
    When I start a car
    Then I should get to know the primitive issues

Step definition looked as below

@pytest.mark.usefixtures("stop_car")
@scenario('../FeatureFiles/Test.feature', 'Test Fixture')
def test_mechanic():
    logging.info('Test Mechanic')


@given("I am a mechanic")
def given_mechanic():
    print('given_mechanic')


@when("I start a car")
def when_mechanic():
    print('when_mechanic')


@then("I should get to know the primitive issues")
def then_mechanic():
    print('then_mechanic')
    assert 1 < 0, 'Failed validation'


@pytest.fixture
def stop_car():
    print('stop car')

Issue Faced

The problem here is the 'stop_car()' function is triggered before the execution of the scenario. I need to run at the end of the scenario. Even if any assertion failed in Given, When or Then the method 'stop_car()' should be executed in any case

KBNanda
  • 595
  • 1
  • 8
  • 25

1 Answers1

1

Any required fixture is run ahead of the test when it's required. Think about it as something which needs to be run (fixed) before the test and in the test you use the result of that. If you do not need the result you can just yield the control to main script. Once that part is finished the rest of the function is run.

@pytest.fixture
def stop_car():
    print('this runs before scenario')
    yield
    print('stop car')

here is the relevant documentation

webduvet
  • 4,220
  • 2
  • 28
  • 39