如何确切看看Behave出了什么问题

JOG*_*JOG 11 bdd cucumber nbehave jbehave python-behave

我们最近开始使用Behave(github链接)用于新的python Web服务的BDD.

有什么方法可以在测试失败时获得有关失败原因的详细信息吗?他们扔了AssertionError,但他们从来没有表明究竟出了什么问题.例如,期望值和进入断言的实际值.

我们一直试图找到这样的现有功能,但我想它不存在.当然,这个问题的一个很好的答案是关于如何通过修改源代码来实现这种行为的提示和技巧,以及这个特性是否存在于其他类似的BDD框架中,如jBehave,NBehave或Cucumber?

今天,当测试失败时,输出结果如下:

  Scenario: Logout when not logged in                  # features\logout.feature:6
    Given I am not logged in                               # features\steps\logout.py:5
    When I log out                                     # features\steps\logout.py:12
    Then the response status should be 401             # features\steps\login.py:18
      Traceback (most recent call last):
        File "C:\pro\venv\lib\site-packages\behave\model.py", line 1037, in run
          match.run(runner.context)
        File "C:\pro\venv\lib\site-packages\behave\model.py", line 1430, in run
          self.func(context, *args, **kwargs)
        File "features\steps\login.py", line 20, in step_impl
          assert context.response.status == int(status)
      AssertionError

      Captured stdout:
      api.new_session
      api.delete_session

      Captured logging:
      INFO:urllib3.connectionpool:Starting new HTTP connection (1): localhost
      ...
Run Code Online (Sandbox Code Playgroud)

我想要更像的东西:

  Scenario: Logout when not logged in                  # features\logout.feature:6
    Given I am not logged in                               # features\steps\logout.py:5
    When I log out                                     # features\steps\logout.py:12
    Then the response status should be 401             # features\steps\login.py:18

ASSERTION ERROR
Expected:   401
But got:    200
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我们通用步骤中的断言清晰地打印出来

`assert context.response.status == int(status)`
Run Code Online (Sandbox Code Playgroud)

但我宁愿有一个像这样的功能

assert(behave.equals, context.response.status, int(status)
Run Code Online (Sandbox Code Playgroud)

或其他任何可以从失败的断言生成动态消息的东西.

小智 15

您可以使用另一个断言提供程序,例如PyHamcrest,谁将为您提供所需的详细信息,而不是使用上面示例中的"原始断言"语句.它会告诉你出了什么问题,比如:

# -- file:features/steps/my_steps.py
from hamcrest import assert_that, equal_to
...
    assert_that(context.response.status, equal_to(int(status)))
Run Code Online (Sandbox Code Playgroud)

也可以看看: