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

**URL:** https://community.gatling.io/t/script-uses-same-name-everytime-for-multiple-requests-instead-of-using-different-name-per-request/3614
**Category:** Gatling (Open-Source)
**Created:** [March 16, 2017, 1:38pm UTC](https://community.gatling.io/t/script-uses-same-name-everytime-for-multiple-requests-instead-of-using-different-name-per-request/3614 "2017-03-16T13:38:23Z")
**Posts on this page:** 8
**Page:** 1

<div class="post-metadata">

### Author: ![Peter](https://avatars.discourse-cdn.com/v4/letter/p/278dde/32.png) [@Peter](https://community.gatling.io/u/Peter)
#### Post date: [March 16, 2017, 1:38pm UTC](https://community.gatling.io/t/script-uses-same-name-everytime-for-multiple-requests-instead-of-using-different-name-per-request/3614/1 "2017-03-16T13:38:23Z")

</div>

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:

```auto
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)
}

```

---

<div class="post-metadata">

### Author: ![Artajew\_Adam](https://avatars.discourse-cdn.com/v4/letter/a/da6949/32.png) [@Artajew\_Adam](https://community.gatling.io/u/Artajew_Adam)
#### Post date: [March 17, 2017, 7:50am UTC](https://community.gatling.io/t/script-uses-same-name-everytime-for-multiple-requests-instead-of-using-different-name-per-request/3614/2 "2017-03-17T07:50:11Z")

</div>

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

---

<div class="post-metadata">

### Author: ![Peter](https://avatars.discourse-cdn.com/v4/letter/p/278dde/32.png) [@Peter](https://community.gatling.io/u/Peter)
#### Post date: [March 20, 2017, 1:33pm UTC](https://community.gatling.io/t/script-uses-same-name-everytime-for-multiple-requests-instead-of-using-different-name-per-request/3614/3 "2017-03-20T13:33:20Z")

</div>

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}"""))  
)  
}

`

---

<div class="post-metadata">

### Author: ![Artajew\_Adam](https://avatars.discourse-cdn.com/v4/letter/a/da6949/32.png) [@Artajew\_Adam](https://community.gatling.io/u/Artajew_Adam)
#### Post date: [March 20, 2017, 2:03pm UTC](https://community.gatling.io/t/script-uses-same-name-everytime-for-multiple-requests-instead-of-using-different-name-per-request/3614/4 "2017-03-20T14:03:52Z")

</div>

Hi Peter,

this is an easy one 🙂 Please read the docs here to find out how to extract session variables:  
[http://gatling.io/docs/current/session/expression\_el/](http://gatling.io/docs/current/session/expression_el/)

Quick hint:

`

```auto
request("page").get("/foo? **${bar}**")

```

`

---

<div class="post-metadata">

### Author: ![Peter](https://avatars.discourse-cdn.com/v4/letter/p/278dde/32.png) [@Peter](https://community.gatling.io/u/Peter)
#### Post date: [March 20, 2017, 2:42pm UTC](https://community.gatling.io/t/script-uses-same-name-everytime-for-multiple-requests-instead-of-using-different-name-per-request/3614/5 "2017-03-20T14:42:05Z")

</div>

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.

---

<div class="post-metadata">

### Author: ![Artajew\_Adam](https://avatars.discourse-cdn.com/v4/letter/a/da6949/32.png) [@Artajew\_Adam](https://community.gatling.io/u/Artajew_Adam)
#### Post date: [March 20, 2017, 3:35pm UTC](https://community.gatling.io/t/script-uses-same-name-everytime-for-multiple-requests-instead-of-using-different-name-per-request/3614/6 "2017-03-20T15:35:11Z")

</div>

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

---

<div class="post-metadata">

### Author: ![Peter](https://avatars.discourse-cdn.com/v4/letter/p/278dde/32.png) [@Peter](https://community.gatling.io/u/Peter)
#### Post date: [March 20, 2017, 4:07pm UTC](https://community.gatling.io/t/script-uses-same-name-everytime-for-multiple-requests-instead-of-using-different-name-per-request/3614/7 "2017-03-20T16:07:26Z")

</div>

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}"""))`

---

<div class="post-metadata">

### Author: ![Bhaskar\_Mishra](https://avatars.discourse-cdn.com/v4/letter/b/3ec8ea/32.png) [@Bhaskar\_Mishra](https://community.gatling.io/u/Bhaskar_Mishra)
#### Post date: [March 22, 2017, 10:18am UTC](https://community.gatling.io/t/script-uses-same-name-everytime-for-multiple-requests-instead-of-using-different-name-per-request/3614/8 "2017-03-22T10:18:21Z")

</div>

You seem to have solved the problem. I am having a similar issue here :  
[https://groups.google.com/forum/#!topic/gatling/ygUwWJsNJXE](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](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  
))

}  
`

`
