You are on page 1of 21

Gatling

Introduction for
Java Users

Section B - Accompanying Documentation


Table of contents

B1 - Section Overview 3

B2 - Application Under Test 4

B3 - Gatling Recorder 5
HTTP Proxy Recorder Mode 6
HAR Converter Mode 10

B4 - Gatling Script First Look 13


Tidy Headers 14
Gatling Script Breakdown 14
Refactor Scenario Definition to Objects 16
Create Multiple Scenarios 18
Feeders for Dynamic data 19
Correlation 20

Gatling Academy - Gatling Introduction - Section B


Page 2
B1 - Section Overview
Section B of this course is going to cover Gatling Script Creation. The following topics will
be covered:

● A detailed look at the application under test - Gatling Computer Database


● Overview of the Gatling Recorder, running in both proxy and HAR converter modes
● First look at a Gatling script generated from the recorder
● Enhancements to the Gatling script with feeders and correlation

Gatling Academy - Gatling Introduction - Section B


Page 3
B2 - Application Under Test
The application that we will be testing against in this module is the Gatling Computer
Database. It is a website with a fictional database of computers, maintained online by the
Gatling team for the purpose of practising Gatling script creation.

Gatling Computer Database

The application has a few typical features that you would expect such as:

● Filter for computers


● Create a new computer
● View/edit computer details
● Browse through the list of pages

Have a look around the application, then we can move on to using the Gatling recorder to
create a Gatling script.

NOTE: The application is running in “read-only” mode. This means that any changes you
(i.e. creating a computer, updating a computer etc.) are not persisted on the backend and
hence won’t be visible in the application.

This has no impact on the Gatling scripts that you will write against this application, which
are ultimately for training purposes.

Gatling Academy - Gatling Introduction - Section B


Page 4
B3 - Gatling Recorder
Now that we are familiar with the application under test, we can use the Gatling recorder to
create a Gatling script against the application.

If you downloaded Gatling directly from the Gatling website, then you can launch the
recorder by browsing into the /bin directory and running recorder.bat if you are on Windows
or recorder.sh if you are on a Mac.

Alternatively, if you are using Gatling through a build tool directly in the IDE, you can launch
the recorder by simply running the Recorder class directly:

Gatling Recorder launched through IntelliJ

Gatling Academy - Gatling Introduction - Section B


Page 5
Once the Gatling recorder loads, you should see a screen similar to this:

Gatling Recorder

The Gatling Recorder has two different modes:

● HTTP Proxy Mode


● HAR Converter Mode

HTTP Proxy Recorder Mode


In this mode, the Gatling recorder acts as a proxy in your web browser and captures traffic.

Refer to the Gatling documentation for full details on the Gatling recorder, including how to
run in different HTTPS modes.

For our application here, we will be leaving all the options as default, but we should click No
static resources in the bottom-right corner. This will ensure that we don’t capture unwanted
transactions such as JavaScript and images.
Click Start and the Gatling recorder will begin to run, capturing traffic on port 8000.

The next thing to do is to configure our web browser to use this proxy. The Firefox web
browser works best for this, as it is more lenient with it’s HTTPS recording settings than
some of the other browsers.

Open your browser settings in Firefox and configure the Network Settings as below:

Gatling Academy - Gatling Introduction - Section B


Page 6
Firefox Proxy Settings for Recording

Gatling Academy - Gatling Introduction - Section B


Page 7
Now that the proxy is configured, you can browse to the Gatling Computer Database
application in the browser. You might receive a message that says Warning: Potential
Security Risk Ahead, this is because we are using an HTTPS self-signed certificate in our
proxy. Click on Advanced then Accept the Risk and Continue

The Computer Database website should now load, and we can begin to capture our user
journey as normal. Before we capture each transaction, it can be a good practice to add a
tag in the Gatling Recorder:

Adding a Tag in the Gatling Recorder

A tag will add a comment into our generated Gatling script, making it easier to understand
which transaction we have captured.

You can now record your user journey through the application. A few ideas of transactions to
record are:

● Clicking Next / Previous, to browse between pages


● Filter for a computer
● Add a new computer
● View the details of a computer by clicking on it

Gatling Academy - Gatling Introduction - Section B


Page 8
Once you have finished, click Stop & Save in the recorder. Your script will be generated and
placed in the simulations folder specified in the recorder:

Simulations folder in Gatling Recorder

Browse to that folder on your computer, and you can open the script in a text editor to take a
look at it.

We will go over the Gatling script that we have captured here shortly.

Gatling Academy - Gatling Introduction - Section B


Page 9
HAR Converter Mode

The second recorder mode is HAR Converter mode. HAR stands for HTTP Archive File, and
these files can be generated from traffic in your web browser.

This mode is a lot easier to use for HTTPS recordings, as it doesn’t require the setup of any
special certificate

To generate a HAR file, open the Google Chrome browser and head over to the Gatling
Computer Database website. Open Developer Tools in Chrome and click on the Network
tab, make sure the red recording icon is displayed, and preserve log is ticked:

Chrome Dev Tools for capturing traffic

Refresh the page you are on to capture the traffic of loading that page. You should see the
traffic start to appear in dev tools.

Gatling Academy - Gatling Introduction - Section B


Page 10
Complete all the transactions of your user journey in the web browser. Once you are
finished, right-click within dev tools and choose to Save all as HAR with content:

Save a HAR file in Chrome

Save this file somewhere on your computer that you will remember.

Gatling Academy - Gatling Introduction - Section B


Page 11
Go back to the Gatling recorder, and make sure the Recorder Mode is set to HAR
Converter. Click Browse and locate the file that you saved in the previous step:

Browse for the HAR file in the Gatling Recorder

Once you have located the file, click the No static resources button in the Gatling recorder.
This will make sure that the generated file doesn’t have any unwanted transactions such as
downloading images or JavaScript files

Now click Start in the Gatling recorder. The recorder will now generate a Gatling script and
save it in the simulations folder that is specified under output. You can open this script now
in a text editor to look around and begin editing.

Gatling Academy - Gatling Introduction - Section B


Page 12
B4 - Gatling Script First Look
Let’s now take a look at the script we have captured in the Gatling Recorder previously, and
make a few small tweaks to it.

When you open the script for the first time, it will likely look something like the one below:

import java.time.Duration;
import java.util.*;

import io.gatling.javaapi.core.*;
import io.gatling.javaapi.http.*;
import io.gatling.javaapi.jdbc.*;

import static io.gatling.javaapi.core.CoreDsl.*;


import static io.gatling.javaapi.http.HttpDsl.*;
import static io.gatling.javaapi.jdbc.JdbcDsl.*;

public class RecordedSimulation extends Simulation {

private HttpProtocolBuilder httpProtocol = http


.baseUrl("https://computer-database.gatling.io")
.inferHtmlResources(AllowList(), DenyList(".*\\.js", ".*\\.css", ".*\\.gif",
".*\\.jpeg", ".*\\.jpg", ".*\\.ico", ".*\\.woff", ".*\\.woff2", ".*\\.(t|o)tf",
".*\\.png", ".*detectportal\\.firefox\\.com.*"))

.acceptHeader("text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,
image/webp,*/*;q=0.8")
.acceptEncodingHeader("gzip, deflate")
.acceptLanguageHeader("en-GB,en;q=0.5")
.upgradeInsecureRequestsHeader("1")
.userAgentHeader("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:98.0)
Gecko/20100101 Firefox/98.0");

private Map<CharSequence, String> headers_0 = Map.ofEntries(


Map.entry("Sec-Fetch-Dest", "document"),
Map.entry("Sec-Fetch-Mode", "navigate"),
Map.entry("Sec-Fetch-Site", "none"),
Map.entry("Sec-Fetch-User", "?1")
);

// … other headers

private ScenarioBuilder scn = scenario("RecordedSimulation")

Gatling Academy - Gatling Introduction - Section B


Page 13
.exec(
http("request_0")
.get("/computers")
.headers(headers_0)
)
.pause(31)
.// SEARCH
.exec(
http("request_1")
.get("/computers?f=MacBook")
.headers(headers_1)
)
.pause(28)
.// SELECT_COMPUTER
.exec(
http("request_2")
.get("/computers/89")
.headers(headers_1)
)
.pause(13)

// … other scenario steps truncated

{
setUp(scn.injectOpen(atOnceUsers(1))).protocols(httpProtocol);
}

Tidy Headers
A good first step is to tidy up the headers in the script, as there is a lot of unnecessary data
captured here that we don’t need. A better practice is to either add headers under the
httpProtocol, or to each individual transaction.

Go through the script and delete all the val headers entries, as well as the corresponding
headers under each transaction name. This will make our script a lot more readable.

Gatling Script Breakdown


Every Gatling script is essentially made up of three distinct parts:

1. Protocol setup - this is where we set the base URL, and also any defaults that we
want to use throughout all the calls in the script. For example, if we wanted a certain
HTTP header to be included in every transaction, we would add it here.

Gatling Academy - Gatling Introduction - Section B


Page 14
2. Scenario Definition - the scenario makes up the actual steps that each virtual user
will take through the system, i.e. the user journey. This is the list of all transactions or
steps that we recorded previously i.e. load computer page, create new computer etc.

3. Load Simulation Design - the setUp block at the end is the load simulation design.
This is where we set the number of users to execute, the speed in which to ramp
those users etc.

Gatling Academy - Gatling Introduction - Section B


Page 15
Refactor Scenario Definition to Objects
At the moment, our entire user journey in the system is one long list of transactions one after
the other.

private ScenarioBuilder scn = scenario("RecordedSimulation")


.exec(
http("request_0")
.get("/computers")
.headers(headers_0)
)
.pause(31)
.// SEARCH
.exec(
http("request_1")
.get("/computers?f=MacBook")
.headers(headers_1)
)
.pause(28)
.// SELECT_COMPUTER
.exec(
http("request_2")
.get("/computers/89")
.headers(headers_1)
)
.pause(13)

// … other transactions excluded

To make our script more readable, and to give ourselves the possibility of reusing code
within our script, a good practice is to refactor these steps into their own static constants. For
example, with the search steps above, we can refactor into a static constant with a
ChainBuilder like this:

ChainBuilder searchForComputer =
exec(http("LoadHomePage")
.get("/computers"))
.pause(2)
.exec(http("SearchComputers")
.get("/computers?f=MacBook")
.pause(2)
.exec(http("SelectComputer")
.get("/computers/89"))
.pause(2);

Gatling Academy - Gatling Introduction - Section B


Page 16
Note that we also renamed our transactions here to more meaningful names. Originally
these were labelled as (http("request_0") but we updated it to http("LoadHomepage". The
transaction name we specify here is what will appear in the Gatling report.

Gatling Academy - Gatling Introduction - Section B


Page 17
We can then add the Search back into our scenario like below. Note that we have also
extracted the browse and createComputer transactions out as well:

private ScenarioBuilder scn = scenario("LoadTest")


.exec(searchForComputer, browse, createComputer);

Create Multiple Scenarios


With that refactoring done, we can now create different scenarios for different types of user.
For example, suppose that we had regular users in our system that only did the Search and
Browser steps, whilst we had Admin users that did those steps plus Create. We could split
those into two scenarios like so:

private ScenarioBuilder admins = scenario("Admins")


.exec(searchForComputer, browse, createComputer);

private ScenarioBuilder users = scenario("Users")


.exec(searchForComputer, browse);

We can then call those scenarios in our load simulation design like so:

{
setUp(
admins.injectOpen(atOnceUsers(1)),
users.injectOpen(atOnceUsers(1))
)
.protocols(httpProtocol);
}

You can read much more about scenario creation in Gatling in the documentation -
https://gatling.io/docs/current/general/scenario/

Gatling Academy - Gatling Introduction - Section B


Page 18
Feeders for Dynamic data
So far in our script, we have hardcoded many of the values. For example, we have
hardcoded the computer that we are searching for as macbook. It is better to do this
through test data, using something like a CSV file.

Gatling has feeders for this purpose, and you can read more about them in the
documentation here - https://gatling.io/docs/gatling/reference/current/core/session/feeder/

In our script, we are going to create a CSV file in the resources/data folder of our project
called search.csv. We can add the following data to it:

searchCriterion,searchComputerName
MacBook,MacBook Pro
Eee,ASUS Eee PC 1005PE
HP,HP Mini 1000

The CSV file has 2 headings (searchCriterion and searchComputerName), and 3 rows of
test data under each of those headings.

We can then add this CSV file into our script and hook it up to our search Transaction like
so:

FeederBuilder.Batchable searchFeeder =
csv("data/search.csv").random();

ChainBuilder searchForComputer =
exec(http("LoadHomePage")
.get("/computers"))
.pause(2)
.feed(searchFeeder)
.exec(http("SearchComputers_#{searchCriterion}")
.get("/computers?f=#{searchCriterion}")

// … other code excluded for brevity

Now instead of searching for a hard-coded computer name, Gatling will take a random value
for #{searchCriterion} from the test data and insert it into the script.

Gatling Academy - Gatling Introduction - Section B


Page 19
Correlation

Further down in our search method, we can see that we have hardcoded the computer that
we are selecting as /computers/89 :

private ScenarioBuilder scn = scenario("RecordedSimulation")


.exec(
http("request_0")
.get("/computers")
.headers(headers_0)
)
.pause(31)
.// SEARCH
.exec(
http("request_1")
.get("/computers?f=MacBook")
.headers(headers_1)
)
.pause(28)
.// SELECT_COMPUTER
.exec(
http("request_2")
.get("/computers/89")
.headers(headers_1)
)
.pause(13)

// … other transactions excluded

It would be better if we could extract the URL to access here from the previous request (i.e.
when we search for a computer). We can do this extraction through a process called
correlation by using a check in Gatling.

You can read all about Gatling checks in the documentation:


https://gatling.io/docs/current/http/http_check/

For our script, we are going to use a CSS check to extract the URL of the computer we are
searching for, save it into a parameter called computerURL, then use that parameter in a
subsequent call:

ChainBuilder searchForComputer =
exec(http("LoadHomePage")
.get("/computers"))
.pause(2)
.feed(searchFeeder)

Gatling Academy - Gatling Introduction - Section B


Page 20
.exec(http("SearchComputers_#{searchCriterion}")
.get("/computers?f=#{searchCriterion}")
.check(css("a:contains('#{searchComputerName}')", "href")
.saveAs("computerURL")))
.pause(2)
.exec(http("LoadComputerDetails_#{searchComputerName}")
.get("#{computerURL}"))
.pause(2);

This allows us to make our scripts truly dynamic.

Gatling Academy - Gatling Introduction - Section B


Page 21

You might also like