问题
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