1 接口测试介绍
接口测试是对系统或组件之间的接口进行测试,主要是校验数据的交换,传递和控制管理过程,以及相互逻辑依赖关系。
接口自动化相对于UI自动化来说,属于更底层的测试,这样带来的好处就是测试收益更大,且维护成本相对来说较低,是我们进行自动化测试的首选;
2 框架选型
目前接口自动化的框架比较多,比如jmeter,就可以集接口自动化和性能测试于一体,该工具编写用例效率不高;还有我们常用的postman,结合newman也可以实现接口自动化;Python+unittest+requests+HTMLTestRunner是目前比较主流的测试框架,对python有一定的编码要求;
本期我们选择robotframework(文中后续统一简称为RF)这一个比较老牌的测试框架进行介绍,RF是一个完全基于关键字测试驱动的框架,它即能够基于它的一定规则,导入你需要的测试库(例如:其集成了selenium的测试库,即可以理解为操作控件的测试底层库),然后基于这些测试库,你能应用TXT形式编写自己的关键字(支持python和java语言,这些关键字即你的库组成),之后,再编写(测试用例由测试关键字组成)进行测试;他支持移动端、UI自动化和接口自动化的测试;
3 环境搭建
python的安装:目前选取的python3以上的版本,RF的运行依赖python
robotframework:参考//www.greatytc.com/p/9dcb4242b8f2
jenkins:用于调度RF的用例执行环境
gitlab:代码仓库
4 需求
4.1 需求内容
接口内容:实现一个下单,并检查订单状态是否正常的场景;该需求涉及到如下三个接口
下单接口
订单结果查询接口
下单必须带上认证标识,生成token的接口
环境覆盖:需要支持能在多套环境运行,比如测试和预发布环境
系统集成:需要能够集成在CICD中,实现版本更新后的自动检测
4.2 用例设计
4.2.1 用例设计,根据业务场景设计测试用例,方便后续实现
4.2.2 测试数据构造,预置不同环境的测试数据,供实现调用
5 整体实现架构
接口测试实现层:在RF,通过引用默认关键字RequestsLibrary(实现http请求)和通过python自定义关键字来完成用例实现的需求;
jenkins调度:在jenkins上配置一个job,设置好RF用例执行的服务器和发送给服务器相关的RF执行的指令,并且在jenkins中配置好测试报告模板,这样用例便可以通过jenkins完成执行并发送测试结果给项目干系人;
生成用例执行的API:上图中蓝色部分,就是为了将jenkins的job生成一个可访问api接口,方便被测项目的CICD集成;
集成到被测系统CICD流程:将上面步骤中封装的API配置在被测应用的gitlab-ci.yml中,完成整个接口自动化的闭环
6 RF用例实现
6.1 引用的内置关键字
RequestsLibrary 构造http的请求,get|post等请求
getRequests
# get请求的入参
[Arguments]${url_domain}${getbody}${geturl}${getToken}
Create session postmain${url_domain}
# 定义header的内容
${head}createdictionary content-type=application/json Authorization=${getToken}MerchantId=${s_merchant_id}
# get请求
${addr}getRequest postmain${geturl}params=${getbody}headers=${head}
# 请求状态码断言
Should BeEqualAs Strings${addr.status_code}200
${response_get_data}To Json${addr.content}
# 返回http_get请求结果
SetTest Variable${response_get_data}
Delete All Sessions
6.2 自定义关键字
getEnvDomain 用于从自定义的configs.ini文件获取对应环境的微服务的请求域名
configs.ini的内容
获取configs.ini的内容
import configparser
def getEnv(path,env):
config = configparser.ConfigParser()
config.read(path)
passport = config[env]['passport']
stock=config[env]['stock']
finance=config[env]['finance']
SUP= config[env]['SUP']
publicApi = config[env]['publicApi']
publicOrder = config[env]['publicOrder']
data_dict={'passport':passport,'stock':stock,'finance':finance,'SUP':SUP,'publicApi':publicApi,'publicOrder':publicOrder}
return data_dict
excelTodict 用户将excel中的内容作为字典返回
import xlrd
'''
通用获取excel数据
@:param path excel文件路径
@:param sheet_name excel文件里面sheet的名称 如:Sheet1
@:env 环境,是IT还是PRE
'''
def getExcelDate(path, sheet_name,env):
bk = xlrd.open_workbook(path)
sh = bk.sheet_by_name(sheet_name)
row_num = sh.nrows
data_list = []
for i in range(1, row_num):
row_data = sh.row_values(i)
data = {}
for index, key in enumerate(sh.row_values(0)):
data[key] = row_data[index]
data_list.append(data)
data_list1 = []
for x in data_list:
#print('这是'+str(x))
if(x.get('env')==env):
data_list1.append(x)
return data_list1
getToken 提供接口下单的授权token
*** Keywords ***
# 根据传入的clientid、secret生成对应的token
getToken
[Arguments] ${client_id} ${client_secret} ${url_domain}
Create session postmain ${url_domain}
${auth} createdictionary grant_type=client_credentials client_id=${client_id} client_secret=${client_secret}
${header} createdictionary content-type=application/x-www-form-urlencoded
${addr} postRequest postmain /oauth/token data=${auth} headers=${header}
Should Be Equal As Strings ${addr.status_code} 200
${responsedata} To Json ${addr.content}
${access} Get From Dictionary ${responsedata} access_token
${token} set variable bearer ${access}
Set Test Variable ${token}
Delete All Sessions
getAllDate 获取该用例下的所有数据
getAllData
[Arguments] ${row_no}
getEnvDomain
getBalance ${row_no}
getStockNum ${row_no}
getSupProPrice ${row_no}
getProPrice ${row_no}
Set Test Variable ${publicOrderUrl}
Set Test Variable ${FPbalance}
Set Test Variable ${Pbalance}
Set Test Variable ${Sbalance}
Set Test Variable ${Jbalance}
Set Test Variable ${Cardnum}
Set Test Variable ${sprice}
Set Test Variable ${price}
Set Test Variable ${j_merchant_id}
Set Test Variable ${s_merchant_id}
Set Test Variable ${stock_id}
Set Test Variable ${p_product_id}
Set Test Variable ${s_product_id}
实现demo
*** Settings ***
Test Template
Resource 引用所有资源.txt
*** Test Cases ***
*** Settings ***
Test Template
Resource 引用所有资源.txt
*** Test Cases ***
01 下单卡密直储商品
[Tags] order
LOG ---------------------获取下单前的数量、余额------------------------------------------
getAllData 0
${Cardnum1} set variable ${Cardnum}
${FPbalance1} set variable ${FPbalance}
${Pbalance1} set variable ${Pbalance}
${Sbalance1} set variable ${Sbalance}
${Jbalance1} set variable ${Jbalance}
${CustomerOrderNo1} Evaluate random.randint(1000000, 9999999) random
${Time} Get Time
log ------------------------下单操作-------------------------------------------------------
getToken 100xxxx 295dab07a9xxxx9780be0eb95xxxx ${casUrl}
${input_cs} create dictionary memberId=${j_merchant_id} clientId=1xxx079 userId=string shopType=string customerOrderNo=${CustomerOrderNo1}
... productId=${p_product_id} buyNum=1 chargeAccount=otest888888 notifyUrl=string chargeIp=string chargePassword=string
... chargeGameName=string chargeGameRole=string chargeGameRegion=string chargeGameSrv=string chargeType=string remainingNumber=0
... contactTel=string contactQQ=string customerPrice=0 poundage=0 batchNumber= originalOrderId=string
... shopName=string appointSupProductId=0 stemFromSubOrderId=123456 externalBizId=456789
postRequests ${publicOrderUrl} ${input_cs} /api/Order ${token}
${data} get from dictionary ${responsedata} data
${orderid} get from dictionary ${data} id
sleep 6
${getdata} create dictionary Id=${orderid} PageIndex=1 PageSize=1
getRequests ${publicOrderUrl} ${getdata} /api/Order/GetList ${token}
${datalist} get from dictionary ${response_get_data} data
${data} get from dictionary ${datalist} list
${dict} set variable ${data}[0]
${orderOuterStatus} get from dictionary ${dict} orderOuterStatus
LOG ---------------------获取下单后的数量、余额----------------------------------------------
getAllData 0
${Cardnum2} set variable ${Cardnum}
${FPbalance2} set variable ${FPbalance}
${Pbalance2} set variable ${Pbalance}
${Sbalance2} set variable ${Sbalance}
${Jbalance2} set variable ${Jbalance}
${sprice} set variable ${sprice}
${price} set variable ${price}
log ------------------断言-----------------------------------------------------------------
${Cardnum3} Evaluate ${Cardnum1}
${Jbalance3} Evaluate ${Jbalance1}
${Sbalance3} Evaluate ${Sbalance1}
${Pbalance3} Evaluate ${Pbalance1}
should be true ${orderOuterStatus}==90
should be true ${Cardnum3}==${Cardnum2}
should be true ${Jbalance3}==${Jbalance2}
should be true ${Sbalance3}==${Sbalance2}
should be true ${Pbalance3}==${Pbalance2}