介绍
- 用Python来做接口自动化测试的好处,我觉得就一点,访问http接口简单,一行代码就行;
- 代码不用写很多,可以把若干接口配置成JSON就行;
- Python解析之后,将访问结果等数据保存到excel中;
大致就上面3点,每家企业的接口调用规则都会有区别,所以下面代码只能提供一种解题思路,不能拿来就用。
实现
json配置(config.json)
{
"service":"http://127.0.0.1:8080",
"versionCode":"1",
"apiList":[
{
"api":"/app/login",
"name":"登录接口",
"type":"POST",
"desc":"登录之后产生的Token是之后接口的基础",
"params":{
"password": "123", "loginName": "test"
}
},
{
"api":"/app/reportInfo",
"name":"上报信息",
"type":"POST",
"params":{
"dyId": "",
"dyName": ""
}
}
]
}
里面的接口api和params信息等需要替换成自己需要测试的内容,而且可以根据自己的api差异进行修改和调整,符合自己的规则才是程序需要做的事。
python实现
import requests
import json
import xlwt
import time
token = ""
headers = {"Content-Type": "application/json", "charset": "UTF-8"}
mTime = time.strftime('%Y年%m月%d日')
mWorkBook = xlwt.Workbook()
mWorkSheet = mWorkBook.add_sheet(mTime)
column = 0
row = 0
# xls error style excel错误样式
def errorStyle():
font = xlwt.Font()
# 字体类型
font.name = 'name Times New Roman'
# 字体颜色
font.colour_index = 1
# 设置背景颜色
pattern = xlwt.Pattern()
# 设置背景颜色的模式
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
# 背景颜色
pattern.pattern_fore_colour = 2
myStyle = xlwt.XFStyle()
myStyle.font = font
myStyle.pattern = pattern # 设置背景颜色
return myStyle
# 读取config.json
def read_config():
""""读取配置"""
with open("./config/config.json",
encoding='utf-8') as json_file:
config = json.load(json_file)
return config
# 遍历接口
def iterateApi():
config = read_config()
serviceAdr = config['service']
for api in config['apiList']:
url = serviceAdr + api['api']
params = api['params']
type = api['type']
if type == "POST":
post_json = requests.post(url=url, json=params, headers=headers)
elif type == "GET":
post_json = requests.get(url=url, json=params, headers=headers)
print("reponse = ", post_json.text)
text = json.loads(post_json.text)
getResult(api["name"], url, params, text)
# 处理返回结果
def getResult(name,
url,
params,
result={
'code': '-1',
'msg': '默认值',
'entity': ""
}):
global column
if (column == 0):
mWorkSheet.write(column, 0, "接口名")
mWorkSheet.write(column, 1, "地址")
mWorkSheet.write(column, 2, "参数")
mWorkSheet.write(column, 3, "结果")
mWorkSheet.write(column, 4, "服务器返回内容")
column += 1
if (result["code"] == "10000"):
writeSheet(name, column, url, params, result)
print("success, tip: ", result["msg"])
entity = result["entity"]
if (type(entity) is dict) and (result["entity"] !=
None) and ("token" in result["entity"]):
global token
token = result["entity"]["token"]
global headers
headers["Cookie"] = "access_token=" + token
print("token = ", token)
else:
print("fail, tip: ", result["msg"])
writeSheet(name, column, url, params, result, True)
# 保存到excel
def writeSheet(name, column, url, params, result, error=False):
if error is True:
myStyle = errorStyle()
else:
myStyle = xlwt.XFStyle()
# print("style = ", type(myStyle))
mWorkSheet.write(column, 0, name, myStyle)
mWorkSheet.write(column, 1, url, myStyle)
mWorkSheet.write(column, 2, json.dumps(params,
indent=2,
ensure_ascii=False), myStyle)
mWorkSheet.write(column, 3, result['msg'], myStyle)
mWorkSheet.write(column, 4, json.dumps(result,
indent=2,
ensure_ascii=False), myStyle)
if __name__ == '__main__':
iterateApi()
mWorkBook.save(mTime + ".xls")
返回参数可以根据自己的接口内容修改,大致讲解下,因为登录之后的token在其他接口都需要使用,所以,需要保存为全局变量中,供其他接口使用。
这套代码只是作为一个参考,具体怎么实现,是需要根据自己需要的接口实现方式进行修改的。