Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Test automation · Robot Framework · Chapter 02 / 07

Test automation learning path

02 · Keywords & control flow

Build readable keyword APIs; use returns, branches, failure handling and reliable setup/teardown.

Keyword interfaces and lifecycle

Keyword interfaces define arguments and return values; control flow, exception handling and setup/teardown determine execution. The examples cover these constructs and their dependencies.

User keywords, arguments, returns and reusable interfaces

Design keywords as small APIs with clear inputs, outputs and responsibility.

User keywords are Robot Framework's main composition mechanism. A good keyword has one clear responsibility, explicit arguments, a useful return value when needed, and a name that communicates domain intent.

*** Keywords ***
Build Greeting
    [Arguments]    ${name}    ${prefix}=Hello
    ${message}=    Set Variable    ${prefix}, ${name}!
    RETURN    ${message}

Validate User
    [Arguments]    ${user}    @{required_roles}
    Should Not Be Empty    ${user}[name]
    FOR    ${role}    IN    @{required_roles}
        List Should Contain Value    ${user}[roles]    ${role}
    END

Arguments can be positional, have defaults, accept varargs (@{args}) and named arguments (&{kwargs}). Use named arguments at call sites when a call would otherwise be ambiguous. RETURN is the modern explicit return syntax.

Embedded arguments can make domain language readable:

*** Keywords ***
User ${name} Has Role ${role}
    Log    Checking ${name} / ${role}

Use them selectively. Overly natural-language-like keywords can become hard to search, refactor and debug.

Robot 7 supports private user keywords through the robot:private tag. Use private keywords for implementation details inside one resource file, while exposing a smaller stable public keyword API.

Key points

  • Treat keywords as APIs, not macros
  • Use explicit arguments and returns
  • Keep a small public domain-keyword surface and hide technical helpers

Common pitfalls

  • Creating giant keywords that mix setup, action, assertions and cleanup

IF, FOR, WHILE, BREAK and CONTINUE

Use native control structures when the test really needs branching or iteration.

Modern Robot Framework has native IF/ELSE, FOR, WHILE, BREAK and CONTINUE. Prefer these structures over old Run Keyword If-style patterns for new code because the flow is visible and nestable.

*** Test Cases ***
Control Flow
    ${status}=    Set Variable    ready
    IF    $status == "ready"
        Log    Continue
    ELSE
        Fail    Unexpected status: ${status}
    END

    FOR    ${value}    IN    alpha    beta    gamma
        IF    $value == "beta"
            CONTINUE
        END
        Log    ${value}
    END

Inside expression-based conditions, $variable exposes the underlying Python value directly. ${variable} is replaced before expression evaluation and can create quoting problems with arbitrary strings, so $variable is often safer for expressions.

WHILE is useful for bounded polling or iterative flows:

VAR    ${attempt}    0
WHILE    $attempt < 3
    ${attempt}=    Evaluate    $attempt + 1
    Log    Attempt ${attempt}
END

Do not use a loop to hide missing synchronization. For UI automation, use the library's waiting/assertion mechanisms instead of repeatedly sleeping and checking DOM state yourself.

Key points

  • Prefer native control structures for new code
  • Use $var in expressions when you need the underlying object
  • Bound every polling loop

Common pitfalls

  • Replacing proper library synchronization with WHILE plus Sleep

Failures, TRY/EXCEPT and expected negative paths

Handle only failures you actually expect; let unexpected failures fail the test.

By default, a failing keyword stops the current test body and Robot continues with teardown. This fail-fast behavior is usually desirable. Catch failures only when failure is part of the expected scenario.

Native TRY/EXCEPT/ELSE/FINALLY matches Robot failure messages:

*** Test Cases ***
Expected Failure Path
    TRY
        Should Be Equal    actual    expected
    EXCEPT    actual != expected
        Log    Expected mismatch was observed
    ELSE
        Fail    The comparison unexpectedly passed
    FINALLY
        Log    Always executed
    END

EXCEPT can match literal messages or use type=GLOB, REGEXP or START. Avoid a broad catch-all unless the test truly accepts any failure; otherwise a network error or broken locator can be mistaken for the expected business rejection.

BuiltIn also contains keywords such as Run Keyword And Return Status and Run Keyword And Expect Error. They are useful for compact negative checks, but native TRY blocks are often clearer once handling becomes multi-step.

Continue-on-failure features exist, especially in teardowns, but do not use them to collect dozens of unrelated failures in one test. A test should still represent one coherent behavior.

Key points

  • Unexpected failures should normally propagate
  • Match expected errors narrowly
  • FINALLY is for unconditional cleanup or evidence, not for hiding failures

Common pitfalls

  • Catching every error and converting infrastructure failures into a passing negative test

Suite, test and keyword setup/teardown

Make lifecycle ownership explicit and guarantee cleanup even after failures.

Robot supports suite, test and user-keyword setup/teardown. Setups establish preconditions; teardowns release resources and are executed even when the corresponding body fails.

*** Settings ***
Suite Setup       Start Environment
Suite Teardown    Stop Environment
Test Setup        Reset Test Data
Test Teardown     Capture Evidence And Clean Up

*** Test Cases ***
Uses Default Lifecycle
    Do Something

Overrides Setup
    [Setup]    Prepare Special State
    Do Something Else

A failed suite setup prevents tests in that suite from running. A suite teardown still runs. A test teardown runs even if the test setup or test body fails. Teardown keywords themselves use continue-on-failure semantics so cleanup steps are attempted even when an earlier cleanup step fails.

Directories can define suite initialization with __init__.robot. This is useful for directory-level suite setup, teardown, metadata and other shared suite settings, but only initialization files that belong to the executed suite hierarchy take effect.

Robot 7 also supports [Setup] and [Teardown] for user keywords. Use keyword teardown when a reusable keyword opens a temporary resource that it must close regardless of the body result.

Key points

  • Put resource ownership at the narrowest lifecycle that can manage it safely
  • Teardowns are guaranteed cleanup paths, not optional final steps
  • A failed suite setup prevents child tests from executing

Common pitfalls

  • Opening expensive global resources per test or keeping mutable resources alive across unrelated suites

Source registry

10 chapter references
Robot Framework User Guide

Core syntax, variables, control structures, suites, execution, output files and extension APIs

Robot Framework Foundation · Official documentation
Source ↗
Robot Framework Guides

Getting started, project structure, libraries, examples and CI guidance

Robot Framework Foundation · Official guides
Source ↗
Robot Framework releases

Current stable releases, maintenance status and release notes

Robot Framework · Official release history
Source ↗
Robot Framework Standard Libraries

BuiltIn, Collections, String, DateTime, OperatingSystem, Process, XML and other bundled libraries

Robot Framework Foundation · Official documentation
Source ↗
Robot Framework Browser

Playwright-backed web automation, locators, assertions, waiting and browser lifecycle

Robot Framework Browser contributors · Official documentation
Source ↗
Robot Framework RequestsLibrary

HTTP API testing with sessionless and session-based requests

MarketSquare / RequestsLibrary contributors · Official library documentation
Source ↗
Robot Framework Python libraries

Creating custom keywords and libraries in Python

Robot Framework Foundation · Official guide
Source ↗
Libdoc

Generating and inspecting library and resource-file documentation

Robot Framework Foundation · Official documentation
Source ↗
Running tests in parallel with Pabot

Parallel suite/test execution, process count, sharding and shared resources

Robot Framework Foundation · Official guide
Source ↗
Robot Framework in GitHub Actions

Running Robot Framework in CI and preserving reports

Robot Framework Foundation · Official guide
Source ↗