您好,登錄后才能下訂單哦!
除了使用性能測試工具進(jìn)行性能測試,我們也可以直接用python多線程進(jìn)行性能測試。
下面,使用這幾個(gè)模塊,對一個(gè)查詢接口做性能測試:
requests:發(fā)送http請求
json:返回的字符串轉(zhuǎn)換成json格式
threading:多線程
time:統(tǒng)計(jì)時(shí)間
具體實(shí)現(xiàn)過程見代碼及注釋。
import requests
import json
import threading
import time
# 定義請求基本地址
base_url = "http://127.0.0.1:8000"
success = 0
fail = 0
# 查詢線程
def get_guest_list_thread(start_user,end_user):
for i in range(start_user,end_user):
phone = 13800138000 + i
r = requests.get(base_url+'/api/get_guest_list/', params={'eid':1,'phone':phone})
# print(r.status_code) # 200
# print(r.content) # b'{"status": 200, "message": "success", "data": {"realname": "alen", "phone": "13800138000", "email": "alen@mail.com", "sign": false}}'
# print(r.json()) # {'status': 200, 'message': 'success', 'data': {'realname': 'alen', 'phone': '13800138000', 'email': 'alen@mail.com', 'sign': False}}
# print(type(r)) # <class 'requests.models.Response'> ,這個(gè)類型有json方法,不需要import json
# print(r) # <Response [200]>
# print(json.loads(r.content)) #需要import json,{'status': 200, 'message': 'success', 'data': {'realname': 'alen', 'phone': '13800138000', 'email': 'alen@mail.com', 'sign': False}}
result = r.json()
global success,fail
try:
if phone=='13800138000' or phone=='13800138001':
assert result['status'] == 20
success +=1
else:
assert result['status'] == 10022
success +=1
except AssertionError as e:
print('get error:'+str(phone))
fail +=1
# 5個(gè)線程,25個(gè)數(shù)據(jù)
# lists = {1:6, 6:11, 11:16, 16:21, 21:26} # 可以這樣寫數(shù)據(jù),也可以通過下面生成
data = 25
n = 5
step = int(data/n)
lists = {}
for i in range(1,n+1):
lists[(i-1)*step+1]=i*step + 1
print(lists)
# 創(chuàng)建線程列表
threads = []
# 創(chuàng)建線程
for start_user,end_user in lists.items():
t = threading.Thread(target=get_guest_list_thread,args=(start_user,end_user)) # args是一個(gè)元組
threads.append(t)
if __name__ == '__main__':
# 開始時(shí)間
start_time = time.time()
# 啟動(dòng)線程
for i in range(len(lists)):
threads[i].start()
for i in range(len(lists)):
threads[i].join()
# 結(jié)束時(shí)間
time.sleep(3) # 為了更明顯看出用例執(zhí)行耗時(shí),加上休眠
end_time = time.time()
print("開始時(shí)間:"+str(start_time)+'>>>>>'+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(start_time)))
print("結(jié)束時(shí)間:"+str(end_time)+'>>>>>'+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(end_time)))
print('總共耗時(shí):' + str(end_time - start_time))
print('總共耗時(shí):%.2f'%(end_time - start_time)) # 保留兩位小數(shù)
print('測試通過用例數(shù):{}, 測試失敗用例數(shù):{}, 測試通過率為:{}'.format(success,fail,str(success*100/(success+fail))+'%'))
結(jié)果:
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。