8.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("/admin/auth/user/")
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', 'admin'),
'password': os.environ.get('LOCUST_PASSWORD', 'password')
},
headers={'X-CSRFToken': csrftoken})
Add CPU Resources#
To get the most out of this test, let’s increase the CPU resource request of
your pod. Change the resource request in deployment/pod.yaml to this:
resources:
requests:
cpu: 1000m
memory: 512Mi
ephemeral-storage: 10Mi
limits:
cpu: 1000m
memory: 512Mi
ephemeral-storage: 10Mi
Make sure you apply the new pod definition. You’ll need to delete the old pod first then recreate it:
$ kubectl delete pod/django
$ kubectl apply -f deployment/
Use kubectl describe to verify the resources have increased and visit the IP
address of your site to make sure it works.
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.