介绍
- 用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信息等需要替换成自己需要测试的内容。 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
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
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)
def writeSheet(name, column, url, params, result, error=False):
if error is True:
myStyle = errorStyle()
else:
myStyle = xlwt.XFStyle()
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")
返回参数可以根据自己的接口内容修改。 这套代码只是作为一个参考,具体怎么实现,是需要根据自己需要的接口实现方式进行修改的。
|