最近一直在用robot framework 做自动化测试项目,老实说对于习惯直接使用python的情况下,被框在这个工具里各种不爽,当然,使用工具的好处也很多,降低了使用成本与难度;当然,在享受工具带来便利的同时也会受制于工具。对于特定的需求,工具没提供相关的Library和关键字的时候,就只能放弃了。

  还好robot framework提供了 Evaluate 关键字,对于Evaluate 关键字的使用等有时间再讲。当robot framework 不能解决需求,我是直接写个.py 程序,通过Evaluate 关键字调用。然后,就受到了批评,不能这么玩,动不动就这么干的话其实robot framework 就成了鸡肋,所以,规范的做法是去封装系统关键字。

  这也是本文的目的,学会了这一招之后,robot framework 就算是玩转了,当然,前提是你要懂点Python才行。

 

  其实我的需求也非常简单,接收一个目录路径,自动遍历目录下以及子目录下的所有批处理(.bat)文件并执行。

  首先在..\Python27\Lib\site-packages目录下创建CustomLibrary目录,用于放自定义的library库。在其下面创建runbat.py 文件:

robotFrameworks_API _selenium(自定义关键字)_lua

#-*- 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)


 

注意在run_all_bat()方法下面加上清晰的注释,最好给个实例。这样在robot framework 的帮助中能看到这些信息,便于使用者理解这个关键字的使用。

  对于创建普通的模块来说这样已经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):
"""
这里也可以装x的写上我们创建的CustomLibrary如何如何。

"""

ROBOT_LIBRARY_SCOPE = 'GLOBAL'


 

  这个文件中其实有用的信息就三行,但必不可少。robot framwork 在启动时会加载这个文件,因为在这个文件里指明了有个runbat文件下面有个Runbat类。从而加载类里的方法(run_all_bat())。

 

下面,启动robot framework RIDE,按F5:

robotFrameworks_API _selenium(自定义关键字)_lua_02

 

找到了我们创建的关键字,下面就是在具体的项目或测试套件中引用CustomLibrary

robotFrameworks_API _selenium(自定义关键字)_加载_03

然后,在具体的测试用例中使用“run all bat” 关键字。

robotFrameworks_API _selenium(自定义关键字)_加载_04

其实核心还是会点Python ,利用工具,但又不受制于工具。