Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use return of one gatling request into another request - Scala

Tags:

scala

gatling

In the following code, I am getting a token in the first Gatling request, saving it in a variable named auth. However, when I try to use it in the second request, it is sending empty string in place of auth variable. So for some reason, the auth string is not being updated till the time it is being used in the second request. Can anyone suggest any workaround so that I can use the value returned in one request into another request?

Code:

  val headers_10 = Map("Content-Type" -> "application/x-www-form-urlencoded")
  var a= "[email protected]"
  var auth = ""
  val scn = scenario("Scenario Name") // A scenario is a chain of requests and pauses
    .exec(http("request_1") // Here's an example of a POST request
      .post("/token")
      .headers(headers_10)
      .formParam("email", a)
      .formParam("password", "password")
      .transformResponse { case response if response.isReceived =>
        new ResponseWrapper(response) {
        val a = response.body.string
        auth = "Basic " + Base64.getEncoder.encodeToString((a.substring(10,a.length - 2) + ":" + "junk").getBytes(StandardCharsets.UTF_8))
     }  
     })
     .pause(2)
     .exec(http("request_2")
       .get("/user")
       .header("Authorization",auth)
       .transformResponse { case response if response.isReceived =>
        new ResponseWrapper(response) {
        val a = response.body.string
     }
   })
like image 265
Kshitij Mittal Avatar asked Jun 13 '16 10:06

Kshitij Mittal


1 Answers

You should store the value you need in the session. Something like this will work, although you'll have to tweak the regex and maybe some other details:

val headers_10 = Map("Content-Type" -> "application/x-www-form-urlencoded")
  var a= "[email protected]"
  var auth = ""
  val scn = scenario("Scenario Name") // A scenario is a chain of requests and pauses
    .exec(http("request_1") // Here's an example of a POST request
      .post("/token")
      .headers(headers_10)
      .formParam("email", a)
      .formParam("password", "password")
      .check(regex("token: (\\d+)").find.saveAs("auth")))
    .pause(2)
    .exec(http("request_2")
      .get("/user")
      .header("Authorization", "${auth}"))

Here's the documentation on "checks", which you can use to capture values from a response:

http://gatling.io/docs/2.2.2/http/http_check.html

Here is the documentation on the gatling EL, which is the easiest way to use session variables (this is the "${auth}" syntax in the last line above):

http://gatling.io/docs/2.2.2/session/expression_el.html

like image 65
dokkaebi Avatar answered Oct 06 '22 00:10

dokkaebi