9.2. Stress Testing with Locust#

Locust is an open source load testing tool written in Python. In this lab you’ll learn how to assess how your application scales by sending it lots of requests.

Locustfile#

Locust needs a Python-based description of how to access your application. Here’s an example that’s all you need. The example code will try to login. It’s not necessary that the login succeed but for the truest results you should make sure that the locust user is registered for your site with the password locust.

Put the following code into a file called locustfile.py in the root of your repository.

import os 

from locust import HttpUser, task

class HelloWorldUser(HttpUser):

    @task
    def hello_world(self):
        self.client.get("/")

    def on_start(self):
        response = self.client.get('/admin/login/?next=/admin/')
        csrftoken = response.cookies['csrftoken']
        self.client.post('/admin/login/?next=/admin/',
            {
            'username': os.environ.get('LOCUST_USER', 'locust'),
            'password': os.environ.get('LOCUST_PASSWORD', 'locust')
            },
            headers={'X-CSRFToken': csrftoken})

Run Locust#

In your development environment (container or Cloud Shell) use pip to install the locust package:

$ pip install locust 

Now run locust:

$  locust
[2024-03-18 20:22:11,421] mouthfeel/INFO/locust.main: Starting web interface at http://0.0.0.0:8089 (accepting connections from all network interfaces)
[2024-03-18 20:22:11,437] mouthfeel/INFO/locust.main: Starting Locust 2.15.1

Notice that Locust is now waiting on a port. Connect with your browser using port forwarding in vscode. When you’re done with Locust you can stop the server with ctrl-c.

Use the Locust Web Interface#

In class I demonstrate how to use the web interface. Make a note of the maximum requests per second.