python实现接口压力测试
直接上代码:
# -*- coding: utf-8 -*-
import json
import requests
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
restime = []
OK=[]
class Interface_pressure_test():
def API(self,URL2,param):
try:
r = requests.get(URL2, params=param, timeout=10)
r.raise_for_status() # 如果响应状态码不是 200,就主动抛出异常
except requests.RequestException as e:
print(e)
else:
js = json.dumps(r.json())
return [r.json(), r.elapsed.total_seconds(),js]
def circulation(self,num,URL2,param):
for i in range(int(num)):
restime.append(Interface_pressure_test.API(URL2,param)[1])
if json.loads(Interface_pressure_test.API(URL2, param)[2])["message"]=='ok':
OK.append(json.loads(Interface_pressure_test.API(URL2, param)[2])["message"])
logger.info('请求第' + str(i+1) + '次,请求'+json.loads(Interface_pressure_test.API(URL2, param)[2])["message"]+',状态码:'+json.loads(Interface_pressure_test.API(URL2, param)[2])["status"])
else:
logger.info('请求第' + str(i+1) + '次,请求' + json.loads(Interface_pressure_test.API(URL2, param)[2])["message"] + ',状态码:' +
json.loads(Interface_pressure_test.API(URL2, param)[2])["status"])
print('测试次数:',num)
print('响应次数:', len(restime))
print('正常响应次数:', len(OK))
print('总响应最大时长:', max(restime))
print('总响应最小时长:', min(restime))
print('总响应时长:', sum(restime))
print('平均响应时长:', sum(restime) / len(restime))
if __name__ == '__main__':
Interface_pressure_test = Interface_pressure_test()
num = input('请输入次数:') #压力测试次数
URL2 = 'http://www.kuaidi100.com/query' #地址
param = {'type' : 'zhongtong' , 'postid' :'73116039505988' } #参数
Interface_pressure_test.circulation(num,URL2,param)
input('Press Enter to exit...')
输出20次压测结果如下:文章来源:https://www.toymoban.com/news/detail-582949.html
文章来源地址https://www.toymoban.com/news/detail-582949.html
到了这里,关于python实现接口压力测试的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!