Script uses same name everytime for multiple requests instead of using different name per request

127 views
Skip to first unread message

Peter

unread,
Mar 16, 2017, 9:38:23 AM3/16/17
to Gatling User Group
Hi All,

I am creating a gatling script which takes names in StringBody. Name should be unique everytime so I have to generate different random names. Here below script generates different names.

For single user it works fine. For multiple users it generates multiple random names but it request with SAME NAME everytime instead of using different name on every requests.

Like if I use userCount = 5, it will generates 5 different strings but unfortunately it request with one same string everytime in stringBody. I want 5 requests with different names. Can anyone please help me? Thanks.

Here is the code:

import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._
import scala.util.Random

class myTerm extends Simulation {

    val scenarioRepeatCount = Integer.getInteger("scenarioRepeatCount", 1).toInt
    val userCount = Integer.getInteger("userCount", 5).toInt
    val TID = System.getProperty("TID", "13203462112")

    // Methods for random char generator
    def randomAlpha(length: Int): String = {
        val chars = ('a' to 'z') ++ ('a' to 'z')
        randomStringFromCharList(length, chars)
    }

    def randomStringFromCharList(length: Int, chars: Seq[Char]): String = {
        val sb = new StringBuilder
        for (i <- 1 to length) {
        val randomNum = util.Random.nextInt(chars.length)
        sb.append(chars(randomNum))
        }
        sb.toString
    }

    val httpProtocol = http
        .connection("""keep-alive""")
        .contentTypeHeader("""application/json""")

    val scn = scenario("Create")
    .repeat (scenarioRepeatCount) {
        exec(http("Create with random names")
                .post(s"""http://someurl/api/thri/$TID/terms""")
                .body(StringBody("""{"term": """" + randomAlpha(7) + """"}""")) // Here randomAlpha(7) creates a string with 7 alphabates
            )
        }
    setUp(scn.inject(atOnceUsers(userCount))).protocols(httpProtocol)
}

adam.a...@pearson.com

unread,
Mar 17, 2017, 3:50:11 AM3/17/17
to Gatling User Group
Hi Peter,

you need to use lambda to make it execute every time the step is encountered by Gatling. Here is the example, the fun part is highlighted in red:

  val scn = scenario("Create Person")
    .exec(
      http("[POST] Create person")
        .post("/persons")
        .body(StringBody(_ => """{"name":"""" + Name.first_name.toLowerCase + """","age":""" + ThreadLocalRandom.current().nextInt(10, 80) + """}"""))
        .check(regex("Created"))
    )

Good luck!
Adam

Peter

unread,
Mar 20, 2017, 9:33:20 AM3/20/17
to Gatling User Group
Hi Adam,

Thanks a lot for the reply. It worked but stuck in another situation. I am facing issues with fetching assetId, it prints 'assetId' instead of value. Please have a look below code. 

.foreach("${IdList}", "assetid") {
exec(http("Load_Asset_Details")
.get(s"""$addTagsUrl/am/images/loader.svg""")
.resources(
   http("Actions_request")
.post(s"""$addTagsUrl/am/actions""")
.headers(headers_52)
.body(StringBody("""{"objects":[{"id":${assetid},"resource":"asset"}]}""")),
            http("variant_request")
.get(s"""$addTagsUrl/am/variants%3BresourceType=asset""")
.headers(headers_6),
            http("Keyframe_request")
.get(s"""$addTagsUrl/am/$${assetid}/keyframes""")
.headers(headers_6)))
.exec(http("Add Tags")
.post(s"""$addTagsUrl/am/$${assetid}/tags""")
.headers(headers_52)
//This prints value of assetid but does not generates random numbers
              //.body(StringBody(s"""{"objectId":$${assetid},"objectType":"asset","name":
"$tagName$randomNumber","accountId":4,"userId":5}"""))
// This generates random numbers but Doesnt assetid it prints "assetid" text instead of value
.body(StringBody(_ => """{"objectId":"""" + assetid + """" ,"objectType":"asset","name": """ + tagName + ThreadLocalRandom.current().nextInt(10, 80) + ""","accountId":4,"userId":5}"""))
)
}

adam.a...@pearson.com

unread,
Mar 20, 2017, 10:03:52 AM3/20/17
to Gatling User Group
Hi Peter,

this is an easy one :) Please read the docs here to find out how to extract session variables:

Quick hint:
request("page").get("/foo?${bar}")

Peter

unread,
Mar 20, 2017, 10:42:06 AM3/20/17
to Gatling User Group
Hi Adam,

I tried with 
{"objectId": "${assetid}"....
but fails.
What i have writter is:
.body(StringBody(_ => """{"objectId": "${assetid}","objectType":"asset","name": """ + tagName + ThreadLocalRandom.current().nextInt(10, 20) + ""","accountId":4,"userId":5}"""))

Can you please help? what is needed to fetch the value of assetid here :-(

Thanks.

adam.a...@pearson.com

unread,
Mar 20, 2017, 11:35:12 AM3/20/17
to Gatling User Group
Yes, you're right - you can't use expression language within lambda. Please try to extract it "manually", like in this example:

body(StringBody(session => "{username: '" + session("username").as[String] + "'}"))

Cheers,
Adam

Peter

unread,
Mar 20, 2017, 12:07:26 PM3/20/17
to Gatling User Group

Understood. Thanks adam for the reply.
Worked...
.body(StringBody(session => s"""{"objectId": """ + session("assetid").as[String] + """ ,"objectType":"asset","name": """" + tagName + ThreadLocalRandom.current().nextInt(10000) + """","accountId":4,"userId":5}"""))

Bhaskar Mishra

unread,
Mar 22, 2017, 6:18:22 AM3/22/17
to Gatling User Group
You seem to have solved the problem. I am having a similar issue here :
https://groups.google.com/forum/#!topic/gatling/ygUwWJsNJXE
Can you please shed some light over it. I construct my JSON payload and pass it as a string. Here is my code:


object GetPayloadData {}

def getSomeData(): String = {


// I am using Json4s to handle json.
   
    val r
= scala.util.Random
    val lines
= scala.io.Source.fromFile("src/test/resources/bodies/SomeJson.json").mkString
    val
Json = parse(lines).transformField {
     
case ("startDate", date) => ("startDate", LocalDate.now().toString() + "T00:00:00-07:00")
     
case ("endDate", endDate) => ("endDate", LocalDate.now().plusDays(r.nextInt(100000)).toString() + "T00:00:00-07:00")
     
case ("numOfAdults", numOfAdults) => ("numOfAdults", r.nextInt(100))   //I use scala utils random to get these values
     
case ("numOfWhatver", numOfChildren) => ("numOfWhatever", r.nextInt(100))  
   
}

   
return (compact(render(Json)))

 
}
 
}




 
class SearchSimulation extends Simulation {


  val
Search_Api_Json = "SimpleSearch.json"
  val searchPayLoad
= new GetPayloadData

  val httpConf
= http
   
.acceptHeader("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") // Here are the common headers
   
.acceptEncodingHeader("gzip, deflate")
   
.acceptLanguageHeader("en-US,en;q=0.5")
   
.userAgentHeader("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:16.0) Gecko/20100101 Firefox/16.0")

  val scn
= scenario("SearchDataLoading") // A scenario is a chain of requests and pauses
   
.exec(http("Search_Request") // Here's an example of a POST request
   
.post("http://some/uri/gatling.search")
   
.body(StringBody(searchPayLoad.getSomeData())).asJSON
   
.check(status.is(200)))


    setUp
(
      scn
.inject(
        atOnceUsers
(10), // 2
        rampUsers
(600) over (60 seconds) // 3
       
))

}
Reply all
Reply to author
Forward
0 new messages