Search code examples
gatlingscala-gatling

Build Dynamic json request using Gatling


I am trying to build random json requests using data from a csv file. I have defined my .scenario function as follows

But when I set the log level to trace I see all the requests having the same values. Is there something I am missing out on?

def getScenario () = {
         scenario("Create API Promotions")
        .exec(
            http("Create Request")
            .post(createApiURL)
            .headers(headers_1)
            .body(StringBody(getCreateRequest))
            .check(status.is(200))
            )
    }


    def getCreateRequest: String = {
         val data = s"""
          {
            "Specification":{  

                "Item":${getItems()}
            }
          }
          """.stripMargin
          data   
    }

def getItems (): String = {
        val record: Map[String, Any] = getItemsFromCSV()
        val code: String = record("Code").toString
        val clientDataType: String = record("Type").toString

        val clientData =    (
                                ("Code" -> code) ~
                                ("Type" -> clientDataType)                                 
                            )
        val targetJson = List(clientData);
        return compact(render(targetJson))
    }

    def getItemsFromCSV() : Map[String, Any] = {

            val items: Seq[Map[String, Any]] = csv("../resources/create/items.csv").readRecords
            return promoTarget(getRandomNumber(0, items.length-1)) 
    }

Solution

  • Gatling EL provide a built-in function (jsonStringify()) that properly formats object into a JSON value (wrap Strings with double quotes, deal with null, etc.)

    Additionally, I think you could use a feeder for getting the csv values.

    val items = csv("../resources/create/items.csv").random
    
    scenario("Create API Promotions")
      .feed(items)
      .exec(buildPostData)
      .exec(http("Create Request")
        .post(createApiURL)
        .headers(headers_1)
        .body(StringBody("${postData.jsonStringify()}"))
        .check(status.is(200))
      )
    
    def buildPostData: Expression[Session] = session => {
      val postData: Map[String, Any] =
          Map(
            "Code" -> session("Code").as[String],
            "Type" -> session("Type").as[String]
          )
      session.set("postData", postData)
    }
    

    Official doc links: