內容來自網絡
https://www.w3xue.com/exp/article/20191/16707.html
https://blog.csdn.net/qq_36255988/article/details/82622044
一、Locust描述
(1)
locust的思想是:在測試期間,一大群"蝗蟲"會攻擊你的網站,每一個"蝗蟲"的行為都是由你自己定義的,同時,可以在一個web界面上實時的監控這群進程。這會幫助你更好的"進行戰斗",在真正的用戶進入之前,就找出代碼中的瓶頸。
locust完全是事件驅動的,因此它能夠在單機支持數以千計的並發用戶,相比許多其他的基於事件的應用,locust不使用回調函數。它使用輕量進程---gevent。每一個訪問你的網站的locust實際上都在它自己的進程內部運行(准確地說,是greenlet),也就是我們通常說的協程。這允許你在不使用帶回調函數的復雜代碼的情形下,使用python寫出非常具有表現力的腳本。
Locust使用Python代碼定義測試場景,目前支持Python 2.7, 3.3, 3.4, 3.5, 3.6和3.7。它自帶一個Web UI,用於定義用戶模型,發起測試,實時測試數據,錯誤統計等。
優點:
1. 易用。很方便地基於Python進行腳本擴展和業務請求實現。
2. 完全基於事件驅動,所以不受進程和線程的限制,可以支持發起更高的並發數請求。
3. 可以分布式發起並發請求
4.Locust有一個整潔的HTML+JS的用戶界面,實時顯示相關測試細節。由於用戶界面是基於網絡的,它是跨平台的和容易擴展。
5. 開源。
缺點:
1. 圖表相對loadrunner 比較簡單。(在Linux 下部署時可以看到圖表,在Windows 下沒有)
2. 不支持監控被測機,需要結合nmon等工具輔助監控。
二、Locust安裝
1.1、 ---> pip3 install locust
1.2 、 通過GitHub上克隆項目安裝(Python3推薦):https://github.com/locustio/locust ,然后執行 ...\locust> python setup.py install
2、安裝 pyzmq
If you intend to run Locust distributed across multiple processes/machines, we recommend you to also install pyzmq.
如果打算運行Locust 分布在多個進程/機器,需要安裝pyzmq.
通過pip命令安裝。 /> pip install pyzmq
3、安裝成功,CMD敲入命令驗證。 /> locust --help
1 Options: 2 -h, --help show this help message and exit 3 -H HOST, --host=HOST Host to load test in the following format: 4 http://10.21.32.33 5 --web-host=WEB_HOST Host to bind the web interface to. Defaults to '' (all 6 interfaces) 7 -P PORT, --port=PORT, --web-port=PORT 8 Port on which to run web host 9 -f LOCUSTFILE, --locustfile=LOCUSTFILE 10 Python module file to import, e.g. '../other.py'. 11 Default: locustfile 12 --csv=CSVFILEBASE, --csv-base-name=CSVFILEBASE 13 Store current request stats to files in CSV format. 14 --master Set locust to run in distributed mode with this 15 process as master 16 --slave Set locust to run in distributed mode with this 17 process as slave 18 --master-host=MASTER_HOST 19 Host or IP address of locust master for distributed 20 load testing. Only used when running with --slave. 21 Defaults to 127.0.0.1. 22 --master-port=MASTER_PORT 23 The port to connect to that is used by the locust 24 master for distributed load testing. Only used when 25 running with --slave. Defaults to 5557. Note that 26 slaves will also connect to the master node on this 27 port + 1. 28 --master-bind-host=MASTER_BIND_HOST 29 Interfaces (hostname, ip) that locust master should 30 bind to. Only used when running with --master. 31 Defaults to * (all available interfaces). 32 --master-bind-port=MASTER_BIND_PORT 33 Port that locust master should bind to. Only used when 34 running with --master. Defaults to 5557. Note that 35 Locust will also use this port + 1, so by default the 36 master node will bind to 5557 and 5558. 37 --heartbeat-liveness=HEARTBEAT_LIVENESS 38 set number of seconds before failed heartbeat from 39 slave 40 --heartbeat-interval=HEARTBEAT_INTERVAL 41 set number of seconds delay between slave heartbeats 42 to master 43 --expect-slaves=EXPECT_SLAVES 44 How many slaves master should expect to connect before 45 starting the test (only when --no-web used). 46 --no-web Disable the web interface, and instead start running 47 the test immediately. Requires -c and -r to be 48 specified. 49 -c NUM_CLIENTS, --clients=NUM_CLIENTS 50 Number of concurrent Locust users. Only used together 51 with --no-web 52 -r HATCH_RATE, --hatch-rate=HATCH_RATE 53 The rate per second in which clients are spawned. Only 54 used together with --no-web 55 -t RUN_TIME, --run-time=RUN_TIME 56 Stop after the specified amount of time, e.g. (300s, 57 20m, 3h, 1h30m, etc.). Only used together with --no- 58 web 59 -L LOGLEVEL, --loglevel=LOGLEVEL 60 Choose between DEBUG/INFO/WARNING/ERROR/CRITICAL. 61 Default is INFO. 62 --logfile=LOGFILE Path to log file. If not set, log will go to 63 stdout/stderr 64 --print-stats Print stats in the console 65 --only-summary Only print the summary stats 66 --no-reset-stats [DEPRECATED] Do not reset statistics once hatching has 67 been completed. This is now the default behavior. See 68 --reset-stats to disable 69 --reset-stats Reset statistics once hatching has been completed. 70 Should be set on both master and slaves when running 71 in distributed mode 72 -l, --list Show list of possible locust classes and exit 73 --show-task-ratio print table of the locust classes' task execution 74 ratio 75 --show-task-ratio-json 76 print json data of the locust classes' task execution 77 ratio 78 -V, --version show program's version number and exit
參數說明:
- -h, --help 查看幫助
- -H HOST, --host=HOST 指定被測試的主機,采用以格式:http://10.21.32.33
- --web-host=WEB_HOST 指定運行 Locust Web 頁面的主機,默認為空 ''。
- -P PORT, --port=PORT, --web-port=PORT 指定 --web-host 的端口,默認是8089
- -f LOCUSTFILE, --locustfile=LOCUSTFILE 指定運行 Locust 性能測試文件,默認為: locustfile.py
- --csv=CSVFILEBASE, --csv-base-name=CSVFILEBASE 以CSV格式存儲當前請求測試數據。
- --master Locust 分布式模式使用,當前節點為 master 節點。
- --slave Locust 分布式模式使用,當前節點為 slave 節點。
- --master-host=MASTER_HOST 分布式模式運行,設置 master 節點的主機或 IP 地址,只在與 --slave 節點一起運行時使用,默認為:127.0.0.1.
- --master-port=MASTER_PORT 分布式模式運行, 設置 master 節點的端口號,只在與 --slave 節點一起運行時使用,默認為:5557。注意,slave 節點也將連接到這個端口+1 上的 master 節點。
- --master-bind-host=MASTER_BIND_HOST Interfaces (hostname, ip) that locust master should bind to. Only used when running with --master. Defaults to * (all available interfaces).
- --master-bind-port=MASTER_BIND_PORT Port that locust master should bind to. Only used when running with --master. Defaults to 5557. Note that Locust will also use this port + 1, so by default the master node will bind to 5557 and 5558.
- --expect-slaves=EXPECT_SLAVES How many slaves master should expect to connect before starting the test (only when --no-web used).
- --no-web no-web 模式運行測試,需要 -c 和 -r 配合使用.
- -c NUM_CLIENTS, --clients=NUM_CLIENTS 指定並發用戶數,作用於 --no-web 模式。
- -r HATCH_RATE, --hatch-rate=HATCH_RATE 指定每秒啟動的用戶數,作用於 --no-web 模式。
- -t RUN_TIME, --run-time=RUN_TIME 設置運行時間, 例如: (300s, 20m, 3h, 1h30m). 作用於 --no-web 模式。
- -L LOGLEVEL, --loglevel=LOGLEVEL 選擇 log 級別(DEBUG/INFO/WARNING/ERROR/CRITICAL). 默認是 INFO.
- --logfile=LOGFILE 日志文件路徑。如果沒有設置,日志將去 stdout/stderr
- --print-stats 在控制台中打印數據
- --only-summary 只打印摘要統計
- --no-reset-stats Do not reset statistics once hatching has been completed。
- -l, --list 顯示測試類, 配置 -f 參數使用
- --show-task-ratio 打印 locust 測試類的任務執行比例,配合 -f 參數使用.
- --show-task-ratio-json 以 json 格式打印 locust 測試類的任務執行比例,配合 -f 參數使用.
- -V, --version 查看當前 Locust 工具的版本.
4、Locust主要由下面的幾個庫構成:
1) gevent
gevent是一種基於協程的Python網絡庫,它用到Greenlet提供的,封裝了libevent事件循環的高層同步API。
2) flask
Python編寫的輕量級Web應用框架。
3) requests
Python Http庫
4) msgpack-python
MessagePack是一種快速、緊湊的二進制序列化格式,適用於類似JSON的數據格式。msgpack-python主要提供MessagePack數據序列化及反序列化的方法。
5) six
Python2和3兼容庫,用來封裝Python2和Python3之間的差異性
6) pyzmq
pyzmq是zeromq(一種通信隊列)的Python綁定,主要用來實現Locust的分布式模式運行
當我們在安裝 Locust 時,它會檢測我們當前的 Python 環境是否已經安裝了這些庫,如果沒有安裝,它會先把這些庫一一裝上。並且對這些庫版本有要求,有些是必須等於某版本,有些是大於某版本。我們也可以事先把這些庫全部按要求裝好,再安裝Locust時就會快上許多。
三、編寫接口壓測腳本文件locustfile.py
腳本模板(參考)
1 from locust import HttpLocust, TaskSet, task 2 3 class UserBehavior(TaskSet): 4 def setup(self): 5 print('task setup') 6 7 def teardown(self): 8 print('task teardown') 9 10 def on_start(self): 11 # 虛擬用戶啟動Task時運行 12 print('start') 13 14 def on_stop(self): 15 # 虛擬用戶結束Task時運行 16 print('end') 17 18 @task(2) 19 def index(self): 20 self.client.get("/") 21 22 @task(1) 23 def profile(self): 24 self.client.get("/profile") 25 26 class WebsiteUser(HttpLocust): 27 def setup(self): 28 print('locust setup') 29 30 def teardown(self): 31 print('locust teardown') 32 33 host = http: // XXXXX.com 34 task_set = UserBehavior 35 min_wait = 5000 36 max_wait = 9000 37 38 if __name__ == '__main__': 39 pass
說明:
Locust類有setup和teardown,TaskSet類有setup、teardown、on_start、on_stop。
每次啟動locust時運行setup方法,退出時運行teardown方法,locust執行TaskSet時運行TaskSet的setup方法,退出時運行teardown方法,每個虛擬用戶執行操作時運行on_start方法,退出時執行on_stop方法,運行上面的腳本,執行順序如下:
執行順序:Locust setup → TaskSet setup → TaskSet on_start → TaskSet tasks → TaskSet on_stop → TaskSet teardown → Locust teardown
舉個腳本栗子
1 from locust import HttpLocust, TaskSet, task 2 3 4 class ScriptTasks(TaskSet): 5 def on_start(self): 6 self.client.post("/login", { 7 "username": "test", 8 "password": "123456" 9 }) 10 11 @task(2) 12 def index(self): 13 self.client.get("/") 14 15 @task(1) 16 def about(self): 17 self.client.get("/about/") 18 19 @task(1) 20 def demo(self): 21 payload = {} 22 headers = {} 23 self.client.post("/demo/", data=payload, headers=headers) 24 25 26 class WebsiteUser(HttpLocust): 27 task_set = ScriptTasks 28 host = "http://example.com" 29 min_wait = 1000 30 max_wait = 5000
腳本解讀:
- 創建ScriptTasks()類繼承TaskSet類: 用戶行為類,用於定義測試業務場景。
- 創建index()、about()、demo()方法分別表示一個行為,訪問http://example.com。用@task() 裝飾該方法為一個任務。1、2表示一個Locust實例被挑選執行的權重,數值越大,執行頻率越高。在當前ScriptTasks()行為下的三個方法得執行比例為2:1:1
- WebsiteUser()類: 用於定義模擬用戶。
- task_set : 指向一個定義了的用戶行為類。
- host: 指定被測試應用的URL的地址
- min_wait : 用戶執行任務之間等待時間的下界,單位:毫秒。
- max_wait : 用戶執行任務之間等待時間的上界,單位:毫秒。
腳本使用場景解讀:
1、在這個示例中,定義了針對http://example.com
網站的測試場景:先模擬用戶登錄系統,然后隨機地訪問首頁(/
)和關於頁面(/about/
),請求比例為2:1,
demo方法主要用來闡述client對post接口的處理方式;並且,在測試過程中,兩次請求的間隔時間為1->
5
秒間的隨機值。
2、從腳本中可以看出,腳本主要包含兩個類(類名可自定義),一個是WebsiteUser
(繼承自HttpLocust
,而HttpLocust
繼承自Locust
),另一個是ScriptTasks
(繼承自TaskSet
)。事實上,在Locust
的測試腳本中,所有業務測試場景都是在Locust
和TaskSet
兩個類的繼承子類中進行描的。
3、那如何理解Locust
和TaskSet
這兩個類呢?簡單地說,Locust類
就好比是一群蝗蟲,而每一只蝗蟲就是一個類的實例。相應的,TaskSet類
就好比是蝗蟲的大腦,控制着蝗蟲的具體行為,即實際業務場景測試對應的任務集。
四、Locust類
實例腳本
偽代碼:
1 from locust import HttpLocust, TaskSet, task 2 3 4 class WebsiteTasks(TaskSet): 5 def on_start(self): # 進行初始化的工作,每個Locust用戶開始做的第一件事 6 payload = { 7 "username": "test_user", 8 "password": "123456", 9 } 10 header = { 11 "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" 12 } 13 self.client.post("/login", data=payload,headers=header) 14 # self.client屬性使用Python request庫的所有方法,調用和使用方法和requests完全一致; 15 16 @task(5) 17 # 通過@task()裝飾的方法為一個事務,方法的參數用於指定該行為的執行權重,參數越大每次被虛擬用戶執行的概率越高,默認為1 18 def index(self): 19 self.client.get("/") 20 21 @task(1) 22 def about(self): 23 self.client.get("/about/") 24 25 26 class WebsiteUser(HttpLocust): 27 host = "https://github.com/" # 被測系統的host,在終端中啟動locust時沒有指定--host參數時才會用到 28 task_set = WebsiteTasks # TaskSet類,該類定義用戶任務信息,必填。這里就是:WebsiteTasks類名,因為該類繼承TaskSet; 29 min_wait = 5000 # 每個用戶執行兩個任務間隔時間的上下限(毫秒),具體數值在上下限中隨機取值,若不指定默認間隔時間固定為1秒 30 max_wait = 15000
偽代碼中對https://github.com/網站的測試場景,先模擬用戶登錄系統,然后隨機訪問首頁/和/about/,請求比例5:1,並且在測試過程中,兩次請求的間隔時間1-5秒的隨機值;
on_start方法,在正式執行測試前執行一次,主要用於完成一些初始化的工作,例如登錄操作;
WebsiteTasks類中如何去調用 WebsiteUser(HttpLocust)類中定義的字段和方法呢?
通過在WebsiteTasks類中self.locust.xxoo xxoo就是我們在WebsiteUser類中定義的字段或方法;
偽代碼:
1 from locust import HttpLocust, TaskSet, task 2 import hashlib 3 import Queue 4 5 6 class WebsiteTasks(TaskSet): 7 @task(5) 8 def index(self): 9 data = self.locust.user_data_queue # 獲取WebsiteUser里面定義的ser_data_queue隊列 10 md5_data = self.locust.md5_encryption() # 獲取WebsiteUser里面定義的md5_encryption()方法 11 self.client.get("/") 12 13 14 class WebsiteUser(HttpLocust): 15 host = "https://github.com/" 16 task_set = WebsiteTasks 17 min_wait = 5000 18 max_wait = 15000 19 user_data_queue = Queue.Queue() 20 21 def md5_encryption(self, star): 22 '''md5加密方法''' 23 obj = hashlib.md5() 24 obj.update(bytes(star, encoding="utf-8")) 25 result = obj.hexdigest() 26 return result
偽代碼中測試場景如何表達?
代碼主要包含兩個類:
- WebsiteUser繼承(HttpLocust,而HttpLocust繼承自Locust)
- WebsiteTasks繼承(TaskSet)
在Locust測試腳本中,所有業務測試場景都是在Locust和TaskSet兩個類的繼承子類中進行描述;
簡單說:Locust類就類似一群蝗蟲,而每只蝗蟲就是一個類的實例。TaskSet類就類似蝗蟲的大腦,控制蝗蟲的具體行為,即實際業務場景測試對應的任務集;
源碼中:class Locust(object)和class HttpLocust(Locust) 此處可查看源代碼
在Locust類中,靜態字段client即客戶端的請求方法,這里的client字段沒有綁定客戶端請求方法,因此在使用Locust時,需要先繼承Locust類class HttpLocust(Locust),然后在self.client =HttpSession(base_url=self.host)綁定客戶端請求方法;
對於常見的HTTP(s)協議,Locust已經實現了HttpLocust類,其self.client=HttpSession(base_url=self.host),而HttpSession繼承自requests.Session。因此在測試HTTP(s)的Locust腳本中,可以通過client屬性來使用Python requests庫的所 有方法,調用方式與 reqeusts完全一致。另外,由於requests.Session的使用,client的方法調用之間就自動具有了狀態記憶功能。常見的場景就是,在登錄系統后可以維持登錄狀態的Session,從而后續HTTP請求操作都能帶上登錄狀態;
Locust類中,除了client屬性,還有幾個屬性需要關注:
- task_set ---> 指向一個TaskSet類,TaskSet類定義了用戶的任務信息,該靜態字段為必填;
- max_wait/min_wait ---> 每個用戶執行兩個任務間隔的上下限(毫秒),具體數值在上下限中隨機取值,若不指定則默認間隔時間為1秒;
- host --->被測試系統的host,當在終端中啟動locust時沒有指定--host參數時才會用到;
- weight--->同時運行多個Locust類時,用於控制不同類型的任務執行權重;
Locust流程,測試開始后,每個虛擬用戶(Locust實例)運行邏輯都會遵守如下規律:
- 先執行WebsiteTasks中的on_start(只執行一次),作為初始化;
- 從WebsiteTasks中隨機挑選(如果定義了任務間的權重關系,那么就按照權重關系隨機挑選)一個任務執行;
- 根據Locust類中min_wait和max_wait定義的間隔時間范圍(如果TaskSet類中也定義了min_wait或者max_wait,以TaskSet中的優先),在時間范圍中隨機取一個值,休眠等待;
- 重復2~3步驟,直到測試任務終止;
class TaskSet
TaskSet類實現了虛擬用戶所執行任務的調度算法,包括規划任務執行順序(schedule_task)、挑選下一個任務(execute_next_task)、執行任務(execute_task)、休眠等待(wait)、中斷控制(interrupt)等待。在此基礎上,就可以在TaskSet子類中采用非常簡潔的方式來描述虛擬用戶的業務測試場景,對虛擬用戶的所有行為進行組織和描述,並可以對不同任務的權重進行配置。
@task
通過@task()裝飾的方法為一個事務。方法的參數用於指定該行為的執行權重。參數越大每次被虛擬用戶執行的概率越高。如果不設置默認為1。
TaskSet子類中定義任務信息時,采取兩種方式:@task裝飾器和tasks屬性。
采用@task裝飾器定義任務信息時:
1 from locust import TaskSet, task 2 3 class UserBehavior(TaskSet): 4 @task(1) 5 def test_job1(self): 6 self.client.get('/test1') 7 8 @task(3) 9 def test_job2(self): 10 self.client.get('/test2')
采用tasks屬性定義任務信息時
1 from locust import TaskSet 2 3 def test_job1(obj): 4 obj.client.get('/test1') 5 6 def test_job2(obj): 7 obj.client.get('/test2') 8 9 class UserBehavior(TaskSet): 10 tasks = {test_job1: 1, test_job2: 2} 11 # tasks = [(test_job1,1), (test_job1,3)] # 兩種方式等價
上面兩種定義任務信息方式中,均設置了權重屬性,即執行test_job2的頻率是test_job1的兩倍。若不指定,默認比例為1:1。
高級用法:
關聯
在某些請求中,需要攜帶之前response中提取的參數,常見場景就是session_id。Python中可用通過re正則匹配,對於返回的html頁面,可用采用lxml庫來定位獲取需要的參數;
1 from locust import HttpLocust, TaskSet, task 2 from lxml import etree 3 4 class WebsiteTasks(TaskSet): 5 def get_session(self, html): # 關聯例子 6 tages = etree.HTML(html) 7 return tages.xpath("//div[@class='btnbox']/input[@name='session']/@value")[0] 8 9 def on_start(self): 10 html = self.client.get('/index') 11 session = self.get_session(html.text) 12 payload = { 13 "username": "test_user", 14 "password": "123456", 15 'session': session 16 } 17 header = { 18 "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"19 } 20 self.client.post("/login", data=payload, headers=header) 21 22 @task(5) 23 def index(self): 24 self.client.get("/") 25 assert response['ErrorCode'] == 0 # 斷言 26 27 @task(1) 28 def about(self): 29 self.client.get("/about/") 30 31 class WebsiteUser(HttpLocust): 32 host = "https://github.com/" 33 task_set = WebsiteTasks 34 min_wait = 5000 35 max_wait = 15000
參數化
作用:循環取數據,數據可重復使用
例如:模擬3個用戶並發請求網頁,共有100個URL地址,每個虛擬用戶都會依次循環加載100個URL地址
1 from locust import TaskSet, task, HttpLocust 2 3 class UserBehavior(TaskSet): 4 def on_start(self): 5 self.index = 0 6 7 @task 8 def test_visit(self): 9 url = self.locust.share_data[self.index] 10 print('visit url: %s' % url) 11 self.index = (self.index + 1) % len(self.locust.share_data) 12 self.client.get(url) 13 14 class WebsiteUser(HttpLocust): 15 host = 'http://debugtalk.com' 16 task_set = UserBehavior 17 share_data = ['url1', 'url2', 'url3', 'url4', 'url5'] 18 min_wait = 1000 19 max_wait = 3000
保證並發測試數據唯一性,不循環取數據;
所有並發虛擬用戶共享同一份測試數據,並且保證虛擬用戶使用的數據不重復;
例如:模擬3用戶並發注冊賬號,共有9個賬號,要求注冊賬號不重復,注冊完畢后結束測試:
采用隊列
1 from locust import TaskSet, task, HttpLocust 2 import Queue 3 4 class UserBehavior(TaskSet): 5 @task 6 def test_register(self): 7 try: 8 data = self.locust.user_data_queue.get() 9 except Queue.Empty: 10 print('account data run out, test ended.') 11 exit(0) 12 print('register with user: {}, pwd: {}'.format(data['username'], data['password'])) 13 payload = { 14 'username': data['username'], 15 'password': data['password'] 16 } 17 self.client.post('/register', data=payload) 18 19 class WebsiteUser(HttpLocust): 20 host = 'http://XXXXX.com' 21 task_set = UserBehavior 22 user_data_queue = Queue.Queue() 23 for index in range(100): 24 data = { 25 "username": "test%04d" % index, 26 "password": "pwd%04d" % index, 27 "email": "test%04d@debugtalk.test" % index, 28 "phone": "186%08d" % index, 29 } 30 user_data_queue.put_nowait(data) 31 min_wait = 1000 32 max_wait = 3000
保證並發測試數據唯一性,循環取數據;
所有並發虛擬用戶共享同一份測試數據,保證並發虛擬用戶使用的數據不重復,並且數據可循環重復使用;
例如:模擬3個用戶並發登錄賬號,總共有9個賬號,要求並發登錄賬號不相同,但數據可循環使用;
1 class UserBehavior(TaskSet): 2 @task 3 def test_register(self): 4 try: 5 data = self.locust.user_data_queue.get() 6 except Queue.Empty: 7 print('account data run out, test ended') 8 exit(0) 9 print('register with user: {0}, pwd: {1}'.format(data['username'], data['password'])) 10 payload = { 11 'username': data['username'], 12 'password': data['password'] 13 } 14 self.client.post('/register', data=payload) 15 self.locust.user_data_queue.put_nowait(data) 16 17 class WebsiteUser(HttpLocust): 18 host = 'http://XXXXXX.com' 19 task_set = UserBehavior 20 user_data_queue = Queue.Queue() 21 for index in range(100): 22 data = { 23 "username": "test%04d" % index, 24 "password": "pwd%04d" % index, 25 "email": "test%04d@debugtalk.test" % index, 26 "phone": "186%08d" % index, 27 } 28 user_data_queue.put_nowait(data) 29 min_wait = 1000 30 max_wait = 3000
斷言(即檢查點)
性能測試也需要設置斷言么? 某些情況下是需要,比如你在請求一個頁面時,就可以通過狀態來判斷返回的 HTTP 狀態碼是不是 200。
通過with self.client.get("url地址",catch_response=True) as response的形式;
response.status_code獲取http響應碼進行判斷,失敗后會加到統計錯誤表中;
python自帶的斷言assert失敗后代碼就不會向下走,且失敗后不會被Locust報表統計進去;
默認不寫參數catch_response=False斷言無效,將catch_response=True才生效;
下面例子中:
首先使用python斷言對接口返回值進行判斷(python斷言不通過,代碼就不向下執行,get請求數為0),通過后對該接口的http響應是否為200進行判斷;
1 @task 2 def all_interface(self): 3 # 豆瓣圖書api為例子 4 with self.client.get("https://api.douban.com/v2/book/1220562", name="/LhcActivity/GetActConfig", 5 catch_response=True) as response: 6 assert response.json()['rating']['max'] == 10 # python斷言對接口返回值中的max字段進行斷言 7 if response.status_code == 200: # 對http響應碼是否200進行判斷 8 response.success() 9 else: 10 response.failure("GetActConfig[Failed!]")
五、Locust運行模式
運行Locust
時,通常會使用到兩種運行模式:單進程運行和多進程分布式運行。
單進程運行模式
Locust
所有的虛擬並發用戶均運行在單個Python
進程中,具體從使用形式上,又分為no_web
和web
兩種形式。該種模式由於單進程的原因,並不能完全發揮壓力機所有處理器的能力,因此主要用於調試腳本和小並發壓測的情況。
當並發壓力要求較高時,就需要用到Locust
的多進程分布式運行模式。從字面意思上看,大家可能第一反應就是多台壓力機同時運行,每台壓力機分擔負載一部分的壓力生成。的確,Locust
支持任意多台壓力機(一主多從)的分布式運行模式,但這里說到的多進程分布式運行模式還有另外一種情況,就是在同一台壓力機上開啟多個slave
的情況。這是因為當前階段大多數計算機的CPU都是多處理器(multiple processor cores
),單進程運行模式下只能用到一個處理器的能力,而通過在一台壓力機上運行多個slave
,就能調用多個處理器的能力了。比較好的做法是,如果一台壓力機有N
個處理器內核,那么就在這台壓力機上啟動一個master
,N
個slave
。當然,我們也可以啟動N
的倍數個slave
,但是根據我的試驗數據,效果跟N
個差不多,因此只需要啟動N
個slave
即可。
no_web形式啟動locust:
如果采用no_web
形式,則需使用--no-web
參數,並會用到如下幾個參數。
-c, --clients
:指定並發用戶數;-r, --hatch-rate
:指定並發加壓速率,默認值位1。
示例:
$ locust -f locustfile.py --host = xxxxx.com --no-web -c 2 -r 1
在此基礎上,當我們想要調試Locust
腳本時,就可以在腳本中需要調試的地方通過print
打印日志,然后將並發數和總執行次數都指定為1
$ locust -f locustfile.py --host = xxxxx.com --no-web -c 1 -r 1
執行測試
通過這種方式,我們就能很方便地對Locust
腳本進行調試了。
Locust
腳本調試通過后,就算是完成了所有准備工作,可以開始進行壓力測試了。
web形式啟動locust:
如果采用web
形式,,則通常情況下無需指定其它額外參數,Locust
默認采用8089
端口啟動web
;如果要使用其它端口,就可以使用如下參數進行指定。
-P, --port
:指定web端口,默認為8089
.- 終端中--->進入到代碼目錄: locust -f locustfile.py --host = xxxxx.com
- -f 指定性能測試腳本文件
- -host 被測試應用的URL地址【如果不填寫,讀取繼承(HttpLocust)類中定義的host】
- 如果
Locust
運行在本機,在瀏覽器中訪問http://localhost:8089
即可進入Locust
的Web管理頁面;如果Locust
運行在其它機器上,那么在瀏覽器中訪問http://locust_machine_ip:8089
即可。
多進程分布式運行
不管是單機多進程
,還是多機負載
模式,運行方式都是一樣的,都是先運行一個master
,再啟動多個slave
。
啟動master
時,需要使用--master
參數;同樣的,如果要使用8089
以外的端口,還需要使用-P, --port
參數。
- D:\workSpaces\ApiAutoTest\TestCases\OpsUltraAPITest\MonitorAPITest>locust -f monitorAgent.py --master --port=8089
- [2018-06-05 15:36:30,654] dengshihuang/INFO/locust.main: Starting web monitor at *:8089
- [2018-06-05 15:36:30,684] dengshihuang/INFO/locust.main: Starting Locust 0.8.1
啟動
啟動后,還需要啟動slave
時需要使用--slave
參數;在slave
中,就不需要再指定端口了。masterslave
才能執行測試任務。
- D:\workSpaces\ApiAutoTest\TestCases\OpsUltraAPITest\MonitorAPITest>locust -f monitorAgent.py --slave
- [2018-06-05 15:36:30,654] dengshihuang/INFO/locust.main: Starting web monitor at *:8089
- [2018-06-05 15:36:30,684] dengshihuang/INFO/locust.main: Starting Locust 0.8.1
- D:\workSpaces\ApiAutoTest\TestCases\OpsUltraAPITest\MonitorAPITest>locust -f monitorAgent.py --slave --master-host=<locust_machine_ip>
master
和slave
都啟動完畢后,就可以在瀏覽器中通過http://locust_machine_ip:8089
進入Locust
的Web管理頁面了。使用方式跟單進程web
形式完全相同,只是此時是通過多進程負載來生成並發壓力,在web
管理界面中也能看到實際的slave
數量。如果slave
與master
不在同一台機器上,還需要通過--master-host
參數再指定master
的IP地址。
運行結果:
Number of users to simulate 設置虛擬用戶數,對應中no_web
模式的-c, --clients
參數;
Hatch rate(users spawned/second)每秒產生(啟動)的虛擬用戶數 , 對應着no_web
模式的-r, --hatch-rate
參數,默認為1。點擊Start swarming 按鈕,開始運行性能測試。
上圖:啟動了一個 master 和兩個 slave,由兩個 slave 來向被測試系統發送請求
性能測試參數
-
Type: 請求的類型,例如GET/POST。
-
Name:請求的路徑。這里為百度首頁,即:https://www.baidu.com/
-
request:當前請求的數量。
-
fails:當前請求失敗的數量。
-
Median:中間值,單位毫秒,一半的服務器響應時間低於該值,而另一半高於該值。
-
Average:平均值,單位毫秒,所有請求的平均響應時間。
-
Min:請求的最小服務器響應時間,單位毫秒。
-
Max:請求的最大服務器響應時間,單位毫秒。
-
Content Size:單個請求的大小,單位字節。
-
reqs/sec:是每秒鍾請求的個數。
相比於LoadRunner
,Locust
的結果展示十分簡單,主要就四個指標:並發數
、RPS
、響應時間
、異常率
。但對於大多數場景來說,這幾個指標已經足夠了。
在上圖中,RPS
和平均響應時間
這兩個指標顯示的值都是根據最近2秒請求響應數據計算得到的統計值,我們也可以理解為瞬時值。
如果想看性能指標數據的走勢,就可以在Charts
欄查看。在這里,可以查看到RPS
和平均響應時間
在整個運行過程中的波動情況。
除了以上數據,Locust
還提供了整個運行過程數據的百分比統計值,例如我們常用的90%響應時間
、響應時間中位值;平均響應時間和錯誤數的統計
,該數據可以通過Download response time distribution CSV和Download request statistics CSV
獲得,數據展示效果如下所示。
-----------------------------------------------------------
注意:
locust雖然使用方便,但是加壓性能和響應時間上面還是有差距的,如果項目有非常大的並發加壓請求,可以選擇wrk
對比方法與結果:
可以准備兩台服務器,服務器A作為施壓方,服務器B作為承壓方
服務器B上簡單的運行一個nginx服務就行了
服務器A上可以安裝一些常用的壓測工具,比如locust、ab、wrk
實測下來,施壓能力上 wrk > golang >> ab > locust
因為locust一個進程只使用一核CPU,所以用locust壓測時,必須使用主從分布式(zeromq通訊)模式,並根據服務器CPU核數來起slave節點數
wrk約為55K QPS
golang net/http 約 45K QPS
ab 大約 15K QPS
locust 最差,而且response time明顯比較長