使用场景:
在工作中,常见某个功能的查询,当查询关联表特别多时,开发写的SQL语句等等问题导致响应时间较慢,那么作为测试需要将每个接口的响应时间进行测试,对同个接口多次执行,并将测试结果写入到excel,方便后期的接口时间分析。
实现路径分析:
(1)在测试接口时,直接返回url和times
(2)将每个接口获取到的url和times写入到txt文件中
(3)将txt内容复制到Excel中(目的:方便筛选和计算总和、平均响应时间等)
框架截图:
代码示例:
(1)write_reponseTime_txt.py 中的方法封装
#!/usr/bin/env python
# coding=UTF-8
'''用途:将每个接口测试的获取到的url、times写入到txt文件中'''
def write_txt(urls,times):
path = "/Users/lucky/Desktop/Auto/iBer_Python_Interface/iBer_Interface/Result/"
with open(path+"API_relult.txt","a") as file:
file.write(urls+" "+times+"
")
(2)write_reponseTime_xls.py 中的方法封装
#!/usr/bin/env python
# coding=UTF-8
import xlwt
'''用途:将txt文件中获取的url、times写入到xls中'''
def write_xls():
path = "/Users/lucky/Desktop/Auto/iBer_Python_Interface/iBer_Interface/Result/"
workbook = xlwt.Workbook(encoding="utf-8")
sheet = workbook.add_sheet("Sheet1")
row = 0
with open(path+"API_relult.txt") as filetxt:
for line in filetxt:
line = line.strip()
fileds = line.split(" ")
for col, value in enumerate(fileds):
sheet.write(row, col, value)
row += 1
workbook.save(path+"API_relult.xls")
(3)Todo_report.py,接口文件中将获取的url和time写入到txt中
#!/usr/bin/env python
# coding=UTF-8
import requests
from Common import gol
from Common.logs import logging
import yaml,sys,os
from requests import exceptions
# 导入yaml中的host
reload(sys)
sys.setdefaultencoding("utf-8")
with open(os.getcwd()[:-5] + "/Config/host_header.yaml", 'rb') as f:
data = yaml.load(f)
host = data["host"] #获取到url
header = data["headers"] #获取到host
class share_report:
def __init__(self):
self.log = logging
def get_share_code(self):
url = host+"todo-report/get-share-code"
url_Write_excel = url[url.rfind('/v2'):] # 获取非域名外的url链接,最后写入到Excel中
data = {}
headers = header #获取请求头
headers.update(uuid=gol.get_value("uuid"), token=gol.get_value("token")) #yaml中的请求头中未加入uuid和token,因此这里需要加入上去
#timeout=(0.01,0.1)
r = requests.post(url=url, data=data, headers=headers, verify=False, timeout=15) # 设置的超时时间为0.5s
'''判断:根据reponse中的某个值来判断接口返回是否成功'''
if str(r.json()["msg"]) == "SUCCESS":
self.log.info("获取分享码成功:%s"%(str(r.json()["data"]["share_code"])))
else:
self.log.error("获取分享码失败")
raise False
self.log.info("请求此接口的响应时间:"+str(r.elapsed.total_seconds()))
self.log.info(r.json()) #打印的reponse返回的所有内容
########################获取URL和times(超时时间)数据的写入txt文件#########################
from Common.API_reponseTime.write_reponseTime_txt import write_txt
urls = url_Write_excel # 获取的url
times = str(r.elapsed.total_seconds()) # 获取到响应时间temeout
write_txt(urls, times)
(4)Run_Test.py,运行文件中加入调用的方法
###########################测试结束,将txt文件中内容写入到Excel中######################################
from Common.API_reponseTime.write_reponseTime_xls import write_xls
write_xls()
实现结果: