Search code examples
pythonseleniumbddpython-behave

Custom error handler for screenshots in Python-Behave


I created a custom error handler to handle screenshots when fail

#error_handler.py

def screenshot_handler(func):
    def func_wrapper(self):
        try:
            return func(self)
        except Exception as e:
            print("screenshot") 
            return func(self)
    return func_wrapper

#page.py

@screenshot_handler
def assert_login(self,a):
    self.find_element(*DashboardPageLocators.AUTOREFRESH_BUTTON)
    return True

#steps.py
"""
i forced this to fail
"""

@then('map should display')
def step_impl(context):
    page = LoginPage(context)
    page.assert_login()

I want to grab the step argument 'map should display' so I create the filename out of it. The most obvious option is to copy the string, but that would be inefficient, is there a behave function that i could call to do handle this


Solution

  • I do this in the after_step function of environments.py:

    def after_step(context, step):
        if step.status == 'failed':
            step_str = step.name
            # Take screen shot and upload to s3
    

    You get immediate access to the test status and step name, and you don't have to include your own error handling decorators.

    The step variable has a number of nifty things in it:

    (Pdb) pp(dir(step))
    
    ['__class__',
     '__delattr__',
     '__dict__',
     '__dir__',
     '__doc__',
     '__eq__',
     '__format__',
     '__ge__',
     '__getattribute__',
     '__gt__',
     '__hash__',
     '__init__',
     '__init_subclass__',
     '__le__',
     '__lt__',
     '__module__',
     '__ne__',
     '__new__',
     '__reduce__',
     '__reduce_ex__',
     '__repr__',
     '__setattr__',
     '__sizeof__',
     '__str__',
     '__subclasshook__',
     '__weakref__',
     'duration',
     'error_message',
     'exc_traceback',
     'exception',
     'filename',
     'keyword',
     'line',
     'location',
     'name',
     'replay',
     'reset',
     'run',
     'set_values',
     'status',
     'step_type',
     'store_exception_context',
     'table',
     'text',
     'type']
    

    The step string is simply test.name