Share variable between two sessions or save session variable to global

Hi everyone!
Could you please help me.
I try to share variable between to sessions.
There is my code:

`

package basic

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

class DataSinkSimulation extends Simulation {

@volatile var token = “”

val scn = scenario(“Auth”)
.exec(http(“auth”)
.post(“https://example.com/authentication”)
.header(“X-Username”, “admin”)
.header(“X-Password”,“p@ssw0rd”)
.header(“Content-Type”,“application/json”)
.check(regex("""“token”:"([^"]+)""").find
.saveAs(“token”))
)
.exec(session => {
val token = session(“token”).as[String]
println(“token:” + token)
session } )

val scn2 = scenario(“ds”)
.exec(_.set(“token”, token))
.exec(http(“ds”)
.post(“https://example.com/datasend”)
.body(StringBody("""{“key”:“value”}"""))
.header(“X-Authorization”, “${token}”)
.header(“Content-Type”,“application/json”)
)

setUp(scn.inject(atOnceUsers(1)),scn2.inject(atOnceUsers(1)))

}

`

I see that session variable is stored to token variable, but token is not available in second scenario

`

@volatile var token = “”

.exec(session => {
val token = session(“token”).as[String]
println(“token:” + token)
session } )

You’re shadowing the global token var so it’s never assigned.

I m not sure I know what part of code shadows token variable?
Could You clear please…

I tried this way and receive the same - token is not defined

Since you run two scenarios in parallel at once, the token is likely not yet acquired/assigned in scn when scn2 is started. Please try to add a pause at the beginning scn2.

On the other hand, if there’s such a dependency, can you run both http requests sequentially in a single scenario?

Hope that helps.

Thank You! It`s definitely working with DoNothingFor in setUp section for second scenario!

Hi,

With the last version I am havin trouble doing the same… I can’t get the authentication working on the second scenario. However if I put the token manually it works correctly.

var token = “”

val scn = scenario(“RecordedSimulation”)
.exec(
http(“request_0”)
.post("/api/auth")
.headers(headers_0)
.body(StringBody("""{“username”:“admin”,“password”:“admin”}""")).asJSON
.check(status is 200)
.check(jsonPath("$.token").saveAs(“token”))
)
.exec(session => {
token = session(“token”).as[String].trim
println(token)
session } )

val scn2 = scenario(“RecordedSimulation2”)
.exec(_.set(“token”, token))
.exec(
http(“request_1”)
.get("/api/protected")
.header(“X-Auth-Token”,"$.token")
.header(“Content-Type”, “application/json”)
.check(status is 200)
)

setUp(
scn.inject(atOnceUsers(1)).protocols(httpProtocol),
scn2.inject(
nothingFor(10 seconds), // 1
atOnceUsers(10), // 2
rampUsers(10) over(5 seconds), // 3
constantUsersPerSec(20) during(15 seconds), // 4
constantUsersPerSec(20) during(15 seconds) randomized, // 5
heavisideUsers(1000) over(20 seconds) // 10

).protocols(httpProtocol)

Any hints?