Lorkenpeist
Lorkenpeist

Reputation: 1495

Robot Framework location and name of keyword

I want to create a python library with a 0 argument function that my custom Robot Framework keywords can call. It needs to know the absolute path of the file where the keyword is defined, and the name of the keyword. I know how to do something similar with test cases using the robot.libraries.BuiltIn library and the ${SUITE_SOURCE} and ${TEST NAME} variables, but I can't find anything similar for custom keywords. I don't care how complicated the answer is, maybe I have to dig into the guts of Robot Framework's internal classes and access that data somehow. Is there any way to do this?

Upvotes: 2

Views: 3705

Answers (2)

Lorkenpeist
Lorkenpeist

Reputation: 1495

Thanks to janne I was able to find the solution.

from robot.running.context import EXECUTION_CONTEXTS

def resource_locator():
    name      = EXECUTION_CONTEXTS.current.keywords[-1].name
    libname   = EXECUTION_CONTEXTS.current.get_handler(name).libname
    resources = EXECUTION_CONTEXTS.current.namespace._kw_store.resources
    path = ""
    for key in resources._keys:
        if resources[key].name == libname:
            path = key
            break
    return {'name': name, 'path': path}

EXECUTION_CONTEXTS.current.keywords is the stack of keywords called, with the earliest first and the most recent last, so EXECUTION_CONTEXTS.current.keywords[-1] gets the last keyword, which is the keyword that called this function.

EXECUTION_CONTEXTS.current.get_handler(name).libname gets the name of the library in which the keyword name is defined. In the case of user defined keywords, it is the filename (not the full path) minus the extension.

EXECUTION_CONTEXTS.current.namespace._kw_store.resources is a dictionary of all included resources, where the key is the absolute path. Because the file path is the key, I have to search for the key such that the value's name is the name of the resource in which the keyword is defined (libname)

Upvotes: 7

janne
janne

Reputation: 1017

I took a relatively quick look through the sources, and it seems that the execution context does have any reference to currently executing keyword. So, the only way I can think of resolving this is:

  1. Your library needs also to be a listener, since listeners get events when a keyword is started
  2. You need to go through robot.libraries.BuiltIn.EXECUTION_CONTEXT._kw_store.resources to find out which resource file contains the keyword currently executing.

I did not do a POC, so I am not sure whether this actually doable, bu that's the solution that comes to my mind currently.

Upvotes: 1

Related Questions