Skip to content

[Python] 使用 Locust 開源壓力測試框架進行壓力測試

Last Updated on 2024-10-09 by Clay

Locust 是一個開源的壓力測試工具,它能幫助我們模擬大量使用者對 Web 應用、API 服務進行負載測試;與傳統的壓力測試工具相比,Locust 具有可客製化、可擴展的優勢 —— 簡單來說,它支持 Python 作為腳本語言,根據我們 API 或網頁服務的不同應用場景來寫測試。


(可選)使用 FastAPI 開幾個模擬的 API 服務

如果我們要使用 Python 開啟幾個 FastAPI 服務,首先需要安裝套件:

pip install fastapi unicorn[standard]


接著就可以寫幾個模擬的 API 服務:

from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.get("/api/home")
async def home():
    return {"message": "Welcome to the homepage!"}

@app.get("/api/about")
async def about():
    return {"message": "About page content."}

@app.post("/api/contact")
async def contact_form(name: str, email: str):
    if not name or not email:
        raise HTTPException(status_code=400, detail="Name and email are required.")
    return {"message": f"Form submitted with name: {name} and email: {email}"}


接著啟動我們的服務:

uvicorn app:app --reload


Output:

INFO:     Will watch for changes in these directories: ['/home/clay/Projects/Locust-Testing']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [36647] using WatchFiles
INFO: Started server process [36649]
INFO: Waiting for application startup.
INFO: Application startup complete.


這樣一來,我們準備的三個 API 服務就完成了。


使用 Locust 做壓力測試

首先安裝 locust

pip3 install locust


接著寫下測試的腳本設定檔 locust_test.py

from locust import HttpUser, task, between

class WebsiteUser(HttpUser):
    wait_time = between(1, 3)
    host = "http://127.0.0.1:8000"

    @task(3)
    def load_homepage(self):
        self.client.get("/api/home")

    @task(2)
    def load_about_page(self):
        self.client.get("/api/about")

    @task(1)
    def submit_contact_form(self):
        self.client.post("/api/contact", data={"name": "John", "email": "[email protected]"})
locust -f locust_test.py 


Output:

[2024-10-09 22:48:11,553] notebook/INFO/locust.main: Starting Locust 2.31.8
[2024-10-09 22:48:11,554] notebook/INFO/locust.main: Starting web interface at http://0.0.0.0:8089


Output:


References


Read More

Tags:

Leave a Reply