Search code examples
pythonpython-3.xrobotframework

Define a keyword to call only on failure in robot framework


Is there any way we can define in setting or any other part of robot code to call keyword immediately when we have a particular kind of failure?

We have Test setup and Test Teardown, which will run at the start as Test Setup or the end of the test case as Test Teardown, similar to that is there any way, we can define and call keyword based on failure

The problem with using Teardown is when we have 5 lines of robot code (Keywords) if the failure happens on the second line, it will skip the third, fourth, and fifth line and directly runs the Teardown this is the issue for me in using Teardown. If we have a failure in the second line, it will call the defined keyword which needs to be run and then comes back and run third, fourth, and fifth line (Without Skipping).


Solution

  • With a listener library you can implement such functionality. Create a keyword that will set the desired keyword to be executed on failure. Implement the end_keyword listener function to detect when a keyword failure occurs.

    Lastly execute the configured keyword using the BuiltIn library run_keyword function.

    Example:

    from robot.api import logger
    from robot.libraries.BuiltIn import BuiltIn
    
    class RunOnFailureLibrary(object):
        ROBOT_LISTENER_API_VERSION = 2
        ROBOT_LIBRARY_SCOPE = 'GLOBAL'
        ROBOT_LIBRARY_VERSION = 0.1
    
        def __init__(self):
            self.ROBOT_LIBRARY_LISTENER = self
            self.keyword_to_run_on_faiure = None
            self.keyword_args = None
    
        def set_keyword_to_run_on_failure(self, keyword, *args):
            self.keyword_to_run_on_faiure = keyword
            if len(args) > 0:
                self.keyword_args = args
            
        def _end_keyword(self, name, attributes):
            if attributes['status'] == 'FAIL':
                logger.info(f"Running keyword:'{self.keyword_to_run_on_faiure}' on failure!")
                if self.keyword_args is None:
                    BuiltIn().run_keyword(self.keyword_to_run_on_faiure)
                else:
                    BuiltIn().run_keyword(self.keyword_to_run_on_faiure, *self.keyword_args)
            
    
    globals()[__name__] = RunOnFailureLibrary
    

    Usage:

    *** Settings ***
    Library    RunOnFailureLibrary
    Suite Setup    Set Keyword To Run On Failure    Log Many    1    2   3
    
    *** Test Cases ***
    Test
        Log    1
        Log    2
        Fail   0
        Log    3
        Log    4
    

    Result (run with robot --pythonpath . test.robot):

    enter image description here

    As I said in the comments, the rest of the test case still won't be executed. To achieve that you have to ignore the failure as others have suggested.