Search code examples
scalagatlingscala-gatling

Gatling Need to run next scenario if previous scenario is passed using doIf


i am new to Scala and gatling. i need to run scenaio if previous scenario is passed using doIf.

My code is:

HttpRequest

object CompanyProfileRequest {

val check_company_profile: HttpRequestBuilder = http("Create Company 
 Profile")
.get(onboarding_url_perf + "/profile")
.headers(basic_headers)
.headers(auth_headers)
.check(status.is(404).saveAs("NOT_FOUND"))


val create_company_profile: HttpRequestBuilder = http("Create Company 
 Profile")
.post(onboarding_url_perf + "/profile")
.headers(basic_headers)
.headers(auth_headers)
.body(RawFileBody("data/company/company_profile_corporation.json")).asJson
.check(status.is(200))
.check(jsonPath("$.id").saveAs("id"))
 }

Scenario class is:-

 object ProfileScenarios {

  val createProfileScenarios: ScenarioBuilder = scenario("Create profile 
  Scenario")
  .exec(TokenScenario.getCompanyUsersGwtToken)
  .exec(CompanyProfileRequest.check_company_profile)
  .doIf(session => session.attributes.contains("NOT_FOUND")) {
   exec(CompanyProfileRequest.create_company_profile).exitHereIfFailed
   }
 }

And Simulation is :-

      private val createProfile = ProfileScenarios
     .createProfileScenarios
     .inject(constantUsersPerSec(1) during (Integer.getInteger("ramp", 1) 
     second))

     setUp(createProfile.protocols(httpConf))

Whenever i am running this simulation, I am not able to check this condition:-

.doIf(session => session.attributes.contains("NOT_FOUND"))

Any help is much appreciated.

Regards, Vikram


Solution

  • I was able to get your example to work, but here's a better way...

    the main issue with using

    .check(status.is(404).saveAs("NOT_FOUND"))
    

    and

    .doIf(session => session.attributes.contains("NOT_FOUND"))
    

    to implement conditional switching is that you've now got a check that will cause check_company_profile to fail when it really shouldn't (when you get a 200, for example).

    A nicer way is to use a check transform to insert a boolean value into the "NOT_FOUND" variable. This way, your check_company_profile action can still pass when the office exists, and the doIf construct can just use the EL syntax and be much clearer as to why it's executing.

    val check_company_profile: HttpRequestBuilder = http("Create Company Profile")
      .get(onboarding_url_perf + "/profile")
      .headers(basic_headers)
      .headers(auth_headers)
      .check(
        status.in(200, 404), //both statuses are valid for this request
        status.transform( status => 404.equals(status) ).saveAs("OFFICE_NOT_FOUND") //if the office does not exist, set a boolean flag in the session
      )
    

    now that you've got a boolean session variable ("OFFICE_NOT_FOUND") you can just use that in your doIf...

    .doIf("${OFFICE_NOT_FOUND}") {
       exec(CompanyProfileRequest.create_company_profile).exitHereIfFailed
    }