The Wayback Machine - https://web.archive.org/web/20241127143022/https://www.geeksforgeeks.org/load-testing-using-locust/
Open In App

Load testing using LOCUST

Last Updated : 30 Oct, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Locust is an open-source load-testing tool. Load testing is a type of software testing that is conducted to check the tolerance/behavior of the system under a specific expected load. The target of locust is load-testing websites and checking the number of concurrent users a system can handle. During a locust test, a swarm of locusts will attack the target i.e website. The behavior of each locust is configurable and the swarming process is monitored from a web UI in real time. 

Specialty of locust:

  • Test scenarios can be written in Python
  • Distributed and scalable
  • Web-based UI
  • Any system can be tested using this tool

Installation: Locust can be installed with pip.

pip install locust

Once the locust is successfully installed, a locust command should be available in your shell. To see more available options:

locust --help

Getting started: 

Python3




from locust import HttpUser, TaskSet, task
from locust import ResponseError
import json
 
 
class UserBehavior(TaskSet):
 
    def __init__(self, parent):
        super(UserBehavior, self).__init__(parent)
        self.token = "
        "
        self.headers = {}
 
    def on_start(self):
        # The on_start method is called
        # when a simulated user starts
        # executing that TaskSet class
        self.token = self.login()
        self.headers = {'Authorization': 'Bearer {}'.format(self.token)}
        self.login()
 
    def login(self):
        # admin login  and retrieving it's access token
        response = self.client.post( & quot
                                    / login/"
                                    ,
                                    data={'username': 'admin',
                                           'password': 'ZYT5nsg3565!'})
 
        return json.loads(response._content)['access']
 
 
class WebsiteUser(HttpUser):
    # The task_set attribute should point
    # to a TaskSet class which defines
    # the behaviour of the user
    task_set = UserBehavior
    min_wait = 5000
    max_wait = 9000


Start locust: To run the above code, create a Python file named locustfile.py, and open the terminal in the directory of the above created file. Then write the following command in the terminal.

locust

Note: By default locust searches for locustfile.py. After the successful execution of the above command, you should open a browser and hit http://127.0.0.1:8089 The Locust UI will appear like below:



Previous Article
Next Article

Similar Reads

How to save and load cookies in Selenium using Python
In web automation and testing, maintaining session information across different runs of scripts is often necessary. Cookies are a great way to save session data to avoid logging in repeatedly. Selenium, a popular tool for web testing, provides straightforward ways to save and load cookies using Python. In this article, we will learn all the steps t
4 min read
numpy.load() in Python
numpy.load() function return the input array from a disk file with npy extension(.npy). Syntax : numpy.load(file, mmap_mode=None, allow_pickle=True, fix_imports=True, encoding='ASCII') Parameters: file : : file-like object, string, or pathlib.Path.The file to read. File-like objects must support the seek() and read() methods. mmap_mode : If not Non
2 min read
How to Dynamically Load Modules or Classes in Python
Python provides a feature to create and store classes and methods and store them for further use. The file containing these sets of methods and classes is called a module. A module can have other modules inside it. Note: For more information, refer to Python Modules Example: A simple example of importing a module is shown below in which, there are
3 min read
Save/load game Function in Pygame
Pygame is a free-to-use and open-source set of Python Modules. And as the name suggests, it can be used to build games, and to save game data or the last position of the player you need to store the position of the player in a file so when a user resumes the game its game resumes when he left. In this case, the text file with JSON format stores the
4 min read
Load JSON String into Pandas DataFrame
Let us see how can we use a dataset in JSON format in our Pandas DataFrame. This can be done using the built-in read_json() function. It enables us to read the JSON in a Pandas DataFrame. Example : Consider the JSON file path_to_json.json : # importing the module import pandas # reading the file data = df.read_json("path_to_json.json") #
1 min read
How to Load a Massive File as small chunks in Pandas?
Pandas in flexible and easy to use open-source data analysis tool build on top of python which makes importing and visualizing data of different formats like .csv, .tsv, .txt and even .db files. For the below examples we will be considering only .csv file but the process is similar for other file types. The method used to read CSV files is read_csv
3 min read
Python - Difference Between json.load() and json.loads()
JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load a
3 min read
How to use Pickle to save and load Variables in Python?
Serialization is a technique used to save the state of an object from any process. We can later use this state by deserialization, to continue the process. Pickle is a python module that makes it easy to serialize or save variables and load them when needed. Unlike JSON serialization, Pickle converts the object into a binary string. JSON is text sp
2 min read
How to load a TSV file into a Pandas DataFrame?
In this article, we will discuss how to load a TSV file into a Pandas Dataframe. The idea is extremely simple we only have to first import all the required libraries and then load the data set by using various methods in Python. Dataset Used: data.tsv Using read_csv() to load a TSV file into a Pandas DataFrame Here we are using the read_csv() metho
1 min read
Load NumPy data in Tensorflow
In this article, we will be looking at the approach to load Numpy data in Tensorflow in the Python programming language. Using tf.data.Dataset.from_tensor_slices() function Under this approach, we are loading a Numpy array with the use of tf.data.Dataset.from_tensor_slices() method, we can get the slices of an array in the form of objects by using
2 min read
Load CSV data in Tensorflow
This article will look at the ways to load CSV data in the Python programming language using TensorFlow. TensorFlow library provides the make_csv_dataset( ) function, which is used to read the data and use it in our programs. Loading single CSV File To get the single CSV data file from the URL, we use the Keras get_file function. Here we will use t
2 min read
Load text in Tensorflow
In this article, we are going to see how to load the text in Tensorflow using Python. Tensorflow is an open-source Machine Learning platform that helps to create production-ready Machine Learning pipelines. Using Tensorflow, one can easily manage large datasets and develop a Neural network model in a few lines of code. These large datasets may incl
3 min read
How to load CSV data from the local to Snowflake?
In today's data-driven world, efficient data management and transfer are critical for business success. Snowflake, a powerful cloud-based data warehousing solution, allows organizations to store and analyze vast amounts of data seamlessly. In this article, we will cover everything from the basics to step-by-step instructions to load CSV to Snowflak
4 min read
How to Fix 'NoSuchModuleError: Can't Load Plugin: sqlalchemy.dialects.postgres.psycopg2' in Python
SQLAlchemy is a powerful SQL toolkit and Object-Relational Mapping (ORM) library for Python. It facilitates interaction with various databases using Python code. However, while working with SQLAlchemy, developers may encounter the error: NoSuchModuleError: Can't Load Plugin: sqlalchemy.dialects.postgres.psycopg2. This error indicates a problem with
3 min read
json.load() in Python
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json . To use this feature, we import the json package in Python script. The text in JSON is done through quoted
4 min read
How To Load Csv File In Jupyter Notebook?
Loading a CSV (Comma Separated Values) file in Jupyter Notebook allows you to work with tabular data conveniently. This process is fundamental for data analysis and manipulation tasks. To load a CSV file in Jupyter Notebook, we can use the Pandas library, which provides easy-to-use functions for reading and manipulating tabular data. Load the CSV f
4 min read
Performing BVA Testing using Pytest
Prerequisite - BVA Testing To perform automated BVA(Boundary Value Analysis) Testing, we can use Pytest or Unittest libraries in Python. Here, we will use the Pytest library to execute test cases written for a simple program. We'll be perform BVA Testing for a program that determines the type of the triangle (i.e. Equilateral, Isosceles, Scalene or
4 min read
Mutation Testing using Mutpy Module in Python
Prerequisite: Mutation Testing Mutpy is a Mutation testing tool in Python that generated mutants and computes a mutation score. It supports standard unittest module, generates YAML/HTML reports and has colorful output. It applies mutation on AST level. Installation: This module does not come built-in with Python. To install it type the below comman
5 min read
Testing in Python using Doctest module
Docstrings in Python are used not only for the description of a class or a function to provide a better understanding of the code and use but, also used for Testing purposes. Testing is a critical aspect of software development that ensures code functions as expected and guards against bugs. In Python, the Doctest module provides a simple yet power
8 min read
Performing Equivalence Class Testing using Pytest
Prerequisite - Equivalence Class Testing To perform automated Equivalence Class Testing, we can make use of Pytest or Unittest Python libraries. In this article, we will use the Pytest library to execute test cases for a simple program. Question : Perform Equivalence Testing for a program that determines the type of triangle given the length of its
4 min read
Python | Exceptional Conditions Testing in Unit Tests
This article aims to write a unit test that cleanly tests if an exception is raised. To test for exceptions, the assertRaises() method is used. Code #1 : Testing that a function raised a ValueError exception import unittest # A simple function to illustrate def parse_int(s): return int(s) class TestConversion(unittest.TestCase): def test_bad_int(se
2 min read
Python | Testing Output to stdout
Testing is a critical part of development as there is no compiler to analyze the code before Python executes it. Given a program that has a method whose output goes to standard Output (sys.stdout). This almost always means that it emits text to the screen. One likes to write a test for the code to prove that, given the proper input, the proper outp
2 min read
PyQt5 QColorDialog - Testing Color Dialog Options
In this article we will see how we can check the option of the QColorDialog widget. There are basically three dialog options available for the QColorDialog widget, below is the options 1. ShowAlphaChannel : Allow the user to select the alpha component of a color 2. NoButtons : Don't display OK and Cancel buttons 3. DontUseNativeDialog : Use Qt's st
2 min read
Object oriented testing in Python
Prerequisite: Object-Oriented Testing Automated Object-Oriented Testing can be performed in Python using Pytest testing tool. In this article, we perform object-oriented testing by executing test cases for classes. We write a program that has one parent class called Product and three child classes - Snack, Beverage, and Staples. We implement all th
5 min read
Training vs Testing vs Validation Sets
In this article, we are going to see how to Train, Test and Validate the Sets. The fundamental purpose for splitting the dataset is to assess how effective will the trained model be in generalizing to new data. This split can be achieved by using train_test_split function of scikit-learn. Training Set This is the actual dataset from which a model t
7 min read
How to split data into training and testing in Python without sklearn
Here we will learn how to split a dataset into Train and Test sets in Python without using sklearn. The main concept that will be used here will be slicing. We can use the slicing functionalities to break the data into separate (train and test) parts. If we were to use sklearn this task is very easy but it can be a little tedious in case we are not
2 min read
How to Use Pytest for Unit Testing
Unit Testing is an important method when it comes to testing the code we have written. It is an important process, as with testing, we can make sure that our code is working right. In this article, we will see how to use Pytest for Unit Testing in Python. Pytest for Unit TestingStep 1: InstallationTo use Pytest for unit testing, we first need to in
5 min read
How To Add Unit Testing to Django Project
Unit testing is the practice of testing individual components or units of code in isolation to ensure they function correctly. In the context of Django, units typically refer to functions, methods, or classes within your project. Unit tests are crucial for detecting and preventing bugs early in development, ensuring that your code behaves as expect
4 min read
Training data vs Testing data
There are two key types of data used for machine learning training and testing data. They each have a specific function to perform when building and evaluating machine learning models. Machine learning algorithms are used to learn from data in datasets. They discover patterns and gain knowledge. make choices, and examine those decisions. In this ar
7 min read
Testing FastAPI Application
The web framework in Python that is used for creating modern and fast APIs is called FastAPI. Once we have created the FastAPI, there is a need to test if the API is working fine or not according to the requirements. In this article, we will discuss the various ways to test the FastAPI application. Testing FastAPI ApplicationBelow are the methods b
3 min read
three90RightbarBannerImg