Checks

HTTP checks can be used to validate your request and extract elements which can be reused later

Concepts

The Check API is used for 2 things:

  • verifying that the response to a request matches expectations
  • eventually capturing some elements in it.

Checks are performed on a request with the check method. For example, on an HTTP request:

http("My Request").get("myUrl").check(status.is(200))

One can of course perform multiple checks:

http("My Request").get("myUrl").check(status.not(404), status.not(500))

This API provides a dedicated DSL for chaining the following steps:

  1. defining the check type
  2. extracting
  3. transforming
  4. validating
  5. saving

Defining the check type

The HTTP Check implementation provides the following built-ins:

HTTP status

  • status

Targets the HTTP response status code.

Page location

  • currentLocation

Targets the current page absolute URL. Useful when following redirects in order to check if the landing page is indeed the expected one.

  • currentLocationRegex(pattern)

Same as above, but pattern is used to apply a regex on the current location.

By default, it can extract 0 or 1 capture group, so the extract type is String.

One can extract more than 1 capture group and define an different type with the ofType[T] extra step:

currentLocationRegex(pattern).ofType[T]

Gatling provides built-in support for extracting String tuples from Tuple2[String] to Tuple8[String].

The example below will capture two capture groups:

currentLocationRegex("http://foo.com/bar?(.*)=(.*)").ofType[(String, String)]

HTTP header

  • header(headerName)

Targets the HTTP response header of the given name. headerName can be a plain String, a String using Gatling EL or an Expression[String].

  • headerRegex(headerName, pattern)

Same as above, but pattern is used to apply a regex on the header value.

By default, it can extract 0 or 1 capture group, so the extract type is String.

One can extract more than 1 capture group and define an different type with the ofType[T] extra step:

headerRegex(headerName, pattern).ofType[T]

Gatling provides built-in support for extracting String tuples from Tuple2[String] to Tuple8[String].

The example below will capture two capture groups:

headerRegex("FOO", "foo(.*)bar(.*)baz").ofType[(String, String)]

HTTP response body

HTTP checks are performed in the order of HTTP element precedence: first status, then headers, then response body.

Beware that, as an optimization, Gatling doesn’t pile up response chunks unless a check is defined on the response body.

  • responseTimeInMillis

Returns the response time of this request in milliseconds = the time between starting to send the request and finishing to receive the response.

  • bodyString

Return the full response body String. Note that this can be matched against content from the the filesystem using RawFileBody or ElFileBody.

  • bodyBytes

Return the full response body byte array.

  • bodyStream

Return an InputStream of the full response body bytes.

  • substring(expression)

Scans for the indices of a given substring inside the body string.

expression can be a plain String, a String using Gatling EL or an Expression[String].

substring("foo") // same as substring("foo").find.exists
substring("foo").findAll.saveAs("indices") // saves a Seq[Int]
substring("foo").count.saveAs("counts") // saves the number of occurrences of foo
  • regex(expression)

Defines a Java regular expression to be applied on any text response body.

expression can be a plain String, a String using Gatling EL or an Expression[String].

It can contain multiple capture groups.

regex("""<td class="number">""")
regex("""<td class="number">ACC${account_id}</td>""")
regex("""/private/bank/account/(ACC[0-9]*)/operations.html""")

By default, it can extract 0 or 1 capture group, so the extract type is String.

You can extract more than 1 capture group and define an different type with the ofType[T] extra step:

regex(expression).ofType[T]

Gatling provides built-in support for extracting String tuples from Tuple2[String] to Tuple8[String].

The example below will capture two capture groups:

regex("foo(.*)bar(.*)baz").ofType[(String, String)]
  • xpath(expression, namespaces)

Defines an XPath 1.0 expression to be applied on an XML response body.

expression can be a plain String, a String using Gatling EL or an Expression[String].

namespaces is an optional List of couples of (prefix, uri)

xpath("//input[@id='text1']/@value")
xpath("//foo:input[@id='text1']/@value", Map("foo" -> "http://foo.com"))
  • jsonPath(expression)

JsonPath is a XPath-like syntax for JSON. It was specified by Stefan Goessner. Please check Goessner’s website for more information about the syntax.

expression can be a plain String, a String using Gatling EL or an Expression[String].

jsonPath("$..foo.bar[2].baz")

By default, it extracts Strings, so JSON values of different types get serialized.

You can define an different type with the ofType[T] extra step:

jsonPath(expression).ofType[T]

Gatling provides built-in support for the following types:

  • String (default): serializes back to valid JSON (meaning that special characters are escaped, e.g. \n and \")
  • Boolean
  • Int
  • Long
  • Double
  • Float
  • Seq (JSON array)
  • Map (JSON object)
  • Any

The example below shows how to extract Ints:

// JSON Response
{
  "foo": 1,
  "bar" "baz"
}

jsonPath("$..foo").ofType[Int] // will match 1
  • jsonpJsonPath(expression)

Same as jsonPath but for JSONP.

  • jmesPath(expression)

JMESPath is a query language for JSON.

expression can be a plain String, a String using Gatling EL or an Expression[String].

jmesPath("foo.bar[2].baz")

By default, it extracts Strings, so JSON values of different types get serialized.

You can define an different type with the ofType[T] extra step:

jmesPath(expression).ofType[T]

Gatling provides built-in support for the following types:

  • String (default): serializes back to valid JSON (meaning that special characters are escaped, e.g. \n and \")
  • Boolean
  • Int
  • Long
  • Double
  • Float
  • Seq (JSON array)
  • Map (JSON object)
  • Any

The example below shows how to extract Ints:

// JSON Response
{
  "foo": 1,
  "bar" "baz"
}

jmesPath("foo").ofType[Int] // will match 1
  • jsonpJmesPath(expression)

Same as jmesPath but for JSONP.

  • css(expression, attribute)

Gatling supports CSS Selectors.

expression can be a plain String, a String using Gatling EL or an Expression[String].

attribute is an optional String.

When filled, check is performed against the attribute value. Otherwise check is performed against the node text content.

css("article.more a", "href")

You can define an different return type with the ofType[T] extra step:

css("article.more a", "href").ofType[Node]

Gatling provides built-in support for the following types:

  • String
  • Node

Specifying a Node let you perform complex deep DOM tree traversing, typically in a transform check step. Node is a Jodd Lagarto DOM Node.

  • form(expression)

This check takes a CSS selector and returns a Map[String, Any] of the form field values. Values are either of type String or Seq[String], depending on if the input is multivalued or not (input with multiple attribute set, or multiple occurrences of the same input name, except for radio).

  • md5 and sha1

Returns a checksum of the response body. Checksums are computed efficiently against body parts as soon as they are received. They are then discarded if not needed.

Extracting

  • find

Returns the first occurrence. If the check targets more than a single element, find is identical to find(0).

Multiple results

  • find(occurrence)

Returns the occurrence of the given rank.

  • findAll

Returns a List of all the occurrences.

  • findRandom

Returns a random match.

  • findRandom(num: Int) and findRandom(num: Int, failIfLess = true)

Returns a given number of random matches, optionally failing is the number of actual matches is less than the expected number.

  • count

Returns the number of occurrences.

find(occurrence), findAll, findRandom and count are only available on check types that might produce multiple results. For example, status only has find.

Transforming

Transforming is an optional step for transforming the result of the extraction before trying to match or save it.

transform(function) takes a X => X2 function, meaning that it can only transform the result when it exists.

transformOption(function) takes a Option[X] => Validation[Option[X2]] function, meaning that it gives full control over the extracted result, even providing a default value.

transform(string => string + "foo")

transformOption(extract => extract.orElse(Some("default")))

Validating

  • is(expected)

Validate that the value is equal to the expected one, e.g.:

status.is(200)

expected is a function that returns a value of the same type of the previous step (extraction or transformation).

In case of a String, it can also be a String using Gatling EL or an Expression[String].

  • isNull

Validate that the extracted value is null, typically a JSON value, e.g.:

jsonPath("$.foo").isNull
  • not(expected)

Validate that the extracted value is different from the expected one:

status.not(500)

expected is a function that returns a value of the same type of the previous step (extraction or transformation).

In case of a String, it can also be a String using Gatling EL or an Expression[String].

  • notNull

Validate that the extracted value is not null, typically a JSON value, e.g.:

jsonPath("$.foo").notNull
  • exists

Validate that the extracted value exists:

jsonPath("$..foo").exists
  • notExists

Validate that the check didn’t match and couldn’t extract anything:

jsonPath("$..foo").notExists
  • in(sequence)

Validate that the extracted value belongs to a given sequence or vararg:

status.in(200, 304)

sequence is a function that returns a sequence of values of the same type of the previous step (extraction or transformation).

  • optional

Always true, used for capture an optional value.

  • validate(validator)

Built-ins validation steps actually resolve to this method.

name is the String that would be used to describe this part in case of a failure in the final error message.

validator is a Expression[Validator[X]] function that performs the validation logic.

trait Validator[A] {
  def name: String
  def apply(actual: Option[A]): Validation[Option[A]]
}

The apply method takes the actual extracted value and return a the Validation: a Success containing the value to be passed to the next step, a Failure with the error message otherwise.

Naming

name(customName)

Naming is an optional step for customizing the name of the check in the error message in case of a check failure.

Saving

saveAs(key)

Saving is an optional step for storing the result of the previous step (extraction or transformation) into the virtual user Session, so that it can be reused later.

key is a String.

Conditional Checking

Check execution can be enslave to a condition.

checkIf(condition)(thenCheck)

The condition can be of two types:

  • Expression[Boolean]
  • (Response, Session) => Validation[Boolean]

Nested thenCheck will only be performed if condition is successful.

Putting it all together

To help you understand the checks, here is a list of examples:

regex("""https://(.*)""").count.is(5)

Verifies that there are exactly 5 HTTPS links in the response.

regex("""https://(.*)/.*""")
  .findAll
  .is(List("www.google.com", "www.mysecuredsite.com"))

Verifies that there are two secured links pointing at the specified websites.

status.is(200)

Verifies that the status is equal to 200.

status.in(200 to 210)

Verifies that the status is one of: 200, 201, 202, …, 209, 210.

regex("aWord").find(1).exists

Verifies that there are at least two occurrences of “aWord”.

regex("aWord").notExists

Verifies that the response doesn’t contain “aWord”.

bodyBytes.is(RawFileBody("expected_response.json"))

Verifies that the response body matches the binary content of the file user-files/bodies/expected_response.json

bodyString.is(ElFileBody("expected_template.json"))

Verifies that the response body matches the text content of the file user-files/bodies/expected_template.json resolved with Gatling Expression Language (EL).

Edit this page on GitHub