robot.api package

robot.api package exposes the public APIs of Robot Framework.

Unless stated otherwise, the APIs exposed in this package are consideredstable, and thus safe to use when building external tools on top ofRobot Framework. Notice that all parsing APIs were rewritten in RobotFramework 3.2.

Currently exposed APIs are:

  • logger module for libraries’ logging purposes.

  • deco module with decorators libraries can utilize.

  • exceptions module containing exceptions that libraries can utilize forreporting failures and other events. These exceptions can be imported also directlyviarobot.api likefromrobot.apiimportSkipExecution.

  • interfaces module containing optional base classes that can be usedwhen creating libraries and other extensions. New in Robot Framework 6.1.

  • types module with types exposed for libraries and other extensions.New in Robot Framework 7.4.

  • parsing module exposing the parsing APIs. This module is new in RobotFramework 4.0. Various parsing related functions and classes were exposeddirectly viarobot.api already in Robot Framework 3.2, but they areeffectively deprecated and will be removed in the future.

  • TestSuite class for creating executabletest suites programmatically andTestSuiteBuilder classfor creating such suites based on existing test data on the file system.

  • SuiteVisitor abstract class for processing testdatabefore execution. This can be used as a base for implementing a pre-runmodifier that is taken into use with--prerunmodifier commandline option.

  • ExecutionResult() factory methodfor reading execution results from XML output files andResultVisitor abstract class to easefurther processing the results.ResultVisitor can also be used as a basefor pre-Rebot modifier that is taken into use with--prerebotmodifiercommandline option.

  • ResultWriter class for writingreports, logs, XML outputs, and XUnit files. Can write results based onXML outputs on the file system, as well as based on the result objectsreturned by theExecutionResult() oran executedTestSuite.

  • TypeInfo class for parsingtype hints and converting values based on them. New in Robot Framework 7.0.

  • Languages andLanguageclasses for external tools that need to work with different translations.The latter is also the base class to use with custom translations.

All of the above classes can be imported like:

fromrobot.apiimportClassName

The public API intends to follow thedistributing type information specificationoriginally specified inPEP 484.

See documentations of the individual APIs for more details.

Tip

APIs related to the command line entry points are exposed directlyvia therobot root package.

Submodules

robot.api.deco module

robot.api.deco.not_keyword(func:F)F[source]

Decorator to disable exposing functions or methods as keywords.

Examples:

@not_keyworddefnot_exposed_as_keyword():# ...defexposed_as_keyword():# ...

Alternatively the automatic keyword discovery can be disabled withthelibrary() decorator or by setting theROBOT_AUTO_KEYWORDSattribute to a false value.

New in Robot Framework 3.2.

robot.api.deco.keyword(func:K,/)K[source]
robot.api.deco.keyword(name:str|None=None,tags:Sequence[str]=(),types:TypeHints|None=())Callable[[K],K]

Decorator to set custom name, tags and argument types to keywords.

This decorator createsrobot_name,robot_tags androbot_typesattributes on the decorated keyword function or method based on theprovided arguments. Robot Framework checks them to determine the keyword’sname, tags, and argument types, respectively.

Name must be given as a string, tags as a list of strings, and typeseither as a dictionary mapping argument names to types or as a listof types mapped to arguments based on position. It is OK to specify typesonly to some arguments, and settingtypes toNone disables typeconversion altogether.

If the automatic keyword discovery has been disabled with thelibrary() decorator or by setting theROBOT_AUTO_KEYWORDSattribute to a false value, this decorator is needed to mark functionsor methods keywords.

Examples:

@keyworddefexample():# ...@keyword('Login as user "${user}" with password "${password}"',tags=['custom name','embedded arguments','tags'])deflogin(user,password):# ...@keyword(types={'length':int,'case_insensitive':bool})deftypes_as_dict(length,case_insensitive):# ...@keyword(types=[int,bool])deftypes_as_list(length,case_insensitive):# ...@keyword(types=None)defno_conversion(length,case_insensitive=False):# ...
robot.api.deco.library(cls:L,/)L[source]
robot.api.deco.library(scope:Literal['GLOBAL','SUITE','TEST','TASK']|None=None,version:str|None=None,converters:dict[type,Callable[[Any],Any]|Callable[[Any,Any],Any]]|None=None,doc_format:Literal['ROBOT','HTML','TEXT','REST']|None=None,listener:Any|None=None,auto_keywords:bool=False)Callable[[L],L]

Class decorator to control keyword discovery and other library settings.

Disables automatic keyword detection by setting class attributeROBOT_AUTO_KEYWORDS=False to the decorated library by default. In thatmode only methods decorated explicitly with thekeyword() decoratorbecome keywords. If that is not desired, automatic keyword discovery can beenabled by usingauto_keywords=True.

Argumentsscope,version,converters,doc_format andlistenerset library’s scope, version, converters, documentation format and listener byusing class attributesROBOT_LIBRARY_SCOPE,ROBOT_LIBRARY_VERSION,ROBOT_LIBRARY_CONVERTERS,ROBOT_LIBRARY_DOC_FORMAT andROBOT_LIBRARY_LISTENER, respectively. These attributes are only set ifthe related arguments are given, and they override possible existing attributesin the decorated class.

Examples:

@libraryclassKeywordDiscovery:@keyworddefdo_something(self):# ...defnot_keyword(self):# ...@library(scope='GLOBAL',version='3.2')classLibraryConfiguration:# ...

The@library decorator is new in Robot Framework 3.2.Theconverters argument is new in Robot Framework 5.0.

robot.api.exceptions module

Exceptions that libraries can use for communicating failures and other events.

These exceptions can be imported also via the top levelrobot.api package likefromrobot.apiimportSkipExecution.

This module and all exceptions are new in Robot Framework 4.0.

exceptionrobot.api.exceptions.Failure(message:str,html:bool=False)[source]

Bases:AssertionError

Report failed validation.

There is no practical difference in using this exception compared to usingthe standardAssertionError. The main benefits are HTML support and thatthe name of this exception is consistent with other exceptions in this module.

Parameters:
  • message – Exception message.

  • html – WhenTrue, message is considered to be HTML and not escaped.

ROBOT_SUPPRESS_NAME=True
exceptionrobot.api.exceptions.ContinuableFailure(message:str,html:bool=False)[source]

Bases:Failure

Report failed validation but allow continuing execution.

Parameters:
  • message – Exception message.

  • html – WhenTrue, message is considered to be HTML and not escaped.

ROBOT_CONTINUE_ON_FAILURE=True
exceptionrobot.api.exceptions.Error(message:str,html:bool=False)[source]

Bases:RuntimeError

Report error in execution.

Failures related to the system not behaving as expected should typically bereported using theFailure exception or the standardAssertionError.This exception can be used, for example, if the keyword is used incorrectly.

There is no practical difference in using this exception compared to usingthe standardRuntimeError. The main benefits are HTML support and thatthe name of this exception is consistent with other exceptions in this module.

Parameters:
  • message – Exception message.

  • html – WhenTrue, message is considered to be HTML and not escaped.

ROBOT_SUPPRESS_NAME=True
exceptionrobot.api.exceptions.FatalError(message:str,html:bool=False)[source]

Bases:Error

Report error that stops the whole execution.

Parameters:
  • message – Exception message.

  • html – WhenTrue, message is considered to be HTML and not escaped.

ROBOT_EXIT_ON_FAILURE=True
ROBOT_SUPPRESS_NAME=False
exceptionrobot.api.exceptions.SkipExecution(message:str,html:bool=False)[source]

Bases:Exception

Mark the executed test or task skipped.

Parameters:
  • message – Exception message.

  • html – WhenTrue, message is considered to be HTML and not escaped.

ROBOT_SKIP_EXECUTION=True
ROBOT_SUPPRESS_NAME=True

robot.api.interfaces module

Optional base classes for libraries and other extensions.

Module contents:

Main benefit of using these base classes is that editors can provide automaticcompletion, documentation and type information. Their usage is not required.Notice also that libraries typically use the static API and do not need anybase class.

Note

These classes are not exposed via the top levelrobot.apipackage and need to imported viarobot.api.interfaces.

This module is new in Robot Framework 6.1.

classrobot.api.interfaces.DynamicLibrary[source]

Bases:ABC

Optional base class for libraries using the dynamic library API.

The dynamic library API makes it possible to dynamically specifywhat keywords a library implements and run them by usingget_keyword_names() andrun_keyword() methods, respectively.In addition to that it has various optional methods for returning moreinformation about the implemented keywords to Robot Framework.

abstractmethodget_keyword_names()Sequence[str][source]

Return names of the keywords this library implements.

Returns:

Keyword names as a list of strings.

name passed to other methods is always in the same format asreturned by this method.

abstractmethodrun_keyword(name:str,args:Sequence[Any],named:Mapping[str,Any])Any[source]

Execute the specified keyword using the given arguments.

Parameters:
  • name – Keyword name as a string.

  • args – Positional arguments as a list.

  • named – Named arguments as a dictionary.

Raises:

Reporting FAIL or SKIP status.

Returns:

Keyword’s return value.

Reporting status, logging, returning values, etc. is handled the sameway as with the normal static library API.

get_keyword_documentation(name:str)str|None[source]

Optional method to return keyword documentation.

The first logical line of keyword documentation is shown inthe execution log under the executed keyword. The wholedocumentation is shown in documentation generated by Libdoc.

Parameters:

name – Keyword name as a string.

Returns:

Documentation as a string orasNone if there is nodocumentation.

This method is also used to get the overall library documentation aswell as documentation related to importing the library. They aregot by calling this method with special names__intro__ and__init__, respectively.

get_keyword_arguments(name:str)Sequence[str|tuple[str]|tuple[str,Any]]|None[source]

Optional method to return keyword’s argument specification.

Returned information is used during execution for argument validation.In addition to that, arguments are shown in documentation generatedby Libdoc.

Parameters:

name – Keyword name as a string.

Returns:

Argument specification using format explained below.

Argument specification defines what arguments the keyword accepts.ReturningNone means that the keywords accepts any arguments.Accepted arguments are returned as a list using these rules:

  • Normal arguments are specified as a list of strings like['arg1','arg2']. An empty list denotes that the keywordaccepts no arguments.

  • Varargs must have a* prefix like['*numbers']. There canbe only one varargs, and it must follow normal arguments.

  • Arguments after varargs like['*items','arg'] are considerednamed-only arguments.

  • If keyword does not accept varargs, a lone* can be useda separator between normal and named-only arguments like['normal','*','named'].

  • Kwargs must have a** prefix like['**config']. There canbe only one kwargs, and it must be last.

Both normal arguments and named-only arguments can have default values:

  • Default values can be embedded to argument names so that they areseparated with the equal sign likename=default. In this casethe default value type is always a string.

  • Alternatively arguments and their default values can be representedas two-tuples like('name','default'). This allows non-stringdefault values and automatic argument conversion based on them.

  • Arguments without default values can also be specified as tuplescontaining just the name like('name',).

  • With normal arguments, arguments with default values must followarguments without them. There is no such restriction with named-onlyarguments.

get_keyword_types(name:str)Mapping[str,type|str|UnionType|tuple[type|str|UnionType|tuple[TypeHint,...],...]]|Sequence[type|str|UnionType|tuple[type|str|UnionType|tuple[TypeHint,...],...]|None]|None[source]

Optional method to return keyword’s type specification.

Type information is used for automatic argument conversion duringexecution. It is also shown in documentation generated by Libdoc.

Parameters:

name – Keyword name as a string.

Returns:

Type specification as a dictionary, as a list, or asNoneif type information is not known.

Type information can be mapped to arguments returned byget_keyword_names() either by names using a dictionary orby position using a list. For example, if a keyword has argumentspecification['arg','second'], it would be possible to returntypes both like{'arg':str,'second':int} and[str,int].

Regardless of the approach that is used, it is not necessarily tospecify types for all arguments. When using a dictionary, somearguments can be omitted altogether. When using a list, it is possibleto useNone to mark that a certain argument does not have typeinformation and arguments at the end can be omitted altogether.

If is possible to specify that an argument has multiple possible typesby using unions like{'arg':Union[int,float]} or tuples like{'arg':(int,float)}.

In addition to specifying types using classes, it is also possibleto use names or aliases like{'a':'int','b':'boolean'}.For an up-to-date list of supported types, names and aliases seethe User Guide.

get_keyword_tags(name:str)Sequence[str]|None[source]

Optional method to return keyword’s tags.

Tags are shown in the execution log and in documentation generated byLibdoc. Tags can also be used with various command line options.

Parameters:

name – Keyword name as a string.

Returns:

Tags as a list of strings orNone if there are no tags.

get_keyword_source(name:str)str|None[source]

Optional method to return keyword’s source path and line number.

Source information is used by IDEs to provide navigation fromkeyword usage to implementation.

Parameters:

name – Keyword name as a string.

Returns:

Source as a string in formatpath:lineno orNoneif source is not known.

The general format to return the source ispath:lineno like/example/Lib.py:42. If the line number is not known, it ispossible to return only the path. If the keyword is in the samefile as the main library class, the path can be omitted and onlythe line number returned like:42.

The source information of the library itself is got automatically fromthe imported library class. The library source path is used with allkeywords that do not return their own path.

classrobot.api.interfaces.HybridLibrary[source]

Bases:ABC

Optional base class for libraries using the hybrid library API.

Hybrid library API makes it easy to specify what keywords a libraryimplements by using theget_keyword_names() method. After gettingkeyword names, Robot Framework usesgetattr to get the actual keywordmethods exactly like it does when using the normal static library API.Keyword name, arguments, documentation, tags, and so on are got directlyfrom the keyword method.

It is possible to implement keywords also outside the main library class.In such cases the library needs to have a__getattr__ method thatreturns desired keyword methods.

abstractmethodget_keyword_names()Sequence[str][source]

Return names of the implemented keyword methods as a list or strings.

Returned names must match names of the implemented keyword methods.

classrobot.api.interfaces.StartSuiteAttributes[source]

Bases:TypedDict

Attributes passed to listener v2start_suite method.

See the User Guide for more information.

id:str
longname:str
doc:str
metadata:dict[str,str]
source:str
suites:list[str]
tests:list[str]
totaltests:int
starttime:str
classrobot.api.interfaces.EndSuiteAttributes[source]

Bases:StartSuiteAttributes

Attributes passed to listener v2end_suite method.

See the User Guide for more information.

endtime:str
elapsedtime:int
status:str
statistics:str
message:str
id:str
longname:str
doc:str
metadata:dict[str,str]
source:str
suites:list[str]
tests:list[str]
totaltests:int
starttime:str
classrobot.api.interfaces.StartTestAttributes[source]

Bases:TypedDict

Attributes passed to listener v2start_test method.

See the User Guide for more information.

id:str
longname:str
originalname:str
doc:str
tags:list[str]
template:str
source:str
lineno:int
starttime:str
classrobot.api.interfaces.EndTestAttributes[source]

Bases:StartTestAttributes

Attributes passed to listener v2end_test method.

See the User Guide for more information.

endtime:str
elapedtime:int
status:str
message:str
id:str
longname:str
originalname:str
doc:str
tags:list[str]
template:str
source:str
lineno:int
starttime:str
classrobot.api.interfaces.OptionalKeywordAttributes[source]

Bases:TypedDict

Extra attributes passed to listener v2start/end_keyword methods.

These attributes are included with control structures. For example, withIF structures attributes includecondition.

variables:list[str]|dict[str,str]
flavor:str
condition:str
limit:str
patterns:list[str]
pattern_type:str
variable:str
classrobot.api.interfaces.StartKeywordAttributes[source]

Bases:OptionalKeywordAttributes

Attributes passed to listener v2start_keyword method.

See the User Guide for more information.

type:str
kwname:str
libname:str
doc:str
args:list[str]
assign:list[str]
tags:list[str]
source:str
lineno:int|None
status:str
starttime:str
variables:list[str]|dict[str,str]
flavor:str
condition:str
limit:str
patterns:list[str]
pattern_type:str
variable:str
classrobot.api.interfaces.EndKeywordAttributes[source]

Bases:StartKeywordAttributes

Attributes passed to listener v2end_keyword method.

See the User Guide for more information.

endtime:str
elapsedtime:int
variables:list[str]|dict[str,str]
flavor:str
condition:str
limit:str
patterns:list[str]
pattern_type:str
variable:str
type:str
kwname:str
libname:str
doc:str
args:list[str]
assign:list[str]
tags:list[str]
source:str
lineno:int|None
status:str
starttime:str
classrobot.api.interfaces.MessageAttributes[source]

Bases:TypedDict

Attributes passed to listener v2log_message andmessages methods.

See the User Guide for more information.

message:str
level:str
timestamp:str
html:str
classrobot.api.interfaces.LibraryAttributes[source]

Bases:TypedDict

Attributes passed to listener v2library_import method.

See the User Guide for more information.

args:list[str]
originalname:str
source:str
importer:str|None
classrobot.api.interfaces.ResourceAttributes[source]

Bases:TypedDict

Attributes passed to listener v2resource_import method.

See the User Guide for more information.

source:str
importer:str|None
classrobot.api.interfaces.VariablesAttributes[source]

Bases:TypedDict

Attributes passed to listener v2variables_import method.

See the User Guide for more information.

args:list[str]
source:str
importer:str|None
classrobot.api.interfaces.ListenerV2[source]

Bases:object

Optional base class for listeners using the listener API version 2.

ROBOT_LISTENER_API_VERSION=2
start_suite(name:str,attributes:StartSuiteAttributes)[source]

Called when a suite starts.

end_suite(name:str,attributes:EndSuiteAttributes)[source]

Called when a suite end.

start_test(name:str,attributes:StartTestAttributes)[source]

Called when a test or task starts.

end_test(name:str,attributes:EndTestAttributes)[source]

Called when a test or task ends.

start_keyword(name:str,attributes:StartKeywordAttributes)[source]

Called when a keyword or a control structure like IF starts.

The type of the started item is inattributes['type']. Controlstructures can contain extra attributes that are only relevant to them.

end_keyword(name:str,attributes:EndKeywordAttributes)[source]

Called when a keyword or a control structure like IF ends.

The type of the started item is inattributes['type']. Controlstructures can contain extra attributes that are only relevant to them.

log_message(message:MessageAttributes)[source]

Called when a normal log message are emitted.

The messages are typically logged by keywords, but also the frameworkitself logs some messages. These messages end up to output.xml andlog.html.

message(message:MessageAttributes)[source]

Called when framework’s internal messages are emitted.

Only logged by the framework itself. These messages end up to the syslogif it is enabled.

library_import(name:str,attributes:LibraryAttributes)[source]

Called after a library has been imported.

resource_import(name:str,attributes:ResourceAttributes)[source]

Called after a resource file has been imported.

variables_import(name:str,attributes:VariablesAttributes)[source]

Called after a variable file has been imported.

output_file(path:str)[source]

Called after the output file has been created.

path is an absolute path to the output file ora stringNone if creating the output file is disabled.

log_file(path:str)[source]

Called after the log file has been created.

path is an absolute path to the log file.Not called if creating the log file is disabled.

report_file(path:str)[source]

Called after the report file has been created.

path is an absolute path to the report file.Not called if creating the report file is disabled.

xunit_file(path:str)[source]

Called after the xunit compatible output file has been created.

path is an absolute path to the xunit file.Only called if creating the xunit file is enabled.

debug_file(path:str)[source]

Called after the debug file has been created.

path is an absolute path to the debug file.Only called if creating the debug file is enabled.

close()[source]

Called when the whole execution ends.

With library listeners called when the library goes out of scope.

classrobot.api.interfaces.ListenerV3[source]

Bases:object

Optional base class for listeners using the listener API version 3.

ROBOT_LISTENER_API_VERSION=3
start_suite(data:TestSuite,result:TestSuite)[source]

Called when a suite starts.

end_suite(data:TestSuite,result:TestSuite)[source]

Called when a suite ends.

start_test(data:TestCase,result:TestCase)[source]

Called when a test or task starts.

end_test(data:TestCase,result:TestCase)[source]

Called when a test or tasks ends.

start_keyword(data:Keyword,result:Keyword)[source]

Called when a keyword starts by default.

This method is called, by default, with user keywords, library keywordsand when a keyword call is invalid. It is not called, however, if a morespecificstart_user_keyword(),start_library_keyword() orstart_invalid_keyword() method is implemented.

The default implementation callsstart_body_item().

New in Robot Framework 7.0.

end_keyword(data:Keyword,result:Keyword)[source]

Called when a keyword ends by default.

This method is called, by default, with user keywords, library keywordsand when a keyword call is invalid. It is not called, however, if a morespecificend_user_keyword(),end_library_keyword() orend_invalid_keyword() method is implemented.

The default implementation callsend_body_item().

New in Robot Framework 7.0.

start_user_keyword(data:Keyword,implementation:UserKeyword,result:Keyword)[source]

Called when a user keyword starts.

The default implementation callsstart_keyword().

New in Robot Framework 7.0.

end_user_keyword(data:Keyword,implementation:UserKeyword,result:Keyword)[source]

Called when a user keyword ends.

The default implementation callsend_keyword().

New in Robot Framework 7.0.

start_library_keyword(data:Keyword,implementation:LibraryKeyword,result:Keyword)[source]

Called when a library keyword starts.

The default implementation callsstart_keyword().

New in Robot Framework 7.0.

end_library_keyword(data:Keyword,implementation:LibraryKeyword,result:Keyword)[source]

Called when a library keyword ends.

The default implementation callsstart_keyword().

New in Robot Framework 7.0.

start_invalid_keyword(data:Keyword,implementation:KeywordImplementation,result:Keyword)[source]

Called when an invalid keyword call starts.

Keyword may not have been found, there could have been multiple matches,or the keyword call itself could have been invalid.

The default implementation callsstart_keyword().

New in Robot Framework 7.0.

end_invalid_keyword(data:Keyword,implementation:KeywordImplementation,result:Keyword)[source]

Called when an invalid keyword call ends.

Keyword may not have been found, there could have been multiple matches,or the keyword call itself could have been invalid.

The default implementation callsend_keyword().

New in Robot Framework 7.0.

start_for(data:For,result:For)[source]

Called when a FOR loop starts.

The default implementation callsstart_body_item().

New in Robot Framework 7.0.

end_for(data:For,result:For)[source]

Called when a FOR loop ends.

The default implementation callsend_body_item().

New in Robot Framework 7.0.

start_for_iteration(data:ForIteration,result:ForIteration)[source]

Called when a FOR loop iteration starts.

The default implementation callsstart_body_item().

New in Robot Framework 7.0.

end_for_iteration(data:ForIteration,result:ForIteration)[source]

Called when a FOR loop iteration ends.

The default implementation callsend_body_item().

New in Robot Framework 7.0.

start_while(data:While,result:While)[source]

Called when a WHILE loop starts.

The default implementation callsstart_body_item().

New in Robot Framework 7.0.

end_while(data:While,result:While)[source]

Called when a WHILE loop ends.

The default implementation callsend_body_item().

New in Robot Framework 7.0.

start_while_iteration(data:WhileIteration,result:WhileIteration)[source]

Called when a WHILE loop iteration starts.

The default implementation callsstart_body_item().

New in Robot Framework 7.0.

end_while_iteration(data:WhileIteration,result:WhileIteration)[source]

Called when a WHILE loop iteration ends.

The default implementation callsend_body_item().

New in Robot Framework 7.0.

start_group(data:Group,result:Group)[source]

Called when a GROUP starts.

The default implementation callsstart_body_item().

New in Robot Framework 7.2.

end_group(data:Group,result:Group)[source]

Called when a GROUP ends.

The default implementation callsend_body_item().

New in Robot Framework 7.2.

start_if(data:If,result:If)[source]

Called when an IF/ELSE structure starts.

The default implementation callsstart_body_item().

New in Robot Framework 7.0.

end_if(data:If,result:If)[source]

Called when an IF/ELSE structure ends.

The default implementation callsend_body_item().

New in Robot Framework 7.0.

start_if_branch(data:IfBranch,result:IfBranch)[source]

Called when an individual IF/ELSE branch starts.

The default implementation callsstart_body_item().

New in Robot Framework 7.0.

end_if_branch(data:IfBranch,result:IfBranch)[source]

Called when an individual IF/ELSE branch ends.

The default implementation callsend_body_item().

New in Robot Framework 7.0.

start_try(data:Try,result:Try)[source]

Called when a TRY/EXCEPT structure starts.

The default implementation callsstart_body_item().

New in Robot Framework 7.0.

end_try(data:Try,result:Try)[source]

Called when a TRY/EXCEPT structure ends.

The default implementation callsend_body_item().

New in Robot Framework 7.0.

start_try_branch(data:TryBranch,result:TryBranch)[source]

Called when an individual TRY/EXCEPT branch starts.

The default implementation callsstart_body_item().

New in Robot Framework 7.0.

end_try_branch(data:TryBranch,result:TryBranch)[source]

Called when an individual TRY/EXCEPT branch ends.

The default implementation callsend_body_item().

New in Robot Framework 7.0.

start_var(data:Var,result:Var)[source]

Called when VAR starts.

The default implementation callsstart_body_item().

New in Robot Framework 7.0.

end_var(data:Var,result:Var)[source]

Called when VAR ends.

The default implementation callsend_body_item().

New in Robot Framework 7.0.

start_break(data:Break,result:Break)[source]

Called when BREAK starts.

The default implementation callsstart_body_item().

New in Robot Framework 7.0.

end_break(data:Break,result:Break)[source]

Called when BREAK ends.

The default implementation callsend_body_item().

New in Robot Framework 7.0.

start_continue(data:Continue,result:Continue)[source]

Called when CONTINUE starts.

The default implementation callsstart_body_item().

New in Robot Framework 7.0.

end_continue(data:Continue,result:Continue)[source]

Called when CONTINUE ends.

The default implementation callsend_body_item().

New in Robot Framework 7.0.

start_return(data:Return,result:Return)[source]

Called when RETURN starts.

The default implementation callsstart_body_item().

New in Robot Framework 7.0.

end_return(data:Return,result:Return)[source]

Called when RETURN ends.

The default implementation callsend_body_item().

New in Robot Framework 7.0.

start_error(data:Error,result:Error)[source]

Called when encountered invalid syntax starts.

The default implementation callsstart_body_item().

New in Robot Framework 7.0.

end_error(data:Error,result:Error)[source]

Called when encountered invalid syntax ends.

The default implementation callsend_body_item().

New in Robot Framework 7.0.

start_body_item(data,result)[source]

Called by default when a keyword or a control structure starts.

New in Robot Framework 7.0.

end_body_item(data,result)[source]

Called by default when a keyword or a control structure ends.

New in Robot Framework 7.0.

log_message(message:Message)[source]

Called when a normal log message are emitted.

The messages are typically logged by keywords, but also the frameworkitself logs some messages. These messages end up to output.xml andlog.html.

message(message:Message)[source]

Called when framework’s internal messages are emitted.

Only logged by the framework itself. These messages end up to the syslogif it is enabled.

library_import(library:TestLibrary,importer:Import)[source]

Called after a library has been imported.

library represents the imported library. It can be inspected andalso modified.importer contains information about the location wherethe library was imported.

New in Robot Framework 7.1.

resource_import(resource:ResourceFile,importer:Import)[source]

Called after a resource file has been imported.

resource represents the imported resource file. It can be inspected andalso modified.importer contains information about the location wherethe resource was imported.

New in Robot Framework 7.1.

variables_import(attrs:dict,importer:Import)[source]

Called after a variable file has been imported.

attrs contains information about the imported variable file. It can beinspected, but modifications to it have no effect.importer` containsinformation about the location where the variable file was imported.

New in Robot Framework 7.1. This method will be changed in the futureso that theattrs dictionary is replaced with an object representingthe imported variable file.

output_file(path:Path|None)[source]

Called after the output file has been created.

path is an absolute path to the output file orNone if creating the output file is disabled.

log_file(path:Path)[source]

Called after the log file has been created.

path is an absolute path to the log file.Not called if creating the log file is disabled.

report_file(path:Path)[source]

Called after the report file has been created.

path is an absolute path to the report file.Not called if creating the report file is disabled.

xunit_file(path:Path)[source]

Called after the xunit compatible output file has been created.

path is an absolute path to the xunit file.Only called if creating the xunit file is enabled.

debug_file(path:Path)[source]

Called after the debug file has been created.

path is an absolute path to the debug file.Only called if creating the debug file is enabled.

close()[source]

Called when the whole execution ends.

With library listeners called when the library goes out of scope.

classrobot.api.interfaces.Parser[source]

Bases:ABC

Optional base class for custom parsers.

Parsers do not need to explicitly extend this class and in simple casesit is possible to implement them as modules. Regardless how a parser isimplemented, it must haveextension attribute andparse()method. Theparse_init() method is optional and only needed ifa parser supports parsing suite initialization files.

The mandatoryextension attribute specifies what file extension orextensions a parser supports. It can be set either as a class or instanceattribute, and it can be either a string or a sequence of strings. Theattribute can also be namedEXTENSION, which typically works betterwhen a parser is implemented as a module.

Example:

frompathlibimportPathfromrobot.apiimportTestSuitefromrobot.api.interfacesimportParser,TestDefaultsclassExampleParser(Parser):extension='.example'defparse(self,source:Path,defaults:TestDefaults)->TestSuite:suite=TestSuite(TestSuite.name_from_source(source),source=source)# parse the source file and add tests to the created suitereturnsuite

The support for custom parsers is new in Robot Framework 6.1.

extension:str|Sequence[str]
abstractmethodparse(source:Path,defaults:TestDefaults)TestSuite[source]

Mandatory method for parsing suite files.

Parameters:
  • source – Path to the file to parse.

  • defaults – Default values set for test in init files.

Thedefaults argument is optional. It is possible to implementthis method also so that it accepts onlysource.

parse_init(source:Path,defaults:TestDefaults)TestSuite[source]

Optional method for parsing suite initialization files.

Parameters:
  • source – Path to the file to parse.

  • defaults – Default values to used with tests in child suites.

Thedefaults argument is optional. It is possible to implementthis method also so that it accepts onlysource.

If this method is not implemented, possible initialization files causean error.

robot.api.logger module

Public logging API for test libraries.

This module provides a public API for writing messages to the log fileand the console. Test libraries can use this API like:

logger.info('My message')

instead of logging through the standard output like:

print('*INFO* My message')

In addition to a programmatic interface being cleaner to use, this APIhas a benefit that the log messages have accurate timestamps.

If the logging methods are used when Robot Framework is not running,the messages are redirected to the standard Pythonlogging moduleusing logger namedRobotFramework.

Log levels

It is possible to log messages using levelsTRACE,DEBUG,INFO,WARN andERROR either using thewrite() function or, morecommonly, with the log level specifictrace(),debug(),info(),warn(),error() functions.

The trace and debug messages are not logged by default, but that can bechanged with the--loglevel command line option. Warnings and errors areautomatically written also to the console and to theTest Execution Errorssection in the log file.

Logging HTML

All methods that are used for writing messages to the log file have anoptionalhtml argument. If a message to be logged is supposed to beshown as HTML, this argument should be set toTrue. Alternatively,write() accepts a pseudo log levelHTML.

Example

fromrobot.apiimportloggerdefmy_keyword(arg):logger.debug(f'Got argument{arg}.')do_something()logger.info('<i>This</i> is a boring example.',html=True)
robot.api.logger.write(msg:str,level:Literal['TRACE','DEBUG','INFO','CONSOLE','HTML','WARN','ERROR']='INFO',html:bool=False)[source]

Writes the message to the log file using the given level.

Valid log levels areTRACE,DEBUG,INFO (default),WARN,andERROR. In addition to that, there are pseudo log levelsHTMLandCONSOLE for logging messages as HTML and for logging messagesboth to the log file and to the console, respectively. With both of thesepseudo levels the level in the log file will beINFO. TheCONSOLElevel is new in Robot Framework 6.1.

Instead of using this method, it is generally better to use the levelspecific methods such asinfo anddebug that have separatehtml argument to control the message format.

robot.api.logger.trace(msg:str,html:bool=False)[source]

Writes the message to the log file using theTRACE level.

robot.api.logger.debug(msg:str,html:bool=False)[source]

Writes the message to the log file using theDEBUG level.

robot.api.logger.info(msg:str,html:bool=False,also_console:bool=False)[source]

Writes the message to the log file using theINFO level.

Ifalso_console argument is set toTrue, the message iswritten both to the log file and to the console.

robot.api.logger.warn(msg:str,html:bool=False)[source]

Writes the message to the log file using theWARN level.

robot.api.logger.error(msg:str,html:bool=False)[source]

Writes the message to the log file using theERROR level.

robot.api.logger.console(msg:str,newline:bool=True,stream:Literal['stdout','stderr']='stdout')[source]

Writes the message to the console.

If thenewline argument isTrue, a newline character isautomatically added to the message.

The message is written to the standard output stream by default.Using the standard error stream is possibly by giving thestreamargument value'stderr'.

robot.api.parsing module

Public API for parsing, inspecting and modifying test data.

Exposed API

The publicly exposed parsing entry points are the following:

Note

This module is new in Robot Framework 4.0. In Robot Framework 3.2 functionsfor getting tokens and model as well as theTokenclass were exposed directly via therobot.api package, but otherparts of the parsing API were not publicly exposed. All code targetingRobot Framework 4.0 or newer should use this module because parsing relatedfunctions and classes will be removed fromrobot.api in the future.

Note

Parsing was totally rewritten in Robot Framework 3.2 and externaltools using the parsing APIs need to be updated. Depending onthe use case, it may be possible to use the higher levelTestSuiteBuilder() instead.

Parsing data to tokens

Data can be parsed to tokens by usingget_tokens(),get_resource_tokens() orget_init_tokens() functions depending on whether the datarepresent a test case (or task) file, a resource file, or a suiteinitialization file. In practice the difference between these functions iswhat settings and sections are valid.

Typically the data is easier to inspect and modify by using the higher levelmodel discussed in the next section, but in some cases having just the tokenscan be enough. Tokens returned by the aforementioned functions areToken instances and they have the token type, value,and position easily available as their attributes. Tokens also have usefulstring representation used by the example below:

fromrobot.api.parsingimportget_tokenspath='example.robot'fortokeninget_tokens(path):print(repr(token))

If theexample.robot used by the above example would contain

*** Test Cases ***ExampleKeywordargumentSecond exampleKeywordxxx*** Keywords ***Keyword    [Arguments]    ${arg}Log    ${arg}

then the beginning of the output got when running the earlier code wouldlook like this:

Token(TESTCASE_HEADER,'*** Test Cases ***',1,0)Token(EOL,'\n',1,18)Token(EOS,'',1,19)Token(TESTCASE_NAME,'Example',2,0)Token(EOL,'\n',2,7)Token(EOS,'',2,8)Token(SEPARATOR,'    ',3,0)Token(KEYWORD,'Keyword',3,4)Token(SEPARATOR,'    ',3,11)Token(ARGUMENT,'argument',3,15)Token(EOL,'\n',3,23)Token(EOS,'',3,24)Token(EOL,'\n',4,0)Token(EOS,'',4,1)

The output shows the token type, value, line number and column offset. When findingtokens by their type, the constants in theToken class suchasToken.TESTCASE_NAME andToken.EOL should be used instead the valuesof these constants like'TESTCASENAME' and'EOL'. These values havechanged slightly in Robot Framework 4.0 and they may change in the future as well.

TheEOL tokens denote end of a line and they include the newline characterand possible trailing spaces. TheEOS tokens denote end of a logicalstatement. Typically a single line forms a statement, but when the...syntax is used for continuation, a statement spans multiple lines. Inspecial cases a single line can also contain multiple statements.

Errors caused by unrecognized data such as non-existing section or setting namesare handled during the tokenizing phase. Such errors are reported using tokensthat haveERROR type and the actual error message in theirerror attribute.Syntax errors such as empty FOR loops are only handled when building the higherlevel model discussed below.

See the documentation ofget_tokens() for detailsabout different ways how to specify the data to be parsed, how to controlshould all tokens or only data tokens be returned, and should variables inkeyword arguments and elsewhere be tokenized or not.

Parsing data to model

Data can be parsed to a higher level model by usingget_model(),get_resource_model(), orget_init_model() functions depending on the type ofthe parsed file same way as whenparsing data to tokens.

The model is represented as an abstract syntax tree (AST) implemented on topof Python’s standardast.AST class. To see how the model looks like, it ispossible to use theast.dump() function or the third-partyastprettymodule:

importastimportastprettyfromrobot.api.parsingimportget_modelmodel=get_model('example.robot')print(ast.dump(model,include_attributes=True))print('-'*72)astpretty.pprint(model)

Running this code with theexample.robot file from the previoussection would produce so much output that it is not included here. Ifyou are going to work with Robot Framework’s AST, you are recommended totry that on your own.

Model objects

The model is build from nodes that are basedast.AST and further categorizedto blocks and statements. Blocks can contain other blocks and statements aschild nodes whereas statements only have tokens containing the actual data asToken instances. Both statements and blocks exposetheir position information vialineno,col_offset,end_lineno andend_col_offset attributes and some nodes have also other special attributesavailable.

Blocks:

Statements:

Inspecting model

The easiest way to inspect what data a model contains is implementingModelVisitor and creatingvisit_NodeName to visit nodes with nameNodeName as needed.The following example illustrates how to find what tests a certain testcase file contains:

fromrobot.api.parsingimportget_model,ModelVisitorclassTestNamePrinter(ModelVisitor):defvisit_File(self,node):print(f"File '{node.source}' has the following tests:")# Call `generic_visit` to visit also child nodes.self.generic_visit(node)defvisit_TestCaseName(self,node):print(f"-{node.name} (on line{node.lineno})")model=get_model('example.robot')printer=TestNamePrinter()printer.visit(model)

When the above code is run using the earlierexample.robot, theoutput is this:

File'example.robot'hasthefollowingtests:-Example(online2)-Secondexample(online5)

Handling errors in model

All nodes in the model haveerrors attribute that contains possible errorsthe node has. These errors include syntax errors such as empty FOR loops or IFwithout a condition as well as errors caused by unrecognized data such asnon-existing section or setting names.

Unrecognized data is handled already during thetokenizing phase. In the modelsuch data is represented asErrornodes and theirerrors attribute contain error information got from theunderlyingERROR tokens. Syntax errors do not createErrornodes, but instead the model has normal nodes such asIfwith errors in theirerrors attribute.

A simple way to go through the model and see are there errors is using theModelVisitordiscussed in the previous section:

classErrorReporter(ModelVisitor):# Implement `generic_visit` to visit all nodes.defgeneric_visit(self,node):ifnode.errors:print(f'Error on line{node.lineno}:')forerrorinnode.errors:print(f'-{error}')ModelVisitor.generic_visit(self,node)

Modifying data

Existing data the model contains can be modified simply by modifying values ofthe underlying tokens. If changes need to be saved, that is as easy as callingthesave() method of the root model object. Whenjust modifying token values, it is possible to still useModelVisitordiscussed in the above section. The next section discusses adding or removingnodes and thenModelTransformershould be used instead.

Modifications to tokens obviously require finding the tokens to be modified.The first step is finding nodes containing the tokens by implementingneededvisit_NodeName methods. Then the exact token or tokenscan be found using nodes’get_token() orget_tokens() methods.If only token values are needed,get_value() orget_values() can be used as a shortcut.First finding nodes and then the right tokens is illustrated bythis keyword renaming example:

fromrobot.api.parsingimportget_model,ModelVisitor,TokenclassKeywordRenamer(ModelVisitor):def__init__(self,old_name,new_name):self.old_name=self.normalize(old_name)self.new_name=new_namedefnormalize(self,name):returnname.lower().replace(' ','').replace('_','')defvisit_KeywordName(self,node):'''Rename keyword definitions.'''ifself.normalize(node.name)==self.old_name:token=node.get_token(Token.KEYWORD_NAME)token.value=self.new_namedefvisit_KeywordCall(self,node):'''Rename keyword usages.'''ifself.normalize(node.keyword)==self.old_name:token=node.get_token(Token.KEYWORD)token.value=self.new_namemodel=get_model('example.robot')renamer=KeywordRenamer('Keyword','New Name')renamer.visit(model)model.save()

If you run the above example using the earlierexample.robot, youcan see that theKeyword keyword has been renamed toNewName. Noticethat a real keyword renamer needed to take into account also keywords usedwith setups, teardowns and templates.

When token values are changed, column offset of the other tokens on sameline are likely to be wrong. This does not affect saving the model or othertypical usages, but if it is a problem then the caller needs to updatedoffsets separately.

Adding and removing nodes

Bigger changes to the model are somewhat more complicated than just modifyingexisting token values. When doing this kind of changes,ModelTransformershould be used instead ofModelVisitorthat was discussed in the previous sections.

Removing nodes is relative easy and is accomplished by returningNonefromvisit_NodeName methods. Remember to return the original node,or possibly a replacement node, from all of these methods when you do notwant a node to be removed.

Adding nodes requires constructing neededModel objects and adding themto the model. The following example demonstrates both removing and adding nodes.If you run it against the earlierexample.robot, you see thatthe first test gets a new keyword, the second test is removed, andsettings section with documentation is added.

fromrobot.api.parsingimport(get_model,Documentation,EmptyLine,KeywordCall,ModelTransformer,SettingSection,SectionHeader,Token)classTestModifier(ModelTransformer):defvisit_TestCase(self,node):# The matched `TestCase` node is a block with `header` and# `body` attributes. `header` is a statement with familiar# `get_token` and `get_value` methods for getting certain# tokens or their value.name=node.header.get_value(Token.TESTCASE_NAME)# Returning `None` drops the node altogether i.e. removes# this test.ifname=='Second example':returnNone# Construct new keyword call statement from tokens. See `visit_File`# below for an example creating statements using `from_params`.new_keyword=KeywordCall([Token(Token.SEPARATOR,'    '),Token(Token.KEYWORD,'New Keyword'),Token(Token.SEPARATOR,'    '),Token(Token.ARGUMENT,'xxx'),Token(Token.EOL)])# Add the keyword call to test as the second item.node.body.insert(1,new_keyword)# No need to call `generic_visit` because we are not# modifying child nodes. The node itself must to be# returned to avoid dropping it.returnnodedefvisit_File(self,node):# Create settings section with documentation. Needed header and body# statements are created using `from_params` method. This is typically# more convenient than creating statements based on tokens like above.settings=SettingSection(header=SectionHeader.from_params(Token.SETTING_HEADER),body=[Documentation.from_params('This is a really\npowerful API!'),EmptyLine.from_params()])# Add settings to the beginning of the file.node.sections.insert(0,settings)# Call `generic_visit` to visit also child nodes.returnself.generic_visit(node)model=get_model('example.robot')TestModifier().visit(model)model.save('modified.robot')

Executing model

It is possible to convert a parsed and possibly modified model into anexecutableTestSuite structure by using itsfrom_model() class method. In this casetheget_model() function should be given thecurdirargument to get possible${CURDIR} variable resolved correctly.

fromrobot.apiimportTestSuitefromrobot.api.parsingimportget_modelmodel=get_model('example.robot',curdir='/home/robot/example')# modify model as neededsuite=TestSuite.from_model(model)suite.run()

For more details about executing the createdTestSuite object, see the documentationof itsrun() method. Notice alsothat if you do not need to modify the parsed model, it is easier toget the executable suite by using thefrom_file_system() class method.

robot.api.types module

Types for libraries and other extensions.

Currently only exposes theSecret type.

New in Robot Framework 7.4.