Search code examples
scalagatling

In Gatling, how can I create a key value pair from returned body and save it in the session?


So I execute a POST call and get a few objects in return. I would like to extract and create a key value pair and save it in the session for later use.

My current code looks as follows:

.exec(http(“Rest call“)
  .post("/api")
  .body(ElFileBody("json/api.json")).asJson
  .check(jsonPath("$.result.objects[*].files[?(@.type == ‘FILE1’)].id").findAll.saveAs(“id”))
  .check(jsonPath("$.result.objects[*].files[?(@.type == ‘FILE1’)].name”).findAll.saveAs(“name”))

Here I end up with two lists(Vectors) in my session, "id" and "name". What I would like to do is create one list of key/value pairs of id/name instead. Obviously the pairs should correlate to the same jsonpath hit.


Solution

  • the easiest way to do this is using scala's collection zipping in a session function

    .exec(http(“Rest call“)
      .post("/api")
      .body(ElFileBody("json/api.json")).asJson
      .check(jsonPath("$.result.objects[*].files[?(@.type == ‘FILE1’)].id").findAll.saveAs(“id”))
      .check(jsonPath("$.result.objects[*].files[?(@.type == ‘FILE1’)].name”).findAll.saveAs(“name”)
    )
    .exec(session => {
      var ids = session("id").as[Seq[String]]
      var names = session("name").as[Seq[String]]
      session.set("pairs", ids zip names)
    })
    

    this will set a session variable called "pairs", with the contents being a List of Tuple2

    check out https://alvinalexander.com/scala/how-to-merge-sequential-collection-pairs-zip-unzip-scala-cookbook