行为步骤 disambiguation/optional 步骤参数

Behave step disambiguation/optional step arguments

我正在尝试支持以下功能场景:

Feature: test
  Scenario: Test optional
      Given attacked by samurai
        And attacked by samurai from behind

我的步骤文件是

from behave import step

@step('attacked by {opponent}')
def step_attacked_by(context, opponent):
    print(opponent)

@step('attacked by {opponent} from {direction}')
def step_attacked_by(context, opponent, direction):
    print(opponent)
    print(direction)

我遇到错误:

behave.step_registry.AmbiguousStep: @step('attacked by {opponent} from {direction}') has already been defined in
  existing step @step('attacked by {opponent}') at steps/test.py:5

然后我尝试使用 optinal arguments:

我的专题文件:

Feature: test
  Scenario: Test optional
      Given attacked by a samurai

我的步骤文件:

import parse

from behave import step, register_type

@parse.with_pattern(r"a\s+")
def parse_word_a(text):
    """Type converter for "a " (followed by one/more spaces)."""
    return text.strip()

register_type(a_=parse_word_a)

@step('attacked by {:a_?}{opponent}')
def step_attacked_by(context, a_, opponent):
    print(a_)
    print(opponent)

我收到这个错误:

    raise ValueError('format spec %r not recognised' % type)
ValueError: format spec 'a_?' not recognised

我认为我真的不需要可选参数,只要我能消除第一个示例中的步骤的歧义即可。

在使用 Behave 时,我注意到在步骤定义文件中定义步骤的顺序很重要。

尝试从最具体的步骤开始定义您的步骤:

@step('attacked by {opponent} from {direction}')
def step_attacked_by(context, opponent, direction):
    print(opponent)
    print(direction)

@step('attacked by {opponent}')
def step_attacked_by(context, opponent):
    print(opponent)

运行 你的 test.feature 不再给我歧义错误了。