如何在加特林比较来自http调用的响应?

时间:2019-07-06 03:47:33

标签: scala gatling scala-gatling gatling-jsonpath

我在2个不同的函数def中有2个http调用,并在加特林会话中从响应主体保存json键。我该如何搭配?

def getAppData():HttpRequestBuilder = {
      http("get application resource")
        .get("host/app")
        .header("Authorization", "Bearer "+ token)
        .check(status.is(200))
        .check(jsonPath("$..${app_info}").saveAs("app_Response"))

}
def getUserData():HttpRequestBuilder = {
      http("get user data ")
        .get("host/user/data")
        .header("Authorization", "Bearer "+ token)
        .check(status.is(200))
        .check(jsonPath("$..${user_info}").saveAs("userdata_Response"))

}

如何比较或验证app_info和user_info的json值是否匹配,即;

app_Responseuserdata_Response

这两个值都是arrays。例如,采用以下格式:

"app_info":
    [
         "name",
         "address"
    ]

与user_info相同。我尝试使用jsonPath()。equals()的内置方法,但我认为这不是比较合适的方法。如果不是使用特定方法的方法,那么也许会发现如何使用Scala执行?

请帮助。

1 个答案:

答案 0 :(得分:1)

基本上,您使用的是json-spray,您应该能够使用==运算符(如此处其他答案所述)进行比较。

Compare json equality in Scala

[编辑] 做这样的事情,我可以比较使用喷雾剂的2个Json:

package example

import io.gatling.core.Predef._
import io.gatling.http.Predef._
import spray.json._
import DefaultJsonProtocol._

class MainSimulation extends Simulation {
  val baseUrl = "http://localhost:8080"
  val httpProtocol = http
    .baseUrl(baseUrl)
    .userAgentHeader("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)")
  val header = Map("Content-Type" -> "application/json”,”Accept-Charset" -> "utf-8")

  val scn = scenario("Scenario")
    .exec(http("Get Hello Json")
      .get("/hello/Alessandro")
      .check(status.is(200))
      .check(jsonPath("$").saveAs("activities-1")))
    .exec(http("Get Hello Json")
      .get("/hello/Ronaldo")
      .check(status.is(200))
      .check(jsonPath("$").saveAs("activities-2")))
    .exec(session => {
      println("=======================================================")
      val activities_1 = session("activities-1").as[String]
      val activities_2 = session("activities-2").as[String]
      println(s"Activities 1: ${activities_1.parseJson}")
      println(s"Activities 2: ${activities_2.parseJson}")
      println(s"Are they equal?: ${activities_1.parseJson == activities_2.parseJson}")
      println("=======================================================")
      session
    })

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

我可以在输出中看到它:

=======================================================
Activities 1: {"activities":["swimming","soccer"],"name":"Alessandro"}
Activities 2: {"activities":["swimming","soccer"],"name":"Alessandro"}
Are they equal?: true
=======================================================