1
votes

Is there a possibility in Robot Framework to allow executing a custom keyword only in Test Setup part (or alternatively in Test Teardown)? Assuming that I have a keyword called My Setup. If My Setup is executed in a normal step (i.e. not in Test Setup), the test should fail. RF Documentation about User keywords and browsing through StackOverflow didn't give me any meaningful results.

For example, the documentation in Robot Framework's built-in function Run keyword if all tests passed states that "Trying to use it anywhere else results in an error", so I was wondering that there should be some kind of way to apply this for custom keywords, too.

I have tried to fix this by parsing the test file before starting the test execution and checking for any occurences of My Setup that are not in Test Setup. This, however, feels very cumbersome, so what I'm looking for is something like following:

def MySetup(self, some_arg):
    if MAGIC.not_inside_test_setup():
        raise AssertionError('"My Setup" can be executed only in Test Setup')
1

1 Answers

2
votes

I managed to solve this issue with a help from a colleague. The solution was the following:

Assuming that My Setup keyword is defined in library called My Library.

  1. Use a Listener to check when the custom keyword My Setup is executed by the help of listener method called start_keyword. The method contains information whether the keyword is executed as a regular keyword or as a Test Setup/Teardown keyword.
  2. If My Setup is run as not-test-setup keyword, in the listener a global error flag inside My Library should be set through an instance of My Library
  3. At the beginning of the execution of My Setup, check if the global error flag in My Library is set; raise an error if set.

MyLibrary.py

SETUP_ERROR = None

class MyLibrary(object):

    def MySetup(self, some_arg):
        global SETUP_ERROR

        if SETUP_ERROR:
            raise AssertionError(SETUP_ERROR)

        # Otherwise continue with the setup

    def _SetError(self, error):
        global SETUP_ERROR
        SETUP_ERROR = error

Listener.py

from MyLibrary import MyLibrary

class MyListener(object):
    # ...
    def start_keyword(self, name, attributes):
        if name == 'MyLibrary.My Setup' and attributes['type'] != 'Setup':
            MyLibrary()._SetError('"My Setup" can be executed only in Test Setup')