Generic automation framework for acceptance testing and robotic process automation (RPA)
—
Robot Framework provides comprehensive APIs for configuration management, language support, type conversion, and variable handling. These systems enable customization of framework behavior, internationalization, and sophisticated variable resolution.
Advanced type conversion system for automatic argument type conversion based on type hints.
class TypeInfo:
"""
Class for parsing type hints and converting values based on them.
New in Robot Framework 7.0.
"""
def __init__(self, type_hint): ...
@classmethod
def from_type_hint(cls, hint): ...
def convert(self, value, name=None):
"""
Convert value based on type information.
Args:
value: Value to convert
name: Argument name for error reporting
Returns:
Converted value
Raises:
ValueError: If conversion fails
"""
def validate(self, value, name=None):
"""
Validate value against type information.
Args:
value: Value to validate
name: Argument name for error reporting
Returns:
True if valid
Raises:
TypeError: If validation fails
"""
@property
def name(self): ...
@property
def nested(self): ...
@property
def is_union(self): ...
@property
def is_string(self): ...
@property
def is_number(self): ...Usage Examples:
from robot.api import TypeInfo
# Create type info from type hints
int_type = TypeInfo.from_type_hint(int)
list_type = TypeInfo.from_type_hint(List[str])
union_type = TypeInfo.from_type_hint(Union[str, int])
# Convert values
number = int_type.convert("42") # Returns 42 (int)
strings = list_type.convert(["a", "b"]) # Returns ["a", "b"] (List[str])
# Validate values
try:
int_type.validate("not_a_number")
except TypeError as e:
print(f"Validation failed: {e}")
# Use in keyword definitions
from robot.api.deco import keyword
class TypedLibrary:
@keyword(types=[int, float, bool])
def calculate_with_types(self, number: int, factor: float, enabled: bool):
"""Robot Framework will automatically convert arguments based on type hints."""
if enabled:
return number * factor
return numberSupport for multiple languages and custom translations.
class Language:
"""
Base class for custom language support.
Defines language-specific translations for Robot Framework syntax.
"""
code: str # Language code (e.g., "en", "fi", "pt")
name: str # Language name (e.g., "English", "Finnish")
settings_header: str # Translation for "*** Settings ***"
variables_header: str # Translation for "*** Variables ***"
test_cases_header: str # Translation for "*** Test Cases ***"
keywords_header: str # Translation for "*** Keywords ***"
comments_header: str # Translation for "*** Comments ***"
# Setting translations
documentation: str # "Documentation"
tags: str # "Tags"
setup: str # "Setup"
teardown: str # "Teardown"
timeout: str # "Timeout"
template: str # "Template"
arguments: str # "Arguments"
return_: str # "Return"
# Control structure translations
for_: str # "FOR"
in_: str # "IN"
end: str # "END"
if_: str # "IF"
else_if: str # "ELSE IF"
else_: str # "ELSE"
try_: str # "TRY"
except_: str # "EXCEPT"
finally_: str # "FINALLY"
while_: str # "WHILE"
# Built-in variable translations
true: List[str] # ["True", "Yes", "On"]
false: List[str] # ["False", "No", "Off"]
null: List[str] # ["None", "Null"]
class Languages:
"""
Container for multiple languages with search and resolution capabilities.
"""
def __init__(self, languages=None): ...
@classmethod
def from_string(cls, languages): ...
def __iter__(self): ...
def __contains__(self, item): ...
def __bool__(self): ...
@property
def languages(self): ...Usage Examples:
from robot.api import Languages, Language
# Define custom language
class Portuguese(Language):
code = 'pt'
name = 'Portuguese'
settings_header = '*** Configurações ***'
variables_header = '*** Variáveis ***'
test_cases_header = '*** Casos de Teste ***'
keywords_header = '*** Palavras-Chave ***'
documentation = 'Documentação'
tags = 'Etiquetas'
setup = 'Configuração'
teardown = 'Finalização'
for_ = 'PARA'
in_ = 'EM'
end = 'FIM'
true = ['Verdadeiro', 'Sim']
false = ['Falso', 'Não']
# Use languages in parsing
languages = Languages([Portuguese()])
# Parse with language support
from robot.api.parsing import get_model
model = get_model('teste.robot', languages=languages)Comprehensive variable handling including resolution, scoping, and evaluation.
def contains_variable(string: str) -> bool:
"""
Check if string contains Robot Framework variables.
Args:
string: String to check
Returns:
True if string contains variables like ${var} or @{list}
"""
def is_variable(string: str) -> bool:
"""Check if string is a variable (${var}, @{list}, &{dict})."""
def is_scalar_variable(string: str) -> bool:
"""Check if string is a scalar variable (${var})."""
def is_list_variable(string: str) -> bool:
"""Check if string is a list variable (@{list})."""
def is_dict_variable(string: str) -> bool:
"""Check if string is a dictionary variable (&{dict})."""
def is_assign(string: str) -> bool:
"""Check if string is a variable assignment."""
def is_scalar_assign(string: str) -> bool:
"""Check if string is a scalar variable assignment."""
def is_list_assign(string: str) -> bool:
"""Check if string is a list variable assignment."""
def is_dict_assign(string: str) -> bool:
"""Check if string is a dictionary variable assignment."""
def search_variable(string: str, ignore_errors: bool = False):
"""
Find variable from string and return match information.
Args:
string: String to search
ignore_errors: Don't raise errors for invalid syntax
Returns:
VariableMatch object or None if no variable found
"""
def evaluate_expression(expression: str, variables, modules=None, namespace=None):
"""
Evaluate Python expressions with variable substitution.
Args:
expression: Python expression to evaluate
variables: Variable container
modules: Additional modules to import
namespace: Additional namespace for evaluation
Returns:
Evaluation result
"""
def variable_not_found(name: str, variables, message=None, recommendations=None):
"""
Handle variable not found errors with recommendations.
Args:
name: Variable name that was not found
variables: Variable container
message: Custom error message
recommendations: Suggested variable names
Raises:
VariableError: With helpful error message
"""Usage Examples:
from robot.variables import (
contains_variable, is_variable, search_variable,
evaluate_expression, Variables
)
# Check for variables in strings
text1 = "Hello ${name}!"
text2 = "No variables here"
print(contains_variable(text1)) # True
print(contains_variable(text2)) # False
print(is_variable("${var}")) # True
print(is_variable("${var} extra")) # False
# Search for variables
match = search_variable("${user_name}")
if match:
print(f"Found variable: {match.name}") # "user_name"
print(f"Full match: {match.match}") # "${user_name}"
# Variable evaluation
variables = Variables()
variables.set_global("${name}", "Robot")
variables.set_global("${version}", "7.3.2")
# Evaluate expressions
result = evaluate_expression("len('${name}')", variables)
print(result) # 5
result = evaluate_expression("'${name}' + ' Framework'", variables)
print(result) # "Robot Framework"
# More complex expressions
variables.set_global("${numbers}", [1, 2, 3, 4, 5])
result = evaluate_expression("sum(${numbers})", variables)
print(result) # 15Advanced variable storage and scope management.
class Variables:
"""
Main variable storage and resolution system.
Handles variable scoping, resolution, and type conversion.
"""
def __init__(self, suite=None, test=None, keyword=None): ...
# Variable setting
def set_global(self, name, value): ...
def set_suite(self, name, value): ...
def set_test(self, name, value): ...
def set_keyword(self, name, value): ...
def set_local(self, name, value): ...
# Variable retrieval
def get(self, name, default=None): ...
def replace_scalar(self, item): ...
def replace_list(self, item): ...
def replace_string(self, item): ...
# Variable queries
def has_key(self, name): ...
def keys(self): ...
def current(self): ...
# Scope management
def start_suite(self): ...
def end_suite(self): ...
def start_test(self): ...
def end_test(self): ...
def start_keyword(self): ...
def end_keyword(self): ...
class VariableScopes:
"""Manages variable scope hierarchy (global, suite, test, keyword, local)."""
def __init__(self, suite=None, test=None, keyword=None): ...
def start_suite(self): ...
def end_suite(self): ...
def start_test(self): ...
def end_test(self): ...
def start_keyword(self): ...
def end_keyword(self): ...
@property
def current(self): ...
class VariableAssignment:
"""Handles variable assignment operations and validation."""
def __init__(self, assignment): ...
@property
def name(self): ...
@property
def value(self): ...
@property
def is_scalar(self): ...
@property
def is_list(self): ...
@property
def is_dict(self): ...Usage Examples:
from robot.variables import Variables, VariableScopes
# Create variable container
variables = Variables()
# Set variables at different scopes
variables.set_global("${GLOBAL_VAR}", "global value")
variables.set_suite("${SUITE_VAR}", "suite value")
variables.set_test("${TEST_VAR}", "test value")
# Retrieve variables
global_val = variables.get("${GLOBAL_VAR}")
suite_val = variables.get("${SUITE_VAR}")
# Replace variables in strings
template = "Hello ${name}, version ${version}!"
variables.set_global("${name}", "Robot Framework")
variables.set_global("${version}", "7.3.2")
result = variables.replace_string(template)
print(result) # "Hello Robot Framework, version 7.3.2!"
# Work with list variables
variables.set_global("@{items}", ["first", "second", "third"])
items = variables.replace_list("@{items}")
print(items) # ["first", "second", "third"]
# Scope management
scopes = VariableScopes()
scopes.start_suite()
scopes.start_test()
scopes.start_keyword()
# ... do work ...
scopes.end_keyword()
scopes.end_test()
scopes.end_suite()Framework-wide configuration for test execution and output processing.
class RobotSettings:
"""
Settings for Robot Framework test execution.
Handles command-line options and execution configuration.
"""
def __init__(self, options=None, **extra_options): ...
# Input/output settings
@property
def suite_names(self): ...
@property
def output_directory(self): ...
@property
def output(self): ...
@property
def log(self): ...
@property
def report(self): ...
@property
def debug_file(self): ...
@property
def xunit(self): ...
# Execution settings
@property
def include_tags(self): ...
@property
def exclude_tags(self): ...
@property
def test_names(self): ...
@property
def suite_names(self): ...
@property
def metadata(self): ...
@property
def variables(self): ...
@property
def variable_files(self): ...
# Behavior settings
@property
def dry_run(self): ...
@property
def exit_on_failure(self): ...
@property
def skip_teardown_on_exit(self): ...
@property
def randomize_executionorder(self): ...
@property
def randomize_suites(self): ...
@property
def randomize_tests(self): ...
class RebotSettings:
"""
Settings for Robot Framework output post-processing.
Handles rebot command-line options and processing configuration.
"""
def __init__(self, options=None, **extra_options): ...
# Similar properties as RobotSettings but for post-processing
@property
def merge(self): ...
@property
def start_time(self): ...
@property
def end_time(self): ...
@property
def elapsed_time(self): ...Usage Examples:
from robot.conf import RobotSettings, RebotSettings
# Configure test execution
settings = RobotSettings({
'outputdir': 'results/',
'loglevel': 'DEBUG',
'include': ['smoke', 'critical'],
'exclude': ['slow'],
'variable': ['ENV:test', 'VERSION:1.0'],
'metadata': ['Version:1.0', 'Environment:Test'],
'randomize': 'tests'
})
# Configure result processing
rebot_settings = RebotSettings({
'outputdir': 'processed_results/',
'name': 'Merged Test Results',
'merge': True,
'include': ['critical'],
'reporttitle': 'Critical Test Report'
})
# Use settings programmatically
from robot import run
result = run('tests/',
outputdir=settings.output_directory,
loglevel='DEBUG',
include=settings.include_tags,
exclude=settings.exclude_tags)Advanced variable search and resolution utilities.
class VariableMatch:
"""
Result of variable search operation.
Contains information about found variable.
"""
@property
def name(self): ... # Variable name without decoration
@property
def identifier(self): ... # Variable identifier (${}, @{}, &{})
@property
def base(self): ... # Base name without index/key
@property
def index(self): ... # Index/key for item access
@property
def match(self): ... # Full matched string
@property
def start(self): ... # Start position in string
@property
def end(self): ... # End position in string
class VariableMatches:
"""Collection of multiple variable matches in a string."""
def __init__(self, string): ...
def __iter__(self): ...
def __len__(self): ...
def __bool__(self): ...
@property
def matches(self): ...
class VariableResolver:
"""Resolves variables in strings and data structures."""
def __init__(self, variables): ...
def resolve(self, item): ...
def replace_scalar(self, item): ...
def replace_list(self, item): ...
class DictVariableResolver:
"""Specialized resolver for dictionary variables."""
def __init__(self, variables): ...
def resolve(self, item): ...Usage Examples:
from robot.variables import search_variable, VariableMatches, Variables
# Find all variables in a string
text = "User ${user} has ${count} items in @{categories}"
matches = VariableMatches(text)
for match in matches:
print(f"Variable: {match.name}")
print(f"Type: {match.identifier}")
print(f"Position: {match.start}-{match.end}")
# Resolve complex variable references
variables = Variables()
variables.set_global("${user}", {"name": "John", "age": 30})
variables.set_global("@{items}", ["book", "pen", "notebook"])
# Access nested variable content
user_name = variables.get("${user}[name]") # "John"
first_item = variables.get("@{items}[0]") # "book"
# Complex variable expressions
variables.set_global("${config}", {
"database": {"host": "localhost", "port": 5432},
"api": {"version": "v1", "timeout": 30}
})
db_host = variables.get("${config}[database][host]") # "localhost"
api_timeout = variables.get("${config}[api][timeout]") # 30# Variable name patterns
VariableName = str # Variable name without decorators
VariableBase = str # Base variable name
VariableIndex = str # Index or key for item access
# Variable types
ScalarVariable = str # ${variable}
ListVariable = str # @{variable}
DictVariable = str # &{variable}
# Variable values
VariableValue = Any # Any Python object
VariableContainer = Dict[str, VariableValue]
# Type conversion
TypeHint = Union[type, str, Tuple["TypeHint", ...]]
TypeConverter = Callable[[Any], Any]
# Language support
LanguageCode = str # Two-letter language code (en, fi, pt, etc.)
Translation = Union[str, List[str]]
# Configuration
ConfigurationOption = Union[str, int, bool, List[str], Dict[str, str]]
ExecutionSettings = Dict[str, ConfigurationOption]
# Expression evaluation
PythonExpression = str
EvaluationResult = Any
EvaluationNamespace = Dict[str, Any]Install with Tessl CLI
npx tessl i tessl/pypi-robotframework