如何对我的功能中使用的所有代码运行检查?

时间:2015-10-19 14:29:07

标签: python bdd python-behave

我有很多功能,并希望控制标签列表,以防止拼写错误和其他命名问题。有没有办法在我的所有功能中获取标签列表?

所以

@opponent
Feature: Fight or flight
  In order to increase the ninja survival rate,
  As a ninja commander
  I want my ninjas to decide whether to take on an
  opponent based on their skill levels

  Scenario: Weaker opponent
    Given the ninja has a third level black-belt
    When attacked by a samurai
    Then the ninja should engage the opponent

  @wip
  Scenario: Stronger opponent
    Given the ninja has a third level black-belt
    When attacked by Chuck Norris
    Then the ninja should run for his life

并且

Feature: showing off behave

  @dummy
  Scenario: run a simple test
    Given we have behave installed
     when we implement a test
     then behave will test it for us!

我获取了代码列表['opponent', 'wip', 'dummy']

2 个答案:

答案 0 :(得分:2)

你可以在你的before_scenario中使用environment.py钩子来迭代场景的标签:

def before_scenario(context, scenario):
    for tag in scenario.tags:
        if tag not in (... tuple of valid values ...):
            raise ValueError("unexpected tag: " + tag)

你想要一个类似的钩子来迭代一个特征的标签。

或者,如果您不关心标签是否附加到方案或功能,您可以使用before_tag挂钩而不是上述两个挂钩:

def before_tag(context, tag):
    if tag not in (... tuple of valid values...):
        raise ValueError("unexpected tag: " + tag)

答案 1 :(得分:0)

我使用以下shell命令来获取我在所有功能文件中使用的所有标签的列表:

grep -r --include="*.feature" -h "^\s*@[[:alnum:]._=:,;()-]\+" | tr "[ \r]" "\n" | sed '/^$/d' | sort | uniq -c

说明:

  • 递归grep以匹配功能文件中以标签开头的所有行,而不打印文件名(-h)。正则表达式根据有效标签here的定义。
  • 使用tr 将空格转换为换行符(对于我来说,回车也返回换行符,因为我在WSL中,并且特征文件具有CRLF结尾)
  • 使用sed删除空白行。
  • 排序。
  • 使用uniq删除重复项,并打印每次遇到标签的次数(-c)。

输出看起来像这样:

     13 @bar
      5 @baz
      2 @disabled
      1 @foo
      1 @wip