robot.model package
Package with generic, reusable and extensible model classes.
This package contains, for example,TestSuite,TestCase,KeywordandSuiteVisitor base classes.These classes are extended both byexecutionandresult related model objects and used alsoelsewhere.
This package is considered stable.
Submodules
robot.model.body module
- classrobot.model.body.BodyItem[source]
Bases:
ModelObject- propertyid:str|None
Item id in format like
s1-t3-k1.See
TestSuite.idformore information.idisNoneonly in these special cases:
- to_dict()→Dict[str,Any][source]
Serialize this object into a dictionary.
The object can be later restored by using the
from_dict()method.With
robot.runningmodel objects new in Robot Framework 6.1,withrobot.resultnew in Robot Framework 7.0.
- parent
- classrobot.model.body.BaseBody(parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None,items:Iterable[BodyItem|DataDict]=())[source]
Bases:
ItemList[BodyItem],Generic[KW,F,W,G,I,T,V,R,C,B,M,E]Base class for Body and Branches objects.
- keyword_class
alias of
type
- for_class
alias of
type
- while_class
alias of
type
- group_class
alias of
type
- if_class
alias of
type
- try_class
alias of
type
- var_class
alias of
type
- return_class
alias of
type
- continue_class
alias of
type
- break_class
alias of
type
- message_class
alias of
type
- error_class
alias of
type
- classmethodregister(item_class:Type[BI])→Type[BI][source]
Register a virtual subclass of an ABC.
Returns the subclass, to allow usage as a class decorator.
- propertycreate
Create a new item using the provided arguments.
- filter(keywords:bool|None=None,messages:bool|None=None,predicate:Callable[[T],bool]|None=None)→list[BodyItem][source]
Filter body items based on type and/or custom predicate.
To include or exclude items based on types, give matching arguments
TrueorFalsevalues. For example, to include only keywords,usebody.filter(keywords=True)and to exclude messages usebody.filter(messages=False). Including and excluding by typesat the same time is not supported and filtering mymessagesis supported only if theBodyobject actually supports messages.Custom
predicateis a callable getting each body item as an argumentthat must returnTrue/Falsedepending on should the item be includedor not.Selected items are returned as a list and the original body is not modified.
It was earlier possible to filter also based on FOR and IF types.That support was removed in RF 5.0 because it was not considered usefulin general and because adding support for all new control structureswould have required extra work. To exclude all control structures, use
body.filter(keywords=True,messages=True)and to only include themusebody.filter(keywords=False, messages=False)``. For more detailedfiltering it is possible to usepredicate.
- flatten(**filter_config)→list[BodyItem][source]
Return steps so that IF and TRY structures are flattened.
Basically the IF/ELSE and TRY/EXCEPT root elements are replacedwith their branches. This is how they are shown in the log file.
filter_configcan be used to filter steps using thefilter()method before flattening. New in Robot Framework 7.2.
- classrobot.model.body.Body(parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None,items:Iterable[BodyItem|DataDict]=())[source]
Bases:
BaseBody[Keyword, For, While, Group, If, Try, Var, Return, Continue, Break, Message, Error]A list-like object representing a body of a test, keyword, etc.
Body contains the keywords and other structures such as FOR loops.
- classrobot.model.body.BaseBranches(branch_class:Type[IT],parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None,items:Iterable[IT|DataDict]=())[source]
Bases:
BaseBody[KW,F,W,G,I,T,V,R,C,B,M,E],BranchType[IT]A list-like object representing IF and TRY branches.
- branch_type
alias of
type
- branch_class
- classrobot.model.body.BaseIterations(iteration_class:Type[FW],parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None,items:Iterable[FW|DataDict]=())[source]
Bases:
BaseBody[KW,F,W,G,I,T,V,R,C,B,M,E],IterationType[FW]- iteration_type
alias of
type
- iteration_class
robot.model.configurer module
- classrobot.model.configurer.SuiteConfigurer(name=None,doc=None,metadata=None,set_tags=None,include_tags=None,exclude_tags=None,include_suites=None,include_tests=None,empty_suite_ok=False)[source]
Bases:
SuiteVisitor- propertyadd_tags
- propertyremove_tags
robot.model.control module
- classrobot.model.control.Branches(branch_class:Type[IT],parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None,items:Iterable[IT|DataDict]=())[source]
Bases:
BaseBranches[Keyword, For, While, Group, If, Try, Var, Return, Continue, Break, Message, Error,IT]
- classrobot.model.control.Iterations(iteration_class:Type[FW],parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None,items:Iterable[FW|DataDict]=())[source]
Bases:
BaseIterations[Keyword, For, While, Group, If, Try, Var, Return, Continue, Break, Message, Error,FW]
- classrobot.model.control.ForIteration(assign:Mapping[str,str]|None=None,parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None)[source]
Bases:
BodyItemRepresents one FOR loop iteration.
- type:str='ITERATION'
- repr_args=('assign',)
- assign
- visit(visitor:SuiteVisitor)[source]
- to_dict()→Dict[str,Any][source]
Serialize this object into a dictionary.
The object can be later restored by using the
from_dict()method.With
robot.runningmodel objects new in Robot Framework 6.1,withrobot.resultnew in Robot Framework 7.0.
- message
- status
- classrobot.model.control.For(assign:Sequence[str]=(),flavor:Literal['IN','INRANGE','INENUMERATE','INZIP']='IN',values:Sequence[str]=(),start:str|None=None,mode:str|None=None,fill:str|None=None,parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None)[source]
Bases:
BodyItemRepresents
FORloops.- type:str='FOR'
- repr_args=('assign','flavor','values','start','mode','fill')
- assign
- flavor
- values
- start
- mode
- fill
- visit(visitor:SuiteVisitor)[source]
- classrobot.model.control.WhileIteration(parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None)[source]
Bases:
BodyItemRepresents one WHILE loop iteration.
- type:str='ITERATION'
- visit(visitor:SuiteVisitor)[source]
- classrobot.model.control.While(condition:str|None=None,limit:str|None=None,on_limit:str|None=None,on_limit_message:str|None=None,parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None)[source]
Bases:
BodyItemRepresents
WHILEloops.- type:str='WHILE'
- repr_args=('condition','limit','on_limit','on_limit_message')
- condition
- on_limit
- limit
- on_limit_message
- visit(visitor:SuiteVisitor)[source]
- classrobot.model.control.Group(name:str='',parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None)[source]
Bases:
BodyItemRepresents
GROUP.- type:str='GROUP'
- repr_args=('name',)
- name
- visit(visitor:SuiteVisitor)[source]
- classrobot.model.control.IfBranch(type:str='IF',condition:str|None=None,parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None)[source]
Bases:
BodyItemRepresents individual
IF,ELSEIForELSEbranch.- repr_args=('type','condition')
- type:str
- condition
- propertyid:str
Branch id omits IF/ELSE root from the parent id part.
- visit(visitor:SuiteVisitor)[source]
- classrobot.model.control.If(parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None)[source]
Bases:
BodyItemIF/ELSE structure root. Branches are stored in
body.- type:str='IF/ELSEROOT'
- propertyid:None
Root IF/ELSE id is always
None.
- visit(visitor:SuiteVisitor)[source]
- classrobot.model.control.TryBranch(type:str='TRY',patterns:Sequence[str]=(),pattern_type:str|None=None,assign:str|None=None,parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None)[source]
Bases:
BodyItemRepresents individual
TRY,EXCEPT,ELSEorFINALLYbranch.- repr_args=('type','patterns','pattern_type','assign')
- type:str
- patterns
- pattern_type
- assign
- propertyid:str
Branch id omits TRY/EXCEPT root from the parent id part.
- visit(visitor:SuiteVisitor)[source]
- classrobot.model.control.Try(parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None)[source]
Bases:
BodyItemTRY/EXCEPT structure root. Branches are stored in
body.- type:str='TRY/EXCEPTROOT'
- propertyid:None
Root TRY/EXCEPT id is always
None.
- visit(visitor:SuiteVisitor)[source]
- classrobot.model.control.Var(name:str='',value:str|Sequence[str]=(),scope:str|None=None,separator:str|None=None,parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None)[source]
Bases:
BodyItemRepresents
VAR.- type:str='VAR'
- repr_args=('name','value','scope','separator')
- name
- value
- scope
- separator
- visit(visitor:SuiteVisitor)[source]
- classrobot.model.control.Return(values:Sequence[str]=(),parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None)[source]
Bases:
BodyItemRepresents
RETURN.- type:str='RETURN'
- repr_args=('values',)
- values
- visit(visitor:SuiteVisitor)[source]
- classrobot.model.control.Continue(parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None)[source]
Bases:
BodyItemRepresents
CONTINUE.- type:str='CONTINUE'
- visit(visitor:SuiteVisitor)[source]
- classrobot.model.control.Break(parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None)[source]
Bases:
BodyItemRepresents
BREAK.- type:str='BREAK'
- visit(visitor:SuiteVisitor)[source]
- classrobot.model.control.Error(values:Sequence[str]=(),parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None)[source]
Bases:
BodyItemRepresents syntax error in data.
For example, an invalid setting like
[Setpu]orENDin wrong place.- type:str='ERROR'
- repr_args=('values',)
- values
- visit(visitor:SuiteVisitor)[source]
robot.model.filter module
- classrobot.model.filter.EmptySuiteRemover(preserve_direct_children:bool=False)[source]
Bases:
SuiteVisitor
- classrobot.model.filter.Filter(include_suites:NamePatterns|Sequence[str]|None=None,include_tests:NamePatterns|Sequence[str]|None=None,include_tags:TagPatterns|Sequence[str]|None=None,exclude_tags:TagPatterns|Sequence[str]|None=None)[source]
Bases:
EmptySuiteRemover- include_suites
- include_tests
- include_tags
- exclude_tags
robot.model.fixture module
robot.model.itemlist module
- classrobot.model.itemlist.ItemList(item_class:Type[T],common_attrs:dict[str,Any]|None=None,items:Iterable[T|Dict[str,Any]]=())[source]
Bases:
MutableSequence[T]List of items of a certain enforced type.
New items can be created using the
create()method and existing itemsadded using the common list methods likeappend()orinsert().In addition to the common type, items can have certain common andautomatically assigned attributes.Starting from Robot Framework 6.1, items can be added as dictionaries andactual items are generated based on them automatically. If the type hasa
from_dictclass method, it is used, and otherwise dictionary data ispassed to the type as keyword arguments.- item_type
alias of
type
- extend(items:Iterable[T|Dict[str,Any]])[source]
S.extend(iterable) – extend sequence by appending elements from the iterable
- index(value[,start[,stop]])→integer--returnfirstindexofvalue.[source]
Raises ValueError if the value is not present.
Supporting start and stop arguments is optional, butrecommended.
- visit(visitor:SuiteVisitor)[source]
robot.model.keyword module
- classrobot.model.keyword.Keyword(name:str|None='',args:Sequence[str]=(),assign:Sequence[str]=(),type:str='KEYWORD',parent:TestSuite|TestCase|UserKeyword|For|ForIteration|If|IfBranch|Try|TryBranch|While|Group|WhileIteration|Keyword|Var|Return|Continue|Break|Error|None=None)[source]
Bases:
BodyItemBase model for a single keyword.
Extended by
robot.running.model.Keywordandrobot.result.model.Keyword.- repr_args=('name','args','assign')
- name
- args
- assign
- type:str
- propertyid:str|None
Item id in format like
s1-t3-k1.See
TestSuite.idformore information.idisNoneonly in these special cases:
- visit(visitor:SuiteVisitor)[source]
Visitorinterfaceentry-point.
robot.model.message module
- classrobot.model.message.Message(message:str='',level:Literal['TRACE','DEBUG','INFO','WARN','ERROR','FAIL','SKIP']='INFO',html:bool=False,timestamp:datetime|str|None=None,parent:BodyItem|None=None)[source]
Bases:
BodyItemA message created during the test execution.
Can be a log message triggered by a keyword, or a warning or an errorthat occurred during parsing or test execution.
- type:str='MESSAGE'
- repr_args=('message','level')
- message
- level
- html
- timestamp
- propertyhtml_message
Returns the message content as HTML.
- propertyid
Item id in format like
s1-t3-k1.See
TestSuite.idformore information.idisNoneonly in these special cases:
- visit(visitor)[source]
Visitorinterfaceentry-point.
robot.model.metadata module
- classrobot.model.metadata.Metadata(initial:Mapping[str,str]|Iterable[tuple[str,str]]|None=None)[source]
Bases:
NormalizedDict[str]Free suite metadata as a mapping.
Keys are case, space, and underscore insensitive.
Initialized with possible initial value and normalizing spec.
Initial values can be either a dictionary or an iterable of name/valuepairs.
Normalizing spec has exact same semantics as with the
normalize()function.
robot.model.modelobject module
- classrobot.model.modelobject.ModelObject[source]
Bases:
object- SUITE='SUITE'
- TEST='TEST'
- TASK='TEST'
- KEYWORD='KEYWORD'
- SETUP='SETUP'
- TEARDOWN='TEARDOWN'
- FOR='FOR'
- ITERATION='ITERATION'
- IF_ELSE_ROOT='IF/ELSEROOT'
- IF='IF'
- ELSE_IF='ELSEIF'
- ELSE='ELSE'
- TRY_EXCEPT_ROOT='TRY/EXCEPTROOT'
- TRY='TRY'
- EXCEPT='EXCEPT'
- FINALLY='FINALLY'
- WHILE='WHILE'
- GROUP='GROUP'
- VAR='VAR'
- RETURN='RETURN'
- CONTINUE='CONTINUE'
- BREAK='BREAK'
- ERROR='ERROR'
- MESSAGE='MESSAGE'
- KEYWORD_TYPES=('KEYWORD','SETUP','TEARDOWN')
- type:str
- repr_args=()
- classmethodfrom_dict(data:Dict[str,Any])→T[source]
Create this object based on data in a dictionary.
Data can be got from the
to_dict()method or created externally.With
robot.runningmodel objects new in Robot Framework 6.1,withrobot.resultnew in Robot Framework 7.0.
- classmethodfrom_json(source:str|bytes|TextIO|Path)→T[source]
Create this object based on JSON data.
The data is given as the
sourceparameter. It can be:a string (or bytes) containing the data directly,
an open file object where to read the data from, or
a path (
pathlib.Pathor string) to a UTF-8 encoded file to read.
The JSON data is first converted to a Python dictionary and the objectcreated using the
from_dict()method.Notice that the
sourceis considered to be JSON data if it isa string and contains{. If you need to use{in a file systempath, pass it in as apathlib.Pathinstance.With
robot.runningmodel objects new in Robot Framework 6.1,withrobot.resultnew in Robot Framework 7.0.
- to_dict()→Dict[str,Any][source]
Serialize this object into a dictionary.
The object can be later restored by using the
from_dict()method.With
robot.runningmodel objects new in Robot Framework 6.1,withrobot.resultnew in Robot Framework 7.0.
- to_json(file:None=None,*,ensure_ascii:bool=False,indent:int=0,separators:tuple[str,str]=(',',':'))→str[source]
- to_json(file:TextIO|Path|str,*,ensure_ascii:bool=False,indent:int=0,separators:tuple[str,str]=(',',':'))→None
Serialize this object into JSON.
The object is first converted to a Python dictionary using the
to_dict()method and then the dictionary is converted to JSON.The
fileparameter controls what to do with the resulting JSON data.It can be:None(default) to return the data as a string,an open file object where to write the data to, or
a path (
pathlib.Pathor string) to a file where to writethe data using UTF-8 encoding.
JSON formatting can be configured using optional parameters thatare passed directly to the underlyingjson module. Notice thatthe defaults differ from what
jsonuses.With
robot.runningmodel objects new in Robot Framework 6.1,withrobot.resultnew in Robot Framework 7.0.
- config(**attributes)→T[source]
Configure model object with given attributes.
obj.config(name='Example',doc='Something')is equivalent to settingobj.name='Example'andobj.doc='Something'.New in Robot Framework 4.0.
- copy(**attributes)→T[source]
Return a shallow copy of this object.
- Parameters:
attributes – Attributes to be set to the returned copy.For example,
obj.copy(name='Newname').
See also
deepcopy(). The difference betweencopyanddeepcopyis the same as with the methods having same names inthecopy module.
robot.model.modifier module
- classrobot.model.modifier.ModelModifier(visitors,empty_suite_ok,logger)[source]
Bases:
SuiteVisitor
robot.model.namepatterns module
robot.model.statistics module
- classrobot.model.statistics.Statistics(suite,suite_stat_level=-1,tag_stat_include=None,tag_stat_exclude=None,tag_stat_combine=None,tag_doc=None,tag_stat_link=None,rpa=False)[source]
Bases:
objectContainer for total, suite and tag statistics.
Accepted parameters have the same semantics as the matching command lineoptions.
- classrobot.model.statistics.StatisticsBuilder(total_builder,suite_builder,tag_builder)[source]
Bases:
SuiteVisitor- start_suite(suite)[source]
Called when a suite starts. Default implementation does nothing.
Can return explicit
Falseto stop visiting.
robot.model.stats module
- classrobot.model.stats.Stat(name)[source]
Bases:
SortableGeneric statistic object used for storing all the statistic values.
- name
Human readable identifier of the object these statisticsbelong to.All Tests for
TotalStatistics,long name of the suite forSuiteStatisticsor name of the tag forTagStatistics
- get_attributes(include_label=False,include_elapsed=False,exclude_empty=True,values_as_strings=False,html_escape=False)[source]
- propertytotal
- classrobot.model.stats.TotalStat(name)[source]
Bases:
StatStores statistic values for a test run.
- type='total'
- classrobot.model.stats.SuiteStat(suite)[source]
Bases:
StatStores statistics values for a single suite.
- type='suite'
- classrobot.model.stats.TagStat(name,doc='',links=None,combined=None)[source]
Bases:
StatStores statistic values for a single tag.
- type='tag'
- doc
Documentation of tag as a string.
- links
List of tuples in which the first value is the link URL andthe second is the link title. An empty list by default.
- combined
Pattern as a string if the tag is combined,
Noneotherwise.
- propertyinfo
Returns additional information of the tag statisticsare about. Eithercombined or an empty string.
robot.model.suitestatistics module
robot.model.tags module
- classrobot.model.tags.Tags(tags:Iterable[str]=())[source]
Bases:
Sequence[str]
- classrobot.model.tags.TagPatterns(patterns:Iterable[str]=())[source]
Bases:
Sequence[TagPattern]- propertyis_constant
- classrobot.model.tags.TagPattern[source]
Bases:
ABC- is_constant=False
- classmethodfrom_string(pattern:str)→TagPattern[source]
- classrobot.model.tags.SingleTagPattern(pattern:str)[source]
Bases:
TagPattern- propertyis_constant
Returns True when the argument is true, False otherwise.The builtins True and False are the only two instances of the class bool.The class bool is a subclass of the class int, and cannot be subclassed.
- classrobot.model.tags.AndTagPattern(patterns:Iterable[str])[source]
Bases:
TagPattern
- classrobot.model.tags.OrTagPattern(patterns:Iterable[str])[source]
Bases:
TagPattern
- classrobot.model.tags.NotTagPattern(must_match:str,must_not_match:Iterable[str])[source]
Bases:
TagPattern
robot.model.tagsetter module
- classrobot.model.tagsetter.TagSetter(add:Sequence[str]|str=(),remove:Sequence[str]|str=())[source]
Bases:
SuiteVisitor- start_suite(suite:TestSuite)[source]
Called when a suite starts. Default implementation does nothing.
Can return explicit
Falseto stop visiting.
robot.model.tagstatistics module
- classrobot.model.tagstatistics.TagStatistics(combined_stats)[source]
Bases:
objectContainer for tag statistics.
- classrobot.model.tagstatistics.TagStatisticsBuilder(included=None,excluded=None,combined=None,docs=None,links=None)[source]
Bases:
object
robot.model.testcase module
- classrobot.model.testcase.TestCase(name:str='',doc:str='',tags:Tags|Sequence[str]=(),timeout:str|None=None,lineno:int|None=None,parent:TestSuite[KW,TestCase[KW]]|None=None)[source]
Bases:
ModelObject,Generic[KW]Base model for a single test case.
Extended by
robot.running.model.TestCaseandrobot.result.model.TestCase.- type:str='TEST'
- repr_args=('name',)
- name
- doc
- timeout
- lineno
- parent
- propertysetup:KW
Test setup as a
Keywordobject.This attribute is a
Keywordobject also when a test has no setupbut in that case its truth value isFalse.Setup can be modified by setting attributes directly:
test.setup.name='Example'test.setup.args=('First','Second')
Alternatively the
config()method can be used to set multipleattributes in one call:test.setup.config(name='Example',args=('First','Second'))
The easiest way to reset the whole setup is setting it to
None.It will automatically recreate the underlyingKeywordobject:test.setup=None
New in Robot Framework 4.0. Earlier setup was accessed like
test.keywords.setup.
- propertyhas_setup:bool
Check does a suite have a setup without creating a setup object.
A difference between using
iftest.has_setup:andiftest.setup:is that accessing thesetupattribute creates aKeywordobject representing the setup even when the test actually does not haveone. This typically does not matter, but with bigger suite structurescontaining a huge about of tests it can have an effect on memory usage.New in Robot Framework 5.0.
- propertyhas_teardown:bool
Check does a test have a teardown without creating a teardown object.
See
has_setupfor more information.New in Robot Framework 5.0.
- propertyid:str
Test case id in format like
s1-t3.See
TestSuite.idformore information.
- propertyfull_name:str
Test name prefixed with the full name of the parent suite.
- propertysource:Path|None
- visit(visitor:SuiteVisitor)[source]
Visitorinterfaceentry-point.
robot.model.testsuite module
- classrobot.model.testsuite.TestSuite(name:str='',doc:str='',metadata:Mapping[str,str]|None=None,source:Path|str|None=None,rpa:bool|None=False,parent:TestSuite[KW,TC]|None=None)[source]
Bases:
ModelObject,Generic[KW,TC]Base model for single suite.
Extended by
robot.running.model.TestSuiteandrobot.result.model.TestSuite.- type:str='SUITE'
- repr_args=('name',)
- doc
- parent
- rpa
- staticname_from_source(source:Path|str|None,extension:Sequence[str]=())→str[source]
Create suite name based on the given
source.This method is used by Robot Framework itself when it builds suites.External parsers and other tools that want to produce suites withnames matching names created by Robot Framework can use this method aswell. This method is also used if
nameis not set and someoneaccesses it.The algorithm is as follows:
If the source is
Noneor empty, return an empty string.Get the base name of the source. Read more below.
Remove possible prefix separated with
__.Convert underscores to spaces.
If the name is all lower case, title case it.
The base name of files is got by callingPath.stem that dropsthe file extension. It typically works fine, but gives wrong resultif the extension has multiple parts like in
tests.robot.zip.That problem can be avoided by giving valid file extension or extensionsas the optionalextensionargument.Examples:
TestSuite.name_from_source(source)TestSuite.name_from_source(source,extension='.robot.zip')TestSuite.name_from_source(source,('.robot','.robot.zip'))
- propertyname:str
Suite name.
If name is not set, it is constructed from source. If source is not set,name is constructed from child suite names by concatenating them with`` &``. If there are no child suites, name is an empty string.
- source
- adjust_source(relative_to:Path|str|None=None,root:Path|str|None=None)[source]
Adjust suite source and child suite sources, recursively.
- Parameters:
relative_to – Make suite source relative to the given path. Callspathlib.Path.relative_to() internally. Raises
ValueErrorif creating a relative path is not possible.root – Make given path a new root directory for the source. Raises
ValueErrorif suite source is absolute.
Adjusting the source is especially useful when moving data around as JSON:
fromrobot.apiimportTestSuite# Create a suite, adjust source and convert to JSON.suite=TestSuite.from_file_system('/path/to/data')suite.adjust_source(relative_to='/path/to')suite.to_json('data.rbt')# Recreate suite elsewhere and adjust source accordingly.suite=TestSuite.from_json('data.rbt')suite.adjust_source(root='/new/path/to')
New in Robot Framework 6.1.
- propertyfull_name:str
Suite name prefixed with the full name of the possible parent suite.
- validate_execution_mode()→bool|None[source]
Validate that suite execution mode is set consistently.
Raise an exception if the execution mode is not set (i.e. the
rpaattribute isNone) and child suites have conflicting execution modes.The execution mode is returned. New in RF 6.1.1.
- suites
- tests
- propertysetup:KW
Suite setup.
This attribute is a
Keywordobject also when a suite has no setupbut in that case its truth value isFalse. The preferred way tocheck does a suite have a setup is usinghas_setup.Setup can be modified by setting attributes directly:
suite.setup.name='Example'suite.setup.args=('First','Second')
Alternatively the
config()method can be used to set multipleattributes in one call:suite.setup.config(name='Example',args=('First','Second'))
The easiest way to reset the whole setup is setting it to
None.It will automatically recreate the underlyingKeywordobject:suite.setup=None
New in Robot Framework 4.0. Earlier setup was accessed like
suite.keywords.setup.
- propertyhas_setup:bool
Check does a suite have a setup without creating a setup object.
A difference between using
ifsuite.has_setup:andifsuite.setup:is that accessing thesetupattribute creates aKeywordobject representing the setup even when the suite actually does not haveone. This typically does not matter, but with bigger suite structuresit can have some effect on memory usage.New in Robot Framework 5.0.
- propertyhas_teardown:bool
Check does a suite have a teardown without creating a teardown object.
See
has_setupfor more information.New in Robot Framework 5.0.
- propertyid:str
An automatically generated unique id.
The root suite has id
s1, its child suites have idss1-s1,s1-s2, …, their child suites get idss1-s1-s1,s1-s1-s2,…,s1-s2-s1, …, and so on.The first test in a suite has an id like
s1-t1, the second has anids1-t2, and so on. Similarly, keywords in suites (setup/teardown)and in tests get ids likes1-k1,s1-t1-k1, ands1-s4-t2-k5.
- propertyall_tests:Iterator[TestCase]
Yields all tests this suite and its child suites contain.
New in Robot Framework 6.1.
- propertytest_count:int
Total number of the tests in this suite and in its child suites.
- propertyhas_tests:bool
- set_tags(add:Sequence[str]=(),remove:Sequence[str]=(),persist:bool=False)[source]
Add and/or remove specified tags to the tests in this suite.
- Parameters:
add – Tags to add as a list or, if adding only one,as a single string.
remove – Tags to remove as a list or as a single string.Can be given as patterns where
*and?work as wildcards.persist – Add/remove specified tags also to new tests addedto this suite in the future.
- filter(included_suites:Sequence[str]|None=None,included_tests:Sequence[str]|None=None,included_tags:Sequence[str]|None=None,excluded_tags:Sequence[str]|None=None)[source]
Select test cases and remove others from this suite.
Parameters have the same semantics as
--suite,--test,--include, and--excludecommand line options. All of themcan be given as a list of strings, or when selecting only one, asa single string.Child suites that contain no tests after filtering are automaticallyremoved.
Example:
suite.filter(included_tests=['Test 1','* Example'],included_tags='priority-1')
- configure(**options)[source]
A shortcut to configure a suite using one method call.
Can only be used with the root test suite.
- Parameters:
options – Passed to
SuiteConfigurerthat will thenset suite attributes, callfilter(), etc. as needed.
Not to be confused with
config()method that suites, tests,and keywords have to make it possible to set multiple attributes inone call.
- remove_empty_suites(preserve_direct_children:bool=False)[source]
Removes all child suites not containing any tests, recursively.
- visit(visitor:SuiteVisitor)[source]
Visitorinterfaceentry-point.
robot.model.totalstatistics module
- classrobot.model.totalstatistics.TotalStatistics(rpa:bool=False)[source]
Bases:
objectContainer for total statistics.
- propertytotal:int
- propertypassed:int
- propertyskipped:int
- propertyfailed:int
- propertymessage:str
String representation of the statistics.
- For example::
2 tests, 1 passed, 1 failed
- classrobot.model.totalstatistics.TotalStatisticsBuilder(suite=None,rpa=False)[source]
Bases:
SuiteVisitor
robot.model.visitor module
Interface to ease traversing through a test suite structure.
Visitors make it easy to modify test suite structures or to collect informationfrom them. They work both with theexecutablemodeland theresultmodel, but the objects passed tothe visitor methods are slightly different depending on the model they areused with. The main differences are that on the execution side keywords donot have child keywords nor messages, and that only the result objects havestatus related attributes likestatus andstart_time.
This module containsSuiteVisitor that implements the core logic tovisit a test suite structure, and theresult package containsResultVisitor that supports visiting the wholetest execution result structure. Both of these visitors should be importedvia therobot.api package when used by external code.
Visitor algorithm
All suite, test, keyword and message objects have avisit() method thataccepts a visitor instance. These methods will then call the correct visitormethodvisit_suite(),visit_test(),visit_keyword() orvisit_message(),depending on the instance where thevisit() method exists.
The recommended and definitely the easiest way to implement a visitor is extendingtheSuiteVisitor base class. The default implementation of itsvisit_x() methods take care of traversing child elements of the objectx recursively. Avisit_x() method first calls a correspondingstart_x() method (e.g.visit_suite() callsstart_suite()),then callsvisit() for all child objects of thex object, andfinally calls the correspondingend_x() method. The defaultimplementations ofstart_x() andend_x() do nothing.
All items that can appear inside tests have their own visit methods. Theseincludevisit_keyword(),visit_message() (only applicable withresults, not with executable data),visit_for(),visit_if(), andso on, as well as their appropriatestart/end methods likestart_keyword()andend_for(). If there is a need to visit all these items, it is possible toimplement onlystart_body_item() andend_body_item() methods that are,by default, called by the appropriatestart/end methods. These generic methodsare new in Robot Framework 5.0.
Visitors extending theSuiteVisitor can stop visiting at a certainlevel either by overriding suitablevisit_x() method or by returningan explicitFalse from anystart_x() method.
Examples
The following example visitor modifies the test suite structure it visits.It could be used, for example, with Robot Framework’s--prerunmodifieroption to modify test data before execution.
"""Pre-run modifier that selects only every Xth test for execution.Starts from the first test by default. Tests are selected per suite."""fromrobot.apiimportSuiteVisitorclassSelectEveryXthTest(SuiteVisitor):def__init__(self,x:int,start:int=0):self.x=xself.start=startdefstart_suite(self,suite):"""Modify suite's tests to contain only every Xth."""suite.tests=suite.tests[self.start::self.x]defend_suite(self,suite):"""Remove suites that are empty after removing tests."""suite.suites=[sforsinsuite.suitesifs.test_count>0]defvisit_test(self,test):"""Avoid visiting tests and their keywords to save a little time."""pass
For more examples it is possible to look at the source code of visitors usedinternally by Robot Framework itself. Some good examples areTagSetter andkeywordremovers.
Type hints
Visitor methods have type hints to give more information about the model objectsthey receive to editors. Because visitors can be used with both running and resultmodels, the types that are used as type hints are base classes from therobot.model module. Actual visitor implementations can import appropriatetypes from therobot.running or therobot.result module instead.For example, this visitor uses the result side model objects:
fromrobot.apiimportSuiteVisitorfromrobot.resultimportTestCase,TestSuiteclassFailurePrinter(SuiteVisitor):defstart_suite(self,suite:TestSuite):print(f"{suite.full_name}:{suite.statistics.failed} failed")defvisit_test(self,test:TestCase):iftest.failed:print(f'-{test.name}:{test.message}')
Type hints were added in Robot Framework 6.1. They are optional and can beremoved altogether if they get in the way.
- classrobot.model.visitor.SuiteVisitor[source]
Bases:
objectAbstract class to ease traversing through the suite structure.
See the
moduleleveldocumentation for moreinformation and an example.- visit_suite(suite:TestSuite)[source]
Implements traversing through suites.
Can be overridden to allow modifying the passed in
suitewithoutcallingstart_suite()orend_suite()nor visiting childsuites, tests or setup and teardown at all.
- start_suite(suite:TestSuite)→bool|None[source]
Called when a suite starts. Default implementation does nothing.
Can return explicit
Falseto stop visiting.
- visit_test(test:TestCase)[source]
Implements traversing through tests.
Can be overridden to allow modifying the passed in
testwithout callingstart_test()orend_test()nor visiting the body of the test.
- start_test(test:TestCase)→bool|None[source]
Called when a test starts. Default implementation does nothing.
Can return explicit
Falseto stop visiting.
- visit_keyword(keyword:Keyword)[source]
Implements traversing through keywords.
Can be overridden to allow modifying the passed in
kwwithoutcallingstart_keyword()orend_keyword()nor visitingthe body of the keyword
- start_keyword(keyword:Keyword)→bool|None[source]
Called when a keyword starts.
By default, calls
start_body_item()which, by default, does nothing.Can return explicit
Falseto stop visiting.
- end_keyword(keyword:Keyword)[source]
Called when a keyword ends.
By default, calls
end_body_item()which, by default, does nothing.
- visit_for(for_:For)[source]
Implements traversing through FOR loops.
Can be overridden to allow modifying the passed in
for_withoutcallingstart_for()orend_for()nor visiting body.
- start_for(for_:For)→bool|None[source]
Called when a FOR loop starts.
By default, calls
start_body_item()which, by default, does nothing.Can return explicit
Falseto stop visiting.
- end_for(for_:For)[source]
Called when a FOR loop ends.
By default, calls
end_body_item()which, by default, does nothing.
- visit_for_iteration(iteration:ForIteration)[source]
Implements traversing through single FOR loop iteration.
This is only used with the result side model because on the running sidethere are no iterations.
Can be overridden to allow modifying the passed in
iterationwithoutcallingstart_for_iteration()orend_for_iteration()nor visitingbody.
- start_for_iteration(iteration:ForIteration)→bool|None[source]
Called when a FOR loop iteration starts.
By default, calls
start_body_item()which, by default, does nothing.Can return explicit
Falseto stop visiting.
- end_for_iteration(iteration:ForIteration)[source]
Called when a FOR loop iteration ends.
By default, calls
end_body_item()which, by default, does nothing.
- visit_if(if_:If)[source]
Implements traversing through IF/ELSE structures.
Notice that
if_does not have any data directly. Actual IF/ELSEbranches are in itsbodyand they are visited separately usingvisit_if_branch().Can be overridden to allow modifying the passed in
if_withoutcallingstart_if()orend_if()nor visiting branches.
- start_if(if_:If)→bool|None[source]
Called when an IF/ELSE structure starts.
By default, calls
start_body_item()which, by default, does nothing.Can return explicit
Falseto stop visiting.
- end_if(if_:If)[source]
Called when an IF/ELSE structure ends.
By default, calls
end_body_item()which, by default, does nothing.
- visit_if_branch(branch:IfBranch)[source]
Implements traversing through single IF/ELSE branch.
Can be overridden to allow modifying the passed in
branchwithoutcallingstart_if_branch()orend_if_branch()nor visiting body.
- start_if_branch(branch:IfBranch)→bool|None[source]
Called when an IF/ELSE branch starts.
By default, calls
start_body_item()which, by default, does nothing.Can return explicit
Falseto stop visiting.
- end_if_branch(branch:IfBranch)[source]
Called when an IF/ELSE branch ends.
By default, calls
end_body_item()which, by default, does nothing.
- visit_try(try_:Try)[source]
Implements traversing through TRY/EXCEPT structures.
This method is used with the TRY/EXCEPT root element. Actual TRY, EXCEPT, ELSEand FINALLY branches are visited separately using
visit_try_branch().
- start_try(try_:Try)→bool|None[source]
Called when a TRY/EXCEPT structure starts.
By default, calls
start_body_item()which, by default, does nothing.Can return explicit
Falseto stop visiting.
- end_try(try_:Try)[source]
Called when a TRY/EXCEPT structure ends.
By default, calls
end_body_item()which, by default, does nothing.
- visit_try_branch(branch:TryBranch)[source]
Visits individual TRY, EXCEPT, ELSE and FINALLY branches.
- start_try_branch(branch:TryBranch)→bool|None[source]
Called when TRY, EXCEPT, ELSE or FINALLY branches start.
By default, calls
start_body_item()which, by default, does nothing.Can return explicit
Falseto stop visiting.
- end_try_branch(branch:TryBranch)[source]
Called when TRY, EXCEPT, ELSE and FINALLY branches end.
By default, calls
end_body_item()which, by default, does nothing.
- visit_while(while_:While)[source]
Implements traversing through WHILE loops.
Can be overridden to allow modifying the passed in
while_withoutcallingstart_while()orend_while()nor visiting body.
- start_while(while_:While)→bool|None[source]
Called when a WHILE loop starts.
By default, calls
start_body_item()which, by default, does nothing.Can return explicit
Falseto stop visiting.
- end_while(while_:While)[source]
Called when a WHILE loop ends.
By default, calls
end_body_item()which, by default, does nothing.
- visit_while_iteration(iteration:WhileIteration)[source]
Implements traversing through single WHILE loop iteration.
This is only used with the result side model because on the running sidethere are no iterations.
Can be overridden to allow modifying the passed in
iterationwithoutcallingstart_while_iteration()orend_while_iteration()nor visitingbody.
- start_while_iteration(iteration:WhileIteration)→bool|None[source]
Called when a WHILE loop iteration starts.
By default, calls
start_body_item()which, by default, does nothing.Can return explicit
Falseto stop visiting.
- end_while_iteration(iteration:WhileIteration)[source]
Called when a WHILE loop iteration ends.
By default, calls
end_body_item()which, by default, does nothing.
- visit_group(group:Group)[source]
Visits GROUP elements.
Can be overridden to allow modifying the passed in
groupwithoutcallingstart_group()orend_group()nor visiting body.
- start_group(group:Group)→bool|None[source]
Called when a GROUP element starts.
By default, calls
start_body_item()which, by default, does nothing.Can return explicit
Falseto stop visiting.
- end_group(group:Group)[source]
Called when a GROUP element ends.
By default, calls
end_body_item()which, by default, does nothing.
- start_var(var:Var)→bool|None[source]
Called when a VAR element starts.
By default, calls
start_body_item()which, by default, does nothing.Can return explicit
Falseto stop visiting.
- end_var(var:Var)[source]
Called when a VAR element ends.
By default, calls
end_body_item()which, by default, does nothing.
- start_return(return_:Return)→bool|None[source]
Called when a RETURN element starts.
By default, calls
start_body_item()which, by default, does nothing.Can return explicit
Falseto stop visiting.
- end_return(return_:Return)[source]
Called when a RETURN element ends.
By default, calls
end_body_item()which, by default, does nothing.
- start_continue(continue_:Continue)→bool|None[source]
Called when a CONTINUE element starts.
By default, calls
start_body_item()which, by default, does nothing.Can return explicit
Falseto stop visiting.
- end_continue(continue_:Continue)[source]
Called when a CONTINUE element ends.
By default, calls
end_body_item()which, by default, does nothing.
- start_break(break_:Break)→bool|None[source]
Called when a BREAK element starts.
By default, calls
start_body_item()which, by default, does nothing.Can return explicit
Falseto stop visiting.
- end_break(break_:Break)[source]
Called when a BREAK element ends.
By default, calls
end_body_item()which, by default, does nothing.
- visit_error(error:Error)[source]
Visits body items resulting from invalid syntax.
Examples include syntax like
ENDorELSEin wrong place andinvalid setting like[Invalid].
- start_error(error:Error)→bool|None[source]
Called when a ERROR element starts.
By default, calls
start_body_item()which, by default, does nothing.Can return explicit
Falseto stop visiting.
- end_error(error:Error)[source]
Called when a ERROR element ends.
By default, calls
end_body_item()which, by default, does nothing.
- visit_message(message:Message)[source]
Implements visiting messages.
Can be overridden to allow modifying the passed in
msgwithoutcallingstart_message()orend_message().
- start_message(message:Message)→bool|None[source]
Called when a message starts.
By default, calls
start_body_item()which, by default, does nothing.Can return explicit
Falseto stop visiting.
- end_message(message:Message)[source]
Called when a message ends.
By default, calls
end_body_item()which, by default, does nothing.
- start_body_item(item:BodyItem)→bool|None[source]
Called, by default, when keywords, messages or control structures start.
More specific
start_keyword(),start_message(),:meth:`start_for,etc. can be implemented to visit only keywords, messages or specific controlstructures.Can return explicit
Falseto stop visiting. Default implementation doesnothing.
- end_body_item(item:BodyItem)[source]
Called, by default, when keywords, messages or control structures end.
More specific
end_keyword(),end_message(),:meth:`end_for,etc. can be implemented to visit only keywords, messages or specific controlstructures.Default implementation does nothing.