一、接口測試python腳本
寫了很久了,一直沒發博客,今兒多發幾篇,先上代碼。
#__author__ = 'chubby_superman'
#_*_coding=utf-8 _*
import requests
from datetime import datetime
class Httpreq():
def __init__(self,url,data,heards):
self.url=url
self.data=data
self.heards=heards
def req_1(self):
requests_statuscode=requests.post(url=self.url,json=self.data).status_code
try:
if requests_statuscode == 200:
print(1)
#return "請求成功,開始判斷響應狀態"
else:
#return requests_statuscode
print("請求失敗if內")
except Exception as e:
print("請求失敗try內")
x = requests.post(url=self.url,json=self.data)
try :
a = x.text
with open(datetime.now().strftime('%Y%m%d%H%M%S') + '.txt','w',encoding="utf-8") as f:
f.write(a)
except Exception as e:
print("寫入文件有問題")
a = x.json()["code"]
if a == 1000:
print("正常返回")
elif a == -1:
print("系統繁忙")
elif a == 1001:
print("partnerId無效")
elif a == 1002:
print("IP白名單錯誤,禁止服務")
elif a == 1003 :
print("簽名錯誤")
elif a == 1004 :
print("缺少必要的參數")
else:
print("返回未知的錯誤")
if __name__ == '__main__':
the_url='http://test.pipifit.com/analysisShopCartOverCate'
#接口url
the_data= {'day': 1, 'period': 1, 'goodsInfo': [{"goodsId": 1213,"goodsNumber":1}], 'sex': 0, 'symptoms': 1001}
#請求body
Httpreq(the_url,the_data,'').req_1()
下面 爲接口併發測試腳本,使用的是多線程,而非協程(也就是說,比較雞肋)。
二、接口併發
腳本1,名爲kepler.py。該腳本功能爲:向京東開普勒發送post請求
#__author__ = 'chubby_superman'
#_*_coding=utf-8 _*
import requests
class Http_request():
def __init__(self,url,**kwargs):
self.url = url
self.kwargs=kwargs
def update_port_datas(self):
datas = {
"method":"biz.product.sku.query",
"app_key":r'appkey',#需要從京東獲得
'access_token':r'token',#需要從京東獲得
'timestamp':'2019-02-1416:13:10',
'v':'1.0',
'format':'json',
'param_json':'{"name":"測試商品池","pageNum":"1"}'
}
try:
for k in self.kwargs:
datas[k]=self.kwargs[k]
except Exception as e:
print(e)
return datas
def post_request(self):
datas =self.update_port_datas()
try:
post_response =requests.post(url=self.url,data=datas)
return post_response.text
except Exception as e:
print (e)
if __name__=="__main__":
url = "https://router.jd.com/api"
a = Http_request(url,method="biz.product.PageNum.query",param_json='{}').post_request()
print(a)
腳本2,名爲test.py。該腳本主要功能:建立線程。
#__author__ = 'chubby_superman'
#_*_coding=utf-8 _*
import threading
import time
#定義一個方法
def tr(a,b):
print([x for x in range(a+b)])
pass
class Mythread(threading.Thread):
#使用繼承實現多線程
def __init__(self,func):
threading.Thread.__init__(self)
self.func=func #功能名
#self.args=args #功能所需參數
#初始化父類 threading.Thread
def run(self):
lock = threading.Lock()
if lock.acquire():
self.func #調用run方法,實現功能的多線程
print(self.name,time.ctime())
lock.release()
#給需要實現多線程的功能 加鎖。注意:run方法爲重寫父類threading.Thread的run方法,函數名不得改變,且此方法必須有。
if __name__=="__main__":
thread_list=[]
for i in range(5): #需要開啓多少線程,range中的數字填多少,此處需要5個
t = thread_list.append(Mythread(tr(3,4)))
for t in thread_list:
t.start()
for t in thread_list:
t.join()
腳本3,名爲port.py。該腳本功能爲:設定線程數,開始併發post請求。
#__author__ = 'chubby_superman'
#_*_coding=utf-8 _*
from kepler import Http_request
from test import Mythread
import gevent
import requests
def tr():
url = "https://router.jd.com/api"
a = Http_request(url,method="biz.product.PageNum.query",param_json='{}').post_request()
print(a)
def calc():
url = 'http://te.pipifit.com/goods/list'
res = requests.get(url,params={'foodId':1},headers={"token":"a93c0fea8150ef04b96ac90ccb8a"})
print(res.text)
def bing_fa(x):
c =0
while 1:
calc()
c+=1
if c>=x:
break
def thread_func(x,tr):
thread_list=[]
for i in range(x): #需要開啓多少線程,range中的數字填多少,此處需要5個
t = thread_list.append(Mythread(tr))
for t in thread_list:
t.start()
for t in thread_list:
t.join()
#
gevent.spawn(thread_func(2,bing_fa(500000)))
執行結果示例
三、總結
總體來說,接口測試並不是很複雜(不考慮pytest或者unittest框架),接口併發也很好構造。但是多線程並不能將單臺機器的性能發揮到極致(滿載),這是由python解釋器是單線程而引起的,所以,以上接口併發腳本並不能滿足工作要求。
當然,python的庫多且牛,推薦給大家一個專門做性能方面的工具,由python編寫的,可以自由構造腳本實現性能測試。他就是:locust。官網:http://locust.io/
另外,給大家一個蟲師講解的安裝使用教程的連接。https://www.cnblogs.com/fnng/p/6081798.html
我是胖超人。chubby superman salutes you