Robot Framework location and name of keyword

坚强是说给别人听的谎言 提交于 2019-12-08 05:28:09

问题


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?


回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/30538356/robot-framework-location-and-name-of-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!