pytest-bdd对不同步骤重复使用相同的方法

rpa*_*pal 5 python bdd pytest

我想对同一步骤的@ given,@ when和@then使用相同的方法。例如

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
Run Code Online (Sandbox Code Playgroud)

如果我在执行步骤中这样做:

@when('login button pressed')
@given('login button pressed')
def loginButtonPressed():
    print 'button pressed'
Run Code Online (Sandbox Code Playgroud)

似乎pytest_bdd无法处理此问题。我得到错误:

没有找到“按下登录按钮”的固定装置,有没有办法为这些步骤取别名?

ajp*_*nam 5

在 pytest-BDD 中,它当前不支持在一个函数定义上使用两种不同的步骤类型/定义的能力。怎么还有“变通办法”

选项 1:关闭 Gherkin 严格模式

@pytest.fixture
def pytestbdd_strict_gherkin():
    return False
Run Code Online (Sandbox Code Playgroud)

这将允许您按任意顺序使用步骤:

@when('login button pressed')
def loginButtonPressed():
    print 'button pressed'
Run Code Online (Sandbox Code Playgroud)

小黄瓜

Scenario: Use given anywhere         
         Given username and password entered
         when login button pressed
         then I am logged in
         when login button pressed
Run Code Online (Sandbox Code Playgroud)

优点:不必创建给定/何时/然后版本...

缺点:可能会降低可读性...违背真正的步骤程序。

查看更多信息放松严格的小黄瓜

选项 2:在新步骤定义中调用先前定义的函数

@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() 
Run Code Online (Sandbox Code Playgroud)

优点:不重复函数体代码,保留给定->何时->然后模式。仍可维护(更改代码 1 处)

缺点:仍然需要为给定的、when、then 版本创建新的函数定义...