DEV Community

Cover image for Getting Started with Load Testing using Locust
Burhanuddin Ahmed
Burhanuddin Ahmed

Posted on • Updated on

Getting Started with Load Testing using Locust

What is Locust

Locust is a load testing tool written in Python. The test script is also written in Python. To use this tools, you need at least very basic knowledge of Python.

https://locust.io/

Across many testing framework, Locust is quite simple and having pretty good and simple UI. You only need to install Python in your machine and just install the tools.

How to install it

Installing Locust is quite simple, just need pip and you can run it.

pip install locust
Enter fullscreen mode Exit fullscreen mode

I usually using virtual env before installing the tools.

Create a virtual env

python3 -m venv venv
Enter fullscreen mode Exit fullscreen mode

Activate the venv

source venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

Then you can run Locust here

Create the testing script

This one simple example to load test on login API.

# index.py

from locust import HttpUser, task, between

class LoginUser(HttpUser):
    wait_time = between(2, 5)  # Wait time between simulated users

    @task
    def login(self):
        # Define the payload for the login request
        login_payload = {
            'username': 'your_username',
            'password': 'your_password'
        }

        # Send a POST request to the login endpoint
        response = self.client.post('/login', json=login_payload)

        # Check if the login was successful
        if response.status_code == 200:
            print("Login successful")
        else:
            print("Login failed")

Enter fullscreen mode Exit fullscreen mode

Now let say, your API needs a token before you hit it, this how we will do it.

from locust import HttpUser, task, between

class UserApiTest(HttpUser):
    wait_time = between(2, 5)  # Wait time between simulated users

    def on_start(self):
        # Log in and get the authentication token
        login_payload = {
            'username': 'your_username',
            'password': 'your_password'
        }
        response = self.client.post('/login', json=login_payload)
        if response.status_code == 200:
            self.auth_token = response.json().get('token')
        else:
            print("Login failed")

    @task
    def get_users(self):
        # Send a GET request to the /users endpoint with the authentication token
        headers = {'Authorization': f'Bearer {self.auth_token}'}
        response = self.client.get('/users', headers=headers)

        # Check if the request was successful
        if response.status_code == 200:
            print("Get users successful")
        else:
            print("Get users failed")

Enter fullscreen mode Exit fullscreen mode

Run it!

To run it, it's very simple.

locust -f index.py
Enter fullscreen mode Exit fullscreen mode

Top comments (0)