Robot Framework is a generic open source automation framework for acceptance testing, acceptance test driven development (ATDD), and robotic process automation (RPA). It has simple plain text syntax and it can be extended easily with libraries implemented using Python or Java.
wget
下来.whl
配合pip install
,或者.zip
解压再unzip后,python setup.py install
都可以robot --version
pip3 install robotframework
安装robot --version
Robot Framework 4.1.2 (Python 3.6.8 on linux)test suite directory
.tsv .txt .robot .rst .rest
.robot
.resource
*** Settings ***
*** Settings *** # 全局设置
Documentation Example using the space separated format.
Library OperatingSystem
*** Variables ***
${
MESSAGE} Hello, world!
*** Test Cases ***
My Test
[Documentation] Example test.
Log ${
MESSAGE}
My Keyword ${
CURDIR}
Another Test
Should Be Equal ${
MESSAGE} Hello, world!
*** Keywords ***
My Keyword
[Arguments] ${
path}
Directory Should Exist ${
path}
# 下面是管道分隔符,可以称为单元格
| *** Settings *** |
| Documentation | Example using the pipe separated format.
| Library | OperatingSystem
| *** Variables *** |
| ${
MESSAGE} | Hello, world!
| *** Test Cases *** | | |
| My Test | [Documentation] | Example test. |
| | Log | ${
MESSAGE} |
| | My Keyword | ${
CURDIR} |
| Another Test | Should Be Equal | ${
MESSAGE} | Hello, world!
| *** Keywords *** | | |
| My Keyword | [Arguments] | ${
path} |
| | Directory Should Exist | ${
path} |
reStructuredText
文件是将code嵌入在robot文件中,可以使用code指令标记,这样的文件以.rst .rest
结尾# 当执行一个包含 reStucturedText 文件的目录时,必须使用 --extension 选项来明确告诉这些文件应该被解析
.. code:: python
# This code block is ignored.
def example():
print('Hello, world!')
#
后的数据,类似python注释*** Test Cases ***
Using backslash(反斜线)
Do Something first arg \
Do Something \ second arg
Using ${EMPTY}
Do Something first arg ${EMPTY}
Do Something ${EMPTY} second arg
\
或者${EMPTY}
表示(相当于占位符)${SPACE}
使空格不被忽略...
*** Settings ***
Documentation Here we have documentation for this suite.
... Documentation is often quite long.
...
... It can also contain multiple paragraphs.
Default Tags default tag 1 default tag 2 default tag 3
... default tag 4 default tag 5
*** Variable ***
${STRING} This is a long string.
... It has multiple sentences.
... It does not have newlines.
*** Test Cases ***
部分定义的*** Test Cases ***
Valid Login # 测试用例名称
Open Login Page # 关键字
Input Username demo
Input Password mode
Submit Credentials
Welcome Page Should Be Open
Setting Variables
Do Something first argument second argument
${value} = Get Some Value
Should Be Equal ${value} Expected value
[ ]
*** Test Cases ***
Test With Settings
[Documentation] Another dummy test # 用于指定 测试用例文档.
[Tags] dummy owner-johndoe
Log Hello, world!
# [Tags] 用于指定 测试用例的标签.
# [Setup], [Teardown] 用于指定 Setup和Teardown.
# [Template] 用于指定 测试模板. 测试用例本身将只包含数据, 每行数据都是传递给该关键字的参数, 最终实现数据驱动的测试.
# [Timeout] 用于设置 test case timeout. timeouts 将在独立的章节讨论
# syntax 语法
*** Test Cases ***
Example
Create Directory ${TEMPDIR}/stuff
Copy File ${CURDIR}/file.txt ${TEMPDIR}/stuff
No Operation
# Create Directory Copy File 都是OperatingSystem library中定义好的关键字
# 这些东西和其他语言一样,带默认值的参数必须放在后面
*** Test Cases ***
Example
Create File ${TEMPDIR}/empty.txt
Create File ${TEMPDIR}/utf-8.txt Hyvä esimerkki
Create File ${TEMPDIR}/iso-8859-1.txt Hyvä esimerkki ISO-8859-1
# Create File 关键字的参数就是 path, content=, encoding=UTF-8. 所以可以只传一个path,content= 表示内容为空
*
来表示*** Test Cases ***
Example
Remove Files ${TEMPDIR}/f1.txt ${TEMPDIR}/f2.txt ${TEMPDIR}/f3.txt
@{paths} = Join Paths ${TEMPDIR} f1.txt f2.txt f3.txt f4.txt
# Remove Files 和 Join Paths, 参数分别是 *paths 和 base, *parts.
# 类似于python中的*args ,使用元组接收
# 和位置参数/缺省参数一起使用时,必须放在最后,这部分参数就没有名字了
@{args}
传递,可能其中包含的命名参数shell=True
将不会被识别*** Test Cases ***
Example
Run Program shell=True # This will not come as a named argument to Run Process
*** Keywords ***
Run Program
[Arguments] @{args}
Run Process program.py @{args} # Named arguments are not recognized from inside @{args}
**kwargs
形式,和Python一样!这里叫任意命名参数(free named argument)*args
是没有名字的,相当于不限数量的位置参数*** Test Cases ***
Using Kwargs
Run Process program.py arg1 arg2 cwd=/home/user
Run Process program.py argument shell=True env=${ENVIRON}
# 当然,如果不看定义关键字的语法,arg1 arg2 可能是位置参数,可能是缺省参数,也可能是可变数量参数;cwd=/home/user
# 可能是缺省参数,也可能是任意命名参数
Test Teardown
模式和特殊的continuable failures
让测试继续执行
*HTML*
*** Test Cases ***
Normal Error
Fail This is a rather boring example...
HTML Error
${number} = Get Number
Should Be Equal ${number} 42 *HTML* Number is not my MAGIC number.
test suite
中是唯一的
${TEST_NAME}
指定,这个变量在测试执行的任何阶段都可以访问到*** Test Cases ***
下第一行顶头的就是用例名,可以使用变量*** Variables ***
${MAX AMOUNT} ${5000000}
*** Test Cases ***
Amount cannot be larger than ${MAX AMOUNT} # 如果这个变量不存在,那就只有左侧的部分
# ...
[Documentation]
用来为用例设置一段文档说明. 这个说明会显示在命令行的输出中, 以及后续的测试日志和测试报告中*** Test Cases ***
Variables
[Documentation] Executed at ${HOST} by ${USER}
No Operation
Splitting
[Documentation] This documentation is split into multiple columns # 两个空格以上,分为多列
No Operation
Many lines
[Documentation] Here we have
... an automatic newline
No Operation
Settings
这个section中可以定义不同类型的Tag
Force Tags
,所有用例都被指定打上这些标签Default Tags
,没有单独设置 [Tags]
的用例将被打上这些默认标签(半强制)[Tags]
,在Test Cases
section中使用,可以设置一个空值(NONE)来覆盖默认标签--settag
,可以通过命令行执行,给所有case加上tagSet Tags, Remove Tags
内置关键字动态操纵tag*** Settings ***
Force Tags req-42
Default Tags owner-john smoke
*** Variables ***
${HOST} 10.0.1.42
*** Test Cases ***
No own tags
[Documentation] This test has tags owner-john, smoke and req-42.
No Operation
With own tags
[Documentation] This test has tags not_ready, owner-mrx and req-42.
[Tags] owner-mrx not_ready # 两个以上空格
No Operation
Own tags with variables
[Documentation] This test has tags host-10.0.1.42 and req-42.
[Tags] host-${HOST}
No Operation
Empty own tags
[Documentation] This test has only tag req-42.
[Tags] # 覆盖默认tag
No Operation
Set Tags and Remove Tags Keywords
[Documentation] This test has tags mytag and owner-john.
Set Tags mytag
Remove Tags smoke req-*
robot-
前缀开头
robot-exit
表示优雅的结束测试--tagstatinclude 'robot:*
显示BuiltIn
中关键字 Run Keywords
来执行多个关键字*** Settings ***
Test Setup Open Application App A
Test Teardown Close Application # 给每个case都加上S&T
*** Test Cases ***
Default values
[Documentation] Setup and teardown from setting table
Do Something
Overridden setup
[Documentation] Own setup, teardown from setting table
[Setup] Open Application App B
Do Something
No teardown
[Documentation] Default setup, no teardown at all
Do Something
[Teardown] # 覆盖Settings section中的设置
[Template]
中指定关键字,后续写参数就可以,也可在Settings中全局设置*** Test Cases **
Normal test case
Example keyword first argument second argument
Templated test case
[Template] Example keyword
first argument second argument
*** Settings ***
Test Template Example keyword
*** Test Cases ***
Templated test case
first round 1 first round 2
second round 1 second round 2
third round 1 third round 2 # 默认失败后继续,第一轮失败了,second round继续
Normal test case with embedded arguments # 内嵌参数的模板
The result of 1 + 1 should be 2
The result of 1 + 2 should be 3
Template with embedded arguments
[Template] The result of ${calculation} should be ${expected}
1 + 1 2
1 + 2 3
Template and for # 带for循环的模板
[Template] Example keyword
:FOR ${item} IN @{ITEMS}
\ ${item} 2nd arg
:FOR ${index} IN RANGE 42
\ 1st arg ${index}
*** Settings ***
Test Template Login with invalid credentials should fail # 高级关键字
*** Test Cases *** USERNAME PASSWORD # 给列命名使得测试用例更易读易懂
Invalid User Name invalid ${VALID PASSWORD}
Invalid Password ${VALID USER} invalid
Invalid User Name and Password invalid invalid
Empty User Name ${EMPTY} ${VALID PASSWORD}
Empty Password ${VALID USER} ${EMPTY}
Empty User Name and Password ${EMPTY} ${EMPTY}
*** Test Cases ***
Invalid Password
[Template] Login with invalid credentials should fail
invalid ${VALID PASSWORD}
${VALID USER} invalid
invalid whatever
${EMPTY} ${VALID PASSWORD}
${VALID USER} ${EMPTY}
${EMPTY} ${EMPTY}
Given-When-Then
格式
And/But
*** Test Cases ***
Valid Login
Given login page is open
When valid username and password are inserted
and credentials are submitted
Then welcome page should be open # 预期是成功登陆
python -> .py -> def
task
的功能,和创建测试文件一样,也能生成套件(task suite)Documentation
Metadata
Suite Setup, Suite Teardown
.
或下划线 _
开头的文件/目录名——忽略--warnonskippedfiles
, 这样就将该消息作为警告处理,警告消息最终出现在 测试执行错误区__init__.ext
,借鉴自pythonDocumentation, Metadata, Suite Setup, Suite Teardown
这些测试套件相关的设置和测试用例文件中的设置一样.
Force Tags
为下面的所有用例指定标签.
Test Setup, Test Teardown, Test Timeout
为下面的测试用例设置默认的 setup/teardown 或 超时动作. 测试用例可以单独设置以覆盖这里的配置.
Default Tags, Test Template
不支持
*** Settings ***
Documentation Example suite
Suite Setup Do Something ${MESSAGE}
Force Tags example
Library SomeLibrary
*** Variables ***
${MESSAGE} Hello, world!
*** Keywords ***
Do Something
[Arguments] ${args}
Some Keyword ${arg}
Another Keyword
my_test_directory
,生成的套件名称就是:My Test Directory
01__some_tests.txt
和 02__more_tests.txt
创建的测试用例集名称分别是 Some Tests
和 More Tests
,并且前者会先执行序号+双下划线
--name
and --doc
*** Settings ***
Metadata Version 2.0
Metadata More Info For more information about *Robot Framework* see http://robotframework.org
Metadata Executed At ${HOST}
name
和value
两部分--metadata
command line 指定test case file -> test suite(this file's cases)
test case file directory -> high level test suite(test case files -> test suites -> cases)
Import
,也可以Library
导入
# 使用的位置也不一样
*** Test Cases ***
Example
Do Something
Import Library MyLibrary arg1 arg2
KW From MyLibrary
*** Settings ***
Library OperatingSystem
Library my.package.TestLibrary
Library MyLibrary arg1 arg2
Library ${LIBRARY}
*** Settings ***
Library PythonLibrary.py
Library /absolute/path/JavaLibrary.java
Library relative/path/PythonDirLib/ possible arguments
Library ${RESOURCES}/Example.class
WITH NAME
*** Settings ***
Library com.company.TestLib WITH NAME TestLib
Library ${LIBRARY} WITH NAME MyName
Library SomeLibrary localhost 1234 WITH NAME LocalLib
Library SomeLibrary server.domain 8080 WITH NAME RemoteLib # 参数放在with name之前
BuiltIn
最特别,可以自动启用,无需导入Collections
DateTime
Dialogs
OperatingSystem
Process
Screenshot
String
Telnet
XML
automation/lib
下${SCALAR}
@{LIST}
&{DICT}
,perl中用%,而且这里都要加花括号%{ENV_VAR}
${PATH}
,小写字母表示局部变量${myVar}
(或者驼峰)
*** Test Cases ***
${GREET} = Hello
${NAME} = 123
Variables
Log ${GREET}
Log ${GREET}, ${NAME} # 先转换成unicode字符串,123->‘123’,这里逗号将两个变量作为一个参数
# 注:如果变量不是单独使用,即这里一个参数中两个及以上变量;its value is first converted into a string and then concatenated with the other data
# 用到python的__str__方法,或者java的toString方法,返回字符串或return值
*** Test Cases ***
Constants
Login robot secret
List Variable
Login @{USER}
*** Test Cases ***
Nested container
${nested} = Evaluate [['a', 'b', 'c'], {'key': ['x', 'y']}]
Log Many @{nested}[0] # Logs 'a', 'b' and 'c'.
Log Many @{nested}[1][key] # Logs 'x' and 'y'.
Slice
${items} = Create List first second third
Log Many @{items}[1:] # Logs 'second' and 'third'. 切片操作什么的和python一致
# 注:不允许字符串作为字符列表使用,但是其它的序列对象如元组或字典是可以的(类似列表的对象)
Keyword @{LIST} @{ANOTHER} @{ONE MORE} # 注意,多个参数要用tab隔开,否则会做字符串处理
*** Settings ***
Library ExampleLibrary @{LIB ARGS} # This works
Library ${LIBRARY} @{LIB ARGS} # This works 可以作为库的参数
Library @{NAME AND ARGS} # This does not work 不能直接传递库名,因为Library一次只能导入一个库,后面的会被当作参数
Suite Setup Some Keyword @{KW ARGS} # This works
Suite Setup ${KEYWORD} @{KW ARGS} # This works
Suite Setup @{KEYWORD} # This does not work 同样,参数可以,关键字名称不能使用列表,suite后只能跟一个关键字
Default Tags @{TAGS} # This works
*** Test Cases ***
Constants
Login name=robot password=secret
Dict Variable
Login &{USER}
Keyword positional @{LIST} &{DICT} # 混用时要注意位置
*** Settings ***
Library ExampleLibrary &{LIB ARGS}
Suite Setup Some Keyword &{KW ARGS} named=arg # 充当参数使用
*** Test Cases ***
Env Variables
Log Current user: %{USER}
Run %{JAVA_HOME}${/}javac
*** Variables ***
${NAME} Robot Framework
${VERSION} 2.0
${ROBOT} ${NAME} ${VERSION}
${NAME} = Robot Framework # = 不是必须的
${VERSION} = 2.0
${true}
就表示true,${None}
就表示python的None*** Variables ***
${EXAMPLE} This value is joined together with a space
${MULTILINE} SEPARATOR=\n First line
... Second line Third line
*** Variables ***
@{NAMES} Matti Teppo
@{NAMES2} @{NAMES} Seppo
@{NOTHING}
@{MANY} one two three four
... five six seven
# 前面的例子也看到使用关键字创建
*** Variables ***
&{USER 1} name=Matti address=xxx phone=123
&{USER 2} name=Teppo address=yyy phone=456
&{MANY} first=1 second=${2} ${3}=third
&{EVEN MORE} &{MANY} first=override empty=
... =empty key\=here=value # 转义
# 字典的获取,比较特殊
&{USER}[name]
${USER.name} # 注意,这里使用 $,和perl语言类似
${MANY.3} # 不可以,${3}是一个变量
使用变量文件可以给变量赋值为任意的对象,还可以动态地创建变量
资源文件通过在 Settings 中设定 Resource
来引入
*** Settings ***
Resource myresources.html
Resource ../data/resources.html
Resource ${RESOURCES}/common.tsv # 推荐使用变量
automation/resource
下(n147-h183)# 相较Library更高级,Library定义的主要是关键字,而Resourse与test case file极狐无异
*** Settings ***
Documentation An example resource file # 这个不会写入日志
Library Selenium2Library
Resource ${RESOURCES}/common.robot
*** Variables ***
${HOST} localhost:7272
${LOGIN URL} http://${HOST}/
${WELCOME URL} http://${HOST}/welcome.html
${BROWSER} Firefox
*** Keywords ***
Open Login Page
[Documentation] Opens browser to login page # 第一行写入日志
Open Browser ${LOGIN URL} ${BROWSER}
Title Should Be Login Page
Input Name
[Arguments] ${name}
Input Text username_field ${name}
Input Password
[Arguments] ${password}
Input Text password_field ${password}
不好意思,走错片场了,应该说变量文件,在 Settings 中设定 Variables
来引入
# 类似的
*** Settings ***
Variables myvariables.py
Variables ../data/variables.py
Variables ${RESOURCES}/common.py
Variables taking_arguments.py arg1 ${ARG2}
--variablefile myvariables.py
指定--variable EXAMPLE:value # 标量
--variable HOST:localhost:7272 --variable USER:robot # 字典
*** Test Cases ***
Returning
${x} = Get X an argument
Log We got ${x}!
${a} ${b} ${c} = Get Three
Example
${list} = Create List first second third # 都可以用标量接收,也可以直接@{list}
Length Should Be ${list} 3
Log Many @{list} # 能当列表用,能当字典用
Set Test Variable
设置的变量在当前测试用例的作用域内处处可用Set Suite Variable
创建的变量在当前执行的测试套件内处处可见,子套件就不可见Set Global Variable
创建的变量在设置之后全局可见,谨慎使用!${SPACE}
和 ${EMPTY}
User Keywords
*** Keywords ***
Open Login Page
Open Browser http://host/login.html
Title Should Be Login Page
Title Should Start With
[Arguments] ${expected}
${title} = Get Title
Should Start With ${title} ${expected}
[Documentation]
用户关键字文档.
[Tags]
Sets tags for the keyword.
[Arguments]
指定用户关键字的参数 specifies
[Return]
Specifies 用户关键字返回值
[Teardown]
Specify 用户关键字的Teardown
[Timeout]
Sets the possible user keyword timeout. Timeouts are discussed in a section of their own.
*DEPRECATED*
可以标记该用户关键字已经不建议使用*** Keywords ***
Settings tags using separate setting
[Tags] my fine tags
No Operation
Settings tags using documentation
[Documentation] I have documentation. And my documentation has tags.
... Tags: my, fine, tags # 牛不牛?
No Operation
# 避免使用robot-
[Argument]
设置,参数的名称和变量一样!什么标量啊花括号啊之类的*** Keywords ***
One Argument
[Arguments] ${arg_name}
Log Got argument ${arg_name}
Three Arguments
[Arguments] ${arg1} ${arg2} ${arg3}
Log 1st argument: ${arg1}
Log 2nd argument: ${arg2}
Log 3rd argument: ${arg3}
# 带默认值的参数
One Argument With Default Value
[Arguments] ${arg}=default value
[Documentation] This keyword takes 0-1 arguments
Log Got argument ${arg}
# 可变参数
Any Number Of Arguments
[Arguments] @{varargs}
Log Many @{varargs}
# 同样的,还有任意命名参数
Kwargs Only
[Arguments] &{kwargs}
Log ${kwargs}
Log Many @{kwargs}
*** Keywords ***
Select ${animal} from list
Open Page Pet Selection
Select Item From List animal_list ${animal}
Select “${city}” “${team}”)
, 然后调用时同样使用引号传参 Select “Los Angeles” “Lakers”)
*** Test Cases ***
Example
I execute "ls"
I execute "ls" with "-lh"
Today is 2011-06-27
*** Keywords ***
I execute "${cmd:[^"]+}" # 表示该参数不能包含任何引号,就能和下面的关键字区分开,避免把 ls" with "-lh 当成参数
Run Process ${cmd} shell=True
I execute "${cmd}" with "${opts}"
Run Process ${cmd} ${opts} shell=True
Today is ${date:\d{4\}-\d{2\}-\d{2\}} # 正则中的花括号必须转义,否则变量会提前结束
Log ${date}
*** Test Cases ***
Add two numbers
Given I have Calculator open # Given, When 和 Then不是关键字名称的一部分
When I add 2 and 40
Then result should be 42
Add negative numbers
Given I have Calculator open
When I add 1 and -2
Then result should be -1
*** Keywords ***
I have ${program} open
Start Program ${program}
I add ${number 1} and ${number 2}
Input Number ${number 1}
Push Button +
Input Number ${number 2}
Push Button =
Result should be ${expected}
${result} = Get Result
Should Be Equal ${result} ${expected}
Return
设置*** Keywords ***
Return One Value
[Arguments] ${arg}
Do Something ${arg}
${value} = Get Some Value
[Return] ${value} # 放在一个标量保存起来!
Return Three Values
[Return] foo bar zap
*** Keywords ***
Return One Value
[Arguments] ${arg}
Do Something ${arg}
${value} = Get Some Value
Return From Keyword ${value}
Fail This is not executed
Find Index # 如何在for循环中使用特殊关键字返回值
[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} # Could also use [Return]
*** Keywords ***
With Teardown
Do Something
[Teardown] Log keyword teardown
Using variables
[Documentation] Teardown given as variable
Do Something
[Teardown] ${TEARDOWN}