Python + Locust(蝗蟲) 壓測

壓力測試工具, load testing, stress testing

引言

試一下 Python 壓測工具。

Locust 官網

Locust 官網

結論

應該滿好用的。

安裝過程紀錄

不同版本可能有不同步驟與“眉角”。試了幾篇安裝紀錄文章都失敗!歸納原因只有一個:版本不同!

建議先到官網看安裝手冊為優先。

結果一個指令就安裝完工了。

pip install locust
# 需事先安裝好 Python 與 pip。

試用與安裝的版號如下

> Locust --version
locust 2.21.0 from C:\Program Files\Python311\Lib\site-packages\locust (python 3.11.3)

測試情境開發紀錄 locustfile.py

先用最簡單的開畫面測試。當然真正的測試情境絕不會這麼簡單。

locustfile.py
from locust import HttpUser, between, task

class WebsiteUser(HttpUser):
    wait_time = between(5,15)
    
    @task
    def index(self):
        self.client.get("/")
        self.client.get("/healthz")

啟動測試

啟動測試成功後會建立網站,預設為http://localhost:8089。自己手動打開。

>locust -f locustfile.py
[2024-01-30 17:47:59,478] xxx/INFO/locust.main: Starting web interface at http://localhost:8089 (accepting connections from all network interfaces)
[2024-01-30 17:47:59,497] xxx/INFO/locust.main: Starting Locust 2.21.0
[2024-01-30 17:52:37,141] xxx/INFO/locust.runners: Ramping to 10 users at a rate of 1.00 per second
[2024-01-30 17:52:46,156] xxx/INFO/locust.runners: All users spawned: {"WebsiteUser": 10} (10 total users)

開啟 GUI 畫面

手動在 browser 打開http://localhost:8089網址。

畫面一: 指定模擬用戶人數與測試網站

畫面二: 開始執行後可以看到正在跑的工作清單與統計過程

畫面三: 開始執行後也可以看到時序變化圖形

(EOF)

Last updated