1. 程式人生 > >python多線程測試接口性能

python多線程測試接口性能

form tar ces logs 耗時 phone hone com glob

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 = 13511001095 + i #13511001100
        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": "13511001100", "email": "[email protected]
/* */", "sign": false}}‘ # print(r.json()) # {‘status‘: 200, ‘message‘: ‘success‘, ‘data‘: {‘realname‘: ‘alen‘, ‘phone‘: ‘13511001100‘, ‘email‘: [email protected], ‘sign‘: False}} # print(type(r)) # <class ‘requests.models.Response‘> ,這個類型有json方法,不需要import json # print(r) # <Response [200]> # print(json.loads(r.content)) #需要import json,{‘status‘: 200, ‘message‘: ‘success‘, ‘data‘: {‘realname‘: ‘alen‘, ‘phone‘: ‘13511001100‘, ‘email‘: [email protected]
/* */, ‘sign‘: False}} result = r.json() global success,fail try: if phone==‘13511001100‘ or phone==‘13511001101‘: 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個線程,25個數據 # lists = {1:6, 6:11, 11:16, 16:21, 21:26} # 可以這樣寫數據,也可以通過下面生成 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) # 創建線程列表 threads = [] # 創建線程 for start_user,end_user in lists.items(): t = threading.Thread(target=get_guest_list_thread,args=(start_user,end_user)) threads.append(t) if __name__ == ‘__main__‘: # 開始時間 start_time = time.time() # 啟動線程 for i in range(len(lists)): threads[i].start() for i in range(len(lists)): threads[i].join() # 結束時間 time.sleep(3) # 為了更明顯看出用例執行耗時,加上休眠 end_time = time.time() print("開始時間:"+str(start_time)+‘>>>>>‘+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(start_time))) print("結束時間:"+str(end_time)+‘>>>>>‘+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(end_time))) print(‘總共耗時:‘+str(end_time - start_time)) # 運行時間 print(‘測試通過用例數:{}, 測試失敗用例數:{}, 測試通過率為:{}‘.format(success,fail,str(success*100/(success+fail))+‘%‘))

  

結果:

技術分享

python多線程測試接口性能