Variable value is not passed in the header.

Hi,

I am unable to pass the value of the variable bearer_token to the header parameter “Authorization”. But if the value is passed directly instead of a variable, then it works.
Attached the code below for reference(highlighted the variable)

Could someone help me in fixing this issue.

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

class test extends Simulation{

val headersLogin = Map(
“Content-Type” → “application/json”,
“Authorization” → “Basic YWRtaW46Tm9raWFOc3AxIQ==”
)

val headersCreateSubscription = Map(
“Content-Type” → “application/json”,
“Accept” → “application/json”
)

var bearer_token = ""

val httpProtocol = http
.baseUrl(“https://135.121.156.59”) // Here is the root for all relative URLs

val scn =
scenario(“Telemetry Viewer Load Testing”)
.exec(
http(“Get Access Token - POST “)
.post(”:443/rest-gateway/rest/api/v1/auth/token”)
.headers(headersLogin)
.body(StringBody(
“”"{“grant_type”: “client_credentials”}""".stripMargin)).asJson
.check(status is 200)
.check(jsonPath("$" ).saveAs(“RESPONSE_DATA” ))
.check(jsonPath("$.access_token").saveAs(“access_token”))
)

.exec(session => {
val response = session(“RESPONSE_DATA”).as[String]
println(s"LOGIN - RESPONSE BODY: \n$response")
val token = session(“access_token”).as[String]
println( s"ACCESS TOKEN - $token")
bearer_token = "Bearer “.concat(token)
println( s"Bearer Token - $bearer_token”)
session
})

.exec(
http(“CREATE SUBSCRIPTION - POST”)
.post(":8619/telemetry-viewer/api/v1/restconf/data/nsp-telemetry-data-subscription:/subscriptions")
.header(“Content-Type” , “application/json”)
.header(“Authorization” , bearer_token)
.header(“Accept” , “application/json”)
.body(StringBody("""

{“subscription”: [{“name”: “ap_2”,“collection-interval”: 60,“time-from”: 1600261668962, “telemetry”: [{“id”: 0,“type”: “telemetry:/base/interfaces/interface”}]}]
}""".stripMargin)).asJson
.check(jsonPath("$" ).saveAs(“CREATE_SUBSCRIPTION_RESPONSE_DATA” )))

.exec(session => {
val res = session(“CREATE_SUBSCRIPTION_RESPONSE_DATA”).as[String]
println(s"CREATE SUBSCRIPTION - RESPONSE BODY: \n$res")
session
})

setUp(scn.inject(atOnceUsers(1)).protocols(httpProtocol))
}

Error during Run(when passed the variable):

Simulation TelemetryViewer.test started…
LOGIN - RESPONSE BODY:
{“access_token”:“VEtOLWFkbWluZjkxMmFmNzYtNzY0MS00Y2RkLTkwMTgtZWUxYjE1MWE0YTQ3”,“refresh_token”:“UkVUS04tYWRtaW5kNmFiNjE3NS02NTk2LTRlYmEtYmQxMC02NGY1ODY1NTFiYzc=”,“token_type”:“Bearer”,“expires_in”:3600}
ACCESS TOKEN - VEtOLWFkbWluZjkxMmFmNzYtNzY0MS00Y2RkLTkwMTgtZWUxYjE1MWE0YTQ3
Bearer Token - Bearer VEtOLWFkbWluZjkxMmFmNzYtNzY0MS00Y2RkLTkwMTgtZWUxYjE1MWE0YTQ3
14:07:22.436 [ERROR] i.g.c.a.b.SessionHookBuilder$$anon$1 - ‘hook-1’ crashed with ‘j.u.NoSuchElementException: No attribute named ‘CREATE_SUBSCRIPTION_RESPONSE_DATA’ is defined’, forwarding to the next one

You misunderstood how Gatling DSL works.

DSL components are builders that are loaded once on boot.

If you write .header(“Authorization” , bearer_token), you’re passing a value, which is null at this time. You have to pass a function: .header(“Authorization” , session => bearer_token)

Actually, using a mutable global isn’t something you should be doing unless you want to share the bearer amongst all virtual users (and then, you have to care about concurrency).
You should store your bearer in the Session, exactly like it’s being demoed in the tutorials.

I tried with session => bearer_token for the header parameter - Authorization. But got the same error.
Here is my full code for reference.

package TelemetryViewer
import io.gatling.commons.validation.Validation
import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._

class test extends Simulation{

  val headersLogin = Map(
    "Content-Type" -> "application/json",
    "Authorization" -> "Basic YWRtaW46Tm9raWFOc3AxIQ=="
  )

  val headersCreateSubscription = Map(
    "Content-Type" -> "application/json",
    "Accept" -> "application/json"
  )

  val httpProtocol = http
    .baseUrl("[https://135.121.156.59](https://135.121.156.59)") // Here is the root for all relative URLs

  val bearer_token = ""

  val scn =
    scenario("Telemetry Viewer Load Testing")
      .exec(
        http("Get Access Token - POST ")
          .post(":443/rest-gateway/rest/api/v1/auth/token")
          .headers(headersLogin)
          .body(StringBody(
            """
              >{
              >     "grant_type": "client_credentials"
              > }""".stripMargin)).asJson
          .check(status is 200)
          .check(jsonPath("$" ).saveAs("RESPONSE_DATA" ))
          .check(jsonPath("$.access_token").saveAs("access_token"))
      )

      .exec(session => {
        val response = session("RESPONSE_DATA").as[String]
        println(s"LOGIN - RESPONSE BODY: \n$response")
        val token = session("access_token").as[String]
        println( s"ACCESS TOKEN - $token")
        val bearer_token = "Bearer ".concat(token)
        println( s"Bearer Token - $bearer_token")
        session.set(bearer_token, "Bearer ".concat(token))
        session
      })

    .exec(
      http("CREATE SUBSCRIPTION - POST")
        .post(":8619/telemetry-viewer/api/v1/restconf/data/nsp-telemetry-data-subscription:/subscriptions")
        .header("Content-Type" , "application/json")
        .header("Authorization" , session => bearer_token)
        .header("Accept" , "application/json")
        .body(StringBody("""
                           >{
                           >    "subscription": [
                           >        {
                           >            "name": "ap_2",
                           >            "collection-interval": 60,
                                        "time-from": 1600261668962,
                           >            "telemetry": [
                           >                {
                           >                "id": 0,
                           >                "type": "telemetry:/base/interfaces/interface"
                           >             }
                           >            ]
                           >        }
                           >    ]
                           >}""".stripMargin)).asJson
        .check(jsonPath("$" ).saveAs("CREATE_SUBSCRIPTION_RESPONSE_DATA" ))
    )

    .exec(session => {
      val res = session("CREATE_SUBSCRIPTION_RESPONSE_DATA").as[String]
      println(s"CREATE SUBSCRIPTION - RESPONSE BODY: \n$res")
      session
    }
    )

  setUp(scn.inject(atOnceUsers(1)).protocols(httpProtocol))

}

You should take some time to read the documentation, it would save you
a lot of time.

https://gatling.io/docs/current/session/session_api/#setting-attributes

        session.set(bearer_token, "Bearer ".concat(token))
        session

[image: Logo] <https://gatling.io>
*Stéphane Landelle**Chief Technical Officer*
twitter: @slandelle <https://twitter.com/slandelle>
site: gatling.io