Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current keyword name for log trace?

I am using RobotFramework for autotest and need write a keyword to print enough log info, but I cannot find a method to get current keyword name for log trace. Does anyone have any idea how to achieve it? thanks a lot.

like image 400
Grant-bobo Avatar asked Dec 28 '25 14:12

Grant-bobo


1 Answers

There is no support in robot for getting the current keyword name. Since the code you're writing must be run from a keyword, your keyword should know what its own name is.

If you write your keyword in python, the python library can also be a listener which can push and pop keywords on a stack. You can then use that information to format your error message.

Here's a simple example:

from robot.libraries.BuiltIn import BuiltIn

class ExampleLibrary(object):
    ROBOT_LISTENER_API_VERSION = 2
    ROBOT_LIBRARY_SCOPE = "GLOBAL"

    def __init__(self):
        self.ROBOT_LIBRARY_LISTENER = self
        self.keywords = []

    def _start_keyword(self, name, attrs):
        self.keywords.append(name)

    def _end_keyword(self, name, attrs):
        self.keywords.pop()

    def log_error_message(self, reason):
        message = "{keyword} failed in testcase {testcase}: {reason}"
        BuiltIn().log(message.format(
            keyword=self.keywords[-2],
            testcase=BuiltIn().get_variable_value("${TEST_NAME}"),
            reason=reason,
        ))

Here's an example test case showing how to use it:

*** Settings ***
Library  ExampleLibrary.py

*** Keywords ***
A keyword
    log  inside A keyword
    Another keyword

Another keyword
    log error message  something went wrong

*** Test Cases ***
Example
    A keyword

When you run the above test, you will get the following in the log:

screenshot of log

like image 57
Bryan Oakley Avatar answered Dec 30 '25 03:12

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!