Skip to content

Support nested keywords with library keywords #4252

Description

@pekkaklarck

Library keywords can execute methods freely, but methods aren't shown in the log file as child keywords. For example,

def do_something():
    do_first_thing('example')
    do_second_thing()

will in the log file be shown as a single keyword without any child keywords. It is possible to use BuiltIn.run_keyword to execute other keywords so that they are shown as child keywords and #4237 discusses better APIs for that usage.

A problem with using BuiltIn.run_keyword is that keywords executed with it must be available as normal keywords either in the library running other keywords or in some other imported library. That's ok if keywords are usable on their own, but it is possible that child keywords cannot be used like that. This problem can be avoided by making it possible to run any callable as the final proposal in #4237 suggests. There could, however, be even better solutions for the underlying need.

A solution I have been thinking is is using a context manager that would create a keyword in log (and in output.xml). We probably could use our existing robot.result.Keyword for that purpose. The usage could be something like this:

def do_something():
    with Keyword('Do first thing', args=['example'], doc='Example'):
        do_first_thing()
    with Keyword('Do second thing'):
        print('No need to call a method, implementation can be directly inside the context manager!')

These are the main benefits of this approach compared to BuitlIn.run_keyword would be:

  1. No need to expose child keywords as real keywords.
  2. No need to even make each child keyword a callable. Implementation could be directly inside the context manager.
  3. It would be possible to add documentation, tags, etc. to be shown in the log file.

Points 1. and 3. would be possible also with execute_keyword proposed in #4237. Executing other keywords has also other use cases than logging child keywords, so #4237 is likely needed anyway. It's not certain is 2. alone worth enough to implement this feature. Possibly using a context manager could result with cleaner code, though.

Activity

  1. added this to the v5.1 milestone on Mar 4, 2022
  2. KotlinIsland commented on Mar 15, 2022

    @KotlinIsland
    Contributor

    Related: #3706 #4038

  3. KotlinIsland commented on Mar 15, 2022

    @KotlinIsland
    Contributor

    I have found that there is often a need to run a single function as a keyword, with the context manager the boilerplate is quite clunky, I use a custom keyword running function (that is correctly typed!)

    def foo():
        keyword(do_thing)("input data")  # appears in log as a child keyword
    
    def do_thing(data: str):
        ...

    This also usable as a decorator that will cause a function to create a log entry every time it is called:

    def foo():
        do_thing("input data")  # appears in log as a child keyword
    
    @keyword
    def do_thing(data: str):
        ...

    Finally it is usable as a context manager, similar to the approach you are proposing, but with the additional functionality of being able to report multiple failures:

    def foo():
        with keyword("Check all the things", continue_on_failure=True):  # appears in the log as a child keyword
            test_failure("fail 1")
            test_failure("fail 2")
            test_failure("fail 3")

    This will log all three errors to the report, albeit the implementation is horrendously hacky.

  4. modified the milestones: v5.1, v5.2 on Jun 20, 2022
  5. modified the milestones: v6.1, on Jan 3, 2023
  6. modified the milestones: , v7.0 on Jun 2, 2023
  7. pekkaklarck commented on Aug 25, 2023

    @pekkaklarck
    MemberAuthor

    No interest towards this lately. Moving to later.

  8. modified the milestones: v7.0, v8.0 on Aug 25, 2023
  9. ian-h-chamberlain commented on Sep 28, 2023

    @ian-h-chamberlain

    @KotlinIsland I know this is an old issue, but are you still using this custom keyword implementation, and if so are you able to share it? I have been looking at doing something similar but I think my implementation is suboptimal, so I'd be curious to see if yours works better for some of the issues I'm facing. This is the gist of what I have so far:

    def keyword(fn):
        ctx = threading.local()
        ctx.called_as_keyword = False
    
        @robot.api.deco.keyword(name=fn.__name__)
        def wrapper(*args, **kwargs):
            if ctx.called_as_keyword:
                args, kwargs = args[:2]
                try:
                    return fn(*args, **kwargs)
                finally:
                    ctx.called_as_keyword = False
    
            ctx.called_as_keyword = True
            return from_robot.run_keyword(fn.__name__, args, kwargs)
    
        return wrapper

    It definitely isn't perfect (has issues when run multithreaded but that is expected), but really what I'd love to have is something like this, but I haven't figured out any way to make _run_some_other_func change its name at runtime to appear how I'd like in the logs. Is this possible with the current API?

    @keyword(name_from_arg=0) # ideally `fn.__name__` shows up in the robot logs
    def _run_some_other_func(fn, *args, **kwargs):
        # do some other random setup or whatever
        fn(*args, **kwargs)
        # do some random teardown
  10. DetachHead commented on Sep 28, 2023

    @DetachHead
    Contributor

    I know this is an old issue, but are you still using this custom keyword implementation, and if so are you able to share it? I have been looking at doing something similar but I think my implementation is suboptimal, so I'd be curious to see if yours works better for some of the issues I'm facing.

    @ian-h-chamberlain a modified version of the decorator @KotlinIsland and I use is available in https://github.com/Detachhead/Pytest-robotframework. The plugin allows you to run robot tests with Pytest and even write your robot tests entirely in python. However you can just use the decorator on its own without any of that if you want:

    from pytest_robotframework import keyword

    However it has no handling for multithreading so I have no idea if it'll work in your case. I didn't even think it was possible to run multiple robot tests at once (due to some of the robot internals I've noticed like how it stores the currently running test in a global EXECUTION_CONTEXTS object) but feel free to raise any issues you encounter

    but really what I'd love to have is something like this, but I haven't figured out any way to make _run_some_other_func change its name at runtime to appear how I'd like in the logs. Is this possible with the current API?

    @keyword(name_from_arg=0) # ideally `fn.__name__` shows up in the robot logs
    def _run_some_other_func(fn, *args, **kwargs):
        # do some other random setup or whatever
        fn(*args, **kwargs)
        # do some random teardown

    You could try this:

    from pytest_robotframework import as_keyword
    
    def _run_some_other_func(fn, *args, **kwargs):
        # do some other random setup or whatever
        with as_keyword(name=fn.__name__):
            fn(*args, **kwargs)
        # do some random teardown
  11. ian-h-chamberlain commented on Sep 29, 2023

    @ian-h-chamberlain

    @DetachHead awesome, thank you!! I am not sure if we will use pytest_robotframework directly as it has a lot of features we don't necessarily need, but it's really helpful to see another implementation for reference. _KeywordDecorator seems like the magic class, and in particular the construction of a StatusReporter and the use of something like @patch_method(LibraryKeywordRunner) might be what I was missing. That is a very interesting project, thanks again for pointing it out!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions