Skip to content

[Python] Using Locust Open Source Load Testing Framework for Stress Testing

Last Updated on 2024-10-23 by Clay

Locust is an open-source load testing tool that helps simulate heavy user traffic on web applications and APIs. Compared to traditional load testing tools, Locust offers more customization and scalability—it supports Python as the scripting language, allowing us to write tests specific to our API or web service use cases.


(Optional) Use FastAPI to Start Some Mock API Services

To use Python to start a few FastAPI services, we first need to install the necessary packages:

pip install fastapi uvicorn[standard]


Next, we can write a few mock API services:

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}"}


Then, we start our service:

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.


With that, our three API services are ready.


Using Locust for Load Testing

First, install locust.

pip3 install locust


Next, write the test script configuration file 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