使用存根值

时间:2017-02-21 21:04:11

标签: json scala load-testing gatling

如何根据JSON文件编写自定义Gatling进纸器,该文件具有某些存根值并且在发送之前需要更换?例如

{"payloads":[
  {"groupId":"<GUID>", "epoch":<TIME>, "report":"somethingInteresting1"},
  {"groupId":"<GUID>", "epoch":<TIME>, "report":"somethingInteresting2"},
  {"groupId":"<GUID>", "epoch":<TIME>, "report":"somethingInteresting3"}
]}

jsonFile("/opt/gatling/user-files/simulation/cannedPayloads.json")

我认为没有工作,因为它在文件中实际上并不是有效的JSON。我试过了:

val jsonFileContents = Source.fromFile("/opt/gatling/user-files/simulation/cannedPayloads.json").getLines.mkString
.replaceAll("<GUID>", java.util.UUID.randomUUID().toString())
.replaceAll("<TIME>", Instant.now().toEpochMilli().toString())

val feeder = JsonPath.query("$.payloads[*]", jsonFileContents).right.get.toArray.circular

val scn1 = scenario("CannedTestSimulation").exec(feed(feeder).exec(
  http("to ingestion").post(url).body(StringBody("$")).asJSON
)

1 个答案:

答案 0 :(得分:0)

我通过阅读文件,执行我的替换,将其写入临时文件,并使用Gatling中的jsonFile构建来环绕它。 JSON基础成了

[
  {"groupId":"<GUID>", "epoch":<TIME>, "report":"somethingInteresting1"},
  {"groupId":"<GUID>", "epoch":<TIME>, "report":"somethingInteresting2"},
  {"groupId":"<GUID>", "epoch":<TIME>, "report":"somethingInteresting3"}
]

场景变为

val scn1 = scenario("CannedTestSimulation").feed(jsonFile(CannedRequests.createTempJsonFile())).exec(
  http("send data").post(url).body(StringBody("$")).asJSON
)

和CannedRequests成为

object CannedRequests {
val jsonFile = "/opt/gatling/user-files/simulations/stubbed_data.json"


def jsonFileContents(testSessionId: String): String = 
Source.fromFile(jsonFile).getLines.mkString
.replaceAll("<GUID>", "gatling_"+testSessionId)
.replaceAll("<TIME>", Instant.now().toEpochMilli().toString())

def createTempFile(contents: String, testSessionId: String): File = {
 val tempFile = File.createTempFile(testSessionId, ".json")
 val bw = new BufferedWriter(new FileWriter(tempFile))
 bw.write(contents)
 bw.close

 tempFile
}

def createTempJsonFile():String = {
val tempSessionId = java.util.UUID.randomUUID().toString()
val tempContents = jsonFileContents(tempSessionId)
val tempFile = createTempFile(tempContents, tempSessionId)

tempFile.getAbsolutePath
}
}