Body length compared to expected length stored in session

I’m trying to perform a check on the expected length of the response body, with a body length that depends on a randomly generated URL, using the following code:

exec({
http(“pull”)
.get(session => {
val objectsForThisRequest = validObjects.filter(x => rand.nextBoolean()) //validObjects is static defined outside, this just selects a random combination of them
val expectedResponseLength = expectedLength(objectsForThisRequest) //calculates my expected response length
session.set(“response_length”, expectedResponseLength)
val str = pullURL(objectsForThisRequest.map(x => x.getHash)) //generates an actual URL
str
})
.check(bodyBytes.transform(_.length).is(session => session(“response_length”).as[Int])) //Tries to retrieve expected response length from the session and compare to expected value
})

I originally had it defining objectsForThisRequest in the outer block, but this was causing it to use the same URL every time, as it was just a static string being passed in, rather than an Expression[String]. Switching it to how I have it now, where it stores the expected length in the session, and then tries to retrieve it in the check, seems like it should work, but I keep getting ‘key not found: response_length’.

I also tried changing the exec() to be as follows, but then it doesn’t do any requests (“java.lang.UnsupportedOperationException: There were no requests sent during the simulation, reports won’t be generated”).

exec(session => {
val objectsForThisRequest = validHashes.filter(x => rand.nextBoolean()) //validObjects is static defined outside, this just selects a random combination of them
val expectedResponseLength = expectedLength(objectsForThisRequest) //calculates my expected response length
http(“pull”)
.get({
val str = pullURL(objectsForThisRequest.map(x => x.getHash))
str
})
.check(bodyBytes.transform(_.length).is(expectedResponseLength) //Tries to check the actual response length against the expected
)
session //return the session
})

I also tried using a var in the outer code, which I then changed after calculating expected response length, but this ran into synchronization issues - it would occasionally compare it to 0 (the initial value) rather than what I set it to.

Is there a way I can either retrieve the expected length within the check call (like I tried to do in the first one) or actually execute the request I defined in the second one?

You have several things wrong:

  1. Session is immutable, so calling Session#set and not returning the result is plain wrong: http://gatling.io/docs/2.1.7/session/session_api.html#setting-attributes
  2. The Gatling DSL components are immutable builders that have to be chained/attached together. Creating a DSL component such as a http request (just a definition) inside a exec(function) doesn’t work. Chain resolution only happens once, when the Simulation is loaded. Those functions are executed later, at runtime.