0
# Configuration and Variables
1
2
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.
3
4
## Capabilities
5
6
### Type Conversion and Validation
7
8
Advanced type conversion system for automatic argument type conversion based on type hints.
9
10
```python { .api }
11
class TypeInfo:
12
"""
13
Class for parsing type hints and converting values based on them.
14
New in Robot Framework 7.0.
15
"""
16
17
def __init__(self, type_hint): ...
18
19
@classmethod
20
def from_type_hint(cls, hint): ...
21
22
def convert(self, value, name=None):
23
"""
24
Convert value based on type information.
25
26
Args:
27
value: Value to convert
28
name: Argument name for error reporting
29
30
Returns:
31
Converted value
32
33
Raises:
34
ValueError: If conversion fails
35
"""
36
37
def validate(self, value, name=None):
38
"""
39
Validate value against type information.
40
41
Args:
42
value: Value to validate
43
name: Argument name for error reporting
44
45
Returns:
46
True if valid
47
48
Raises:
49
TypeError: If validation fails
50
"""
51
52
@property
53
def name(self): ...
54
@property
55
def nested(self): ...
56
@property
57
def is_union(self): ...
58
@property
59
def is_string(self): ...
60
@property
61
def is_number(self): ...
62
```
63
64
**Usage Examples:**
65
66
```python
67
from robot.api import TypeInfo
68
69
# Create type info from type hints
70
int_type = TypeInfo.from_type_hint(int)
71
list_type = TypeInfo.from_type_hint(List[str])
72
union_type = TypeInfo.from_type_hint(Union[str, int])
73
74
# Convert values
75
number = int_type.convert("42") # Returns 42 (int)
76
strings = list_type.convert(["a", "b"]) # Returns ["a", "b"] (List[str])
77
78
# Validate values
79
try:
80
int_type.validate("not_a_number")
81
except TypeError as e:
82
print(f"Validation failed: {e}")
83
84
# Use in keyword definitions
85
from robot.api.deco import keyword
86
87
class TypedLibrary:
88
89
@keyword(types=[int, float, bool])
90
def calculate_with_types(self, number: int, factor: float, enabled: bool):
91
"""Robot Framework will automatically convert arguments based on type hints."""
92
if enabled:
93
return number * factor
94
return number
95
```
96
97
### Language and Localization
98
99
Support for multiple languages and custom translations.
100
101
```python { .api }
102
class Language:
103
"""
104
Base class for custom language support.
105
Defines language-specific translations for Robot Framework syntax.
106
"""
107
108
code: str # Language code (e.g., "en", "fi", "pt")
109
name: str # Language name (e.g., "English", "Finnish")
110
settings_header: str # Translation for "*** Settings ***"
111
variables_header: str # Translation for "*** Variables ***"
112
test_cases_header: str # Translation for "*** Test Cases ***"
113
keywords_header: str # Translation for "*** Keywords ***"
114
comments_header: str # Translation for "*** Comments ***"
115
116
# Setting translations
117
documentation: str # "Documentation"
118
tags: str # "Tags"
119
setup: str # "Setup"
120
teardown: str # "Teardown"
121
timeout: str # "Timeout"
122
template: str # "Template"
123
arguments: str # "Arguments"
124
return_: str # "Return"
125
126
# Control structure translations
127
for_: str # "FOR"
128
in_: str # "IN"
129
end: str # "END"
130
if_: str # "IF"
131
else_if: str # "ELSE IF"
132
else_: str # "ELSE"
133
try_: str # "TRY"
134
except_: str # "EXCEPT"
135
finally_: str # "FINALLY"
136
while_: str # "WHILE"
137
138
# Built-in variable translations
139
true: List[str] # ["True", "Yes", "On"]
140
false: List[str] # ["False", "No", "Off"]
141
null: List[str] # ["None", "Null"]
142
143
class Languages:
144
"""
145
Container for multiple languages with search and resolution capabilities.
146
"""
147
148
def __init__(self, languages=None): ...
149
150
@classmethod
151
def from_string(cls, languages): ...
152
153
def __iter__(self): ...
154
def __contains__(self, item): ...
155
def __bool__(self): ...
156
157
@property
158
def languages(self): ...
159
```
160
161
**Usage Examples:**
162
163
```python
164
from robot.api import Languages, Language
165
166
# Define custom language
167
class Portuguese(Language):
168
code = 'pt'
169
name = 'Portuguese'
170
settings_header = '*** Configurações ***'
171
variables_header = '*** Variáveis ***'
172
test_cases_header = '*** Casos de Teste ***'
173
keywords_header = '*** Palavras-Chave ***'
174
documentation = 'Documentação'
175
tags = 'Etiquetas'
176
setup = 'Configuração'
177
teardown = 'Finalização'
178
for_ = 'PARA'
179
in_ = 'EM'
180
end = 'FIM'
181
true = ['Verdadeiro', 'Sim']
182
false = ['Falso', 'Não']
183
184
# Use languages in parsing
185
languages = Languages([Portuguese()])
186
187
# Parse with language support
188
from robot.api.parsing import get_model
189
model = get_model('teste.robot', languages=languages)
190
```
191
192
### Variable System
193
194
Comprehensive variable handling including resolution, scoping, and evaluation.
195
196
```python { .api }
197
def contains_variable(string: str) -> bool:
198
"""
199
Check if string contains Robot Framework variables.
200
201
Args:
202
string: String to check
203
204
Returns:
205
True if string contains variables like ${var} or @{list}
206
"""
207
208
def is_variable(string: str) -> bool:
209
"""Check if string is a variable (${var}, @{list}, &{dict})."""
210
211
def is_scalar_variable(string: str) -> bool:
212
"""Check if string is a scalar variable (${var})."""
213
214
def is_list_variable(string: str) -> bool:
215
"""Check if string is a list variable (@{list})."""
216
217
def is_dict_variable(string: str) -> bool:
218
"""Check if string is a dictionary variable (&{dict})."""
219
220
def is_assign(string: str) -> bool:
221
"""Check if string is a variable assignment."""
222
223
def is_scalar_assign(string: str) -> bool:
224
"""Check if string is a scalar variable assignment."""
225
226
def is_list_assign(string: str) -> bool:
227
"""Check if string is a list variable assignment."""
228
229
def is_dict_assign(string: str) -> bool:
230
"""Check if string is a dictionary variable assignment."""
231
232
def search_variable(string: str, ignore_errors: bool = False):
233
"""
234
Find variable from string and return match information.
235
236
Args:
237
string: String to search
238
ignore_errors: Don't raise errors for invalid syntax
239
240
Returns:
241
VariableMatch object or None if no variable found
242
"""
243
244
def evaluate_expression(expression: str, variables, modules=None, namespace=None):
245
"""
246
Evaluate Python expressions with variable substitution.
247
248
Args:
249
expression: Python expression to evaluate
250
variables: Variable container
251
modules: Additional modules to import
252
namespace: Additional namespace for evaluation
253
254
Returns:
255
Evaluation result
256
"""
257
258
def variable_not_found(name: str, variables, message=None, recommendations=None):
259
"""
260
Handle variable not found errors with recommendations.
261
262
Args:
263
name: Variable name that was not found
264
variables: Variable container
265
message: Custom error message
266
recommendations: Suggested variable names
267
268
Raises:
269
VariableError: With helpful error message
270
"""
271
```
272
273
**Usage Examples:**
274
275
```python
276
from robot.variables import (
277
contains_variable, is_variable, search_variable,
278
evaluate_expression, Variables
279
)
280
281
# Check for variables in strings
282
text1 = "Hello ${name}!"
283
text2 = "No variables here"
284
285
print(contains_variable(text1)) # True
286
print(contains_variable(text2)) # False
287
print(is_variable("${var}")) # True
288
print(is_variable("${var} extra")) # False
289
290
# Search for variables
291
match = search_variable("${user_name}")
292
if match:
293
print(f"Found variable: {match.name}") # "user_name"
294
print(f"Full match: {match.match}") # "${user_name}"
295
296
# Variable evaluation
297
variables = Variables()
298
variables.set_global("${name}", "Robot")
299
variables.set_global("${version}", "7.3.2")
300
301
# Evaluate expressions
302
result = evaluate_expression("len('${name}')", variables)
303
print(result) # 5
304
305
result = evaluate_expression("'${name}' + ' Framework'", variables)
306
print(result) # "Robot Framework"
307
308
# More complex expressions
309
variables.set_global("${numbers}", [1, 2, 3, 4, 5])
310
result = evaluate_expression("sum(${numbers})", variables)
311
print(result) # 15
312
```
313
314
### Variable Containers and Scoping
315
316
Advanced variable storage and scope management.
317
318
```python { .api }
319
class Variables:
320
"""
321
Main variable storage and resolution system.
322
Handles variable scoping, resolution, and type conversion.
323
"""
324
325
def __init__(self, suite=None, test=None, keyword=None): ...
326
327
# Variable setting
328
def set_global(self, name, value): ...
329
def set_suite(self, name, value): ...
330
def set_test(self, name, value): ...
331
def set_keyword(self, name, value): ...
332
def set_local(self, name, value): ...
333
334
# Variable retrieval
335
def get(self, name, default=None): ...
336
def replace_scalar(self, item): ...
337
def replace_list(self, item): ...
338
def replace_string(self, item): ...
339
340
# Variable queries
341
def has_key(self, name): ...
342
def keys(self): ...
343
def current(self): ...
344
345
# Scope management
346
def start_suite(self): ...
347
def end_suite(self): ...
348
def start_test(self): ...
349
def end_test(self): ...
350
def start_keyword(self): ...
351
def end_keyword(self): ...
352
353
class VariableScopes:
354
"""Manages variable scope hierarchy (global, suite, test, keyword, local)."""
355
356
def __init__(self, suite=None, test=None, keyword=None): ...
357
358
def start_suite(self): ...
359
def end_suite(self): ...
360
def start_test(self): ...
361
def end_test(self): ...
362
def start_keyword(self): ...
363
def end_keyword(self): ...
364
365
@property
366
def current(self): ...
367
368
class VariableAssignment:
369
"""Handles variable assignment operations and validation."""
370
371
def __init__(self, assignment): ...
372
373
@property
374
def name(self): ...
375
@property
376
def value(self): ...
377
@property
378
def is_scalar(self): ...
379
@property
380
def is_list(self): ...
381
@property
382
def is_dict(self): ...
383
```
384
385
**Usage Examples:**
386
387
```python
388
from robot.variables import Variables, VariableScopes
389
390
# Create variable container
391
variables = Variables()
392
393
# Set variables at different scopes
394
variables.set_global("${GLOBAL_VAR}", "global value")
395
variables.set_suite("${SUITE_VAR}", "suite value")
396
variables.set_test("${TEST_VAR}", "test value")
397
398
# Retrieve variables
399
global_val = variables.get("${GLOBAL_VAR}")
400
suite_val = variables.get("${SUITE_VAR}")
401
402
# Replace variables in strings
403
template = "Hello ${name}, version ${version}!"
404
variables.set_global("${name}", "Robot Framework")
405
variables.set_global("${version}", "7.3.2")
406
result = variables.replace_string(template)
407
print(result) # "Hello Robot Framework, version 7.3.2!"
408
409
# Work with list variables
410
variables.set_global("@{items}", ["first", "second", "third"])
411
items = variables.replace_list("@{items}")
412
print(items) # ["first", "second", "third"]
413
414
# Scope management
415
scopes = VariableScopes()
416
scopes.start_suite()
417
scopes.start_test()
418
scopes.start_keyword()
419
# ... do work ...
420
scopes.end_keyword()
421
scopes.end_test()
422
scopes.end_suite()
423
```
424
425
### Configuration Settings
426
427
Framework-wide configuration for test execution and output processing.
428
429
```python { .api }
430
class RobotSettings:
431
"""
432
Settings for Robot Framework test execution.
433
Handles command-line options and execution configuration.
434
"""
435
436
def __init__(self, options=None, **extra_options): ...
437
438
# Input/output settings
439
@property
440
def suite_names(self): ...
441
@property
442
def output_directory(self): ...
443
@property
444
def output(self): ...
445
@property
446
def log(self): ...
447
@property
448
def report(self): ...
449
@property
450
def debug_file(self): ...
451
@property
452
def xunit(self): ...
453
454
# Execution settings
455
@property
456
def include_tags(self): ...
457
@property
458
def exclude_tags(self): ...
459
@property
460
def test_names(self): ...
461
@property
462
def suite_names(self): ...
463
@property
464
def metadata(self): ...
465
@property
466
def variables(self): ...
467
@property
468
def variable_files(self): ...
469
470
# Behavior settings
471
@property
472
def dry_run(self): ...
473
@property
474
def exit_on_failure(self): ...
475
@property
476
def skip_teardown_on_exit(self): ...
477
@property
478
def randomize_executionorder(self): ...
479
@property
480
def randomize_suites(self): ...
481
@property
482
def randomize_tests(self): ...
483
484
class RebotSettings:
485
"""
486
Settings for Robot Framework output post-processing.
487
Handles rebot command-line options and processing configuration.
488
"""
489
490
def __init__(self, options=None, **extra_options): ...
491
492
# Similar properties as RobotSettings but for post-processing
493
@property
494
def merge(self): ...
495
@property
496
def start_time(self): ...
497
@property
498
def end_time(self): ...
499
@property
500
def elapsed_time(self): ...
501
```
502
503
**Usage Examples:**
504
505
```python
506
from robot.conf import RobotSettings, RebotSettings
507
508
# Configure test execution
509
settings = RobotSettings({
510
'outputdir': 'results/',
511
'loglevel': 'DEBUG',
512
'include': ['smoke', 'critical'],
513
'exclude': ['slow'],
514
'variable': ['ENV:test', 'VERSION:1.0'],
515
'metadata': ['Version:1.0', 'Environment:Test'],
516
'randomize': 'tests'
517
})
518
519
# Configure result processing
520
rebot_settings = RebotSettings({
521
'outputdir': 'processed_results/',
522
'name': 'Merged Test Results',
523
'merge': True,
524
'include': ['critical'],
525
'reporttitle': 'Critical Test Report'
526
})
527
528
# Use settings programmatically
529
from robot import run
530
531
result = run('tests/',
532
outputdir=settings.output_directory,
533
loglevel='DEBUG',
534
include=settings.include_tags,
535
exclude=settings.exclude_tags)
536
```
537
538
### Variable Resolution and Matching
539
540
Advanced variable search and resolution utilities.
541
542
```python { .api }
543
class VariableMatch:
544
"""
545
Result of variable search operation.
546
Contains information about found variable.
547
"""
548
549
@property
550
def name(self): ... # Variable name without decoration
551
@property
552
def identifier(self): ... # Variable identifier (${}, @{}, &{})
553
@property
554
def base(self): ... # Base name without index/key
555
@property
556
def index(self): ... # Index/key for item access
557
@property
558
def match(self): ... # Full matched string
559
@property
560
def start(self): ... # Start position in string
561
@property
562
def end(self): ... # End position in string
563
564
class VariableMatches:
565
"""Collection of multiple variable matches in a string."""
566
567
def __init__(self, string): ...
568
569
def __iter__(self): ...
570
def __len__(self): ...
571
def __bool__(self): ...
572
573
@property
574
def matches(self): ...
575
576
class VariableResolver:
577
"""Resolves variables in strings and data structures."""
578
579
def __init__(self, variables): ...
580
581
def resolve(self, item): ...
582
def replace_scalar(self, item): ...
583
def replace_list(self, item): ...
584
585
class DictVariableResolver:
586
"""Specialized resolver for dictionary variables."""
587
588
def __init__(self, variables): ...
589
590
def resolve(self, item): ...
591
```
592
593
**Usage Examples:**
594
595
```python
596
from robot.variables import search_variable, VariableMatches, Variables
597
598
# Find all variables in a string
599
text = "User ${user} has ${count} items in @{categories}"
600
matches = VariableMatches(text)
601
602
for match in matches:
603
print(f"Variable: {match.name}")
604
print(f"Type: {match.identifier}")
605
print(f"Position: {match.start}-{match.end}")
606
607
# Resolve complex variable references
608
variables = Variables()
609
variables.set_global("${user}", {"name": "John", "age": 30})
610
variables.set_global("@{items}", ["book", "pen", "notebook"])
611
612
# Access nested variable content
613
user_name = variables.get("${user}[name]") # "John"
614
first_item = variables.get("@{items}[0]") # "book"
615
616
# Complex variable expressions
617
variables.set_global("${config}", {
618
"database": {"host": "localhost", "port": 5432},
619
"api": {"version": "v1", "timeout": 30}
620
})
621
622
db_host = variables.get("${config}[database][host]") # "localhost"
623
api_timeout = variables.get("${config}[api][timeout]") # 30
624
```
625
626
## Types
627
628
```python { .api }
629
# Variable name patterns
630
VariableName = str # Variable name without decorators
631
VariableBase = str # Base variable name
632
VariableIndex = str # Index or key for item access
633
634
# Variable types
635
ScalarVariable = str # ${variable}
636
ListVariable = str # @{variable}
637
DictVariable = str # &{variable}
638
639
# Variable values
640
VariableValue = Any # Any Python object
641
VariableContainer = Dict[str, VariableValue]
642
643
# Type conversion
644
TypeHint = Union[type, str, Tuple["TypeHint", ...]]
645
TypeConverter = Callable[[Any], Any]
646
647
# Language support
648
LanguageCode = str # Two-letter language code (en, fi, pt, etc.)
649
Translation = Union[str, List[str]]
650
651
# Configuration
652
ConfigurationOption = Union[str, int, bool, List[str], Dict[str, str]]
653
ExecutionSettings = Dict[str, ConfigurationOption]
654
655
# Expression evaluation
656
PythonExpression = str
657
EvaluationResult = Any
658
EvaluationNamespace = Dict[str, Any]
659
```