(二)robotfromwork自动化--BuiltIn库翻译

作为一门表格语言,为了保持简单的结构,RF没有像别的高级语言那样提供类似if else while等内置关键字来实现各种逻辑功能,而是提供给了用户BuiltIn库。如果用户想在测试用例中实现比较复杂的逻辑,那就需要对BuiltIn中的重要关键字有一些了解。BuiltIn库中还封装了很多常见方法和能够控制RF运行状态的关键字,如果想用好RF,一定要对BuiltIn库中的函数有一个比较全面的理解。下面就带着大家认识一下BuiltIn库中比较重要的关键字。

Evaluate 关键字:

Arguments:[ expression | modules=None | namespace=None ]Evaluates the given expression in Python and returns the results.

如果你需要进行一些数值运算并得到结果,你就需要用到Evaluate关键字。Evaluate会把你想要计算的表达式直接传递给Python,并把Python的计算结果返回给你。这是最经常要用到的。

Should 系列关键字:

Should系列关键字是Should打头的一系列关键字。

Should Be Empty--------验证给定项是否为空。
Should Be Equal--------如果给定的对象不相等则失败。 

Should Be Equal As Integers --------如果将对象转换(转换)为整数后对象不相等则失败。
Should Be Equal As Numbers--------如果将对象转换(转换)为实数后对象不相等则失败。

Should Be Equal As Strings--------如果对象在将它们转换(转换)为字符串后不相等则失败。 
Should Be True--------如果给定条件(状态)不成立则失败。

Should Contain--------参数:[ container | item | msg=None | values=True | ignore_case=False ]果容器一次或多次不包含(包含)项,则失败。
Should Contain X Times--------参数:[ item1 | item2 | count | msg=None | ignore_case=False ]如果item1不包含item2计数次数,则失败。
Should End With--------参数:[ str1 | str2 | msg=None | values=True | ignore_case=False ]如果字符串str1没有以字符串str2结尾,则失败。
Should Match--------参数:[ string | pattern | msg=None | values=True | ignore_case=False ]除非给定的字符串与给定的模式匹配,否则失败。

Should Match Regexp --------参数:[ string | pattern | msg=None | values=True ]如果字符串与作为正则表达式的模式不匹配,则失败(正则表达式).

Should Start With--------参数:[ str1 | str2 | msg=None | values=True | ignore_case=False ]如果字符串str1不以字符串str2开头,则失败。

Should Not Be Empty
Should Not Be Equal
Should Not Be Equal As Integers
Should Not Be Equal As Numbers
Should Not Be Equal As Strings
Should Not Be True
Should Not Contain
Should Not End With
Should Not Match
Should Not Match Regexp
Should Not Start With

这些关键字都是用作判断时用的,每个用例都会用到,比如我们的执行结果得到了一个字符串,我们要判断这个字符串要与一个预期字符串相等,否则用例就无法通过,这时候,肯定会用上Should Be Equal As String关键字,其它关键字我们通过关键字的名字就能顾名思义,知道它的作用。

Convert To系列关键字:

Convert To Binary
Convert To Boolean
Convert To Hex 
Convert To Integer 
Convert To Number 
Convert To Octal 
Convert To String

做类型转换,将某个值转换为相对应的类型。

Run keyword系列关键字:

Run Keyword If------Arguments:[ condition | name | *args ]如果condition为true,则使用给定的参数运行给定的关键字。
Run Keyword If All Critical Tests Passed
Run Keyword If All Tests Passed
Run Keyword If Any Critical Tests Failed
Run Keyword If Any Tests Failed
Run Keyword If Test Failed
Run Keyword If Test Passed
Run、Keyword If Timeout Occurred

这些关键字能根据一个判断条件的真假来看是否执行关键字。一般使用这些关键字来实现高级语言中的ifelse功能。最常用的是Run Keyword If 和 Run Keyword unless 他们俩实现的效果正好相反。

Exit For Loop关键字:

用作退出循环,一般和Run Keyword If关键字联合使用,来实现条件退出。

Wait Until Keyword Succeeds关键字:

这是一个将异步调用变为同步调用的关键字。举一个例子:如果call某个WebService,并且需要得到返回结果才能做下一部操作。我们就会用到这个关键字

比如日期相关的关键字GetTime。让测试暂停的Sleep等。都相当有用。

RF目前仅有2个内置关键字:FOF 和 IN,来实现循环结构。功能还是比较弱的。

Keywords

KeywordArgumentsDocumentation
Call Method

object,

method_name

,*args

, **kwargs

使用提供的参数调用给定对象的命名方法。

返回方法的可能返回值,并将其分配给变量。如果对象没有具有给定名称的方法或者执行该方法引发异常,则关键字都会失败。

支持**kwargsRobot Framework 2.9中的新功能。因为其他参数中可能的等号必须用反斜杠转义\=

例子:

Call Method${hashtable}putmynamemyvalue
${isempty} =Call Method${hashtable}isEmpty 
Should Not Be True${isempty}   
${value} =Call Method${hashtable}getmyname
Should Be Equal${value}myvalue  
Call Method${object}kwargsname=valuefoo=bar
Call Method${object}positionalescaped\=equals 
Catenate*items

将给定的项目连接在一起并返回结果字符串。

默认情况下,项目用空格连接,但如果第一项包含字符串SEPARATOR=<sep><sep>则使用分隔符。必要时,项目将转换为字符串。

例子:

${str1} =CatenateHelloworld 
${str2} =CatenateSEPARATOR=---Helloworld
${str3} =CatenateSEPARATOR=Helloworld

=>

${str1} = 'Hello world'
${str2} = 'Hello---world'
${str3} = 'Helloworld'
Comment*messages

将日志文件中的给定消息显示为关键字参数。

此关键字对其接收的参数不起任何作用,但由于它们在日志中可见,因此该关键字可用于显示简单消息。鉴于参数被彻底忽略,它们甚至可以包含不存在的变量。如果您对变量值感兴趣,可以使用LogLog Many关键字。

Continue For Loop 

跳过当前的循环迭代并从下一个继续。

跳过当前for循环迭代中的剩余关键字,并从下一个继续。可以直接在for循环中使用,也可以在循环使用的关键字中使用。

例:

:FOR${var}IN@{VALUES}
 Run Keyword If'${var}' == 'CONTINUE'Continue For Loop
 Do Something${var} 

要在不使用Run Keyword If或其他包装关键字的情况下有条件地继续for循环。请参阅Continue For Loop If

New in Robot Framework 2.8.

Continue For Loop Ifcondition

如果condition为true ,则跳过当前for循环迭代。

Continue For Loop的包装器根据给定条件继续for循环。使用与Should Be True关键字相同的语义来评估条件。

例:

:FOR${var}IN@{VALUES}
 Continue For Loop If'${var}' == 'CONTINUE' 
 Do Something${var} 

New in Robot Framework 2.8.

Convert To Binary

item, 

base=None,

prefix=None,

length=None

将给定项转换为二进制字符串。

item,带有可选的base,首先被转换为使用整数转换为整型内部。之后,它被转换为二进制数(基数2),表示为字符串,如1011

返回的值可以包含一个可选项,prefix并且可以要求最小值length(不包括前缀和可能的减号)。如果该值最初短于所需长度,则用零填充。

例子:

${result} =Convert To Binary10  # Result is 1010
${result} =Convert To BinaryFbase=16prefix=0b# Result is 0b1111
${result} =Convert To Binary-2prefix=Blength=4# Result is -B0010

See also Convert To IntegerConvert To Octal and Convert To Hex.

Convert To Booleanitem

将给定项转换为布尔值true或false。

按预期处理字符串TrueFalse(不区分大小写),否则使用Python的方法返回项的真值bool()

Convert To Bytes

input,

input_type=text

input根据要求将给定转换为字节input_type

下面列出了有效的输入类型:

  • text:逐个字符地将文本转换为字节。可以使用序号低于256的所有字符,并将其转换为具有相同值的字节。许多角色最容易使用\x00或等代码表示\xff。支持Unicode字符串和字节。
  • int:将由空格分隔的整数转换为字节。类似地,与转换为整数,也可以通过添加前缀的值使用二进制,八进制,或十六进制值0b0o0x分别。
  • hex:将十六进制值转换为字节。单字节总是两个字符长(例如01FF)。空格被忽略,可以作为可视分隔符自由使用。
  • bin:将二进制值转换为字节。单字节总是八个字符长(例如00001010)。空格被忽略,可以作为可视分隔符自由使用。

除了将输入作为字符串提供外,还可以使用包含单个字符或数字的列表或其他迭代。在这种情况下,数字不需要填充到一定长度,并且它们不能包含额外的空格。

示例(最后一列显示返回的字节):

${bytes} =Convert To Byteshyvä # hyv\xe4
${bytes} =Convert To Bytes\xff\x07 # \xff\x07
${bytes} =Convert To Bytes82 70int# RF
${bytes} =Convert To Bytes0b10 0x10int# \x02\x10
${bytes} =Convert To Bytesff 00 07hex# \xff\x00\x07
${bytes} =Convert To Bytes5246212121hex# RF!!!
${bytes} =Convert To Bytes0000 1000bin# \x08
${input} =Create List1212
${bytes} =Convert To Bytes${input}int# \x01\x02\x0c
${bytes} =Convert To Bytes${input}hex# \x01\x02\x12

如果需要使用特定编码将文本转换为字节,请String库中使用Encode String To Bytes

New in Robot Framework 2.8.2.

Convert To Hex

item, 

base=None,

prefix=None,

length=None,

lowercase=False

将给定项转换为十六进制字符串。

item,带有可选的base,首先被转换为使用整数转换为整型内部。之后,它被转换为十六进制数字(基数16),表示为字符串,如FF0A

返回的值可以包含一个可选项,prefix并且可以要求最小值length(不包括前缀和可能的减号)。如果该值最初短于所需长度,则用零填充。

默认情况下,该值作为大写字符串返回,但lowercase参数为true值(请参阅布尔参数)将值(但不是给定的前缀)转换为小写。

例子:

${result} =Convert To Hex255  # Result is FF
${result} =Convert To Hex-10prefix=0xlength=2# Result is -0x0A
${result} =Convert To Hex255prefix=Xlowercase=yes# Result is Xff

See also Convert To IntegerConvert To Binary and Convert To Octal.

Convert To Integer

item, 

base=None

将给定项转换为整数。

如果给定的项是字符串,则默认情况下它应该是基数为10的整数。有两种方法可以从其他基数转换:

  • 明确将base作为base参数提供给关键字。
  • 用基数作为给定字符串的前缀,这0b意味着二进制(基数2),0o意味着八进制(基数8),0x意味着十六进制(基数16)。只有在base没有给出参数时才会考虑前缀,并且前缀本身可能带有加号或减号前缀。

语法不区分大小写,可能的空格被忽略。

例子:

${result} =Convert To Integer100 # Result is 100
${result} =Convert To IntegerFF AA16# Result is 65450
${result} =Convert To Integer1008# Result is 64
${result} =Convert To Integer-1002# Result is -4
${result} =Convert To Integer0b100 # Result is 4
${result} =Convert To Integer-0x100 # Result is -256

See also Convert To NumberConvert To BinaryConvert To OctalConvert To Hex, and Convert To Bytes.

Convert To Number

item,

precision=None

将给定项转换为浮点数。

如果可选项precision为正数或零,则返回的数字将四舍五入为该十进制数字。负精度意味着数字四舍五入到绝对精度的最大倍数10。如果一个数字同样接近某个精度,则它总是从零开始舍入。

例子:

${result} =Convert To Number42.512 # Result is 42.512
${result} =Convert To Number42.5121# Result is 42.5
${result} =Convert To Number42.5120# Result is 43.0
${result} =Convert To Number42.512-1# Result is 40.0

请注意,机器通常无法准确存储浮点数。这可能会导致这些数字出现意外情况,也可能会出现意外情况。有关更多信息,请参阅,例如,这些资源:

如果需要整数,请改用 Convert To Integer 

Convert To Octal

item, 

base=None,

prefix=None,

length=None

将给定项转换为八进制字符串。

item,带有可选的base,首先被转换为使用整数转换为整型内部。之后,它被转换为八进制数字(基数8),表示为字符串,如775

返回的值可以包含一个可选项,prefix并且可以要求最小值length(不包括前缀和可能的减号)。如果该值最初短于所需长度,则用零填充。

例子:

${result} =Convert To Octal10  # Result is 12
${result} =Convert To Octal-Fbase=16prefix=0# Result is -017
${result} =Convert To Octal16prefix=octlength=4# Result is oct0020

See also Convert To IntegerConvert To Binary and Convert To Hex.

Convert To Stringitem

将给定项转换为Unicode字符串。

用途__unicode____str__方法与Python对象和toString与Java对象。

如果需要使用不同的编码在Unicode和字节字符串之间进行转换,请使用Encode String To BytesDecode Bytes To StringString库中的关键字。如果您只想创建字节字符串,请使用Convert To Bytes

Create Dictionary*items

根据给定的内容创建并返回字典items

通常使用与在Variable表中创建变量key=value相同的方法给出项&{dictionary}。键和值都可以包含变量,并且可以使用反斜杠转义可能的等号键escaped\=key=value。也可以通过简单地使用它们来从现有词典中获取项目&{dict}

或者,可以指定项目,以便分别给出键和值。这个和key=value语法甚至可以组合在一起,但必须先单独给出项目。

如果多次使用相同的键,则最后一个值具有优先权。返回的字典是有序的,带字符串作为键的值也可以使用方便的点访问语法来访问${dict.key}

例子:

&{dict} =Create Dictionarykey=valuefoo=bar  # key=value syntax
Should Be True${dict} == {'key': 'value', 'foo': 'bar'}     
&{dict2} =Create Dictionarykeyvaluefoobar# separate key and value
Should Be Equal${dict}${dict2}    
&{dict} =Create Dictionary${1}=${2}&{dict}foo=new # using variables
Should Be True${dict} == {1: 2, 'key': 'value', 'foo': 'new'}     
Should Be Equal${dict.key}value   # dot-access

这个关键字在Robot Framework 2.9中以多种方式进行了更改:

  • Collections图书馆搬到了BuiltIn
  • key=value语法中也支持非字符串键。
  • 返回的字典是有序且可点访问的。
  • 不推荐使用分别给出键和值的旧语法,但后来在RF 3.0.1中删除了弃用。
Create List*items

返回包含给定项的列表。

返回的列表可以分配给变量${scalar}@{list}变量。

例子:

@{list} =Create Listabc
${scalar} =Create Listabc
${ints} =Create List${1}${2}${3}
Evaluate

expression,

modules=None,

namespace=None

在Python中计算给定的表达式并返回结果。

expression评估表达式中所述,在Python中进行评估

modules 参数可用于指定要导入并添加到评估命名空间的Python模块的逗号分隔列表。

namespace参数可用于将自定义评估命名空间作为字典传递。可能modules会添加到此命名空间。这是Robot Framework 2.8.4中的一项新功能。

使用的变量${variable}在评估前的表达式中被替换。变量也可以在评估命名空间中使用,并且可以使用特殊语法进行访问$variable。这是Robot Framework 2.9中的一个新功能,它在评估表达式时得到了更全面的解释。

示例(期望${result}为3.14):

${status} =Evaluate0 < ${result} < 10# Would also work with string '3.14'
${status} =Evaluate0 < $result < 10# Using variable itself, not string representation
${random} =Evaluaterandom.randint(0, sys.maxint)modules=random, sys
${ns} =Create Dictionaryx=${4}y=${2}
${result} =Evaluatex*10 + ynamespace=${ns}

=>

${status} = True
${random} = <random integer>
${result} = 42
Exit For Loop 

停止执行封闭for循环。

退出封闭的for循环并继续执行。可以直接在for循环中使用,也可以在循环使用的关键字中使用。

例:

:FOR${var}IN@{VALUES}
 Run Keyword If'${var}' == 'EXIT'Exit For Loop
 Do Something${var} 

请参阅Exit For Loop If 要在不使用Run Keyword If或其他包装关键字的情况下有条件地退出for循环。

Exit For Loop Ifcondition

如果condition为true ,则停止执行封闭for循环。

Exit For Loop的包装器根据给定条件退出for循环。使用与Should Be True关键字相同的语义来评估条件。

例:

:FOR${var}IN@{VALUES}
 Exit For Loop If'${var}' == 'EXIT' 
 Do Something${var} 

New in Robot Framework 2.8.

Failmsg=None, *tags

使用给定消息使测试失败,并可选地更改其标记。

使用msg参数指定错误消息。通过为错误添加前缀,可以在给定的错误消息中使用HTML,类似于接受错误消息的任何其他关键字*HTML*

可以通过在消息之后传递标记来修改当前测试用例的标记。以连字符(例如-regression)开头的标签将被删除,并添加其他标签。在内部使用“ 设置标记”和“ 删除标记”修改标记,语义设置和删除它们与这些关键字相同。

例子:

FailTest not ready  # Fails with the given message.
Fail*HTML*<b>Test not ready</b>  # Fails using HTML in the message.
FailTest not readynot-ready # Fails and adds 'not-ready' tag.
FailOS not supported-regression # Removes tag 'regression'.
FailMy messagetag-t*# Removes all tags starting with 't' except the newly added 'tag'.

如果需要停止整个测试执行,请参阅Fatal Error

在Robot Framework 2.7.4和2.8中的HTML消息支持中添加了对修改标签的支持。

Fatal Errormsg=None

停止整个测试执行。

使用此关键字的测试或套件将失败并显示提供的消息,后续测试将失败并显示预设消息。尽管如此,可能会执行拆解。

如果您只想无条件地停止一个测试用例,请参阅Fail

Get Countitem1, item2

返回并记录item2从中找到的次数item1

此关键字适用于Python字符串和列表以及具有count方法或可以转换为Python列表的所有对象。

例:

${count} =Get Count${some item}interesting value
Should Be True5 < ${count} < 10  
Get Lengthitem

返回并以整数形式记录给定项的长度。

该项可以是具有长度的任何项,例如,字符串,列表或映射。关键字首先尝试使用Python函数获取长度,该函数len__len__内部调用item的方法。如果失败,关键字会尝试直接调用项目的可能lengthsize方法。最后的尝试是尝试获取项目length属性的值。如果所有这些尝试都不成功,则关键字将失败。

例子:

${length} =Get LengthHello, world! 
Should Be Equal As Integers${length}13 
@{list} =Create ListHello,world!
${length} =Get Length${list} 
Should Be Equal As Integers${length}2 

See also Length Should BeShould Be Empty and Should Not Be Empty.

Get Library Instance

name=None,

all=False

返回指定测试库的当前活动实例。

此关键字使测试库可以轻松地与具有状态的其他测试库进行交互。下面的Python示例说明了这一点:

from robot.libraries.BuiltIn import BuiltIn

def title_should_start_with(expected):
    seleniumlib = BuiltIn().get_library_instance('SeleniumLibrary')
    title = seleniumlib.get_title()
    if not title.startswith(expected):
        raise AssertionError("Title '%s' did not start with '%s'"
                             % (title, expected))

也可以在测试数据中使用此关键字,并将返回的库实例传递给另一个关键字。如果使用自定义名称导入库,则name用于获取实例的实例必须是该名称,而不是原始库名称。

如果给可选参数all赋予true值,则将返回将所有库名称映射到实例的字典。此功能是Robot Framework 2.9.2中的新功能。

例:

&{all libs} =Get library instanceall=True
Get Time

format=timestamp,

time_=NOW

以请求的格式返回给定时间。

注意: Robot Framework 2.8.5中添加的DateTime库包含更灵活的关键字,用于获取当前日期和时间以及日常和时间处理。

如何返回时间是根据给定的format字符串确定的,如下所示。请注意,所有检查都不区分大小写。

1)如果format包含该单词epoch,则在UNIX纪元(1970-01-01 00:00:00 UTC)之后以秒为单位返回时间。返回值始终为整数。

2)如果format包含任何的话yearmonthdayhourmin,或sec,仅选定部分被返回。返回部分的顺序始终是前一句中的顺序,单词的顺序format并不重要。这些部分作为零填充字符串返回(例如May - > 05)。

3)否则(默认情况下)时间将作为格式的时间戳字符串返回2006-02-24 15:08:31

默认情况下,此关键字返回当前本地时间,但可以使用time参数更改,如下所述。请注意,涉及字符串的所有检查都不区分大小写。

1)如果time是数字或可以转换为数字的字符串,则将其解释为自UNIX纪元以来的秒数。该文档最初是在纪元后的1177654467秒写的。

2)如果time是时间戳,将使用该时间。有效的时间戳格式为YYYY-MM-DD hh:mm:ssYYYYMMDD hhmmss

3)如果time等于NOW(默认),则使用当前本地时间。这次是使用Python的time.time()功能。

4)如果time等于UTC,则使用UTC中的当前时间。这次是time.time() + time.altzone在Python中使用的。

5)如果time格式为NOW - 1 dayUTC + 1 hour 30 min,则使用当前本地/ UTC时间加/减时间字符串指定的时间。时间字符串格式在Robot Framework用户指南的附录中描述。

示例(预计当前的当地时间是2006-03-29 15:06:21):

${time} =Get Time   
${secs} =Get Timeepoch  
${year} =Get Timereturn year  
${yyyy}${mm}${dd} =Get Timeyear,month,day
@{time} =Get Timeyear month day hour min sec  
${y}${s} =Get Timeseconds and year 

=>

${time} = '2006-03-29 15:06:21'
${secs} = 1143637581
${year} = '2006'
${yyyy} = '2006', ${mm} = '03', ${dd} = '29'
@{time} = ['2006', '03', '29', '15', '06', '21']
${y} = '2006'
${s} = '21'

示例(预计当前当地时间是2006-03-29 15:06:21,UTC时间是2006-03-29 12:06:21):

${time} =Get Time 1177654467#给出时间秒的时间
${secs} =Get Timesec2007-04-27 09:14:27# 作为时间戳给出的时间
${year} =Get TimeyearNOW#本地执行时间
@{time} =Get Timehour min secNOW + 1h 2min 3s#1h 2min 3s加入当地时间
@{utc} =Get Timehour min secUTC# UTC执行时间
${hour} =Get TimehourUTC - 1 hour# 从UTC时间减去#1h

=>

${time} = '2007-04-27 09:14:27'
${secs} = 27
${year} = '2006'
@{time} = ['16', '08', '24']
@{utc} = ['12', '06', '21']
${hour} = '11'

Robot Framework 2.7.5中添加了对UTC时间的支持,但直到2.7.7才能正常工作

Get Variable Value

name, 

default=None

返回变量值或default变量不存在。

变量的名称可以作为普通变量名称(例如${NAME})或以转义格式(例如\${NAME})给出。请注意,前者在Set Suite Variable中有一些限制。

例子:

${x} =Get Variable Value${a}default
${y} =Get Variable Value${a}${b}
${z} =Get Variable Value${z} 

=>

${x} gets value of ${a} if ${a} exists and string 'default' otherwise
${y} gets value of ${a} if ${a} exists and value of ${b} otherwise
${z} is set to Python None if it does not exist previously

See Set Variable If for another keyword to set variables dynamically.

Get Variablesno_decoration=False

返回包含当前范围中所有变量的字典。

变量作为特殊字典返回,允许以空间,大小写和下划线不敏感方式访问变量,类似于访问测试数据中的变量。此字典支持与普通Python字典相同的所有操作,例如,可以使用集合库来访问或修改它。修改返回的字典对当前范围中可用的变量没有影响。

默认情况下,变量返回${}@{}&{}基于变量类型进行修饰。给可选参数赋予一个真值(参见布尔参数no_decoration将返回没有装饰的变量。此选项是Robot Framework 2.9中的新选项。

例:

${example_variable} =Set Variableexample value 
${variables} =Get Variables  
Dictionary Should Contain Key${variables}\${example_variable} 
Dictionary Should Contain Key${variables}\${ExampleVariable} 
Set To Dictionary${variables}\${name}value
Variable Should Not Exist\${name}  
${no decoration} =Get Variablesno_decoration=Yes 
Dictionary Should Contain Key${no decoration}example_variable 

注意:在Robot Framework 2.7.4之前,变量作为不支持所有字典方法的自定义对象返回。

Import Libraryname, *args

使用给定名称和可选参数导入库。

此功能允许在测试运行时动态导入库。如果库本身是动态的并且在处理测试数据时尚不可用,那么这可能是必要的。在正常情况下,应使用“设置”表中的“库”设置导入库。

此关键字支持使用库名称和物理路径导入库。使用路径时,必须以绝对格式给出或从搜索路径中找到它们。正斜杠可用作所有操作系统中的路径分隔符。

可以将参数传递给导入的库,并且如果库支持,则命名参数语法也可以工作。WITH NAME语法可用于为导入的库提供自定义名称。

例子:

Import LibraryMyLibrary   
Import Library${CURDIR}/../Library.pyarg1named=arg2 
Import Library${LIBRARIES}/Lib.javaargWITH NAMEJavaLib
Import Resourcepath

使用给定路径导入资源文件。

使用“资源”设置在“设置”表中导入时,使用此关键字导入的资源类似地设置到测试套件范围中。

给定路径必须是绝对路径或从搜索路径中找到。无论操作系统如何,正斜杠都可以用作路径分隔符。

例子:

Import Resource${CURDIR}/resource.txt
Import Resource${CURDIR}/../resources/resource.html
Import Resourcefound_from_pythonpath.robot
Import Variablespath, *args

使用给定路径和可选参数导入变量文件。

使用“变量”设置在“设置”表中导入变量时,使用此关键字导入的变量也会被设置到测试套件范围中。这些变量会覆盖具有相同名称的可能现有变量。因此,此功能可用于导入新变量,例如,用于测试套件中的每个测试。

给定路径必须是绝对路径或从搜索路径中找到。无论操作系统如何,正斜杠都可以用作路径分隔符。

例子:

Import Variables${CURDIR}/variables.py  
Import Variables${CURDIR}/../vars/env.pyarg1arg2
Import Variablesfile_from_pythonpath.py  
Keyword Should Existname, msg=None

除非当前范围中存在给定关键字,否则将失败。

如果有多个具有相同名称的关键字,则也会失败。使用短名称(例如Log)和全名(例如BuiltIn.Log)。

可以使用msg参数覆盖默认错误消息。

See also Variable Should Exist.

Length Should Beitem, length,msg=None

验证给定项目的长度是否正确。

The length of the item is got using the Get Length keyword. 可以使用msg参数覆盖默认错误消息

Log

message,

level=INFO,

html=False,

console=False,

repr=False

使用给定级别记录给定消息。

有效级别为TRACE,DEBUG,INFO(默认),HTML,WARN和ERROR。低于当前活动日志级别的消息将被忽略。有关设置级别--loglevel的更多详细信息,请参阅设置日志级别关键字和命令行选项。

使用WARN或ERROR级别记录的消息也将在控制台和日志文件的“测试执行错误”部分中自动显示。

日志可以通过选配的配置htmlconsolerepr论据。它们默认是关闭的,但可以通过赋予它们真正的值来启用。有关true和false值的更多信息,请参阅布尔参数部分。

如果html参数被赋予真值,则该消息将被视为HTML,并且诸如其中的特殊字符<不会被转义。例如,日志记录<img src="image.png">html为true 时创建图像,否则消息就是该字符串。使用html参数的另一种方法是使用HTML伪日志级别。它使用INFO级别将消息记录为HTML。

如果console参数为true,则除了日志文件之外,该消息还将写入启动测试执行的控制台。此关键字始终使用标准输出流,并在写入消息后添加换行符。如果不希望出现其中任何一个,请使用Log To Console

如果repr参数为true,则pprint.pformat()在记录之前,给定项将通过Python 函数的自定义版本传递。例如,在处理包含不可见字符的字符串或字节时,或者在使用嵌套数据结构时,这很有用。自定义版本与标准版本不同,因此它省略了uUnicode字符串的前缀,并b为字节字符串添加了前缀。

例子:

LogHello, world!  # Normal INFO message.
LogWarning, world!WARN # 警告.
Log<b>Hello</b>, world!html=yes # INFO消息为HTML.
Log<b>Hello</b>, world!HTML # 与上述相同.
Log<b>Hello</b>, world!DEBUGhtml=true# DEBUG as HTML.
LogHello, console!console=yes # 也记录到控制台.
LogHyvä \x00repr=yes # Log 'Hyv\xe4 \x00'.

如果要一次记录多条消息,请参阅Log Many;如果只想写入控制台,请参阅Log To Console

参数htmlconsole并且repr是Robot Framework 2.8.2中的新功能。

Pprint支持何时repr使用是Robot Framework 2.8.6中的新增功能,并且它被更改为删除u前缀并b在Robot Framework 2.9中添加前缀。

Log Many*messages

使用INFO级别将给定消息记录为单独的条目。

还支持单独记录列表和字典变量项。

例子:

Log ManyHello${var}
Log Many@{list}&{dict}

如果要使用备用日志级别,使用HTML或登录到控制台,请参阅 Log 和 Log To Console 

Log To Console

message,

stream=STDOUT,

no_newline=False

将给定消息记录到控制台。

默认情况下使用标准输出流。使用标准错误流可能是通过给出stream参数值STDERR(不区分大小写)。

默认情况下,会在记录的消息中附加换行符。这可以通过赋予no_newline参数一个真值来禁用(参见布尔参数)。

例子:

Log To ConsoleHello, console! 
Log To ConsoleHello, stderr!STDERR
Log To ConsoleMessage starts here and isno_newline=true
Log To Consolecontinued without newline. 

此关键字不会将消息记录到普通日志文件中。如果需要,可以使用Log关键字,可能带参数console

New in Robot Framework 2.8.2.

Log Variableslevel=INFO使用给定的日志级别记录当前作用域中的所有变量。
No Operation 不做任何操作
Pass Executionmessage, *tags

通过PASS状态跳过当前测试,设置或拆卸的其余部分。

此关键字可以在测试数据中的任何位置使用,但使用的位置会影响行为:

  • 在任何设置或拆卸(套件,测试或关键字)中使用时,通过设置或拆卸。执行已启动关键字的可能关键字拆解。否则不会影响执行或状态。
  • 当在外部设置或拆卸测试中使用时,通过该特定测试用例。执行可能的测试和关键字拆解。

在使用此关键字之前可能的可持续故障以及执行的拆解中的故障将无法执行。

必须提供一条消息,说明执行的原因。默认情况下,该消息被视为纯文本,但启动它*HTML*允许使用HTML格式。

Fail关键字一样,也可以修改消息后传递标记的测试标记。以连字符(例如-regression)开头的标签将被删除,并添加其他标签。在内部使用“ 设置标记”和“ 删除标记”修改标记,语义设置和删除它们与这些关键字相同。

例子:

Pass ExecutionAll features available in this version tested.  
Pass ExecutionDeprecated test.deprecated-regression

此关键字通常包含在某些其他关键字中,例如Run Keyword If,以根据条件传递。最常见的情况也可以使用 Pass Execution If:

Run Keyword If${rc} < 0Pass ExecutionNegative values are cool.
Pass Execution If${rc} < 0Negative values are cool. 

应谨慎使用在测试,安装或拆卸过程中执行执行。在最坏的情况下,它会导致测试跳过所有可能实际发现测试应用程序中的问题的部分。如果执行无法继续执行外部因素,则通常会使测试用例失败并使其变得非关键性更安全。

New in Robot Framework 2.8.

Pass Execution If

condition,

message, *tags

有条件地通过PASS状态跳过当前测试,设置或拆卸的其余部分。

Pass Execution的包装器,用于跳过基于给定的当前测试,设置或拆卸的其余部分condition。与Should Be True关键字类似地评估条件,message并且*tags具有与Pass Execution相同的语义。

例:

:FOR${var}IN@{VALUES}
 Pass Execution If'${var}' == 'EXPECTED'Correct value was found
 Do Something${var} 

New in Robot Framework 2.8.

Regexp Escape*patterns

回转义的每个参数字符串,以用作正则表达式。

此关键字可用于转义要与Should Match Regexp Should Not Match Regexp关键字一起使用的字符串。

使用Python的re.escape()函数完成转义。

例子:

${escaped} =Regexp Escape${original}
@{strings} =Regexp Escape@{strings}
Reload Libraryname_or_instance

重新检查指定库提供的关键字。

可以在测试数据中显式调用,也可以在库提供的关键字发生变化时由库本身调用。

可以通过名称或库的活动实例指定库。如果库本身将此关键字称为方法,则后者特别有用。

New in Robot Framework 2.9.

Remove Tags*tags

tags从当前测试或套件中的所有测试中删除。

可以精确地给出标签,也可以使用*匹配任何内容并?匹配一个字符的模式。

Set Tags关键字类似,此关键字可以影响测试套件中的一个测试用例或所有测试用例。

当前标签可作为内置变量使用@{TEST TAGS}

例:

Remove Tagsmytagsomething-*?ython

See Set Tags if you want to add certain tags and Fail if you want to fail the test case after setting and/or removing tags.

如果你想添加某些标签,请参见Set Tags,如果你想失败设置和/或删除标记后的测试案例,请参见Fail 

Repeat Keywordrepeat, name,*args

多次执行指定的关键字。

nameargs定义与Run Keyword类似地执行的关键字repeat指定关键字应执行的次数(作为计数)或多长​​时间(作为超时)。

如果repeat以count为单位,则指定关键字应执行的次数。repeat可以作为整数或作为可以转换为整数的字符串给出。如果它是一个字符串,它可以有postfix timesx(case和space insensitive)使表达式更明确。

如果repeat作为超时给出,则它必须是Robot Framework的时间格式(例如1 minute2 min 3 s)。单独使用数字(例如11.5)在此上下文中不起作用。

如果repeat为零或负数,则根本不执行关键字。如果任何执行轮次失败,此关键字将立即失败。

例子:

Repeat Keyword5 timesGo to Previous Page  
Repeat Keyword${var}Some Keywordarg1arg2
Repeat Keyword2 minutesSome Keywordarg1arg2

指定repeat为超时是Robot Framework 3.0中的新增功能。

Replace Variablestext

用给定文本中的当前值替换给定文本中的变量。

如果文本包含未定义的变量,则此关键字将失败。如果给定text只包含一个变量,则其值按原样返回,并且可以是任何对象。否则此关键字始终返回一个字符串。

例:

文件template.txt包含Hello ${NAME}!和变量${NAME}具有值Robot

${template} =Get File${CURDIR}/template.txt
${message} =Replace Variables${template}
Should Be Equal${message}Hello Robot!
Return From Keyword*return_values

从封闭的user关键字返回。

此关键字可用于从具有PASS状态的用户关键字返回,而无需完全执行。也可以与[Return]设置类似地返回值。有关使用返回值的更多详细信息,请参阅“用户指南”。

此关键字通常包含在某些其他关键字中,例如Run Keyword IfRun Keyword If Test Passed,以根据条件返回:

Run Keyword If${rc} < 0Return From Keyword
Run Keyword If Test PassedReturn From Keyword 

也可以使用此关键字从for循环中的关键字返回。在以下有些高级示例中,Find Index关键字演示了该值以及返回值。请注意,将这种复杂的逻辑移动到测试库中通常是个好主意。

*** Variables ***
@{LIST} =    foo    baz

*** Test Cases ***
Example
    ${index} =    Find Index    baz    @{LIST}
    Should Be Equal    ${index}    ${1}
    ${index} =    Find Index    non existing    @{LIST}
    Should Be Equal    ${index}    ${-1}

*** Keywords ***
Find Index
   [Arguments]    ${element}    @{items}
   ${index} =    Set Variable    ${0}
   :FOR    ${item}    IN    @{items}
   \    Run Keyword If    '${item}' == '${element}'    Return From Keyword    ${index}
   \    ${index} =    Set Variable    ${index + 1}
   Return From Keyword    ${-1}    # Also [Return] would work here.

最常见的用例,基于表达式返回,可以使用Return From Keyword If直接完成。这两个关键字都是Robot Framework 2.8中的新功能。

See also Run Keyword And Return and Run Keyword And Return If.

Return From Keyword If

condition,

*return_values

如果condition为true,则从封闭用户关键字返回。

返回关键字的包装器,根据给定条件返回。使用与Should Be True关键字相同的语义来评估条件。

给出与返回关键字相同的示例,我们可以重写Find Index关键字,如下所示:

*** Keywords ***
Find Index
   [Arguments]    ${element}    @{items}
   ${index} =    Set Variable    ${0}
   :FOR    ${item}    IN    @{items}
   \    Return From Keyword If    '${item}' == '${element}'    ${index}
   \    ${index} =    Set Variable    ${index + 1}
   Return From Keyword    ${-1}    # Also [Return] would work here.

See also Run Keyword And Return and Run Keyword And Return If.

New in Robot Framework 2.8.

Run Keywordname, *args

使用给定的参数执行给定的关键字。

因为要执行的关键字的名称是作为参数给出的,所以它可以是变量,因此可以动态设置,例如从另一个关键字的返回值或命令行设置。

Run Keyword And Continue On Failurename, *args

运行关键字并继续执行即使发生故障。

关键字名称和参数与Run Keyword一样

例:

Run Keyword And Continue On FailureFailThis is a stupid example
LogThis keyword is executed 

如果失败是由无效语法,超时或致命异常引起的,则不会继续执行。自Robot Framework 2.9起,此关键字会捕获变量错误。

Run Keyword And Expect Error

expected_error,

name, *args

运行关键字并检查是否发生了预期的错误。

必须以与Robot Framework报告中相同的格式给出预期错误。它可以是包含字符的模式?,它与任何单个字符*匹配,并且与任意数量的任何字符匹配。name并且*args具有与Run Keyword相同的语义。

如果发生预期错误,则返回错误消息,如果需要,可以进一步处理/测试。如果没有错误,或者错误与预期错误不匹配,则此关键字失败。

例子:

Run Keyword And Expect ErrorMy errorSome Keywordarg1arg2
${msg} =Run Keyword And Expect Error*My KW 
Should Start With${msg}Once upon a time in  

此关键字不会捕获由无效语法,超时或致命异常导致的错误。自Robot Framework 2.9起,此关键字会捕获变量错误。

Run Keyword And Ignore Errorname, *args

使用给定的参数运行给定的关键字并忽略可能的错误。

此关键字返回两个值,因此第一个是字符串PASS或者FAIL,具体取决于执行的关键字的状态。第二个值是关键字的返回值或收到的错误消息。请参阅Run Keyword And Return Status如果您只对执行状态感兴趣。

关键字名称和参数的工作方式与Run Keyword。有关用法示例,请参阅Run Keyword If

  此关键字不会捕获由无效语法,超时或致命异常导致的错误。否则此关键字本身永远不会失败 自Robot Framework 2.9起,此关键字会捕获变量错误

Run Keyword And Returnname, *args

运行指定的关键字并从封闭的user关键字返回。

要执行的关键字与定义name,并*args与酷似Run Keyword。运行关键字后,从封闭的user关键字返回,并进一步从执行的关键字传递可能的返回值。从关键字返回的语义与Return From Keyword语义完全相同。

例:

Run Keyword And ReturnMy Keywordarg1arg2
# Above is equivalent to:   
${result} =My Keywordarg1arg2
Return From Keyword${result}  

如果要运行关键字并根据条件返回,使用 Run Keyword And Return If 

New in Robot Framework 2.8.2.

Run Keyword And Return If

condition, 

name,*args

运行指定的关键字并从封闭的user关键字返回。

Run Keyword and Return的包装器根据给定的运行和返回condition。使用与Should Be True关键字相同的语义来评估条件。

例:

Run Keyword And Return If${rc} > 0My Keywordarg1arg2 
# 以上相当于:     
Run Keyword If${rc} > 0Run Keyword And ReturnMy Keywordarg1arg2

 如果要根据条件返回特定值,使用Return From Keyword If

New in Robot Framework 2.8.2.

Run Keyword And Return Statusname, *args

使用给定参数运行给定关键字并将状态返回为布尔值。

True如果执行的关键字成功并且False失败,则此关键字返回Boolean 。例如,与Run Keyword If结合使用时,这非常有用。如果您对错误消息或返回值感兴趣,请改用

 Run Keyword And Ignore Error 

关键字名称和参数的工作方式与 Run Keyword 相同

Exmple:

${passed} =Run Keyword And Return StatusKeywordargs
Run Keyword If${passed}Another keyword 

此关键字不会捕获由无效语法,超时或致命异常导致的错误。否则此关键字本身永远不会失败

New in Robot Framework 2.7.6.

Run Keyword If

condition, 

name,*args

如果condition为true ,则使用给定的参数运行给定的关键字。

给定condition的值在Python中进行评估,如Evaluating expressionsname并且*args具有与Run Keyword.相同的语义

例如,一个简单的if / else结构:

${status}${value} =Run Keyword And Ignore ErrorMy Keyword
Run Keyword If'${status}' == 'PASS'Some Actionarg
Run Keyword Unless'${status}' == 'PASS'Another Action 

在此示例中,根据“ 我的关键字”的状态,仅执行“ 某些操作”或“ 其他操作”。您还可以使用 Run Keyword And Return Status来代替Run Keyword And Ignore Error

${variable}与上述示例中一样使用的变量在评估之前的表达式中被替换。变量也可以在评估命名空间中使用,并且可以使用特殊语法进行访问$variable。这是Robot Framework 2.9中的一个新功能,它在 Evaluating expressions时得到了更全面的解释。

Example:

Run Keyword If$result is None or $result == 'FAIL'Keyword

从Robot版本2.7.4开始,此关键字还支持可选的ELSE和ELSE IF分支。这两个都是定义的*args,必须分别使用格式ELSE或格式ELSE IF。ELSE分支必须首先包含要执行的关键字的名称,然后包含其可能的参数。ELSE IF分支必须首先包含一个条件,比如此关键字的第一个参数,然后是要执行的关键字及其可能的参数。ELSE IF之后可以有ELSE分支,并且有多个ELSE IF分支。

在前面的例子中,if / else构造也可以像这样创建:

${status}${value} =Run Keyword And Ignore ErrorMy Keyword  
Run Keyword If'${status}' == 'PASS'Some ActionargELSEAnother Action

返回值是已执行的关键字之一,如果没有执行关键字,则返回None(即,如果condition为false)。因此,建议使用ELSE和/或ELSE IF分支有条件地将关键字的返回值分配给变量(有条件地将固定值分配给变量,请参阅Set Variable If)。

下面的示例说明了这一点:). 

${var1} =Run Keyword If${rc} == 0Some keyword returning a value  
...ELSE IF0 < ${rc} < 42Another keyword  
...ELSE IF${rc} < 0Another keyword with args${rc}arg2
...ELSEFinal keyword to handle abnormal cases${rc}  
${var2} =Run Keyword If${condition}Some keyword  

在此示例中,如果$ {condition}为false,则$ {var2}将设置为None。

注意ELSEELSE IF控制字必须明确使用,因此不能来自变量。如果你需要使用文字ELSEELSE IF字符串作为参数,你可以像一个反斜杠逃脱他们\ELSE\ELSE IF

从Robot Framework 2.8开始,Python的ossys模块在评估时自动导入condition。因此,它们包含的属性可用于以下条件:

Run Keyword Ifos.sep == '/'Unix Keyword 
...ELSE IFsys.platform.startswith('java')Jython Keyword
...ELSEWindows Keyword 
Run Keyword If All Critical Tests Passedname, *args

如果所有关键测试都通过,则使用给定的参数运行给定的关键字。

此关键字只能在套件拆解中使用。试图在任何其他地方使用它将导致错误。

否则,此关键字与Run Keyword完全相同,请参阅其文档以获取更多详细信息。

Run Keyword If All Tests Passedname, *args

如果所有测试都通过,则使用给定的参数运行给定的关键字。

此关键字只能在套件拆解中使用。尝试在其他地方使用它会导致错误。

否则,此关键字与Run Keyword完全相同,请参阅其文档以获取更多详细信息。

Run Keyword If Any Critical Tests Failedname, *args

如果任何关键测试失败,则使用给定参数运行给定关键字。

此关键字只能在套件拆解中使用。尝试在其他地方使用它会导致错误。

否则,此关键字与Run Keyword完全相同,请参阅其文档以获取更多详细信息。

Run Keyword If Any Tests Failedname, *args

如果一个或多个测试失败,则使用给定的参数运行给定的关键字。

此关键字只能在套件拆解中使用。尝试在其他地方使用它会导致错误。

否则,此关键字与Run Keyword完全相同,请参阅其文档以获取更多详细信息。

Run Keyword If Test Failedname, *args

如果测试失败,则使用给定的参数运行给定的关键字。

此关键字只能用于测试拆解。尝试在其他地方使用它会导致错误。

否则,此关键字与Run Keyword完全相同,请参阅其文档以获取更多详细信息。

在Robot Framework 2.9之前,此关键字未检测到测试拆解本身的故障。

Run Keyword If Test Passedname, *args

如果测试通过,则使用给定的参数运行给定的关键字。

此关键字只能用于测试拆解。尝试在其他地方使用它会导致错误。

否则,此关键字与Run Keyword完全相同,请参阅其文档以获取更多详细信息。

在Robot Framework 2.9之前,此关键字未检测到测试拆解本身的故障。

Run Keyword If Timeout Occurredname, *args

如果发生测试或关键字超时,则运行给定的关键字。

此关键字只能用于测试拆解。尝试在其他地方使用它会导致错误。

否则,此关键字与Run Keyword完全相同,请参阅其文档以获取更多详细信息。

Run Keyword Unless

condition, 

name,*args

如果condition为false ,则使用给定参数运行给定关键字。

有关详细信息和示例,请参阅Run Keyword

Run Keywords*keywords

按顺序执行所有给定的关键字。

当关键字需要处理多个操作并且创建新的更高级别用户关键字时,这个关键字主要用于设置和拆卸。

默认情况下,所有参数都应该是要执行的关键字。

例子:

Run KeywordsInitialize databaseStart serversClear logs
Run Keywords${KW 1}${KW 2} 
Run Keywords@{KEYWORDS}  

从Robot Framework 2.7.6开始,关键字也可以使用大写AND作为关键字之间的分隔符来运行。执行关键字,以便第一个参数是第一个关键字和继续参数,直到第一个AND参数为其参数。第一个参数之后的第一个参数AND是第二个关键字和继续参数,直到下一个AND参数为其参数。等等。

例子:

Run KeywordsInitialize databasedb1ANDStart serversserver1server2 
Run KeywordsInitialize database${DB NAME}ANDStart servers@{SERVERS}ANDClear logs
Run Keywords${KW}AND@{KW WITH ARGS}    

请注意,AND必须显式使用control参数,并且它本身不能来自变量。如果你需要使用文字AND字符串作为参数,你可以使用变量或使用反斜杠转义它\AND

Set Global Variablename, *values

使变量在所有测试和套件中全局可用。

使用此关键字设置的变量在设置后执行的所有测试用例和套件中全局可用。因此,使用此关键字设置变量与使用选项--variable或从命令行创建具有相同的效果--variablefile。由于此关键字可以在任何地方更改变量,因此应谨慎使用。

有关更多信息和示例,请参阅Set Suite Variable .

Set Library Search Order*search_order

设置名称与多个关键字匹配时使用的分辨率顺序。

当测试数据中的关键字名称与多个关键字匹配时,库搜索顺序用于解决冲突。选择包含关键字的第一个库(或资源,见下文),并使用该关键字实现。如果未在任何库(或资源)中找到关键字,则测试执行失败的方式与未设置搜索顺序时相同。

使用此关键字时,无需使用长LibraryName.Keyword Name记法。例如,而不是拥有

MyLibrary.Keywordarg
MyLibrary.Another Keyword 
MyLibrary.Keywordxxx

你可以有

Set Library Search OrderMyLibrary
Keywordarg
Another Keyword 
Keywordxxx

此关键字还可用于设置不同资源文件中关键字的顺序。在这种情况下,资源名称必须没有路径或扩展名,如:

Set Library Search Orderresourceanother_resource

注意:

  • 搜索顺序仅在使用此关键字的套件中有效。
  • 无论搜索顺序如何,资源中的关键字始终优先于库中的关键字。
  • 返回旧订单,可用于稍后重置搜索顺序。
  • 搜索顺序中的库和资源名称都是大小写和空间不敏感的。
Set Log Levellevel

将日志阈值设置为指定级别并返回旧级别。

级别以下的消息不会被记录。默认日志记录级别为INFO,但可以使用命令行选项覆盖它--loglevel

可用级别:TRACE,DEBUG,INFO(默认),WARN,ERROR和NONE(无日志记录)。

Set Suite Documentation

doc, 

append=False,

top=False

设置当前测试套件的文档。

默认情况下,可能的现有文档会被覆盖,但可以使用可选append参数更改,与Set Test Message关键字类似。

此关键字默认设置当前套件的文档。如果可选top参数被赋予true值(请参阅布尔参数),则会更改顶级套件的文档。

当前套件的文档可作为内置变量使用${SUITE DOCUMENTATION}

Robot Framework 2.7中的新功能。支持appendtop在2.7.7中添加。

Set Suite Metadata

name, 

value,

append=False,

top=False

设置当前测试套件的元数据。

默认情况下,可能会覆盖可能的现有元数据值,但可以使用可选append参数更改此值,与Set Test Message关键字类似。

此关键字默认设置当前套件的元数据。如果可选top参数被赋予true值(请参阅布尔参数),则会更改顶级套件的元数据。

当前套件的元数据可作为${SUITE METADATA}Python字典中的内置变量使用。请注意,直接修改此变量不会影响套件的实际元数据。

机器人框架2.7.4中的新功能。支持appendtop在2.7.7中添加。

Set Suite Variablename, *values

使变量在当前套件的范围内随处可用。

使用此关键字设置的变量可在当前执行的测试套件范围内的任何位置使用。因此,使用此关键字设置变量与使用测试数据文件中的变量表创建变量或从变量文件导入变量具有相同的效果。

可能的子测试套件默认情况下看不到使用此关键字设置的变量。从Robot Framework 2.9开始,可以通过使用children=<option>最后一个参数来控制。如果指定<option>的是非空字符串或Python中认为为true的任何其他值,则该变量也将设置为子套件。父级和兄弟套件永远不会看到使用此关键字设置的变量。

变量的名称可以被给予或者作为正常变量名称(例如${NAME}),或在转义格式\${NAME}$NAME。可以使用与在Variable表中创建变量时相同的语法来给出变量值。

如果新范围内已存在变量,则其值将被覆盖。否则,将创建一个新变量。如果变量已存在于当前范围内,则该值可以保留为空,新范围内的变量将获取当前范围内的值。

例子:

Set Suite Variable${SCALAR}Hello, world! 
Set Suite Variable${SCALAR}Hello, world!children=true
Set Suite Variable@{LIST}First itemSecond item
Set Suite Variable&{DICT}key=valuefoo=bar
${ID} =Get ID  
Set Suite Variable${ID}  

要使用空值覆盖现有值,请使用内置变量${EMPTY}@{EMPTY}或者&{EMPTY}

Set Suite Variable${SCALAR}${EMPTY} 
Set Suite Variable@{LIST}@{EMPTY}# New in RF 2.7.4
Set Suite Variable&{DICT}&{EMPTY}# New in RF 2.9

注意:如果变量的值本身是变量(转义或不转义),则必须始终使用转义格式设置变量:

例:

${NAME} =Set Variable\${var} 
Set Suite Variable${NAME}value# Sets variable ${var}
Set Suite Variable\${NAME}value# Sets variable ${NAME}

此限制也适用于 Set Test VariableSet Global VariableVariable Should ExistVariable Should Not Exist and Get Variable Value keywords.

Set Tags*tags

tags为当前测试或套件中的所有测试添加的内容。

在测试用例中使用此关键字时,该测试将获取指定的标记,而其他测试不会受到影响。

如果在套件设置中使用此关键字,则该套件中的所有测试用例都会递归地获取给定的标记。在套件拆解中使用此关键字失败。

当前标签可作为内置变量使用@{TEST TAGS}

请参见Remove Tags,如果你想删除某些标签和Fail,如果你想失败设置和/或删除标记后的测试案例。

Set Test Documentationdoc, append=False

设置当前测试用例的文档。

默认情况下,可能的现有文档会被覆盖,但可以使用可选append参数更改,与Set Test Message关键字类似。

当前的测试文档可作为内置变量使用${TEST DOCUMENTATION}。此关键字无法在套件设置或套件拆卸中使用。

Robot Framework 2.7中的新功能。支持append在2.7.7中添加。

Set Test Message

message,

append=False

设置当前测试用例的消息。

如果可选append参数被赋予真值(参见布尔参数),则message通过使用空格连接消息,在可能的先前消息之后添加给定。

在测试拆解中,此关键字可以更改可能的失败消息,但是否则失败会覆盖此关键字设置的消息。请注意,在拆解时,消息可作为内置变量使用${TEST MESSAGE}

通过启动消息可以在消息中使用HTML格式*HTML*

例子:

Set Test MessageMy message 
Set Test Messageis continued.append=yes
Should Be Equal${TEST MESSAGE}My message is continued.
Set Test Message*HTML* <b>Hello!</b> 

此关键字无法在套件设置或套件拆卸中使用。

支持append在机器人框架2.7.7和支持,增加了对HTML格式2.8。

Set Test Variablename, *values

使变量在当前测试的范围内随处可用。

使用此关键字设置的变量可在当前执行的测试用例范围内的任何位置使用。例如,如果在user关键字中设置变量,则它在测试用例级别以及当前测试中使用的所有其他用户关键字中都可用。其他测试用例不会看到使用此关键字设置的变量。

有关更多信息和示例,请参阅Set Suite Variable 

Set Variable*values

返回给定值,然后可以将其分配给变量。

该关键字主要用于设置标量变量。此外,它还可用于将包含列表的标量变量转换为列表变量或多个标量变量。建议在创建新列表时使用“ Create List 

例子:

${hi} =Set VariableHello, world!  
${hi2} =Set VariableI said: ${hi}  
${var1}${var2} =Set VariableHelloworld
@{list} =Set Variable${list with some items}  
${item1}${item2} =Set Variable${list with 2 items} 

使用此关键字创建的变量仅在创建它们的范围内可用。有关如何设置变量以便它们在更大范围内可用的信息,请参阅 Set Global VariableSet Test Variable and Set Suite Variable 

Set Variable Ifcondition, *values

根据给定条件设置变量。

基本用法是给出一个条件和两个值。首先以与Should Be True关键字相同的方式评估给定条件。如果条件为true,则返回第一个值,否则返回第二个值。第二个值也可以省略,在这种情况下它有一个默认值None。这种用法在下面的例子中说明,${rc}假设为零。

${var1} =Set Variable If${rc} == 0zerononzero
${var2} =Set Variable If${rc} > 0value1value2
${var3} =Set Variable If${rc} > 0whatever 

=>

${var1} = 'zero'
${var2} = 'value2'
${var3} = None

通过用另一个条件替换第二个值并在其后面有两个新值,也可以使用“else if”支持。如果第一个条件不为真,则计算第二个条件,并根据其真值返回其后的一个值。这可以通过添加更多条件而不受限制来继续。

${var} =Set Variable If${rc} == 0zero
...${rc} > 0greater than zeroless then zero
    
${var} =Set Variable If  
...${rc} == 0zero 
...${rc} == 1one 
...${rc} == 2two 
...${rc} > 2greater than two 
...${rc} < 0less than zero 

如果需要根据变量是否存在动态设置变量,请使用 Get Variable Value 

Should Be Emptyitem, msg=None

验证给定项目是否为空。

使用Get Length关键字获取项目的长度。可以使用msg参数覆盖默认错误消息。

 

Should Be Equal

first, 

second,

msg=None,

values=True,

ignore_case=False

如果给定的对象不相等则失败。

可选msgvalues参数指定如果此关键字失败,如何构造错误消息:

  • 如果msg没有给出,则出现错误消息<first> != <second>
  • 如果msg给定并values获得真值(默认值),则错误消息为<msg>: <first> != <second>
  • 如果msg给出并values获得false值,则错误消息就是<msg>。有关使用false值的更多详细信息,请参阅Boolean arguments

如果ignore_case给出了一个真值(参见Boolean arguments)并且参数是字符串,则表明比较应该不区分大小写。Robot Framework 3.0.1中的新选项。

如果两个参数都是多行字符串,则使用multiline string comparisons完成比较

例子:

Should Be Equal${x}expected  
Should Be Equal${x}expectedCustom error message 
Should Be Equal${x}expectedCustom messagevalues=False
Should Be Equal${x}expectedignore_case=True 
Should Be Equal As Integers

first, second,

msg=None,

values=True,

base=None

如果将对象转换为整数后对象不相等则失败。

有关如何使用参数或前缀从10以外的其他基数转换整数的信息,请参见转换为整数Convert To Integerbase0b/0o/0x

有关如何使用和覆盖默认错误消息的说明,请参阅“ 应该等于Should Be Equal ” 。

例子:

Should Be Equal As Integers42${42}Error message
Should Be Equal As IntegersABCDabcdbase=16
Should Be Equal As Integers0b101111 
Should Be Equal As Numbers

first, second,

msg=None,

values=True,

precision=6

Fails if objects are unequal after converting them to real numbers.

The conversion is done with Convert To Number keyword using the given precision.

Examples:

Should Be Equal As Numbers${x}1.1 # Passes if ${x} is 1.1
Should Be Equal As Numbers1.1231.1precision=1# Passes
Should Be Equal As Numbers1.1231.4precision=0# Passes
Should Be Equal As Numbers112.375precision=-2# Passes

As discussed in the documentation of Convert To Number, machines generally cannot store floating point numbers accurately. Because of this limitation, comparing floats for equality is problematic and a correct approach to use depends on the context. This keyword uses a very naive approach of rounding the numbers before comparing them, which is both prone to rounding errors and does not work very well if numbers are really big or small. For more information about comparing floats, and ideas on how to implement your own context specific comparison algorithm, see http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/.

See Should Not Be Equal As Numbers for a negative version of this keyword and Should Be Equal for an explanation on how to override the default error message with msg and values.

Should Be Equal As Strings

first, second,

msg=None,

values=True,

ignore_case=False

Fails if objects are unequal after converting them to strings.

See Should Be Equal for an explanation on how to override the default error message with msg and values.

If ignore_case is given a true value (see Boolean arguments), it indicates that comparison should be case-insensitive. New option in Robot Framework 3.0.1.

If both arguments are multiline strings, the comparison is done using multiline string comparisons.

Should Be Truecondition,msg=None

Fails if the given condition is not true.

If condition is a string (e.g. ${rc} < 10), it is evaluated as a Python expression as explained in Evaluating expressions and the keyword status is decided based on the result. If a non-string item is given, the status is got directly from its truth value.

The default error message (<condition> should be true) is not very informative, but it can be overridden with the msg argument.

Examples:

Should Be True${rc} < 10 
Should Be True'${status}' == 'PASS'# Strings must be quoted
Should Be True${number}# Passes if ${number} is not zero
Should Be True${list}# Passes if ${list} is not empty

Variables used like ${variable}, as in the examples above, are replaced in the expression before evaluation. Variables are also available in the evaluation namespace and can be accessed using special syntax $variable. This is a new feature in Robot Framework 2.9 and it is explained more thoroughly in Evaluating expressions.

Examples:

Should Be True$rc < 10 
Should Be True$status == 'PASS'# Expected string must be quoted

Starting from Robot Framework 2.8, Should Be True automatically imports Python's os and sys modules that contain several useful attributes:

Should Be Trueos.linesep == '\n'# Unixy
Should Be Trueos.linesep == '\r\n'# Windows
Should Be Truesys.platform == 'darwin'# OS X
Should Be Truesys.platform.startswith('java')# Jython
Should Contain

container, 

item,msg=None,

values=True,

ignore_case=False

Fails if container does not contain item one or more times.

Works with strings, lists, and anything that supports Python's in operator.

See Should Be Equal for an explanation on how to override the default error message with arguments msg and values.

If ignore_case is given a true value (see Boolean arguments) and compared items are strings, it indicates that comparison should be case-insensitive. If the container is a list-like object, string items in it are compared case-insensitively. New option in Robot Framework 3.0.1.

Examples:

Should Contain${output}PASS  
Should Contain${some list}valuemsg=Failure!values=False
Should Contain${some list}valuecase_insensitive=True 
Should Contain Any

container, 

*items,

**configuration

Fails if container does not contain any of the *items.

Works with strings, lists, and anything that supports Python's in operator.

Supports additional configuration parameters msgvalues and ignore_case, which have exactly the same semantics as arguments with same names have with Should Contain. These arguments must always be given using name=value syntax after all items.

Note that possible equal signs in items must be escaped with a backslash (e.g. foo\=bar) to avoid them to be passed in as **configuration.

Examples:

Should Contain Any${string}substring 1substring 2  
Should Contain Any${list}item 1item 2item 3 
Should Contain Any${list}item 1item 2item 3ignore_case=True
Should Contain Any${list}@{items}msg=Custom messagevalues=False 

New in Robot Framework 3.0.1.

Should Contain X Times

item1, 

item2,

count, 

msg=None,

ignore_case=False

Fails if item1 does not contain item2 count times.

Works with strings, lists and all objects that Get Count works with. The default error message can be overridden with msg and the actual count is always logged.

If ignore_case is given a true value (see Boolean arguments) and compared items are strings, it indicates that comparison should be case-insensitive. If the item1 is a list-like object, string items in it are compared case-insensitively. New option in Robot Framework 3.0.1.

Examples:

Should Contain X Times${output}hello2 
Should Contain X Times${some list}value3ignore_case=True
Should End With

str1, str2,

msg=None,

values=True,

ignore_case=False

Fails if the string str1 does not end with the string str2.

See Should Be Equal for an explanation on how to override the default error message with msg and values, as well as for semantics of the ignore_case option.

Should Match

string, 

pattern,

msg=None,

values=True,

ignore_case=False

Fails unless the given string matches the given pattern.

Pattern matching is similar as matching files in a shell, and it is always case-sensitive. In the pattern, * matches to anything and ?matches to any single character.

See Should Be Equal for an explanation on how to override the default error message with msg and values, as well as for semantics of the ignore_case option.

Should Match Regexp

string, pattern,

msg=None,values=True

Fails if string does not match pattern as a regular expression.

Regular expression check is implemented using the Python re module. Python's regular expression syntax is derived from Perl, and it is thus also very similar to the syntax used, for example, in Java, Ruby and .NET.

Things to note about the regexp syntax in Robot Framework test data:

1) Backslash is an escape character in the test data, and possible backslashes in the pattern must thus be escaped with another backslash (e.g. \\d\\w+).

2) Strings that may contain special characters, but should be handled as literal strings, can be escaped with the Regexp Escape keyword.

3) The given pattern does not need to match the whole string. For example, the pattern ello matches the string Hello world!. If a full match is needed, the ^ and $ characters can be used to denote the beginning and end of the string, respectively. For example, ^ello$ only matches the exact string ello.

4) Possible flags altering how the expression is parsed (e.g. re.IGNORECASEre.MULTILINE) can be set by prefixing the pattern with the (?iLmsux) group like (?im)pattern. The available flags are i (case-insensitive), m (multiline mode), s (dotall mode), x (verbose), u(Unicode dependent) and L (locale dependent).

If this keyword passes, it returns the portion of the string that matched the pattern. Additionally, the possible captured groups are returned.

See the Should Be Equal keyword for an explanation on how to override the default error message with the msg and values arguments.

Examples:

Should Match Regexp${output}\\d{6}# Output contains six numbers
Should Match Regexp${output}^\\d{6}$# Six numbers and nothing more
${ret} =Should Match RegexpFoo: 42(?i)foo: \\d+
${match}${group1}${group2} = 
...Should Match RegexpBar: 43(Foo|Bar): (\\d+)

=>

${ret} = 'Foo: 42'
${match} = 'Bar: 43'
${group1} = 'Bar'
${group2} = '43'
Should Not Be Emptyitem, msg=None

Verifies that the given item is not empty.

The length of the item is got using the Get Length keyword. The default error message can be overridden with the msg argument.

Should Not Be Equal

first, second,

msg=None,

values=True,

ignore_case=False

Fails if the given objects are equal.

See Should Be Equal for an explanation on how to override the default error message with msg and values.

If ignore_case is given a true value (see Boolean arguments) and both arguments are strings, it indicates that comparison should be case-insensitive. New option in Robot Framework 3.0.1.

Should Not Be Equal As Integers

first, second,

msg=None,

values=True,

base=None

Fails if objects are equal after converting them to integers.

See Convert To Integer for information how to convert integers from other bases than 10 using base argument or 0b/0o/0x prefixes.

See Should Be Equal for an explanation on how to override the default error message with msg and values.

See Should Be Equal As Integers for some usage examples.

Should Not Be Equal As Numbers

first, second,

msg=None,

values=True,

precision=6

Fails if objects are equal after converting them to real numbers.

The conversion is done with Convert To Number keyword using the given precision.

See Should Be Equal As Numbers for examples on how to use precision and why it does not always work as expected. See also Should Be Equal for an explanation on how to override the default error message with msg and values.

Should Not Be Equal As Strings

first, second,

msg=None,

values=True,

ignore_case=False

Fails if objects are equal after converting them to strings.

If ignore_case is given a true value (see Boolean arguments), it indicates that comparison should be case-insensitive. New option in Robot Framework 3.0.1.

See Should Be Equal for an explanation on how to override the default error message with msg and values.

Should Not Be Truecondition,msg=None

Fails if the given condition is true.

See Should Be True for details about how condition is evaluated and how msg can be used to override the default error message.

Should Not Contain

container, 

item,msg=None,

values=True,

ignore_case=False

Fails if container contains item one or more times.

Works with strings, lists, and anything that supports Python's in operator.

See Should Be Equal for an explanation on how to override the default error message with arguments msg and valuesignore_case has exactly the same semantics as with Should Contain.

Examples:

Should Not Contain${some list}value 
Should Not Contain${output}FAILEDignore_case=True
Should Not Contain Any

container, 

*items,

**configuration

Fails if container contains one or more of the *items.

Works with strings, lists, and anything that supports Python's in operator.

Supports additional configuration parameters msgvalues and ignore_case, which have exactly the same semantics as arguments with same names have with Should Contain. These arguments must always be given using name=value syntax after all items.

Note that possible equal signs in items must be escaped with a backslash (e.g. foo\=bar) to avoid them to be passed in as **configuration.

Examples:

Should Not Contain Any${string}substring 1substring 2  
Should Not Contain Any${list}item 1item 2item 3 
Should Not Contain Any${list}item 1item 2item 3ignore_case=True
Should Not Contain Any${list}@{items}msg=Custom messagevalues=False 

New in Robot Framework 3.0.1.

Should Not End With

str1, str2,

msg=None,

values=True,

ignore_case=False

如果字符串str1以字符串结尾,则失败str2

有关如何使用和,以及选项的语义覆盖默认错误消息的说明,请参阅 Should Be Equal 

Should Not Match

string, pattern,

msg=None,

values=True,

ignore_case=False

如果给定的string匹配给定,则失败pattern

模式匹配与shell中的匹配文件类似,并且始终区分大小写。在模式*匹配任何东西和?匹配任何单个字符。

有关如何使用和,以及选项的语义覆盖默认错误消息的说明,请参阅Should Be Equal 

Should Not Match Regexp

string, pattern,

msg=None,values=True

如果string匹配pattern作为正则表达式,则失败。

有关参数的更多信息,请参阅Should Match Regexp 

Should Not Start With

str1, str2,

msg=None,

values=True,

ignore_case=False

如果字符串str1以字符串开头,则失败str2

有关如何使用和,以及选项的语义覆盖默认错误消息的说明,请参阅Should Be Equal 

Should Start With

str1, str2,

msg=None,

values=True,

ignore_case=False

如果字符串str1不以字符串开头则失败str2

有关如何使用和,以及选项的语义覆盖默认错误消息的说明,请参阅Should Be Equal 

Sleeptime_, reason=None

暂停在给定时间内执行的测试。

time可以是数字或时间字符串。时间字符串的格式如1 day 2 hours 3 minutes 4 seconds 5millisecondsor 1d 2h 3m 4s 5ms,并且在Robot Framework用户指南的附录中对它们进行了详细说明。可选原因可用于解释为什么需要睡觉。睡觉的时间和原因都被记录下来。

例子:

Sleep42 
Sleep1.5 
Sleep2 minutes 10 seconds 
Sleep10sWait for a reply
Variable Should Existname, msg=None

除非给定变量存在于当前范围内,否则失败。

变量的名称可以作为普通变量名称(例如${NAME})或以转义格式(例如\${NAME})给出。请注意,前者在Set Suite Variable中有一些限制。

可以使用msg参数覆盖默认错误消息。

See also Variable Should Not Exist and Keyword Should Exist.

Variable Should Not Existname, msg=None

如果给定变量存在于当前范围内,则失败。

变量的名称可以作为普通变量名称(例如${NAME})或以转义格式(例如\${NAME})给出。请注意,前者在Set Suite Variable中有一些限制。

可以使用msg参数覆盖默认错误消息。

See also Variable Should Exist and Keyword Should Exist.

Wait Until Keyword Succeeds

retry,retry_interval

,name, *args

运行指定的关键字,如果失败则重试。

nameargs定义与Run Keyword类似地执行的关键字。使用retry参数作为超时或计数来定义重试运行关键字的时间。retry_interval是在上一次运行失败后再次尝试运行关键字之前等待的时间。

如果retry是作为超时,就必须在机器人Framework的时间格式(例如1 minute2 min 3 s4.5),该机器人Framework用户手册的附录中阐述。如果它作为计数给出,它必须具有timesx后缀(例如5 times10 x)。retry_interval必须始终以Robot Framework的时间格式给出。

如果关键字无论重试都不成功,则此关键字将失败。如果执行的关键字通过,则返回其返回值。

例子:

Wait Until Keyword Succeeds2 min5 secMy keywordargument
${result} =Wait Until Keyword Succeeds3x200msMy keyword

此关键字捕获所有正常故障。由无效语法,测试或关键字超时或致命异常(例如由致命错误引起)导致的错误未被捕获。

在此关键字内多次运行相同的关键字可以创建大量输出,并显着增加生成的输出文件的大小。从Robot Framework 2.7开始,可以使用--RemoveKeywords WUKS命令行选项从输出中删除不必要的关键字。

支持指定retry重试次数是Robot Framework 2.9中的新功能。自Robot Framework 2.9起,此关键字会捕获变量错误。

Altogether 103 keywords. 
Generated by Libdoc on 2018-04-25 23:41:28.

参考文档:http://robotframework.org/robotframework/latest/libraries/BuiltIn.html


版权声明:本文为shuishen520原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。