一、Locust工具介紹
1.概述
Locust是一款易於使用的分布式負載測試工具,完全基於事件,使用python開發,即一個locust節點也可以在一個進程中支持數千並發用戶,不使用回調,通過gevent使用輕量級過程(即在自己的進程內運行)。
2.常見性能測試工具比較
3.環境搭建
Python3.7.9
源碼安裝:下載源碼https://github.com/locustio/locust,進入文件夾執行安裝命令:python setup.py install
pip安裝:pip install locust==1.4.3
二、Locust常用類和方法
三、Locust常用參
四、案例
1.參數化
# -*- coding: utf-8 -*- import os,random from locust import TaskSet, task,HttpUser, between #任務類 class Testlocust(TaskSet): def on_start(self): self.login_headers={'x-client-id': 'xxxxxx'} #頭文件 self.data=[ { "account_name": "登錄賬號1", "user_name": "登錄賬號1", "hashed_password": "登錄密碼1" }, { "account_name": "登錄賬號2", "user_name": "登錄賬號2", "hashed_password": "登錄密碼2" }, { "account_name": "登錄賬號3", "user_name": "登錄賬號3", "hashed_password": "登錄密碼3" } ] #登錄賬號密碼 print("------on start------") @task() def userlogin(self): r = self.client.post(url='/v1/auth/users/login', headers=self.login_headers,json=random.choice(self.data),name='登錄',verify=False) #使用choice方法參數化隨機登錄 assert r.status_code == 200 and r.json()['status']==0 #登錄斷言 def on_stop(self): print("------on stop------") #用戶類 class WebsiteUser(HttpUser): #locust1.0版本以前是HttpLocust tasks = [Testlocust] #locust1.0版本以前是task_set=Testlocust host = 'https://xxxxxx' #被測主機地址 wait_time = between(min_wait=1,max_wait=5) #任務之間的等待時間 if __name__ == "__main__": os.system("locust -f locust_XX.py") #執行locust腳本
2.關聯
# -*- coding: utf-8 -*- import os,requests from locust import TaskSet, task,HttpUser, between #任務類 class Testlocust(TaskSet): def on_start(self): print("------on start------") access_token = self.userlogin() #返回登錄token self.headers = {} #定義headers self.headers['x-api-key'] = 'fZkQSHC1dp2s0tL21EMtaNX3UjF7P6L9' #添加headers值 self.headers['Authorization'] = 'Bearer ' + access_token self.headers['x-key-hash'] = '1607675936446;abcdefg;bca1ef2b5835e454a15929f7ce9cb5d7ebaf580377624019002' self.headers['Content-Type'] = 'application/json' self.params = {"name": "CDR", "page": "1", "size": "10", "series": "CDR80"} #查詢接口參數 def userlogin(self): #登錄方法 login_url = 'https://xxxxxx/v1/auth/users/login' #登錄url data = { "account_name": "賬號1", "user_name": "賬號1", "hashed_password": "密碼1" } #登錄賬號密碼 login_headers = {'x-client-id': '46bf882df2959ea2'} r = requests.request('POST', url=login_url, headers=login_headers, json=data) #登錄 return r.json()['access_token'] #返回登錄token @task() def search(self): #查詢設備信息 r = self.client.get(url='/v1/assets/device/search', headers=self.headers,params=self.params, name='查詢', verify=False) #查詢 assert r.status_code == 200 and r.json()['code'] == 0 #結果斷言 #用戶類 class WebsiteUser(HttpUser): #locust1.0版本以前是HttpLocust tasks = [Testlocust] #locust1.0版本以前是task_set=Testlocust host = 'https://xxxxxx.com' #被測主機地址 wait_time = between(min_wait=1,max_wait=5) #任務之間的等待時間 if __name__ == "__main__": os.system("locust -f locust_XX.py") #執行參數