Skip to main content

Python Libraries

Talk Creating Libraries - Why and How from RoboCon 2021

Static Library

A static library has all of its robot framework keywords defined as python functions.

Static Library With a Class

class DemoLibrary:
def __init__(self, *args, **kwargs):
print(f"Sample Library initialized with args: {args} and kwargs: {kwargs}")

def my_keyword(self, *args, **kwargs):
print(f"Keyword got args: {args} and kwargs: {kwargs}")
return "Hello World"
*** Settings ***
Library DemoLibrary.py

*** Test Cases ***
Use a Keyword with multiple arguments
My Keyword Argument 1 Argument 2 Named Argument=One Value

Static Library without a Class

import base64

def encode_as_base64(string):
"""
Encode string as base64.
"""
return base64.b64encode(string.encode())

def decode_from_base64(string):
"""
Decode string from base64.
"""
return base64.b64decode(string).decode()
*** Settings ***
Library LibraryWithoutClass.py

*** Test Cases ***
Use Custom Keywords
${base64} Encode As Base64 This is a Test String
Log ${base64}
${decoded} Decode From Base64 ${base64}
Log ${decoded}

Decorators

You can add decorators like @keyword @not_keyword to mark your functions as keywords and e.g. provide another name for the keyword.

from robot.api.deco import keyword, not_keyword


@keyword('Login via user panel')
def login(username, password):
# ...

@not_keyword
def this_is_not_keyword():
pass

It can even be used to add tags or change the argument conversion.

from robot.api.deco import keyword


@keyword(tags=['tag1', 'tag2'])
def login(username, password):
# ...

@keyword('Custom name', ['tags', 'here'])
def another_example():
# ...

@keyword(types={'count': int, 'case_insensitive': bool})
def example_keyword(count, case_insensitive=True):
if case_insensitive:
# ...

@keyword(types=[int, bool])
def example_keyword(count, case_insensitive=True):
if case_insensitive:
# ...

A simple Calculate.py library with a single keyword that calculates a mathematical expression.

def calculate(term):
if term == "":
return 0
else:
return eval(term)
*** Settings ***
Library Calculate.py

*** Test Cases ***
Perform Calculations
${result} Calculate 1 + 2
Should Be Equal As Numbers ${result} 3
${result} Calculate 10 * 5
Should Be Equal As Numbers ${result} 50
${result} Calculate 8 / 4
Should Be Equal As Numbers ${result} 2
${result} Calculate 2 - 1
Should Be Equal As Numbers ${result} 1

Examples