Search code examples
scalagatling

Using UUID.randomUUID().toString for setting a key in request body giving issues- scala


I'm new to using scala and gatling. I'm defining a scenario which is doing the http post call to create a resource . In one of the key/fields of request body I want to put a unique identifier for the name hence using UUID.randomUUID()however the request is failing when use the below code.

val uuid = UUID.randomUUID().toString
println(uuid)

val scn = scenario("Testing !")
    .exec(http("create resource")
                .post("/data")
                .body(StringBody(
                """{
                   "add_name": "${uuid}",
                }""")).asJSON
                .check(status is(200)))

Even though printing uuid does print the id in console but throws error on the post request body as I believe "${uuid}" might be wrong but I'm not sure of.

Any suggestions/help greatly appreciated!


Solution

  • You're getting mixed-up between gatling's internal Expression substitution and scala's string interpolation.

    Lots of gatling DSL methods will allow you to use tokens like '${uuid}' in strings - when this occurs, gatling actually fetches the session value 'uuid' and substitutes it in. But this only works for keys that exist in the session. If they're not present, gatling will just use '${uuid}' as a string literal.

    Scala supports string interpolation using s"$uuid". In this case it would build a string that has the value of the scala variable 'uuid'.

    In your case, you have a 'uuid' variable, but you have not put in into the gatling session. You could just use the scala variable with the scala string interpolation syntax, but that won't give you the results you expect as all the gatling dsl methods define builders that are executed at startup - all your uuid's will have the same value.

    what you need to do is build a feeder that generates the random uuids and then use the gatling feeder construct to get a unique value into each execution.

    private val uuidFeeder = Iterator.continually(Map("uuid" -> UUID.randomUUID().toString))
    
    val scn = scenario("Testing !")
    .feed(uuidFeeder) //this gets the next random uuid and puts it in the session
    .exec(http("create resource")
                .post("/data")
                .body(StringBody(
                """{
                   "add_name": "${uuid}",
                }""")).asJSON
                .check(status is(200)))