Skip to content

Ferdinand Agyei-Yeboah

Locust Performance Testing

March 16, 2022

Background

The biggest name when it comes to performance testing is Jmeter. However, Jmeter isn’t very initituive to set up, even for a simple test.

Locust is a great alternative, and in my opinion, much easier to use than Jmeter. Locust performance tests are written in python code, meaning you have the power of a programming language to construct your tests, making it a lot easier than searching and configuring plugins. If you simply need HTTP REST API performance testing, check out Locust.

The documentation can be found here. The rest of this post will be summarizing details that can be found in the documentation.

Installation

If you don’t have python 3.6+, install it. I recommend using pyenv to manage your python versions. (Below uses brew to do initial pyenv download, you can use anything else depending on your platform)

brew install pyenv -> pyenv install 3.7.6 -> pyenv global 3.7.6

Install Locust: pip install locust

How Locust Tests Work

Locust tests are simply python files, like below

from locust import HttpUser, task
class HelloWorldUser(HttpUser):
@task
def hello_world(self):
self.client.get("/hello")
self.client.get("/world")

This performance testing simply calls two api endpoints, one after another. More explanation below.

The User Class

All locust tests need to inherit from the HttpUser class to be able to run. The HttpUser represents a simulated user for the load test. The tests and tasks (more on that later) are written in mind that a single user is going to be “executing” the methods in the script. That means you wouldn’t write code that makes 4 http calls if you are trying to simulate 4 users, instead you would write code that makes 1 http call, and tell locust to run it simulating 4 users (more on that later).

The Task Decorator

Takes are the actual functions that will be executed in the performance tests. So any http calls you want the simulated users to invoke would be placed inside a method decorated with @task. If a function isn’t decorated with @task, it will not be executed automatically by locust. Non-decorated methods can be used as helper functions.

Making HTTP Calls

The HttpUser class comes with a http client in the form of self.client that you can use to make http calls. It uses the popular python requests package.

Running the tests

To run the tests execute: locust -f locust-file.py

When you run the tests, it will spin up the Locust UI which will ask you the users, spawn rate, and host to run the performance tests against.


Software Engineering Tutorials & Best Practices