Search code examples
scalagatlingscala-gatling

Use the value generated inside a Gatling Feeder of one request inside the feeder of a consequent request for the same user


I am using Gatling to test a system which expects 2 sequential Post requests say, R1 and R2. These Post requests have different Json request bodies but one common key "ID". So one user should execute R1-R2 in order and a new random ID should be generated per user. This ID generated in R1 should be passed to R2 and hence added as the value of the ID key in its request bodies.

The random ID is generated inside a feeder at the R1 request:

val R1Id = Iterator.continually(Map("randId1" -> R1_requestBody.replace("0000000000", randomTokenGenerator.generateTokenID())))

val r1 = 
scenario("R1Scenarios").feed(R1Id)
.exec(http("POST R1")
.....
.body(StringBody(session => """${randId1}""")).asJSON                        

Now, in R2, I want to feed want had been ID value had been generated inside the feeder of R1.

val R2Id = Iterator.continually(Map("randId2" -> R2_requestBody.replace("0000000000", ***Token generated in the first request***)))

 val R2= {
scenario("R2 Scenarios")
.exec(R1.r1) 

//calls the first scenario as R2 should be executed after R1
.feed(R2Id )
.exec(http("POST R2")
....
.body(StringBody(session => """${randId2}""")).asJSON

Finally executing the simulation:

val jsonScenario = R2.r2.inject(constantUsersPerSec(2) during (1 second))

setUp(jsonScenario)
.protocols(httpConf)

Solution

  • Instead of generating whole body in feeder you can generate only that random id, lets call it userToken:

    val tokenFeeder = Iterator.continually(Map(
      "userToken" -> randomTokenGenerator.generateTokenID()
    ))
    

    and replace it while building request body:

    .body(
        StringBody(session => R1_requestBody.replace(
          "0000000000",
          session("userToken").as[String]
        ))
    ).asJSON
    

    Or even cleaner and better - use fact that Gatling replaces every string containing placeholder like ${sessionAttributeName} with that session attribute string value and instead of using "0000000000" in your body template use ${userToken} placeholder fe:

    val bodyTemplate ="""{
      |"userName": "John Doe",
      |"userToken": "${userToken}"
      |}""".stripMargin
    

    and then just use that template for body and Gatling expression language will do the magic:

    .body(StringBody(bodyTemplate)).asJSON