Learn Steps

How to do load testing using locust and python for your applications.

Load testing or performance testing is used to make sure that your application perform at very high traffic or at least the traffic that you intended it to run. In this article we are going to talk about how we can use locust to do load testing for our application or api. With simple knowledge of python you can easily do a load testing for your application. Lets see how to do load testing using locust.

Locust is an open source load testing tool which we will be using here to de a load testing on one of our application.

Installation:

pip install locustio

This will install locust and now we will write file to run the load test. Look at the below code. This code is simple python code.

Usage:

from locust import HttpLocust, TaskSet, task

HEADERS = {
'Content-Type': 'application/json'
}


class MyTaskSet(TaskSet):
    @task(10)
    def users(self):
        self.client.get("/api/url1", headers=HEADERS)

    @task(10)
    def test2(self):
        self.client.get("/api/url2", headers=HEADERS)

class MyLocust(HttpLocust):
    task_set = MyTaskSet
    min_wait = 1000
    max_wait = 5000

Here the we defined two classes, MyLocust class which inherits HttpLocust class and MyTaskSet class which inherits TaskSet class.

In MyLocust class we define(override the parameters that we will be using).
min_wait, max_wait are the minimum and maximum time  in milliseconds, that a simulated user will wait between executing each task.

MyTaskSet is the task that the users will simulate. It contains two apis to hit /api/url1 and /api/url2.

Now we need to run the below command to start the load test.

locust -f name_of_file.py --host=the_host_where_your_app_running
example: locust -f load.py --host=http://example.com

Now if will give you an url to open in browser and from there you can run the test, you can specify the number of user to simulate and rate to spawn the users.

Once you fill the values it will start running and will start giving the results like below.

Now that this is just one machine and it will be tough to push significant load on application in this case you can run it in master slave mode. You can use the below command to run it.

To run master

locust -f name_of_file.py --host=the_host_where_your_app_running --master

To run slaves

locust -f name_of_file.py --host=the_host_where_your_app_running --slave --master-host=ip_of_master

This was how you can use locust for load test your application.

If you like the article please share and subscribe.