Gatling Tutorial: Getting Started With Gatling Load Testing

This Gatling Video Tutorial provides a Comprehensive Review of Gatling including Features, Installation Steps, and Examples Of using Gatling Simulation Recorder:

Gatling is an open-source testing framework based on Scala. It’s gaining a lot of popularity these days with more than 3 million downloads in the last 3 years.

It is available as an open-source as well as an enterprise variant called Gatling Frontline with more integrations and support from the Gatling team. But all practical use cases can be worked upon using the Gatling community edition which is free and an open-source.

Gatling Tutorial

List Of Tutorials In This Gatling Series:

Tutorial #1: Introduction to Gatling: Installation, Execution and Other Features [This Tutorial]
Tutorial #2: Gatling End to End Script: Creating Gatling Project using Maven Archetype
Tutorial #3: Understanding the Feature-Rich HTML Based Gatling Reports


Gatling Video Tutorial

Let’s see the steps required to get started with Gatling. We will also cover some of the important features of Gatling as part of this tutorial.

Here is a video tutorial on Gatling Introduction:

Installation

Gatling can be installed in 2 different ways. This can be explained as follows:

#1) Using Gatling as a standalone tool, you can simply install the installer/application, using the official Gatling website and follow the installation instructions.

Please note that the installed zip folder contains both shell and batch files which makes Gatling suitable to be used across different operating systems like – Windows, MacOS, Linux/Unix, etc.

The installer is nothing but a Java-based Gatling script recorder, which records user actions through the browser in the tool and which could then be converted into a script or scenario that needs to be load and tested. We will see this in detail in the upcoming sections.

#2) Another way to install/use Gatling is by using it as a package through Maven/Gradle or through Scala build tools.

An important point to note here is that Gatling scripts are all Scala-based, hence creating a Scala-based project could use the Gatling library which can be imported by any build tools like Maven/Gradle or SBT.

Features Of Gatling

These are as follows: 

#1) Asynchronous Architecture & Lightweight Threads

Gatling has an advanced architecture based on the Akka toolkit and is fully asynchronous. This gives it an upper hand in comparison to other performance testing tools like JMeter where each thread corresponds to a single user.

Here, a single thread can simulate multiple users as it has a messaging architecture through the Actor model.
In a nutshell, a Gatling test can handle a number of concurrent users per machine as compared to other tools like Jmeter and hence results in a considerable saving in CPU and RAM.

Recommended Reading=> Actor model and Asynchronous architecture of Gatling 

#2) Domain Specific Language makes tests readable

Gatling scripts are written in Scala and have a friendly DSL which makes the scripts highly readable and less prone to errors. For more details around Gatling DSL, please refer here.

#3) Protocol Agnostic Support

Gatling supports a wide variety of protocols including HTTP, HTTPS, and Web sockets. It also has extensions for load testing SQL queries/scripts.

#4) Reporting and Assertions

Gatling provides out of the box support for creating detailed HTML reports for the scenarios that are executed and also has capabilities to apply assertions on the individual requests in scenarios – For example, Response times, JSON content validation, etc.

#5) Friendly GUI based test recorder

Gatling comes with an easy to use graphical test recorder which can generate simulation script by recording user activity or user actions on a web browser. The generated scripts are Scala-based scripts that could be executed at a future time and can be modified as per the requirements.

Application Under Test And Sample Script Recording

For creating sample simulation, we will use Gatling’s officially provided hosted application

We will be using Gatling’s simulation recorder to get started with creating load and doing performance testing. Before going further, let’s discuss the scenario where we want to load test.

The scenario is a use case that we are trying to load test. What this, it essentially means that we want to imitate a user action into a scenario or set of steps that need to be put under test.

For example, suppose a user accesses any eCommerce website like Amazon.com and searches for a product and adds it to the cart and finally checkout with the payment information.

This entire user action is a single scenario which contains individual steps like

  • Navigating to website Amazon.com.
  • Waiting for the page to load.
  • Searching for a product through the product search bar.
  • Adding the product to the cart.
  • Going to cart and checkout with the product.
  • Making the payment.

In order to load test this complete scenario, from system or server perspective, we need to understand that it’s nothing but a collection or series of API calls that are being made to the backend server, and that’s what we want in the performance test.

For this example, we will use the below scenario on Gatling hosted application:

#1) Navigate to Gatling hosted application.

Computer Database

#2) Click on “Add a new computer”.

#3) Select Computer name as Apple and company name as “Apple Inc” from the dropdown as shown in the below image.

add-new-computer

#4) Click on ‘ Create this computer’ after entering the details.

Click on ' Create this computer'

Setup Gatling Recorder And Record The First Script

In this section, we will discuss how to set up the Gatling test recorder to create a simulation for the scenario that we have discussed in the previous section.

We will be using Gatling simulation recorder which is in a very simple form, an HTTP proxy – you must be familiar with other HTTP recording tools like Fiddler or chrome Http proxy, etc. So, the Gatling recorder is similar to additional features of converting the recording into a test simulation script.

So let’s first see how to set up the Gatling recorder:

#1) Once the Gatling zip folder is installed, simply unzip the folder to the location where you want the Gatling to be installed.

#2) After this step, we need to set 2 environment variables named – GATLING_HOME (for Gatling home directory) and GATLING_CONF (for the config folder location of Gatling).

Depending upon the type of OS, (i.e. Windows or Mac or Linux), set these environment variables with below values:

GATLING_HOME={gatling-install-directory}

Example:

GATLING_HOME=/Users/username/gatling-charts-highcharts-bundle-3.3.0/

GATLINE_CONF = {gatling-install-directory}/conf

Example:

GATLING_CONF=/Users/username/gatling-charts-highcharts-bundle-3.3.0/conf

Once the variables are set to validate, you can simply hit on the terminal the command – export | grep “GATLING” and the output should show the 2 environment variables that we have just set.

set 2 environment variables

#3) Once these environment variables are set then we need to start our Gatling script recorder. For windows-based OS, there is a batch file provided with Gatling installation and for Linux/MacOS based OS, there is a shell file provided.

Below is the file structure of the bin folder:

file structure of the bin folder

#4) So, depending on the OS type, we can choose the filetype to execute for the running recorder. Please note that there are 2 files here that we will be using:

  • Gatling.sh / Gatling.bat file – to run the simulation script.
  • Recorder.sh / recorder.bat file – to run/open the Gatling simulation recorder.

#5) Lets run the recorder script to open the Gatling recorder. Use Mac/Linux terminal to run the shell script (or directly run theWindows batch file).

. /$GATLING_HOME/bin/recorder.sh

#6) If the environment variables are set properly, then the above command should open the Gatling script recorder.

#7) Notice the Http/https port in the recorder (default selection is 8000 or 8080) – this is the port where the Http traffic proxy listener of Gatling is configured. We can change this port number as per our convenience (or we can continue with default values).

#8) Now let’s configure the chrome proxy to listen to this port – i.e. essentially we want to route our Http traffic from the browser through this proxy listener or recorder.
Follow this link to set up a proxy on chrome for different OS.

#9) Once the port is configured, we will then execute our scenario on the Gatling hosted application.

#10) Before the scenario execution starts, we will first need to configure the package name and class name for the resultant test script and then start the proxy listener by simply clicking on the “Start” button in the script recorder.

start-proxy-listener

#11) As soon as the proxy recorder starts, a new window will show up, and essentially it captures all the requests that are fired when the scenario gets executed on the browser.

gatling-recorder

#12) Navigate to Gatling hosted application in the browser.

If you can see the request is recorded in the recorder window, that means that the proxy setup for browser is correct and Gatling recorder is now able to record the requests as per the test scenario that is being executed (if not go back to step #7 to fix the proxy configuration for browser/system).

Request from browser

#13) Now, once we are sure that the setup is working fine, click on “Clear” to remove everything from the recorder and begin executing the scenario as mentioned below:

  • Navigate to Gatling hosted application
  • Click on “Add a new computer button”. Ensure that you land up on a new computer form with browser URL as http://computer-database.gatling.io/computers/new
  • Now fill in values in the form with – Computer name as Apple and company as “Apple inc” as well from the dropdown.
  • Click on “Create this computer” and you will get redirected to the homepage
  • This is the entire scenario that we want to execute and create an automation script using the Gatling script recorder. Once the above steps are executed, the recorder should capture all the HTTP calls being made and should look like below.

recorder captures all the HTTP calls being made

  • Please note that there are a couple of “PAUSE” commands as well in the recorded script. These are nothing but the “think-time” that the recorder captures to imitate user action – i.e. the time taken between requests. These values can be configured/changed once the script is executed depending upon real neds.

#14) In order to complete the script creation, click “Stop & Save” on the recorder window.

#15) The simulation script should get created in the directory or simulation folder that’s displayed on the Gatling recorder configuration screen.

Select a request to see details

Understanding The Simulation Script

Once the script for the executed scenario is created, navigate to the simulation folder and open the script.

Please note that the script will get created as the same package structured that was specified before starting the recorder – in our case, it will be com.learn.gatling and the class name will be “AddProduct”.

Let’s open the AddProduct.scala file and try to go through the different sections of the script.

This can be explained as follows:

#1) Setup Configuration: i.e httpProtocol and headers – In this section overall configuration of data for the script is done, such as:

  • Type of protocol – Http or https,
  • Other things like baseUrl to be used in subsequent requests.
  • Header information – common header information as well as the headers to be sent with individual requests. Refer to header_0 and headers_2 in the code snippet below:
val httpProtocol = http  
        .baseUrl("http://computer-database.gatling.io")  
        .inferHtmlResources(BlackList(""".*\.js""", """.*\.css""", """.*\.gif""", """.*\.jpeg""", """.*\.jpg""", """.*\.ico""", 
""".*\.woff""", """.*\.woff2""", """.*\.(t|o)tf""", """.*\.png""", """.*detectportal\.firefox\.com.*"""), WhiteList())  
        .acceptHeader
("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8, application/signed-exchange;v=b3")  
        .acceptEncodingHeader("gzip, deflate")  
        .acceptLanguageHeader("en-GB,en-US;q=0.9,en;q=0.8")  
        .upgradeInsecureRequestsHeader("1")  
        .userAgentHeader("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) 
Chrome/77.0.3865.120 Safari/537.36") 
val headers_0 = Map("Proxy-Connection" -> "keep-alive")
val headers_2 = Map(
		"Origin" -> "http://computer-database.gatling.io",
		"Proxy-Connection" -> "keep-alive")

#2) Scenario Definition: This contains the actual scenario and the order of requests that need to be executed in order to re-create the scenario that was running in the browser window.

Also, an important point to note here is – we’ve just mentioned relative URL’s here for the requests, instead of the complete URL. This is because we will use httpProtocol configuration we have discussed in point #1, where the scenario configuration data is defined.

val scn = scenario("AddProduct")  
        .exec(http("request_0")  
            .get("/computers")  
            .headers(headers_0)  
            .resources(http("request_1")  
            .get("/computers/new")  
            .headers(headers_0)))  
        .pause(4)  
        .exec(http("request_2")  
            .post("/computers")  
            .headers(headers_2)  
            .formParam("name", "apple")  
            .formParam("introduced", "")  
            .formParam("discontinued", "")  
            .formParam("company", "1"))  

#3) Scenario Execution: This section is the most important section which contains the scenario setup steps.

The inject configuration here is the number of users/threads or in other words, the load with which we want to test this scenario.

The default value for a number of users is always 1 and this can be changed before the scenario is executed.

Also, please note that we are also using the httpProtocol definition that we have discussed in point#1 which contains all the basic configurations for the scenario to be executed.

setUp(scn.inject(atOnceUsers(1))).protocols(httpProtocol)

We will be looking at more details around inject and load configuration in the next tutorial.

Executing Test Using Simulation Script

Now, we will see how to execute the scenario using this simulation script that was created using the recorder. The resultant script that gets created is actually a Scala-based class which contains details around the scenario that was executed through the browser.

Here is a video tutorial for Gatling Script Execution:

The Gatling installation comes with a shell script (for Windows users, it is a batch script) that could be used to execute this simulation.

Please follow the steps below to execute the created simulation:

#1) Navigate to the bin folder of the Gatling installation or simply go to – $GATLING_HOME/bin

#2) Execute the Gatling.sh file for Linux/Mac os (or the Gatling.bat file for Windows users).

#3) In case of multiple script files present in the simulation folder, the script will prompt the user to select the simulation that the user wants to run (To simulate this, create the same scenario in different packages, and when Gatling script is run, you can see that it displays 2 different scripts).

script files

#4) Simulation is selected (or it is set to default to the simulation present in the folder if there is just one simulation script available).

#5) The script now prompts to add an optional run description. You can simply ignore this and press enter to start the simulation execution.

#6) While the simulation is executing, you can see execution reports getting printed on the terminal and the parameters like response time, total requests, success/failures, etc summarized view will be displayed once the scenario execution completes.

gatling-execution-metrics

#7) Gatling also generates a detailed HTML based report at the end of the scenario execution completion which contains a lot of different data points with respect to the executed scenario.

We will look into the details of the generated report in the next tutorial.

Advantages Of Using Gatling

Gatling provides a lot of feature-rich capabilities in order to build a good performance automation test suite leveraging the wide Gatling DSL as well as growing community support for assistance and get queries answered.

It’s important to note here that unlike other tools like JMeter, Gatling does involve a steep learning curve, but in lieu of that, it gives a lot of programming capabilities to create a robust and fully functional set of performance and load testing simulation scripts.

Some of these advantages are as follows:

  • It’s lightweight and allows a single thread to be used for more than one request, unlike most other perf tools where a thread is equated to a user.
  • Using a single thread for multiple requests allows Gatling to scale more and generate greater load even through on a single Machine.
  • Gatling provides the capability to run in distributed mode when there’s a huge load that needs to be simulated.
  • Provides support for a lot of other protocols other than HTTP, for example, Websockets, MQTT, JDBC, etc all can be performance tested using Gatling.
  • Gatling provides a feature-rich DSL – Domain Specific Language, that has an easy syntax and provides powerful capabilities when combined to create a simulation script.
  • It also provides lots of complex simulation control capabilities like looping constructs, simulate think time, throttling requests beyond the desired RPS, etc.
  • It has rich reporting capabilities out of the box and they can be customized too depending on the requirements.

Conclusion

In this tutorial, we have touched upon the basics of using Gatling as a load testing tool of choice. With the expressive DSL and excellent support for HTTP Protocol, Gatling is fast gaining popularity to be used as a tool of choice for many.

We also learned about the Gatling recorder and Gatling script runner with a sample simulation script which helped to understand the basic concept of recording a simulation script which could be then executed in the future using the Gatling Script executor.

In the next tutorial, we will cover writing Gatling scripts as Scala projects – i.e. without using the recorder and understand the report templates that get generated when the Gatling completes the simulation execution.

NEXT Tutorial