0

我有一个行为步骤,它调用另一个 python 类中的方法,如下所示

@when('we query for a specific resource')
def step_impl(context):

context.resource='myresource'
jsonutil=JSONUtil.JSONUtil()
response=jsonutil.parseJSON(context.resource)
assert True

JSONUtil类中的parsejson方法如下

def parseJSON(self,resource):

    url= "http://"+data.test.engine_url+'/api/v1/policies?resource='+resource
    response=requests.get(url)
    time.sleep(5)
    json_data = json.loads(response.text)
    #time.sleep(5)
    #print(json_data)
    x=[1,2,3]
    for i in x:
        print("%d" % i)

    #for json_obj in json_data:
    #        if 'statements' in json_obj:
    #            print(json_obj['statements'][0]['resource'][0])

    return response

执行此步骤时。我得到以下输出

1
2
<<Note that 3 does not get printed>>

但是当通过以下方式调用 parsejson 方法时

J=JSONUtil()
J.parseJSON('myJSON')

我得到以下输出

1
2
3

关于为什么使用行为调用代码时执行for循环n-1次的任何原因/指针?

4

1 回答 1

0

我所知道的唯一一件事可以解释为什么在 Behave 外部正确生成预期行的代码会突然产生缺少最后一行的输出,如果Behave 中运行:输出将被 Behave 的输出覆盖。默认情况下,在 Behave 运行步骤之前,它会以中性颜色将步骤名称打印到屏幕上,在步骤运行之后 Behave用步骤名称覆盖输出的最后一行,颜色指示步骤是否失败、成功、是否未定义等

我的补救措施是在我的打印输出中添加更多换行符。您也可以使用--no-color. 我更喜欢有颜色,所以我添加换行符。

这是一个插图。考虑这个功能文件:

Feature: foo

Scenario: foo
  When something
  And something else
  And and another thing

这些步骤:

@when("something")
def step_impl(context):
    for i in (1, 2, 3):
        print("%d" % i)

@when("something else")
def step_impl(context):
    for i in (1, 2, 3):
        print("%d" % i)
    print()

@when("and another thing")
def step_impl(context):
    pass

如果你运行behave --no-capture

behave --no-capture
Feature: foo # features/foo.feature:1

  Scenario: foo           # features/foo.feature:3
    When something        # features/steps/steps.py:1
1
2
    When something        # features/steps/steps.py:1 0.000s
    And something else    # features/steps/steps.py:6
1
2
3
    And something else    # features/steps/steps.py:6 0.000s
    And and another thing # features/steps/steps.py:12 0.000s

1 feature passed, 0 failed, 0 skipped
1 scenario passed, 0 failed, 0 skipped
3 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.000s

(上面的输出将是彩色的,但复制和粘贴不会保留颜色。)

步骤“当某事”缺少最后一行输出,而“当某事”有所有预期的行,只是因为它最后有一个额外print的行。但是,请注意对于这两个步骤,步骤名称如何在输出中出现两次。考虑到颜色,在这两种情况下,步骤名称第一次出现时为灰色,第二次出现时为绿色。如果你也运行它--no-color,你会得到:

Feature: foo # features/foo.feature:1

  Scenario: foo           # features/foo.feature:3
    When something        # features/steps/steps.py:1
1
2
3
    And something else    # features/steps/steps.py:6
1
2
3

    And and another thing # features/steps/steps.py:12

1 feature passed, 0 failed, 0 skipped
1 scenario passed, 0 failed, 0 skipped
3 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.000s

两个循环都输出预期的行,并且步骤的名称不会出现多次。

于 2016-04-27T10:37:08.473 回答