Skip to content

Support method of failing current keyword/test and continuing in python  #3706

Closed

Description

@KotlinIsland

I have a Python function keyword described as A context manager that runs as a Robot keyword that supports continue on error.

@keyword
def test(): # will show as passed in log
    with keyword("will fail", continue_on_error=True): # will show as failed in log and will fail the test
       BuiltIn().fail("foo")
    logger.info("bar") # will run

But the report looks janky because it doesn't make test failed and the error needs to be raised in cleanup.

I guess it boils down to: I want a pure python implementation of "Run Keyword And Continue On Failure"

Here's a rough implementation of keyword:

from contextlib import contextmanager

from robot.libraries.BuiltIn import BuiltIn
from robot.running.statusreporter import StatusReporter

exception_store = None


@contextmanager
def keyword(name, continue_on_error=False):
    """A context manager that runs as a Robot keyword

    continue_on_error: if an error occurs in this keyword, exit and report as failed but continue test
    """
    try:
        with StatusReporter(BuiltIn()._context, Keyword(kwname=name)):
            yield
    except Exception as err:
        if continue_on_error:
            global exception_store
            exception_store = err
            return
        raise err


def cleanup():
    if exception_store:
        raise exception_store

Activity

  1. KotlinIsland commented on Oct 8, 2020

    @KotlinIsland
    ContributorAuthor
    def test():
        BuiltIn().run_keyword_and_continue_on_failure("bar")
        logger.info("foo")  # doesn't run
    
    def bar():
        BuiltIn().fail("bar")
  2. bhirsz commented on Jan 8, 2021

    @bhirsz
    Contributor

    Did you think about using custom exception?

    class MyCustomError(Exception):
        ROBOT_CONTINUE_ON_FAILURE = True
    

    There are also ROBOT_EXIT_ON_FAILURE and ROBOT_SUPPRESS_NAME attributes - check them out from UserGuide.

  3. pekkaklarck commented on Feb 26, 2021

    @pekkaklarck
    Member

    First of all, sorry for missing this issue earlier. Could you @KotlinIsland please explain what you try to accomplish? If you want a pure-Python Run Keyword And Continue On Failure, why isn't using BuiltIn.run_keyword_and_continue_on_failure() enough? Alternatively your libraries could use continuable failures as @bhirsz already mentioned. Starting from RF 4.0 you can simply import ContinuableFailure from robot.api (#3685).

  4. KotlinIsland commented on Mar 18, 2021

    @KotlinIsland
    ContributorAuthor

    @pekkaklarck
    Run Keyword And Continue On Failure doesn't continue the python function:

    rf = BuiltIn()
    
    def keyword1() -> None:
        rf.run_keyword_and_continue_on_failure("bar")
        rf.log("foo")  # doesn't run
    
    
    def bar() -> None:
        raise ContinuableFailure("hi")

    image

    What I want

    I want to be able to write:

    def keyword1() -> None:
        rf.log("start")
        with keyword("kw1"):
            rf.log("in kw1")
            raise ContinuableFailure("hi")
            rf.log("unreachable")
        rf.log("end")

    Currently my keyword function produces the following report:
    image
    Issues with this:

    • the test passes
    • all calling keywords are marked as passed
  5. pekkaklarck commented on Mar 18, 2021

    @pekkaklarck
    Member

    It's certainly true that in the first example i.e. in

    rf = BuiltIn()
    
    def keyword1() -> None:
        rf.run_keyword_and_continue_on_failure("bar")
        rf.log("foo")  # doesn't run

    the last line won't be run. I don't know what we could do with that nor why you just don't use try/except instead.

    The second example I don't understand at all.

  6. KotlinIsland commented on Mar 18, 2021

    @KotlinIsland
    ContributorAuthor

    I can't use try/except because then the test would pass, that would involve wrapping everything with boilerplate eg:

    rf = BuiltIn()
    
    def keyword1() -> None:
        err = None
        try:
            rf.run_keyword_and_continue_on_failure("bar")
        except e:
            err = e
        rf.log("foo")  # runs now :)
        if err: 
            raise err

    I want nested keywords within python code where the report looks nice and the python looks nice. I also want to be able to raise assertion errors within those keywords that will fail the keyword, the keyword will exit early, but will not exit anything else, and will make the entire testcase fail.

    I want this because it makes the report and code logically structured and look similar.

    def foo():
        with keyword("outer"):
            with keyword("inner1"):
                assert 1 == 2
            with keyword("inner2"):
                assert 1 == 2
            rf.log('blah blah")

    Currently I would have to introduce boilerplate to achieve what I want.

  7. pekkaklarck commented on Mar 19, 2021

    @pekkaklarck
    Member

    Supporting something like

    some_code_that_raises_an_exception()
    code_that_nevertheless_continues()

    is totally out of scope of RF. I guess it could be possible with some Python magic but not something for us.

    I'm still not sure what the latter example is supposed to do. We do have @keyword decorator but you need to explain what you try to do with with keyword(...).

  8. KotlinIsland commented on Mar 19, 2021

    @KotlinIsland
    ContributorAuthor

    Here is my keyword function:

    @contextmanager
    def keyword(name: str, continue_on_fail) -> Iterator[None]:
        kw = Keyword()
        kw.name = name
        try:
            with StatusReporter(kw, KeywordResult(kwname=name), rf._context):
                yield
        except Exception as err:
            if not continue_on_fail:
                raise err

    This is how it's used:
    image

    The issue is that I'm not sure how to make outer, Foo, and the test fail.

    So currently what I do is store a variable saying that the test should fail and raise it in cleanup.

  9. KotlinIsland commented on Mar 19, 2021

    @KotlinIsland
    ContributorAuthor
    def foo() -> None:
        with keyword("outer"):
            with keyword("inner1"):
                raise ContinuableFailure("hi")
            rf.log("inner1 should fail")
    
            with keyword("inner2"):
                rf.log("this should be passed")
            rf.log("inner2 should pass")
    
            with keyword("inner3"):
                raise ContinuableFailure("hi")
            rf.log("inner3 should fail")
        rf.log("outer should fail")
        rf.log("foo should fail")
        rf.log("test should fail")
        global status
        if err := status:
            status = None
            raise err
    
    
    status: Optional[Exception] = None
    
    
    @contextmanager
    def keyword(name: str) -> Iterator[None]:
        global status
        previous_status = status
        kw = Keyword()
        kw.name = name
        try:
            with StatusReporter(kw, KeywordResult(kwname=name), rf._context):
                yield
                if not previous_status and status:
                    raise status
        except Exception as err:
            status = err

    This works correctly and fails the test as I want, the only downside is that I need to put this boilerplate on every function

        global status
        if err := status:
            status = None
            raise err
  10. KotlinIsland commented on Mar 21, 2021

    @KotlinIsland
    ContributorAuthor

    @pekkaklarck So I guess the last piece of what I need is to add a wrapper to every user keyword. Is there a way I can hook the test library import process and wrap all the functions that get imported?

  11. KotlinIsland commented on May 26, 2021

    @KotlinIsland
    ContributorAuthor

    @pekkaklarck I think I've found a way to get the desired outcome, does this look right to you?

    from contextlib import contextmanager
    from functools import wraps
    from typing import Optional, Iterator
    
    from robot.libraries.BuiltIn import BuiltIn
    from robot.api import ContinuableFailure
    from robot.result import Keyword as KeywordResult
    from robot.running import Keyword
    from robot.running.statusreporter import StatusReporter
    
    rf = BuiltIn()
    
    
    def foo() -> None:
        with keyword("outer"):
            with keyword("inner1"):
                raise ContinuableFailure("hi")
            rf.log("inner1 should fail")
    
            with keyword("inner2"):
                rf.log("this should be passed")
            rf.log("inner2 should pass")
    
            with keyword("inner3"):
                raise ContinuableFailure("hi")
            rf.log("inner3 should fail")
        rf.log("outer should fail")
        rf.log("foo should fail")
        rf.log("test should fail")
    
    
    status: Optional[Exception] = None
    
    
    @contextmanager
    def keyword(name: str) -> Iterator[None]:
        global status
        previous_status = status
        kw = Keyword()
        kw.name = name
        try:
            with StatusReporter(kw, KeywordResult(kwname=name), rf._context):
                yield
                if not previous_status and status:
                    raise status
        except Exception as err:
            status = err
    
    
    def set_up():
        def wrapper(fn):
            @wraps(fn)
            def inner(*args, **kwargs):
                fn(*args, **kwargs)
                global status
                if err := status:
                    status = None
                    raise err
    
            return inner
    
        for l in rf._namespace.libraries:
                for h in l.handlers._normal.values():
                    h._method = wrapper(h._method)
    *** Settings ***
    Suite Setup    set_up
    Library    main
    
    *** Test Cases ***
    test1
        foo
  12. pekkaklarck commented on Sep 14, 2021

    @pekkaklarck
    Member

    I still don't fully understand what you try to accomplish. Based on the above and newer #4038 it seems like you want to run Python code so that you get keywords created in the log file. As I just commented #4038, we could have an API for that purpose but someone needed to design (and implement it).

    I cannot comment the example above much without trying it out myself and I don't have time for that. What I can say is that you are using some internal APIs (e.g. StatusReporter) that aren't guaranteed to be stable between major releases. An official stable and public API for this purpose would thus be a lot better.

  13. pekkaklarck commented on Sep 14, 2021

    @pekkaklarck
    Member

    It seems to me that what this issue originally asks i.e.

    Support method of failing current keyword/test and continuing in python

    isn't in out scope. Having an API to create keywords that are shown in the log file would probably be a good idea, though, and a separate issue should be submitted about that. Or did I miss something here?

  14. pekkaklarck commented on Mar 15, 2022

    @pekkaklarck
    Member

    The underlying feature request seems to be same as proposed in #4252. Closing this one.

  15. KotlinIsland commented on Mar 15, 2022

    @KotlinIsland
    ContributorAuthor

    The underlying feature request seems to be same as proposed in #4252. Closing this one.

    @pekkaklarck Unfortunately #4252 is unrelated to the underlying request 😔. I have re-raised this issue as #4276.

  16. pekkaklarck commented on Mar 15, 2022

    @pekkaklarck
    Member

    This issue proposes adding new context manager that would create nested keywords under a library keyword exactly like #4252 proposes. I thought that was the main point.

  17. KotlinIsland commented on Mar 15, 2022

    @KotlinIsland
    ContributorAuthor

    No, the keyword context manager was just to illustrate the desire to fail current keyword and continue, while also making parent keywords fail.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions