No history yet

Advanced Keyword Logic

Making Decisions in Your Tests

Your tests often need to react to different situations. Instead of writing rigid, linear scripts, you can build logic directly into your Robot Framework files. This lets your tests make decisions on the fly, just like a user would.

The simplest way to do this is with conditional execution. The BuiltIn library provides keywords that run other keywords only when a certain condition is met. The two most common are Run Keyword If and Run Keyword Unless.

Run Keyword If executes a keyword when an expression is true. Run Keyword Unless does the opposite, executing only when the expression is false.

These keywords take a Python expression as their first argument. For example, you might check if a variable ${user_status} is equal to 'active'. This approach keeps your logic clean and readable within the test suite itself, reducing the need for custom Python helper files for simple branching.

*** Settings ***
Library    BuiltIn

*** Test Cases ***
User Status Check
    ${user_status}=    Set Variable    pending

    Run Keyword If    '${user_status}' == 'active'    Log    User is active.
    ...    ELSE IF    '${user_status}' == 'pending'    Log    User is pending approval.
    ...    ELSE    Log    User status is unknown or inactive.

    ${is_admin}=    Set Variable    ${False}
    Run Keyword Unless    ${is_admin}    Log    This action is for non-admins only.

Handling Errors Gracefully

Not all failures are created equal. Sometimes, a keyword failing is an expected part of a test, and it shouldn't bring the entire execution to a halt. For example, you might want to check if an element is gone by trying to click it, expecting it to fail. Robot Framework provides tools to manage these scenarios.

Run Keyword And Ignore Error allows a keyword to fail silently. The test continues, and the failure isn't reported. This is useful when a failure is a valid, acceptable outcome.

For situations where you want to record the failure but continue with the current test case, you can use Run Keyword And Continue On Failure. This marks the keyword as failed in the logs but allows the subsequent steps in the test to run. This helps you gather more information about the system's state after an initial failure.

*** Settings ***
Library    BuiltIn

*** Keywords ***
Attempt to Close Popup
    # This keyword might fail if the popup is already closed.
    Run Keyword And Ignore Error    Click Element    id=popup-close-button

Verify Error Message and Continue
    # We expect an error, but want to continue checking other things.
    Run Keyword And Continue On Failure    Page Should Contain    Invalid username or password.
    Log    Continuing test to check page layout.
    Element Should Be Visible    id=login-form

*** Test Cases ***
Login Test with Optional Popup
    [Documentation]    Logs in a user, closing a promotional popup if it appears.
    Open Browser    https://example.com/login    chrome
    Attempt to Close Popup
    Input Text    id=username    user
    Input Text    id=password    wrongpass
    Click Button    id=login-button
    Verify Error Message and Continue

Mastering Variable Scope

In Robot Framework, variables don't just hold values; they also have a specific lifetime and visibility, known as their scope. Understanding scope is crucial for managing data and state across your tests. A variable created in one test case is normally not available in another. But what if you need to share data, like an authentication token or a session ID?

This is where variable scoping keywords come in. You can promote a variable's scope to make it accessible across multiple tests or even the entire suite. There are three main levels of scope beyond the default local scope.

ScopeVisibilityHow to Set
TestThroughout a single test case.Set Test Variable
SuiteThroughout all test cases in a suite.Set Suite Variable
GlobalThroughout all suites in an execution.Set Global Variable

Using the correct scope prevents conflicts and makes your test data flow predictable. Generally, you should use the narrowest scope possible. Only elevate a variable to Suite or Global scope when it's truly necessary to share state between tests.

*** Settings ***
Suite Setup    Get Auth Token

*** Keywords ***
Get Auth Token
    ${token}=    Generate Fake Token
    Set Suite Variable    ${AUTH_TOKEN}    ${token}
    Log    Suite-level token set: ${AUTH_TOKEN}

Generate Fake Token
    RETURN    abc-123-def-456

*** Test Cases ***
Test Endpoint A
    [Documentation]    Uses the suite-level auth token.
    Log    Using token: ${AUTH_TOKEN}
    # ... API call using the token ...

Test Endpoint B
    [Documentation]    Also uses the same suite-level token.
    Log    Using token: ${AUTH_TOKEN}
    # ... another API call ...

Working with Complex Data

Modern testing often involves more than simple strings. You'll frequently work with structured data like lists and dictionaries, especially when dealing with API responses (JSON) or complex configurations. The Collections library is your primary tool for this.

It provides a rich set of keywords for creating, inspecting, and modifying lists and dictionaries directly within your Robot files. This allows you to build dynamic tests that can adapt to the data they receive. For instance, you could fetch a list of users from an API, add a new user to the list, and then verify the new user's details.

*** Settings ***
Library    Collections

*** Test Cases ***
Manage User Dictionary
    # Create a dictionary
    ${user}=    Create Dictionary    username=testuser    status=active    id=101

    # Add a new key-value pair
    Set To Dictionary    ${user}    email=test@example.com

    # Get and log a value
    ${email}=    Get From Dictionary    ${user}    email
    Log    User email is ${email}

    # Check for a key
    Dictionary Should Contain Key    ${user}    status

    # Convert to a list and check length
    ${user_keys}=    Get Dictionary Keys    ${user}
    Length Should Be    ${user_keys}    4

Logic Reuse with Test Templates

What if you need to run the same logical flow with many different data sets? For example, testing a login form with ten different username/password combinations. Copying and pasting the test case is inefficient and hard to maintain. A better way is to use a Test Templates.

A test template links a single keyword to a test case. The test case then becomes a container for data, passing it line by line to the template keyword. This creates a powerful data-driven testing approach, cleanly separating the test logic (the keyword) from the test data (the arguments in the test case).

*** Settings ***
Library           SeleniumLibrary
Test Template     Login with Credentials Should Succeed or Fail

*** Keywords ***
Login with Credentials Should Succeed or Fail
    [Arguments]    ${username}    ${password}    ${expected_status}
    Input Text        id:username    ${username}
    Input Text        id:password    ${password}
    Click Button      id:login-button
    Run Keyword If    '${expected_status}' == 'SUCCESS'    Page Should Contain    Welcome, ${username}!
    ...    ELSE    Page Should Contain    Invalid credentials.
    Go To             /logout

*** Test Cases ***    # USERNAME        # PASSWORD        # EXPECTED_STATUS
Valid User           validuser         validpass         SUCCESS
Invalid Password     validuser         wrongpass         FAIL
Invalid User         invaliduser       anypass           FAIL
Empty Credentials    ${EMPTY}          ${EMPTY}          FAIL

By combining conditional logic, error handling, proper scoping, and data-driven templates, you can build test automation frameworks that are not only powerful but also highly maintainable and easy to read.