Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 36 ยท Libraries and Resources

Writing Python Keyword Libraries

Create your own Robot Framework keyword library in Python: functions as keywords, the @keyword and @library decorators, class libraries, scope, logging and failures.

When a task is awkward in Robot syntax (calculations, parsing, calling an API, talking to a database), write it in Python. A keyword library is a Python module or class whose functions or methods become keywords automatically. There is no base class and no registration: that is what makes Robot such an easy tool to extend.

All the Python in this lesson that talks to Robot (robot.api) is read-only; the runnable blocks are stand-ins that reproduce how keywords are discovered and run.

A library as a module

MyHelpers.py:

Python
def add_numbers(first, second):
    """Return the sum of two numbers."""
    return int(first) + int(second)

def word_count(text):
    """Return how many words the text has."""
    return len(text.split())

def _private_helper():
    pass   # names starting with an underscore are not keywords

Use it:

ROBOTFRAMEWORK
*** Settings ***
Library    ../libs/MyHelpers.py

*** Test Cases ***
Helpers work
    ${sum}=      Add Numbers    2    3
    ${words}=    Word Count     one two three
    Should Be Equal As Integers    ${sum}    5
    Should Be Equal As Integers    ${words}  3

Rules:

  • Every public function (no leading underscore) is a keyword. add_numbers is called as Add Numbers.
  • The first line of the docstring is the documentation shown by libdoc and IDEs.
  • Arguments from the data are strings, so convert them (int(first)) or use type hints (below).
  • The return value can be assigned to a variable. Returning a list or dict works with @{}/&{} assignment.
  • To fail a keyword, raise an exception, usually AssertionError("message"). The exception message becomes the failure message.

Type hints convert arguments for you

Robot converts string arguments to the types in your annotations and defaults:

Python
def add_numbers(first: int, second: int = 0) -> int:
    return first + second

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

Now Add Numbers 2 3 passes real integers, and an argument like abc fails with a clear conversion error before your code runs. Supported types include int, float, bool, Decimal, bytes, datetime, date, timedelta, Path, list, dict, set, enums, Literal[...] and unions.

The @keyword decorator

Use it to give a keyword a different name, tags, or to rename arguments:

Python
from robot.api.deco import keyword

@keyword("Convert Celsius To Fahrenheit", tags=["temperature"])
def celsius_to_fahrenheit(celsius: float) -> float:
    return celsius * 9 / 5 + 32

@keyword("Temperature of ${city} should be ${value:\\d+}")
def temperature_should_be(city, value):
    ...

The second example shows an embedded-argument keyword written in Python. Normal Python names stay readable in code; the decorator gives the Robot-facing name.

Class libraries and scope

A class groups related keywords and can hold state:

Python
from robot.api import logger
from robot.api.deco import keyword, library

@library(scope="SUITE", version="1.0")
class Counter:
    def __init__(self, start: int = 0):
        self.value = start

    def increment(self, step: int = 1) -> int:
        self.value += step
        logger.info(f"counter is now {self.value}")
        return self.value

    def counter_should_be(self, expected: int):
        if self.value != expected:
            raise AssertionError(f"{self.value} != {expected}")

    def _format(self) -> str:    # leading underscore: not a keyword
        return f"Counter({self.value})"

Import it with constructor arguments: Library Counter.py start=10.

The library scope controls how long an instance lives:

Scope New instance for each Typical use
GLOBAL (default) whole run Connections, expensive setup
SUITE suite State shared by one file
TEST test case Isolated state, safest for tests

Without the decorator, set ROBOT_LIBRARY_SCOPE = "SUITE" as a class attribute. The decorator @library also controls auto_keywords=False, which makes only methods with @keyword into keywords, a good habit for larger libraries.

Logging and console output

Python
from robot.api import logger

logger.info("Shown in the log")
logger.debug("Only at DEBUG level")
logger.warn("Also shown in the console and the errors list")
logger.info("Visible live in the terminal", also_console=True)
logger.info("<b>HTML</b>", html=True)

Use logger rather than print(): plain print output goes to the log at INFO level, but logger offers levels and HTML. For long operations, log progress so a stuck test is easy to diagnose.

Other failure types

  • AssertionError is the usual choice: a failed check.
  • Any other exception (for example ValueError) also fails the keyword, but Robot shows the exception name in the message. That is useful for "unexpected error".
  • from robot.api import Failure, ContinuableFailure, FatalError, SkipExecution give special effects: ContinuableFailure lets the test continue, FatalError stops the whole run, SkipExecution marks the test skipped.
  • Setting ROBOT_SUPPRESS_NAME = True on an exception hides its class name in the message.

Testing your library

Because keywords are plain Python functions, test them with pytest without Robot at all. Keep keywords thin: parse the arguments, call tested helper code, raise AssertionError on a failed check.

Stand-in 1: keyword discovery

The blocks below are not Robot Framework (it cannot run here). They reproduce what Robot does when it imports a library: collect public callables, turn their names into Title Case, read the docstring, and convert arguments using type hints.

Python Stand-in: discovering keywords in a module

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.

Stand-in 2: library scope

A SUITE or GLOBAL library keeps its state between calls; a TEST library starts fresh. The stand-in creates library instances per test according to the scope and shows the effect on a counter.

Python Stand-in: library scope

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.

(With a single suite, GLOBAL and SUITE behave the same; they differ when several suites run, because a SUITE library is re-created for each suite.)

Where to put libraries

Keep them in a libs/ folder and import by path (Library ../libs/MyHelpers.py), or install them as a package and import by module name (Library shop_helpers.api). To make a folder importable use --pythonpath libs. Dotted names work for modules in packages: Library mypackage.mymodule. For a class with the same name as its module, such as Counter.py containing class Counter, importing Counter.py gives you the class directly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does the Python function add_numbers appear in Robot?

    Robot turns underscores into spaces; matching ignores case, so Add Numbers works. The decorator is only needed for a different name.
  2. 2. How does a library keyword report a failed check?

    Any exception fails a keyword, and AssertionError is the convention for a failed assertion.
  3. 3. Which library scope creates a new instance for every test?

    TEST gives isolated state. GLOBAL (the default) shares one instance for the whole run.
  4. 4. What do type hints such as first: int do?

    Robot uses annotations and default values to convert argument types and reports clear errors for values that cannot be converted.

Summary

  • Public functions of a module, or public methods of a class, become keywords automatically.
  • Use type hints for argument conversion, docstrings for documentation, @keyword for custom names and tags.
  • Raise AssertionError to fail; log with robot.api.logger.
  • Class libraries keep state; choose GLOBAL, SUITE or TEST scope deliberately.
  • Keep keywords thin and unit-test the Python behind them.

Next: Variable Files, Environments and libdoc