使用場景:
在工作中,常見某個功能的查詢,當查詢關聯表特別多時,開發寫的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+"\n")
(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()
實現結果: