接口测试是对系统或组件之间的接口进行测试,主要是校验数据的交换,传递和控制管理过程,以及相互逻辑依赖关系。
接口自动化相对于UI自动化来说,属于更底层的测试,这样带来的好处就是测试收益更大,且维护成本相对来说较低,是我们进行自动化测试的首选
目前接口自动化的框架比较多,比如jmeter,就可以集接口自动化和性能测试于一体,该工具编写用例效率不高;还有我们常用的postman,结合newman也可以实现接口自动化;Python+unittest+requests+HTMLTestRunner?是目前比较主流的测试框架,对python有一定的编码要求;
本期我们选择robotframework(文中后续统一简称为RF)这一个比较老牌的测试框架进行介绍,RF是一个完全基于?关键字?测试驱动的框架,它即能够基于它的一定规则,导入你需要的测试库(例如:其集成了selenium的测试库,即可以理解为操作控件的测试底层库),然后基于这些测试库,你能应用TXT形式编写自己的关键字(支持python和java语言,这些关键字即你的库组成),之后,再编写(测试用例由测试关键字组成)进行测试;他支持移动端、UI自动化和接口自动化的测试
4.1 需求内容
接口内容:实现一个下单,并检查订单状态是否正常的场景;该需求涉及到如下三个接口
环境覆盖:需要支持能在多套环境运行,比如测试和预发布环境
系统集成:需要能够集成在CICD中,实现版本更新后的自动检测
4.2 用例设计
4.2.1 用例设计,根据业务场景设计测试用例,方便后续实现
?
4.2.2 测试数据构造,预置不同环境的测试数据,供实现调用
接口测试实现层:在RF,通过引用默认关键字?RequestsLibrary?(实现http请求)和通过python自定义关键字来完成用例实现的需求;
jenkins调度:在jenkins上配置一个job,设置好RF用例执行的服务器和发送给服务器相关的RF执行的指令,并且在jenkins中配置好测试报告模板,这样用例便可以通过jenkins完成执行并发送测试结果给项目干系人;
生成用例执行的API:上图中蓝色部分,就是为了将jenkins的job生成一个可访问api接口,方便被测项目的CICD集成;
集成到被测系统CICD流程:将上面步骤中封装的API配置在被测应用的__gitlab-ci.yml__中,完成整个接口自动化的闭环
6.1 引用的内置关键字
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 Be Equal As Strings ${addr.status_code} 200
${response_get_data} To Json ${addr.content}
# 返回http_get请求结果
Set Test Variable ${response_get_data}
Delete All Sessions
6.2 自定义关键字
# 获取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
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
*** 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
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}
*** 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}
7.1 jenkins配置job
通过jenkins的参数化构建,定义it和pre两套环境
jenkins发送RF执行的命令
7.2 封装的jenkins_job的执行接口地址
通过python的flask框架,根据测试和pre两套环境包一层jenkins的job执行接口
__author__ = 'paul'
# !/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask, abort, request, jsonify
import jenkins
server = jenkins.Jenkins('http://10.0.1.xxx:80', username='xxx', password='fuluxxxx')
app = Flask(__name__)
tasks = []
# it的测试集合http请求接口
@app.route('/test/it', methods=['get'])
def robot_Test_It():
server.build_job('CI_FuluOrder', {'environment': 'IT'})
return jsonify({'result': 'success'})
# pre的测试集合http请求接口
@app.route('/test/pre', methods=['get'])
def robot_Test_Pre():
server.build_job('CI_FuluOrder', {'environment': 'PRE'})
return jsonify({'result': 'success'})
if __name__ == "__main__":
# 将host设置为0.0.0.0,则外网用户也可以访问到这个服务
app.run(host="0.0.0.0", port=80, debug=True)
7.3 将上述flask封装的接口打包成镜像
根据dockerfile生成镜像
FROM python:3.6
WORKDIR /app
EXPOSE 80
COPY . .
RUN pip install -r requirements.txt?
ENTRYPOINT ["python","robotTestApi.py"]
7.4 将镜像部署到kubernetes,对外提供服务
供触发测试执行的调用入口 ,这部分封装的接口部署在本地的k8s集群下ordermiddle
IT:?http://ordermiddle.xxx.cn/test/it
pre:http://ordermiddle.xxx.cn/test/pre
7.5 被测项目的CICD集成接口自动化测试
gitlab目前采取直接对CICD脚本加入测试步骤,在部署到容器30秒后(考虑到容器在K8S启动时间)调用测试接口
7.6 发送测试报告
Python接口自动化测试零基础入门到精通(2024最新版)