上一小节,你已经感受到了 Robot Framework 的基本说法,这一小节你将会看到 Robot Framework 更多强大的用法。

if 语句


通过 “run keyword if” 关键字可以编写 if 分支语句。

*** Test Cases ***

test case8
    ${a}    Set variable    59
    run keyword if ${a}>=90 log 优秀 ... ELSE IF ${a}<=70 log 良好 ... ELSE IF ${a}<=60 log 及格 ... ELSE log 不及格 

首先定义变量 a 等于 59 。

If 判断 a 大于等于 90 ,满足条件 log 输出 “优秀 ”;

不满足上面的条件,接着 else if 判断 a 大于等于 70 ,满足条件 log 输出 “良好”;

不满足上面的条件,接着 else if 判断 a 大于等于 60 ,满足条件 log 输出 “及格”;

上面的条件都不满足,else log 输出“不及格”。

注意 sele if 和 else 前面的三个点点点(

for 循环


在 Robot Framework 中编写循环通过 “:FOR” 。

1、循环 0~9 。

*** Test Cases ***

test case9
    :FOR    ${i}    IN RANGE    10
    \    log ${i} 

通过“:FOR”定义 for 循环;IN RANGE 用于指定循环的范围。

2、遍历列表。

*** Test Cases ***

test case10
    @{abc}    create list    a    b    c
    : FOR    ${i}    IN    @{abc}
    \    log ${i} 

“create list” 关键字用来定义列表(a,b,c),“@{}”用来存放列表。通过过 “:FOR” 循环来来遍历@{abc}列表中的字符。

强大的 Evaluate


为什么说“Evauate”关键字强大呢。因为通过它可以使用 Python 语言中所提供的方法。

1、 生成随即数

在 Python 中我们可以这样来引和并使用方法:

C:\Users\fnngj> python

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import random >>> random.randint(1000, 9999) 9777 

random 模块的 randint()方法用于获取当前时间。

在 Robot Framework 中使用 “Evauate” 也可以调用 Python 所提供的 random 模块下的 randint()方法。


*** Test Cases ***

test case11
    ${d}    Evaluate    random.randint(1000, 9999)    random
    log ${d} 

2、 调用自己编写的 Python 程序

首先创建 D:/rf_test/count.py 文件。


def add(a,b): return a + b if __name__ == "__main__": a = add(4,5) print(a) 

通过add函数实现两个数相加,这是再简单不过的小程序了。

下面就通过 Robot Framework 调用 count.py 文件中的 add()函数。


*** Test Cases ***

test case12
    Import Library    D:/rf_test/count.py
    ${a}    Evaluate    int(4)
    ${b} Evaluate int(5) ${add} add ${a} ${b} log ${add} 

在 Robot Framework 中所有的内容都不是字符串类型,所以,需要通过 “Evaluate” 将 4 和 5 转化为 int 类型后,再调用 add 计算两个数的和。

注释


Robot Framework 中添加注释也非常简单。“Comment” 关键字用于设置脚本中的注释。除此之外,你也可以像 Python 一样使用“#”号进行注释。


*** Test Cases ***

test case13
    Comment    这是注释
    #这也是注释

如果你熟悉 Python 编程语言,那么 Robot Framework 几乎没有实现不了的功能。