Search code examples
gatling

Gatling how to store and load a value for a later request


I'd like to build a load test where the second request is fed from first response. The data extraction is done in a method because it is not only one line of code. My problem is storing the value (id) and load it later. How should the value be stored and loaded? I tried some different approaches, and I come up with this code. The documentation has not helped me.

    object First {
        val first = {
            exec(http("first request")
            .post("/graphql")
            .headers(headers_0)
            .body(RawFileBody("computerdatabase/recordedsimulation/first.json"))
            .check(bodyString.saveAs("bodyResponse"))
            )
            .exec {
              session =>
                    val response = session("bodyResponse").as[String]
                    session.set("Id", getRandomValueForKey("id", response))
                session}
            .pause(1)
        }
    }

    object Second {
        val second = {
            exec(http("Second ${Id}")
                .post("/graphql")
                .headers(headers_0)
                .body(RawFileBody("computerdatabase/recordedsimulation/second.json"))
            )
            .pause(1)
        }
    }

    val user = scenario("User")
        .exec(
            First.first,
            Second.second
        )

    setUp(user.inject(
        atOnceUsers(1),
    )).protocols(httpProtocol)


Solution

  • Your issue is that you're not using the Session properly.

    From the documentation:

    Warning

    Session instances are immutable!

    Why is that so? Because Sessions are messages that are dealt with in a multi-threaded concurrent way, so immutability is the best way to deal with state without relying on synchronization and blocking.

    A very common pitfall is to forget that set and setAll actually return new instances.

    This is exactly what you're doing:

    exec { session =>
      val response = session("bodyResponse").as[String]
      session.set("Id", getRandomValueForKey("id", response))
      session
    }
    

    It should be:

    exec { session =>
      val response = session("bodyResponse").as[String]
      session.set("Id", getRandomValueForKey("id", response))
    }