我们最近开始为一个新的python服务的BDD使用行为(github链接)。
问题
当测试失败时,我们是否可以获得关于失败原因的详细信息?他们抛出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
...我想要的更像:
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如您所见,泛型步骤中的断言清楚地显示
`assert context.response.status == int(status)`但我宁愿有这样的功能
assert(behave.equals, context.response.status, int(status)或者任何其他使从失败的断言生成动态消息成为可能的事情。
发布于 2014-04-07 00:40:58
与上面示例中的“原始断言”语句不同,您可以使用另一个断言提供程序,比如PyHamcrest,它将为您提供所需的详细信息。它会告诉你出了什么问题,就像:
# -- file:features/steps/my_steps.py
from hamcrest import assert_that, equal_to
...
assert_that(context.response.status, equal_to(int(status)))另请参阅:
发布于 2014-03-12 07:16:29
根据https://pythonhosted.org/behave/tutorial.html?highlight=debug,and的说法,这个实现是适合我的。
通过使用after_step()钩子,可以很容易地提供“错误/失败上的调试”功能。当步骤失败时,将启动调试器。
通常,只在需要时(在交互模式下)启用此功能是一个好主意。在本例中,这是通过使用环境变量来实现的。
# -- FILE: features/environment.py
# USE: BEHAVE_DEBUG_ON_ERROR=yes (to enable debug-on-error)
from distutils.util import strtobool as _bool
import os
BEHAVE_DEBUG_ON_ERROR = _bool(os.environ.get("BEHAVE_DEBUG_ON_ERROR", "no"))
def after_step(context, step):
if BEHAVE_DEBUG_ON_ERROR and step.status == "failed":
# -- ENTER DEBUGGER: Zoom in on failure location.
# NOTE: Use IPython debugger, same for pdb (basic python debugger).
import ipdb
ipdb.post_mortem(step.exc_traceback)发布于 2019-12-03 07:59:28
不要忘记,您可以始终向断言语句添加信息消息。例如:
assert output is expected, f'{output} is not {expected}'https://stackoverflow.com/questions/22045592
复制相似问题