Skip to content

Better API for library keywords to execute other keywords #4237

Description

@pekkaklarck

It is a relatively common need for library keywords to be able to run other keywords. One good example is SeleniumLibrary, that makes it possible to register a keyword that will be executed if any of its own keywords fails. Sometimes, especially when doing task automation, it is also beneficial to log actions done by the keyword in the log file separately. For example,

def do_something():
    do_first_thing()
    do_second_thing()

will in the log file be shown as a single keyword without any child keywords, but there are sometimes needs to show do_first_thing and do_second_thing as child keywords.

Nowadays keywords can execute other keywords by using BuiltIn.run_keyword. It works but has several problems:

  1. Arguments are resolved twice. This means replacing variables and handling syntax like \n. For example, if we have a keyword like

    def example(arg):
        BuiltIn().run_keyword('Log To Console', arg)

    and call it like

    Example    c:\\temp
    

    the actually logged string has a tab character. The reason is that \\t is first resolved to string \t which is then on the second round resolved to a tab.

    Double resolving can be avoided be registering the keyword to be a "run keyword variant", but that API isn't really public and it's also pretty bad in general. We have Clean-up semi-public API to register "run keyword variants" and to disable variable resolving in arguments #2190 about enhancing it and making it public, but it would probably be better to avoid this double resolving altogether.

  2. Related to above, the keyword using BuiltIn.run_keyword cannot safely call it without escaping strings. For example, something like BuiltIn.run_keyword('Log To Console', 'c:\\temp') won't work correctly and the argument should be c:\\\\temp instead.

  3. BuiltIn.run_keyword only accepts positional arguments. For example, if we had a keyword implemented like

    def example(upper=False):
        ...
    

    we couldn't call it like BuiltIn.run_keyword('Example', upper=True) but instead needed to use BuiltIn.run_keywod('Example', 'upper=True').

The above examples ought to make it clear that a better API is needed. I have some ideas how to API could look and will write separate comments about that a bit later.

Activity

  1. added this to the v5.1 milestone on Feb 16, 2022
  2. pekkaklarck commented on Mar 3, 2022

    @pekkaklarck
    MemberAuthor

    One possible way to implement this would be using our current robot.running.Keyword. It's already used by BuiltIn.run_keyword and it needed to be enhanced to avoid the problems explained in the above description. This is how it can be used currently:

    kw = Keyword('Log', args=['c:\\\\temp', 'console=True'])
    kw.run(context)

    This usage has several problems:

    1. Arguments have exactly the same problems as explained in the description above. This could be avoided by allowing passing arguments to run instead of passing them to Keyword.
    2. We would need to expose context somehow. Alternatively, and probably better, Keyword.run could find it out itself somehow if not given.
    3. Keyword accepts also many arguments not valid in this kind of usage such as assign.
    4. Executed keyword must be available in some imported library. It would be convenient to be able to just run some callable as a keyword.

    Basically the best we could do would be this:

    kw = Keyword('Log')
    kw.run(args=['c:\\temp'], named_args={'cosole': True})

    This would be an enhancement to the current situation but still not great.

  3. pekkaklarck commented on Mar 3, 2022

    @pekkaklarck
    MemberAuthor

    A benefit of using robot.running.Keyword that was discussed above is that we already have it and it is part of the public API. A problem is that it actually represents a keyword call in test data like:

    ${x} =    Keyword    arg    named=value
    

    Because robot.running.Keyword represents a keyword call, it contains assign and its args contains whatever there is in the data. This causes most of the problems discussed earlier. The class should arguably also be called KeywordCall or something like that instead of Keyword. Due to it being a part of the public API (e.g. visitors use it) renaming it isn't practical.

    We'd actually need something that represents a keyword in a library that we could then call with whatever arguments we want. We have such model objects in robot.running as well, but unfortunately they are pretty bad and not something we want to expose publicly. They should be enhance also for other reasons, but that is likely quite a bit task and not something we can do in RF 5.1.

  4. pekkaklarck commented on Mar 3, 2022

    @pekkaklarck
    MemberAuthor

    In addition to having model objects representing actual keywords, not keyword calls, under robot.running, also robot.libdocpkg implementing Libdoc has them. These model objects aren't a mess like those under robot.running but they aren't part of the public API either. We might want to expose them more publicly so that e.g. IDE plugins could use them, but I'm not sure would they still work well in this particular usage.

    Libdoc is in general working with libraries that it imports, but in here we'd just need to directly get a keyword somehow. Libdoc doesn't have access to the execution context and doesn't know what keywords are available.

  5. pekkaklarck commented on Mar 3, 2022

    @pekkaklarck
    MemberAuthor

    Because we don't have any model objects that could directly be used for this purpose, it could be that the best solution is adding a new entry point to robot.api. I guess something like this would be fine:

    def execute_keyword(name_or_callable, args, named_args):
        ...

    The function could work so that you can either pass a name of the keyword to execute, like you can with BuiltIn.run_keyword, or a callable to execute as a keyword. In the latter case the name to show in logs would naturally be got from the __name__ of the callable. Arguments would be passed to the keyword as-is to avoid problems BuiltIn.run_keyword has.

    The usage would be like this:

    execute_keyword('Log', ['c:\\temp'], {'console': True})

    An alternative API would be:

    def execute_keyword(name_or_callable, *args, **named):
        ...

    It would make the usage nicer

    execute_keyword('Log', 'c:\\temp', console=True)

    but make it impossible to add possible configuration options to execute_keyword itself. We possibly would like to add things like doc and tags to add to the log and there could also be other configuration needs later.

  6. pekkaklarck commented on Mar 4, 2022

    @pekkaklarck
    MemberAuthor

    One thing to take into account with the possible new API is how to handle argument conversion. As this example demonstrates, BuiltIn.run_keyword handles conversion automatically. If we add an API to replace it, that API probably should handle conversion as well.

  7. KotlinIsland commented on Mar 15, 2022

    @KotlinIsland
    Contributor

    Desired functionality: perform "run keyword and continue on failure" and support continuable failures in python code
    (psuedo code moment)

    Continue Example
        Validate All Things On Page
        Log    end
    def validate_all_things_on_page():
      with robot.api.continue_on_failures():
        validate("expected a", get_a())
        validate("expected b", get_b())
        validate("expected c", get_c())
      print("Done!")
    
    def validate_all_things_on_page_alt():
      continuable_validate("expected a", get_a())
      continuable_validate("expected b", get_b())
      continuable_validate("expected c", get_c())
      print("Done!")
    
    def validate(expected, actual):
        if expected != actual:
            robot.api.fail("Unfortunately a '!=' moment was detected in your code 😳")
    
    def continuable_validate(expected, actual):
        if expected != actual:
            robot.api.fail("Unfortunately a '!=' moment was detected in your code 😳", continue=True)

    image

  8. pekkaklarck commented on Mar 15, 2022

    @pekkaklarck
    MemberAuthor

    I don't think continue-on-failure functionality is that important with Python code. You can simply avoid raising exceptions, and catch exceptions caused by code you call, until the keyword ends. For example, instead of something like

    for act, exp in zip(actual, expected):
        if act != exp:
            raise AssertionError(...)

    you can use

    failures = []
    for act, exp in zip(actual, expected):
        if act != exp:
            failures.append((act, exp))
    if failures:
        raise AssertionError(...)

    This way you have a full control on the final error message. Another problem with us automatically trying to catch exceptions in Python code is that it would likely be rather complicated and even more likely slow down execution.

    Being able to log multiple individual failure messages under a single keyword could be nice, though. That we could easily support by making it possible to raise an exception so that its message is actually a list of messages. In the simplest form it could just mean AssertiongError(['First error', 'Second error']). We could log each error separately and then generate "Several failures occurred" error based on the errors automatically. This would be easy to implement and doesn't have that much to do with an API to run other keywords. It would need its own issue, though, so please submit one!

  9. KotlinIsland commented on Mar 15, 2022

    @KotlinIsland
    Contributor

    This way you have a full control on the final error message.

    Sure, but 99% of the time I want exactly whats in my mockup. Also this leads to a massive amount of boilerplate and potential to make a small mistake that could hide real errors.

    automatically trying to catch exceptions in Python code is that it would likely be rather complicated and even more likely slow down execution.

    My example doesn't raise any exceptions, a hypothetical implementation of robot.api.fail could just correctly logs, and appends the failures to a list, and when a keyword is finished that list of errors is handled and flushed.

    In the simplest form it could just mean AssertiongError

    I don't like this, as it would lose the context of when the error occurred, my pseudo code retains the order, timestamp etc of the messages.

    though, so please submit one!

    I have been asking for this feature for ages across a couple of issues, but sure, I'm happy to raise another. 😀

  10. KotlinIsland commented on Mar 15, 2022

    @KotlinIsland
    Contributor
  11. modified the milestones: v5.1, v5.2 on Jun 20, 2022
  12. modified the milestones: v6.1, on Jan 3, 2023
  13. modified the milestones: , v7.0 on Jun 2, 2023
  14. pekkaklarck commented on Aug 25, 2023

    @pekkaklarck
    MemberAuthor

    No interest towards this lately. Moving to later.

  15. modified the milestones: v7.0, v8.0 on Aug 25, 2023
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