Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest-bdd reuse same method for different steps

Tags:

python

pytest

bdd

I want to use same method for @given, @when and @then of same step. e.g.

Scenario: Launch an application         
    Given username and password entered
    And login button pressed
    Then the app launches

Scenario: Launch application again          
    Given user logged out
    And username and password entered
    When login button pressed
    Then the app launches

If I do this in the implementation of step:

@when('login button pressed')
@given('login button pressed')
def loginButtonPressed():
    print 'button pressed'

It seems, pytest_bdd cannot handle this. I get the error:

fixture 'login button pressed' not found Is there a way I can maybe alias the steps?

like image 963
rpal Avatar asked Aug 28 '16 14:08

rpal


1 Answers

In pytest-BDD it does not currently support the ability to use two different step types/definitions on one function definition. How ever there are "work arounds"

Option 1: Turn off Gherkin strict mode

@pytest.fixture
def pytestbdd_strict_gherkin():
    return False

This will allow you to use steps in any order:

@when('login button pressed')
def loginButtonPressed():
    print 'button pressed'

In gherkin

Scenario: Use given anywhere         
         Given username and password entered
         when login button pressed
         then I am logged in
         when login button pressed

pros: don't have to create given/when/then versions...

cons: can make less readable... goes against true step procedure.

see for more info Relax strict gherkin

Option 2: Call previously defined function in new step definition

@given('login button pressed')
    def loginButtonPressed():
        # do stuff...
        # do more stuff...
        print 'button pressed'

@when('login button pressed')
    def when_loginButtonPressed():
        loginButtonPressed() 

@then('login button pressed')
    def then_loginButtonPressed():
        loginButtonPressed() 

pros: Doesn't duplicate function body code, keep given->when->then pattern. Still maintainable (change code 1 place)

cons: Still have to create new function definitions for given, when, then versions...

like image 101
Arthur Putnam Avatar answered Nov 04 '22 19:11

Arthur Putnam