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:
loggermodule for libraries’ logging purposes.decomodule with decorators libraries can utilize.exceptionsmodule containing exceptions that libraries can utilize forreporting failures and other events. These exceptions can be imported also directlyviarobot.apilikefromrobot.apiimportSkipExecution.interfacesmodule containing optional base classes that can be usedwhen creating libraries and other extensions. New in Robot Framework 6.1.typesmodule with types exposed for libraries and other extensions.New in Robot Framework 7.4.parsingmodule exposing the parsing APIs. This module is new in RobotFramework 4.0. Various parsing related functions and classes were exposeddirectly viarobot.apialready in Robot Framework 3.2, but they areeffectively deprecated and will be removed in the future.TestSuiteclass for creating executabletest suites programmatically andTestSuiteBuilderclassfor creating such suites based on existing test data on the file system.SuiteVisitorabstract class for processing testdatabefore execution. This can be used as a base for implementing a pre-runmodifier that is taken into use with--prerunmodifiercommandline option.ExecutionResult()factory methodfor reading execution results from XML output files andResultVisitorabstract class to easefurther processing the results.ResultVisitorcan also be used as a basefor pre-Rebot modifier that is taken into use with--prerebotmodifiercommandline option.ResultWriterclass 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.TypeInfoclass for parsingtype hints and converting values based on them. New in Robot Framework 7.0.LanguagesandLanguageclasses 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 withthe
library()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 creates
robot_name,robot_tagsandrobot_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 setting
typestoNonedisables typeconversion altogether.If the automatic keyword discovery has been disabled with the
library()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 attribute
ROBOT_AUTO_KEYWORDS=Falseto 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.Arguments
scope,version,converters,doc_formatandlistenerset library’s scope, version, converters, documentation format and listener byusing class attributesROBOT_LIBRARY_SCOPE,ROBOT_LIBRARY_VERSION,ROBOT_LIBRARY_CONVERTERS,ROBOT_LIBRARY_DOC_FORMATandROBOT_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
@librarydecorator is new in Robot Framework 3.2.Theconvertersargument 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:
AssertionErrorReport failed validation.
There is no practical difference in using this exception compared to usingthe standard
AssertionError. 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 – When
True, message is considered to be HTML and not escaped.
- ROBOT_SUPPRESS_NAME=True
- exceptionrobot.api.exceptions.ContinuableFailure(message:str,html:bool=False)[source]
Bases:
FailureReport failed validation but allow continuing execution.
- Parameters:
message – Exception message.
html – When
True, 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:
RuntimeErrorReport error in execution.
Failures related to the system not behaving as expected should typically bereported using the
Failureexception 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 standard
RuntimeError. 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 – When
True, message is considered to be HTML and not escaped.
- ROBOT_SUPPRESS_NAME=True
robot.api.interfaces module
Optional base classes for libraries and other extensions.
Module contents:
DynamicLibraryfor libraries using thedynamic library API.HybridLibraryfor libraries using thehybrid library API.Parserforcustom parsers. AlsoTestDefaultsused inParsertype hints is exposed via this module.Type definitions used by the aforementioned classes.
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:
ABCOptional 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 using
get_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.
namepassed 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 oras
Noneif 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.Returning
Nonemeans 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 like
name=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 as
Noneif type information is not known.
Type information can be mapped to arguments returned by
get_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 use
Noneto 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 or
Noneif 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 format
path:linenoorNoneif source is not known.
The general format to return the source is
path:linenolike/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:
ABCOptional base class for libraries using the hybrid library API.
Hybrid library API makes it easy to specify what keywords a libraryimplements by using the
get_keyword_names()method. After gettingkeyword names, Robot Framework usesgetattrto 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.
- classrobot.api.interfaces.StartSuiteAttributes[source]
Bases:
TypedDictAttributes passed to listener v2
start_suitemethod.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:
StartSuiteAttributesAttributes passed to listener v2
end_suitemethod.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:
TypedDictAttributes passed to listener v2
start_testmethod.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:
StartTestAttributesAttributes passed to listener v2
end_testmethod.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:
TypedDictExtra attributes passed to listener v2
start/end_keywordmethods.These attributes are included with control structures. For example, withIF structures attributes include
condition.- 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:
OptionalKeywordAttributesAttributes passed to listener v2
start_keywordmethod.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:
StartKeywordAttributesAttributes passed to listener v2
end_keywordmethod.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:
TypedDictAttributes passed to listener v2
log_messageandmessagesmethods.See the User Guide for more information.
- message:str
- level:str
- timestamp:str
- html:str
- classrobot.api.interfaces.LibraryAttributes[source]
Bases:
TypedDictAttributes passed to listener v2
library_importmethod.See the User Guide for more information.
- args:list[str]
- originalname:str
- source:str
- importer:str|None
- classrobot.api.interfaces.ResourceAttributes[source]
Bases:
TypedDictAttributes passed to listener v2
resource_importmethod.See the User Guide for more information.
- source:str
- importer:str|None
- classrobot.api.interfaces.VariablesAttributes[source]
Bases:
TypedDictAttributes passed to listener v2
variables_importmethod.See the User Guide for more information.
- args:list[str]
- source:str
- importer:str|None
- classrobot.api.interfaces.ListenerV2[source]
Bases:
objectOptional 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 in
attributes['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 in
attributes['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.
pathis an absolute path to the output file ora stringNoneif creating the output file is disabled.
- log_file(path:str)[source]
Called after the log file has been created.
pathis 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.
pathis 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.
pathis an absolute path to the xunit file.Only called if creating the xunit file is enabled.
- classrobot.api.interfaces.ListenerV3[source]
Bases:
objectOptional base class for listeners using the listener API version 3.
- ROBOT_LISTENER_API_VERSION=3
- 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 morespecific
start_user_keyword(),start_library_keyword()orstart_invalid_keyword()method is implemented.The default implementation calls
start_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 morespecific
end_user_keyword(),end_library_keyword()orend_invalid_keyword()method is implemented.The default implementation calls
end_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 calls
start_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 calls
end_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 calls
start_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 calls
start_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 calls
start_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 calls
end_keyword().New in Robot Framework 7.0.
- start_for(data:For,result:For)[source]
Called when a FOR loop starts.
The default implementation calls
start_body_item().New in Robot Framework 7.0.
- end_for(data:For,result:For)[source]
Called when a FOR loop ends.
The default implementation calls
end_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 calls
start_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 calls
end_body_item().New in Robot Framework 7.0.
- start_while(data:While,result:While)[source]
Called when a WHILE loop starts.
The default implementation calls
start_body_item().New in Robot Framework 7.0.
- end_while(data:While,result:While)[source]
Called when a WHILE loop ends.
The default implementation calls
end_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 calls
start_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 calls
end_body_item().New in Robot Framework 7.0.
- start_group(data:Group,result:Group)[source]
Called when a GROUP starts.
The default implementation calls
start_body_item().New in Robot Framework 7.2.
- end_group(data:Group,result:Group)[source]
Called when a GROUP ends.
The default implementation calls
end_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 calls
start_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 calls
end_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 calls
start_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 calls
end_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 calls
start_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 calls
end_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 calls
start_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 calls
end_body_item().New in Robot Framework 7.0.
- start_var(data:Var,result:Var)[source]
Called when VAR starts.
The default implementation calls
start_body_item().New in Robot Framework 7.0.
- end_var(data:Var,result:Var)[source]
Called when VAR ends.
The default implementation calls
end_body_item().New in Robot Framework 7.0.
- start_break(data:Break,result:Break)[source]
Called when BREAK starts.
The default implementation calls
start_body_item().New in Robot Framework 7.0.
- end_break(data:Break,result:Break)[source]
Called when BREAK ends.
The default implementation calls
end_body_item().New in Robot Framework 7.0.
- start_continue(data:Continue,result:Continue)[source]
Called when CONTINUE starts.
The default implementation calls
start_body_item().New in Robot Framework 7.0.
- end_continue(data:Continue,result:Continue)[source]
Called when CONTINUE ends.
The default implementation calls
end_body_item().New in Robot Framework 7.0.
- start_return(data:Return,result:Return)[source]
Called when RETURN starts.
The default implementation calls
start_body_item().New in Robot Framework 7.0.
- end_return(data:Return,result:Return)[source]
Called when RETURN ends.
The default implementation calls
end_body_item().New in Robot Framework 7.0.
- start_error(data:Error,result:Error)[source]
Called when encountered invalid syntax starts.
The default implementation calls
start_body_item().New in Robot Framework 7.0.
- end_error(data:Error,result:Error)[source]
Called when encountered invalid syntax ends.
The default implementation calls
end_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.
libraryrepresents the imported library. It can be inspected andalso modified.importercontains 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.
resourcerepresents the imported resource file. It can be inspected andalso modified.importercontains 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.
attrscontains 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 the
attrsdictionary is replaced with an object representingthe imported variable file.
- output_file(path:Path|None)[source]
Called after the output file has been created.
pathis an absolute path to the output file orNoneif creating the output file is disabled.
- log_file(path:Path)[source]
Called after the log file has been created.
pathis 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.
pathis 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.
pathis an absolute path to the xunit file.Only called if creating the xunit file is enabled.
- classrobot.api.interfaces.Parser[source]
Bases:
ABCOptional 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 have
extensionattribute andparse()method. Theparse_init()method is optional and only needed ifa parser supports parsing suite initialization files.The mandatory
extensionattribute 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.
The
defaultsargument 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.
The
defaultsargument 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 are
TRACE,DEBUG,INFO(default),WARN,andERROR. In addition to that, there are pseudo log levelsHTMLandCONSOLEfor 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 as
infoanddebugthat have separatehtmlargument to control the message format.
- robot.api.logger.trace(msg:str,html:bool=False)[source]
Writes the message to the log file using the
TRACElevel.
- robot.api.logger.debug(msg:str,html:bool=False)[source]
Writes the message to the log file using the
DEBUGlevel.
- robot.api.logger.info(msg:str,html:bool=False,also_console:bool=False)[source]
Writes the message to the log file using the
INFOlevel.If
also_consoleargument 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 the
WARNlevel.
- robot.api.logger.error(msg:str,html:bool=False)[source]
Writes the message to the log file using the
ERRORlevel.
- robot.api.logger.console(msg:str,newline:bool=True,stream:Literal['stdout','stderr']='stdout')[source]
Writes the message to the console.
If the
newlineargument 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 the
streamargument 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:
get_tokens(),get_resource_tokens(), andget_init_tokens()functions forparsing data to tokens.Tokenclass that contains all token types asclass attributes.get_model(),get_resource_model(), andget_init_model()functions forparsing data to model represented asan abstract syntax tree (AST).Model objects used by the AST model.
ModelVisitorto easeinspecting model andmodifying data.
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:
ForceTagsReturn(deprecated, will meanReturnStatementin RF 8.0)ReturnSetting(alias forReturn, new in RF 6.1)GroupHeader(new in RF 7.2)Var(new in RF 7.0)Config(new in RF 6.0)
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.