Skip to content

Instantly share code, notes, and snippets.

@Amerousful
Last active March 7, 2025 14:31
Show Gist options
  • Save Amerousful/00db6f6b999ed519f15cef776c7a631e to your computer and use it in GitHub Desktop.
Save Amerousful/00db6f6b999ed519f15cef776c7a631e to your computer and use it in GitHub Desktop.
Gatling: How to pass the session variables between two scenarios?

Gatling: How to pass the session variables between two scenarios?

I have a general solution which can easy to use. There are several steps how to do it.

Create methods which get all session variable from one scenario and another method which sets this variables:

import scala.collection.concurrent.{Map => ConcurrentMap}

def passAnotherSession(implicit transferVariable: ConcurrentMap[String, Any]): Expression[Session] =
    (currentSession: Session) => {
      currentSession.setAll(transferVariable)
    }

def saveSessionToVariable(implicit transferVariable: ConcurrentMap[String, Any]): Expression[Session] =
    (currentSession: Session) => {
      val systemKeys = List("gatling.http.ssl.sslContexts", "gatling.http.cache.contentCache", "gatling.http.cache.dns")
      transferVariable ++= currentSession.removeAll(systemKeys: _*).attributes
      currentSession
    }

// For pass certain keys
def saveSessionToVariable(onlyKeys: String*)(implicit transferVariable: ConcurrentMap[String, Any]): Expression[Session] =
    (currentSession: Session) => {
      val systemKeys = List("gatling.http.ssl.sslContexts", "gatling.http.cache.contentCache", "gatling.http.cache.dns")
      val unnecessaryKeys = currentSession.attributes.keySet.diff(onlyKeys.toSet).toList
      transferVariable ++= currentSession
        .removeAll(systemKeys ++ unnecessaryKeys: _*).attributes
      currentSession
    }

I defined methods above in my abstract base class which is inherited in all simulations/scenario classes.


Then in my simulations/scenario class I defined a concurrent map (via implicit) for store session variable:

import scala.collection.concurrent.{Map => ConcurrentMap}

implicit val setUpSessionConcurrentMap[String, Any] = new TrieMap()

Now, let's start using this methods. Below is an example of a scenario that gets the desired variable:

val setUpScenario = scenario(...)
.exec(...) // some action with save desired variable 
.exec(saveSessionToVariable) // this save all session variables to above defined implicit map

And this is already a scenario that needs a variable:

val mainScenario = scenario(...)
.exec(passAnotherSession)    // get variable from setUpScenario
.exec(...)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment