HTTP 请求未执行之前和之后的 Gatling

Gatling Before and After HTTP requests not getting executed

我正在为我的 ElasticSearch 索引编写大量负载测试。我需要在负载测试中设置和拆除我的索引。为此,我写了这段代码

  before {
    println("going to setup index")
    scenario("SetupIndex")
        .exec(
            http("createindex")
                .put("/test")
        )
        .inject(atOnceUsers(1))
        .protocols(httpConf)
  }  

  setUp(
      scn
        .inject(
            constantUsersPerSec(10) during (60 seconds) randomized
        )
        .protocols(httpConf)
  )

  after {
    scenario("DeleteIndex")
        .exec(
            http("deleteindex")
                .delete("/test")
        )
        .inject(atOnceUsers(1))
        .protocols(httpConf)
    println("finished executing cleanup....")
  }

我看到它打印了 "finished executing cleanup" 但它并没有真正执行删除操作。我可以通过 curl -XDELETE http://localhost:9200/test

轻松删除索引

当我运行我的模拟。它 运行 成功了。但是我可以看到测试索引还在。

您不能在 beforeafter 中使用 Gatling DSL,或者更准确地说,您可以,但它不会像您预期的那样工作。 Gatling DLS 方法不执行任何它们用于创建 ScenarioBuilder 对象(这更像是一个配置而不是可执行代码)然后它可以传递给要执行的 setUp 方法(也不是直接)。但是在 beforeafter 方法中,您使用普通的 Scala,因此如果您在其中放置一个 scenario 方法,您将只创建一个从未使用过的新 ScenarioBuilder 对象。因此,如果您想从这些方法中 运行 一些 API 调用,那么您必须使用一些 http 客户端。

你可以使用添加在库中的jar,比如okhttp。例如:

import okhttp3.{OkHttpClient,Request}     
before {
    println("Simulation is about to start!")


    val request = new Request.Builder().url("http://computer-database.gatling.io").build
    val response = new OkHttpClient().newCall(request).execute()

    println(response.body().string())
    if (response != null) response.close()

    println("Simulation initialized!")
  }

Gatling 使用导入 io.gatling.http.client.HttpClient。没有添加库你应该可以使用这个。