Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current behave step with Python?

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?

like image 475
Lucas Mello Avatar asked Jul 21 '15 14:07

Lucas Mello


People also ask

How do I run a feature file in behave?

You can run a feature file by using -i or --include flags and then the name of the feature file. For more information check the documentation for command line arguments. There's a lot of useful information hidden in their appendix section.

What is context in Python behave?

Context is a very important feature in Python Behave where the user and Behave can store information to share around. It holds the contextual information during the execution of tests. It is an object that can store user-defined data along with Python Behave-defined data, in context attributes.


1 Answers

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)
like image 133
Louis Avatar answered Oct 07 '22 11:10

Louis