How to get the current behave step with Python?

喜夏-厌秋 提交于 2019-12-31 01:01:14

问题


I'm using behave with Python to do my tests. In the step file, I want to get the current step name, because if the test fails, I take a screenshot and rename the file to the step name.

Something like this:

Given user is logged in
When user does something
Then something happens

And I wanted my step code to be like this:

@given('user is logged in')  
try:  
   # MY CODE HERE  
except:  
   # GET THE STEP NAME HERE

Anyone have an idea how to do this?


回答1:


I've done essentially what you are trying to do, take a screenshot of a failed test, by setting an after_step hook in my environment.py file.

def after_step(context, step):
    if step.status == "failed":
        take_the_shot(context.scenario.name + " " + step.name)

You most likely want the scenario name in there too if a step can appear in multiple scenarios.

If the above does not work for you, unfortunately behave does not set a step field on context with the current step like it does for scenario with the current scenario or feature with the current feature. You could have a before_step hook that performs such assignment and then in the step itself, you'd access the step's name as context.step.name. Something like:

def before_step(context, step):
    context.step = step

And the step implementation:

def step_impl(context):
    if some_condition:
        take_the_shot(context.scenario.name + " " + context.step.name)


来源:https://stackoverflow.com/questions/31541758/how-to-get-the-current-behave-step-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!