Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 36 ยท Patterns and Extensions

Writing custom Python libraries

Extend Robot Framework with your own Python library: functions as keywords, classes, the @keyword decorator, type hints, library scope and failing with messages.

Robot Framework's own keywords cover a lot, but real projects soon need something custom: calculate a checksum, read a CSV, call an internal service, compare two files. Instead of bending test files into programs, you write the logic in Python and call it as a keyword. A Python module becomes a Robot library.

This lesson shows how functions turn into keywords, how to name them, how arguments and return values map, how to fail properly, and how classes keep state. The real Robot import is shown read-only; the runnable examples are plain Python that you can test directly (which is itself a big advantage of this approach).

A function is a keyword

Create StringTools.py next to your tests:

Python
def reverse_text(text):
    """Return the text reversed."""
    return text[::-1]

def count_words(text):
    """Return how many words the text contains."""
    return len(text.split())

Import it in Settings and call the functions. Robot matches names ignoring case, spaces and underscores, so reverse_text is Reverse Text:

TEXT
*** Settings ***
Library    StringTools.py

*** Test Cases ***
Reverse And Count
    ${r}=    Reverse Text    robot
    Should Be Equal    ${r}    tobor
    ${n}=    Count Words    one two three
    Should Be Equal As Integers    ${n}    3

Arguments in a test are separated by two spaces and arrive as strings unless a type hint says otherwise. The return value goes into the ${variable} on the left. The docstring appears in the generated documentation (the libdoc tool).

From Python to a keyword

Function def reverse_text(text)
Name Reverse Text
Arguments Spaces separate them.
Return value Assigned to a variable.
1 / 2

Type hints convert arguments

Without hints, a test passing 3 gives your function the string "3". With type hints, Robot converts for you (since Robot Framework 3.1):

Python
def add(a: int, b: int) -> int:
    return a + b

def is_valid_age(age: int, strict: bool = False) -> bool:
    return 18 <= age <= 65 if strict else age >= 18

Now Add 2 3 gives 5, and Is Valid Age 30 strict=True works too. A wrong value such as Add two 3 fails with a clear conversion error before your code runs. Hints also appear in the keyword documentation.

Custom names and the keyword decorator

If you want a keyword name that differs from the function name, or tags and a readable name, use the @keyword decorator:

Python
from robot.api.deco import keyword, library

@library
class OrderTools:
    @keyword("Order Total Should Be")
    def check_total(self, items: list, expected: float):
        total = sum(price * qty for price, qty in items)
        if round(total, 2) != round(expected, 2):
            raise AssertionError(f"Total was {total:.2f}, expected {expected:.2f}")

@library (Robot 4+) marks a class as a library; with @keyword only the decorated methods become keywords, which keeps helper methods hidden. In a test you would write Order Total Should Be ${items} 12.50.

Failing the right way

A keyword fails when it raises an exception. Any exception works, but use AssertionError for "the check is false", since Robot treats it as an ordinary failure with just the message. Make the message say what was expected and what happened:

Python
raise AssertionError(f"Expected status 200 but got {status}")

Other exception types produce a failure with the exception name in front of the message. Two special base classes in robot.api give you control: Failure (an ordinary failure) and Error (stops the whole run). A third idea is a continuable failure (ContinuableFailure) which lets the test carry on after the error is recorded.

Writing assert statements in library code is fine too, but remember Python can be started with -O, which removes asserts. For test logic you rely on, raise AssertionError explicitly.

State with classes and scope

A class library can remember things between keyword calls. Each library has a scope that decides how long the object lives:

Python
class Counter:
    ROBOT_LIBRARY_SCOPE = "TEST"      # TEST, SUITE or GLOBAL

    def __init__(self):
        self.count = 0

    def increment(self):
        self.count += 1
        return self.count
Scope A new instance is created for
TEST (default) every test case
SUITE every suite file
GLOBAL the whole run

Use GLOBAL for expensive setup such as a database connection, but then clean up carefully, since tests share it.

Logging from a library

Use the standard logging module or the Robot API logger so messages land in log.html:

Python
from robot.api import logger

def start_service(name):
    logger.info(f"Starting {name}")
    logger.debug("Details only at DEBUG level")
    logger.warn("Port 8080 was busy, using 8081")
    logger.info("<b>bold</b> message", html=True)

Test your keywords without Robot

A major benefit of Python libraries: you can unit test them with pytest or just call them. This first stand-in is a small library with type-hint style functions and an assertion-style keyword, run directly.

Python Stand-in: a library as plain Python

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

How Robot calls your function

To see what happens under the hood, this second stand-in mimics Robot's name matching and string-to-type conversion using inspect and type hints. It is much simpler than the real thing, but shows the idea.

Python Stand-in: name matching and type conversion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Documenting with libdoc

The libdoc tool generates a web page of your keywords from names, type hints and docstrings:

Terminal
libdoc StringTools.py StringTools.html

Good docstrings (first line a one-sentence summary, then arguments and an example) make the library usable by testers who never open the Python.

When to write Python, when to stay in Robot

Keep in Robot Move to Python
Test steps in business language Parsing, math, dates, files
Short compositions of keywords Loops with real logic, nested conditions
Anything a tester must read Anything you would want to unit test

Rule of thumb: if a user keyword needs more than a few IF or FOR blocks, it wants to be a Python function. See also layered architecture.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does Robot match the keyword Reverse Text to a Python function?

    Keyword names are compared ignoring case, spaces and underscores.
  2. 2. What do type hints such as a: int do for a keyword?

    Robot uses hints to convert arguments and report conversion errors early.
  3. 3. How should a library keyword report a failed check?

    Raising an exception fails the keyword; AssertionError with expected and actual values is the convention.
  4. 4. Which library scope keeps one instance for the whole run?

    GLOBAL creates one instance shared by all suites; TEST is the default.

Summary

  • A Python module or class becomes a library; functions and methods become keywords.
  • Names match ignoring case, spaces and underscores; @keyword sets custom names.
  • Type hints convert arguments; return values go to variables.
  • Fail by raising AssertionError with a helpful message; log with robot.api.logger.
  • ROBOT_LIBRARY_SCOPE controls instance lifetime; document with docstrings and libdoc.

Next: Listeners and pre-run modifiers