Search code examples
robotframework

Robot Framework: How to build teardown dynamically


I am trying to build teardown actions dynamically in my test case. For e.g. for every step in the test case I am having a corresponding teardown step. So depending on at which point the test case fails, I am trying to run only those many clean actions in the teardown.

I am expecting something like below to work (unfortunately Run Keywords need to have AND mentioned specifically in the syntax)

*** Settings ***
Library    Collections

*** Test Cases ***
Sample Test1
    ${Cleanup KWS}=    Create List    Log    Cleanup Step1
    Log    Test Step1
    ${Cleanup KW}=    Create List    Log    Cleanup Step2    AND
    ${Cleanup KWS}=    Combine Lists    ${Cleanup KW}    ${Cleanup KWS}
    Log    Test Step2
    ${Cleanup KW}=    Create List    Log    Cleanup Step3    AND
    ${Cleanup KWS}=    Combine Lists    ${Cleanup KW}    ${Cleanup KWS}
    Log    Test Step3

    [Teardown]    Run Keywords    @{Cleanup KWS}

If the above is possible, the test case execution might be more efficient (if test fails in-between) and/or I can avoid unnecessary failures in the teardown stage.

Is there any other elegant way to support the above kind of desired behavior?


Solution

  • You can do this by defining each teardown step in the Keywords sections:

    *** Keywords ***
    Teardown_Step_1
        log to console    Teardown for step 1
    
    Teardown_Step_2
        log to console    Teardown for step 2
    
    Teardown_Step_3
        log to console    Teardown for step 3
    
    Execute teardown steps
        [Documentation]    Execute a list of keywords
        [Arguments]  @{keywords}
        [Return]     @{result}
    
        @{result}=   create list
        FOR  ${keyword}  IN  @{keywords}
            ${keyword result}=  Run keyword  ${keyword}
            Append to list  ${result}  ${keyword result}
        END
    

    And then in the test you can use the above keywords like this:

    Sample Test1
    
        @{teardown_list} =   create list
    
        Log    Test Step1
        append to list    ${teardown_list}     Teardown_Step_1
        Log    Test Step2
        append to list    ${teardown_list}     Teardown_Step_2
        Log    Test Step3
        append to list    ${teardown_list}     Teardown_Step_3
    
        [Teardown]    Execute teardown steps    @{teardown_list}