How to Use Python to Load Test Websites

choubertsprojects

VPN offers!

1. NordVPN

2. Surfshark

3. ExpressVPN

Python is a powerful and flexible programming language, with many libraries available to help integrate into any application. This tutorial will show you how easy it is to load test websites using one of these Python libraries.

The “python performance testing pytest” is a way of using Python to load test websites. It is possible to use this tool with the Flask framework, which is an open-source web application framework written in Python.

How to Use Python to Load Test Websites

Consider the following scenario: you have a new online application that you know works well with a limited set of users. But how would your application react if the traffic surged above what was expected? Python may be used to load test your web application.

In this post, you’ll learn how to load test a web site by simulating hundreds of people simultaneously accessing it.

Continue reading to learn how to load test websites.

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

How to Generate an Azure SAS Token for Storage Account Access

Constructing a Static Website

You must first create a sample site before performing a load test against it. For this lesson, you’ll create a static website and a sample API, although you’ll concentrate on the static website first. A static website will teach you the fundamentals of load testing, while an API will show you how to provide various parameters to mimic various actions.

Related:How to Host a Cloudflare-Backed Azure Static Website

You may skip to the following phase, where you’ll install and run Locust on your workstation, if you wish to start conducting the load test against API. The Swagger Petstore demo API is used in the examples in this lesson.

  1. Create a new file in your favourite code editor, paste the code below into it, then save it with a name you want. The file name for this example is load test page.html.

When accessed in a web browser, the HTML document below shows the words “This is a test page.”

<!DOCTYPE html> <html> <head> <title>ATA Load Balancing Demo</title> </head> <body> <h1>This is a test page.</h1> </body> </html>

2. Then, on your chosen web browser, go to the Azure Portal and find your storage account.

3. To enable static website hosting inside a storage account and establish your website’s main page, follow the procedures below:

  • On the left-hand navigation panel, choose Static website. The files for your sample site will be uploaded to the Static website page.
  • To enable static website hosting, click Enabled, as shown below.
  • In the Index document name area, type load test page.html and save. This generates a blob container as well as a URL (main endpoint) that refers to your website. The URL will not work right now, but you can store it for later.

Static Website Hosting Enablement Static Website Hosting Enablement

4. In the left panel, go to Storage Explorer (Preview) and then to Blob Containers $web. All of your static files will be stored in the $web blob container, which was generated via the Static website feature.

After that, upload the load test page.html file you made in step one.

Static Files Uploading (HTML Page) Static Files Uploading (HTML Page)

5. Finally, open a new tab in your web browser and go to the URL you wrote down in step two to test whether it works now.

Accessing Static Website's URL Getting to the URL of a Static Website

Locust Framework Installation

You now have a website to test, but you’ll still need load testing software. Writing code to handle heavy load testing takes time and is prone to errors. Why not make use of the Locust framework instead? Locust is a Python-based open-source program that you may install using the pip package management.

Python functions for newcomers is a good place to start if you need to brush up on your Python.

Locust can do load testing on static websites, web apps, and APIs. The only stipulation is that everything you’re testing has an HTTP(S) endpoint that your device can access.

On Linux and MacOS, the pip package manager by default installs packages in the /.local directory, which is not on the system path. Because that route is only accessible in a Python virtual environment, you’ll utilize pip in this tutorial.

  1. To build a new virtual environment and install Locust, open your terminal and enter the instructions below.

# python3 -m venv venv python3 -m venv venv python3 -m venv venv python3 -m venv venv python3 -m venv venv # Run venv/bin/activate to activate the virtual environment. python3 -m pip install locust in the new virtual environment set up locust

In a virtual environment, start and install locust. In a virtual environment, start and install locust.

2. Create a new directory and go to it using the instructions below. This separates the locust files from the rest of your codebase, making them simpler to manage. The locust dir directory is used in this example.

locust dir cd locust dir mkdir locust dir

3. Finally, in the locust dir directory, create a new file named locustfile.py, and copy/paste the code below into it. This file will include your test instructions, such as how to imitate users, which endpoints they’ll access, and which arguments to send along.

When Locust is started, it searches for a file called locustfile.py. So store that file in a different directory (locust dir) so Locust can discover it and you may build new tests without overwriting existing ones.

The code below runs an HTTP GET request against the path of the hostname you provide, which is equivalent to running curl http://<Host>/ from the command line.

When Locust receives a response, it instantly sends the next request, and the procedure is repeated for each virtual user in the test.

# Locust import HttpUser, task # Create a new virtual user class HelloWorldUser(HttpUser): # This instructs locust to consider the function below # as though it were performed by a virtual user @task # Create a new method with the name hello world(self): # This method will make an HTTP GET call to the site you’re testing self.client on the route ‘/’. get(“/”)

If the method’s route seems to be incomplete, it is because it is. In a locust file, just the path and query parameters are specified, while the host is provided at runtime. In the following phase, this strategy will make more sense.

Python Functions for Newbies is related to Getting Started: Python Functions for Newbies.

Performing a Load Test on Static Websites

It’s time to conduct a load test now that you’ve loaded Locust! Load testing is more than just sending a series of web requests to check how well your application performs. Across many endpoints and settings, a comprehensive test collects response times, failure rates, and error codes.

Locust may be operated from the command line or via a web interface, giving it a lot of flexibility. In this article, you’ll perform a load test against a static site using the web interface.

Start the locust graphical program using the test scenario from your locustfile.py file by running the locust command.

Activate the locust command.Activate the locust command.

2. To access Locust, open a web browser and go to http://localhost:8089/. Locust uses the 8089 port as its default port.

Remember the URL (primary endpoint) that you noted in step three under the “Constructing a Static Website” section? Now is the time to use it in the next step!

3. Finally, in the Host section (as seen in the picture below), enter the URL (main endpoint) and click Start swarming to begin the load test. Any tests in your locustfile.py will run against the URL you supplied in the Host box if you do so.

Changing the value of the Number of users or Spawn rate variables is optional for this example.

The number of users is the maximum number of virtual users that may be created at the same time. At the same time, the Spawn rate is the number of new users produced per second until Locust achieves maximum virtual user concurrency. Until you finish the test, the number of virtual users remains at its maximum.

1647497644_608_How-to-Use-Python-to-Load-Test-Websites Locust load test is running on localhost:8089.

Locust adds the host while running tests, then makes a request to each route in the user class in real-time. When Locust receives an answer, it quickly sends another.

Below is a list of the endpoints that were tested, along with some information on response times, errors, and requests per second.

Viewing the Locust Chart for the Test Case, which shows the number of requests, failures, and response times. Viewing the Locust Chart for the Test Case, which shows the number of requests, failures, and response times.

Click on the Charts tab to display your website’s performance data in a graphical format, as shown below.

Statistics from load testing may be shown in a graphical format. Statistics from load testing may be shown in a graphical format.

Performing a Load Test on APIs

Let’s look at a more realistic test scenario now that you’re acquainted with the fundamentals of Locust. When it comes to performance testing, a static site is rather steady, and there isn’t much that can go wrong. So, what’s the point of doing a load test against an API?

An API has a lot more unpredictability in answers, fewer dependable hosting alternatives, and a lot more potential effect on your business if it goes down.

If you’re unfamiliar with APIs and how they function, there’s an article that covers the fundamentals, such as authentication, HTTP methods, and JSON answers. Although this essay is focused on PowerShell, the API principles will be useful later on.

  1. Replace the contents of the locustfile.py file with the following code, which accomplishes many goals:
  • When Locust creates a new virtual user, it sends a GET request to authenticate the user.
  • Executes a GET request on the host, which fails since the resource isn’t available.
  • Sends a POST request with a JSON body to a set of objects in the same endpoint.

import time # Importing time from Python system library from locust import HttpUser, task class HelloWorldUser(HttpUser): # This task will run when the user is instanciated def on_start(self): # The petstore API doesn’t have a user database, # so any username and password will work username = “foo” password = “bar” # This needs to conform to the loginUser endpoint from the API docs self.client.get(“/user/login?username=”+username+”&password=”+password) # This task will fail because there is no endpoint at https://petstore.swagger.io/v2/ @task def hello_world(self): self.client.get(“/”) # The (3) after the task decorator tells Locust to run this task 3 times as often @task(3) def update_pets(self): # Using a for loop, count from 0-4 and use in HTTP request below for pet_id in range(5): # Run HTTP POST request and pass a JSON Body self.client.post(f”/pet?petId={pet_id}”, json={“name”:”Mittens”}) time.sleep(1) # Wait for 1 second before continuing

Other methods would produce a “403 Not Authorized” response if Locust attempted to test them without a on start line in your test class. To check how this technique impacts the test, comment it out and rerun Locust.

Understanding Python Loops and Flow Control: A Beginner’s Guide

2. Next, go to the pet shop API documentation. Because the test case above was designed expressly for this API, having this page open while following along with this tutorial will make it easier to navigate the endpoints.

Activate the locust command. below as you did in the “Performing a Load Test on Static Websites” section (step one).

Activate the locust command.Activate the locust command.

Finally, in the Locust UI, enter https://petstore.swagger.io/v2 as the host.

Endpoints of the pet shop API that are being tested are being viewed.Endpoints of the pet shop API that are being tested are being viewed.

Conclusion

You learnt how to perform a load test against a static website and an API in this lesson. Now you know how to prepare your website for a significant flood of visitors. When preparing an application for release to clients, load testing comes in helpful. Testing auto-scaling configurations or application performance for low latency is the same.

Consider the programs you now use or those you support. How would they react if a swarm of people tried to utilize it at the same time? What do you believe load test scenarios may reveal in order to improve the performance of your application?

The “python load testing library” is a Python library that allows for the creation of load tests. It’s easy to use and allows for quick development.

Related Tags

  • python load testing tools
  • python load testing rest api
  • locust python
  • python website testing
  • how to use locust for load testing