Search code examples
gatling

How to set a global variable for all virtual users during gatling simulation?


In my simulation users are simply sending requests in a loop. Each request contains a custom header and its value is read from a variable. However, I would like to change the value of the variable during simulation so that all virtual users (including active) start sending a new value in the custom header from this point.

Here's what I've tried but with no luck:

class MySimulation extends Simulation {
  
  var GLOBAL_LIMIT = "49"

  def myRequest: HttpRequestBuilder =
    http("My request")
      .get("/")
      .header("LIMIT", GLOBAL_LIMIT)
      .check(status.is(200))

  def myScenario: ScenarioBuilder =
    scenario("Poll")
      .forever(
        pace(1.second)
          .exec(myRequest)
      )

  def changeLimit(limit: String): ScenarioBuilder =
    scenario("Change limit")
      .exec(session => {
        GLOBAL_LIMIT = limit
        session
      })

  setUp(
    myScenario.inject(
      constantUsersPerSec(1) during 30.seconds
    ),
    changeLimit("59").inject(
      nothingFor(10.seconds),
      atOnceUsers(1)
    )
  ).protocols(http.baseUrl("http://localhost:8081"))
}

I've also tried to store the value with scala.util.Properties.setProp() and than read it with scala.util.Properties.propOrElse() but that doesn't work either. All requests have the custom header set to initial value of "49".

Is there a way to set (and then change) global variables for simulation, something like session but common for all virtual users?


Solution

  • That's because when you're writing .header("LIMIT", GLOBAL_LIMIT), you're passing a value as the header method's second parameter, and this value is evaluated once when the simulation is loaded. At this point in time, GLOBAL_LIMIT is still null as it will only be populated later when the simulation will be running.

    Instead, you must pass a function that will be evaluated every time a virtual user tries to generate this request:

    .header("LIMIT", session => GLOBAL_LIMIT)