Robot Framework关键字
Robot Framework关键字分为用户关键字和系统关键字,用户关键字指的是在项目中或者在测试套件中创建的关键字,只在该项目中有效;系统关键字是导入的库封装的类或方法,如Selenium2Library库,也通过自己开发。
一、用户关键字
在一个项目中,用户关键字可以有多个,为了将这些关键字更好地封装和复用,可将关键字分类整合在一起,以资源的形式导入到项目中。
1、创建资源
选中项目,右击--》New Resource ,输入资源名称
2、创建关键字
选中资源,右击--》New User Keyword,输入关键字名称,关键字参数可以在创建的时候写,也可以在编辑中添加;
3、编辑关键字
点击百度搜索关键字, 进入脚本编辑页面, 编写脚本;
其中${search_content}和${result}是该关键字参数,编辑时这两个参数为红色,是因为还没有定义,定义后,参数就会变成绿色。
4、在测试套件中导入资源
选中测试套件,进入编辑页面,点击右边的Resource,找到创建的资源,导入
4、关键字的使用
在使用关键字时,填写的参数必须按照关键字定义时定义参数的顺序要一致。
5、执行脚本
选中脚本,点击运行按钮;从运行结果上看,运行成功。
二、系统关键字
通过导入外部包,关键字可以直接使用,如不清楚关键字的用法,按F5有比较清楚的解释。
系统关键字除了通过导入其他封装好的库得到,还可以自己开发自定义系统关键字。(引用虫师的例子)
关键字实现的功能是接收一个目录路径,自动遍历目录下以及子目录下的所有批处理(.bat)文件并执行。
.首先在 ..\Python27\Lib\site-packages目录下创建CustomLibrary目录,用于放自定义的library库。在其下面创建runbat.py 文件:
#-*- coding:utf-8 -*-
'''
created by bugmaster 2015-01-29
'''
__version__ = '0.1'
from robot.api import logger
import os
class Runbat(object):
def run_all_bat(self,path):
u'''接收一个目录的路径,并执行目录下的所有bat文件.例
| run all bat | filepath |
'''
for root,dirs,files in os.walk(path):
for f in files:
if os.path.splitext(f)[1] == '.bat':
os.chdir(root)
#print root,f
os.system(f)
def __execute_sql(self, path):
logger.debug("Executing : %s" % path)
print path
def decode(self,customerstr):
return customerstr.decode('utf-8')
if __name__ == "__main__":
path = u'D:\\test_boject'
run = Runbat()
run.run_all_bat(path)
对于创建普通的模块来说这样已经ok了。但要想在robot framework启动后加载这个关键字,还需要在CustomLibrary目录下创建__init__.py文件,并且它不是空的。
# Copyright (c) 2010 Franz Allan Valencia See
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from runbat import Runbat
__version__ = '0.1'
class CustomLibrary(Runbat):
"""
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
robot framwork 在启动时会加载这个文件,因为在这个文件里指明了有个runbat文件下面有个Runbat类。从而加载类里的方法(run_all_bat())。
在测试套件中导入CustomLibrary库,库名显示黑色,说明导入成功;
按F5可以看到CustomLibrary库包含的关键字。
编写脚本,执行