== Custom Library==
终于到了重点了,自定义Library。自定义Library可以用实Python模块和python或java的类来实现。简单写一个python模块实现的
新建mylib.py内含一个md5签名算法函数:
import hashlib
def gen_sign(*args):
m = hashlib.md5()
m.update(''.join(args))
return m.hexdigest()
修改demo.robot如下:
多个关键字有隐式联系的时候要用到基于类的关键字。新建yourLib.py:
基于类的自定义Library,引入的时候创建了一个该类的实例,调用关键字可以改变实例的属性和状态。
*** Settings ***
Documentation Example test cases using the keyword-driven testing approach.
Resource pub.txt
Library Collections
Library mylib.py
*** Test Cases ***
First Case
[Documentation] variable type
Log to console ${var1}
Log to console ${list1}[0]
Log to console ${list1[0]}
Log to console ${dict1}['key1']
Log to console ${dict1['key1']}
Log to console ${dict1.key1}
Second Case
[Documentation] Default values with user-keywords
Calculate and Check Equals
Calculate and Check Equals 1+5
Calculate and Check Equals 7-2 ${5}
Calculate and Check Equals expression=6+3 expected=${9}
Third Case
[Documentation] Varargs with user-keywords
Varargs keyword a f ${var1}
Varargs keyword @{list1} ${var1}
Kwargs keyword key1=value1 key2=789
Kwargs keyword &{dict1}
Kwargs keyword &{dict1} mykey=tututu &{dict1}
Fourth Case
[Documentation] data-driven case
[Template] Calculate "${expression}" and Check Equals "${expected}"
2+4 ${6}
9-2 ${7}
6*4 ${24}
Fifth Case
[Documentation] builtIn library
[Template] Calculate "${expression}" and Check Equals "${expected}"
2+4 ${6}
9-2 ${7}
6*4 ${24}
Sixth Case
[Documentation] custome keyword
${sign} gen_sign @{list1}
Log to console ${sign}
传入计算1234的md5并返回打印到console,结果如下:
多个关键字有隐式联系的时候要用到基于类的关键字。新建yourLib.py:
class yourLib(object):
def __init__(self, member=None):
self.members = [member] if member else []
def add_member(self, name):
self.members.append(name)
return self.members
修改demo.robot如下:
*** Settings *** Documentation Example test cases using the keyword-driven testing approach. Resource pub.txt Library Collections Library mylib.py Library yourLib.py ...... ...... Sixth Case [Documentation] custome keyword ${sign} gen_sign @{list1} Log to console ${sign} ${members} add member ${var1} Log to console ${members} ${members} add member LLisisi Log to console ${members}执行结果如下:
基于类的自定义Library,引入的时候创建了一个该类的实例,调用关键字可以改变实例的属性和状态。