6

我刚刚开始使用行为,一个使用Gherkin 语法的 Pythonic BDD 框架。行为具有特征,例如:

Scenario: Calling the metadata API
   Given A matching server
   When I call metadata
   Then metadata response is JSON
   And response status code is 200

还有一个步骤文件,例如:

...
@then('response status code is {expected_status_code}')
def step_impl(context, expected_status_code):
    assert_equals(context.response.status_code, int(expected_status_code))

@then('metadata response is JSON')
def step_impl(context):
    json.loads(context.metadata_response.data)
...

并将它们组合成漂亮的测试报告:

试验结果

其中一些步骤 - 例如:

  • metadata response is JSON
  • response status code is {expected_status_code}

在我的许多项目中都使用过,我想将它们分组到一个可以导入和重用的通用步骤文件中。

我尝试将有用的步骤提取到一个单独的文件并导入它,但收到以下错误:

@then('response status code is {expected_status_code}')
NameError: name 'then' is not defined

如何创建通用步骤文件并导入它?

4

2 回答 2

5

仅针对所有(像我一样)试图导入单步定义的人:不要!

只需导入整个模块。

在这里,所有仍然需要更多细节的人(比如我......):

如果您的项目结构如下所示:

foo/bar.py
foo/behave/steps/bar_steps.py
foo/behave/bar.feature
foo/common_steps/baz.py

做就是了

import foo.common_steps.baz

在 foo/behave/steps/bar_steps.py (这是您的常规步骤文件)

于 2016-05-24T11:36:19.337 回答
3

在导入的文件中,then必须导入行为装饰器(如 ):

from behave import then
from nose.tools import assert_equals

@then('response status code is {expected_status_code}')
def step_impl(context, expected_status_code):
    assert_equals(context.response.status_code, int(expected_status_code))

...
于 2014-02-03T09:25:16.430 回答