本人工作中主要對接口與web進行性能測試,而接口測試主要為http協議接口和webservice接口,本文主要對locust框架http接口測試先進行簡單介紹。
1、測試需求
對某系統登錄接口進行測試,登錄前需進行身份認證(摘要認證)。
2、環境准備
pycharm
Python 3.6
Windows 7
3、基本功能實現
對該系統進行摘要認證,實現登錄功能,代碼如下:

1 import requests 2 #導入HTTPDigestAuth,實現摘要認證 3 from requests.auth import HTTPDigestAuth 4 url = r'http://172.20.x.xxx:xxxx/login' 5 #請求頭部 6 header = {"APP-Version":"ios-1.1"} 7 #摘要認證,post方法請求服務器 8 r=requests.post(url,auth=HTTPDigestAuth('username','password'),headers = header) 9 #打印服務器返回 10 print("返回碼:"+str(r.status_code)+"\r\n"+"響應報文:"+"\n"+str(r.text))
4、壓力發起
結合locust框架,形成壓測腳本,對該系統發起壓力,具體代碼如下:

1 from locust import HttpLocust,TaskSet,task 2 import subprocess 3 import json 4 from requests.auth import HTTPDigestAuth 5 import requests 6 #TaskSet類. 7 class UserBehavior(TaskSet): 8 #開始前執行 9 def on_start(self): 10 pass 11 #等同於loadrunner事務 12 @task(1) 13 def login(self): 14 header = {"APP-Version": "ios-1.1"} 15 r = self.client.post("/login", auth=HTTPDigestAuth('username', 'password'), headers=header) 16 if json.loads(r.content)["tel_phone"] == ' ': 17 print("Got wrong response:"+str(r.content)) 18 19 #This is another HttpLocust class. 20 class MobileUserLocust(HttpLocust): 21 weight = 3 22 task_set = UserBehavior 23 host = 'http://1.82.238.163:3001' 24 min_wait = 3000 25 max_wait = 6000
進入終端,執行命令:
locust -f D:\Locust\http接口測試.py
在瀏覽器輸入localhost:8089,輸入模擬用戶數,點擊“Start swarming”開始測試
進入主界面,實時TPS監控效果圖:
響應時間效果圖:
可以導出需要的數據:
以上對http接口測試locust框架進行了簡單的介紹,locust性能測試框架部署及使用詳解請參考:http://www.cnblogs.com/zhang-zhi/p/7642017.html,如有錯誤請大神指出!