Как поместить ответ json в цикл с условием?

Я проанализировал ответ json и сохранил его с помощью .findAll (). Что я хочу сделать, так это игнорировать keyframeId, если значение равно '-1', иначе поместить keyframeId в запрос .get () с помощью цикла. Я написал код, но значение не установлено в запросе get () и выдает «KO». Здесь он берет все значения в векторе и помещает все в один HTTP-вызов, см. Подробности об ошибке. Также я не уверен в условии doIf. Не могли бы вы помочь? Спасибо. У меня такой формат ответа Json.

{
totalCount: 1134,
limit: 9,
offset: 0,
resources: [
        {
        title: "Test",
        keyframeId: -1
        }
        {
        title: "Test1",
        keyframeId: 12345
        }
        {
        title: "Test2",
        keyframeId: 12341
        }
        {
        title: "Test3",
        keyframeId: -1
        }
        {
        title: "Test4",
        keyframeId: 135481
        }
        ....
        ....
]}

Вот сценарий Гатлинга,

import scala.concurrent.duration._
import io.gatling.core.Predef._
import io.gatling.http.Predef._
import io.gatling.jdbc.Predef._

class MamamSearch extends Simulation {

    val testServerUrl = System.getProperty("testServerUrl", "https://someurl")
    val username = System.getProperty("username", "ma")
    val password = System.getProperty("password", "ma")
    val userCount = Integer.getInteger("userCount", 1).toInt

    val httpProtocol = http
        .baseURL(testServerUrl)
        .inferHtmlResources(BlackList(""".*\.js""", """.*\.css""", """.*\.gif""", """.*\.jpeg""", """.*\.jpg""", """.*\.ico""", """.*\.woff""", """.*\.(t|o)tf""", """.*\.png"""), WhiteList())

    val headers_0 = Map(
        "Accept" -> "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "Cache-Control" -> "max-age=0",
        "Upgrade-Insecure-Requests" -> "1")

    val headers_2 = Map("Accept" -> "text/css,*/*;q=0.1")

    val headers_6 = Map(
        "Accept" -> "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "Accept-Encoding" -> "gzip, deflate, br",
        "Cache-Control" -> "max-age=0",
        "Origin" -> testServerUrl,
        "Upgrade-Insecure-Requests" -> "1")

    val headers_80 = Map(
        "Accept" -> "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "Upgrade-Insecure-Requests" -> "1")

    val headers_7 = Map("Accept" -> "image/webp,image/*,*/*;q=0.8")

    val headers_11 = Map("Origin" -> testServerUrl)

    val headers_12 = Map(
        "Cache-Control" -> "no-cache",
        "If-Modified-Since" -> "Mon, 26 Jul 1997 05:00:00 GMT",
        "Pragma" -> "no-cache",
        "X-Requested-With" -> "XMLHttpRequest")

    val headers_15 = Map(
        "Accept" -> "application/json, text/plain, */*",
        "Cache-Control" -> "no-cache",
        "If-Modified-Since" -> "Mon, 26 Jul 1997 05:00:00 GMT",
        "Pragma" -> "no-cache",
        "X-Requested-With" -> "XMLHttpRequest")

    val headers_16 = Map("Accept" -> "*/*")

    val headers_18 = Map(
        "Accept" -> "text/html",
        "Cache-Control" -> "no-cache",
        "If-Modified-Since" -> "Mon, 26 Jul 1997 05:00:00 GMT",
        "Pragma" -> "no-cache",
        "X-Requested-With" -> "XMLHttpRequest")

    val headers_19 = Map(
        "Accept" -> "*/*",
        "Accept-Encoding" -> "gzip, deflate, br",
        "Origin" -> testServerUrl)

    val headers_27 = Map(
        "Accept" -> "*/*",
        "Accept-Encoding" -> "gzip, deflate, br",
        "Content-type" -> "text/plain",
        "Origin" -> testServerUrl)

    val uri1 = testServerUrl + "/mamam"
    val uri2 = "https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0"

    // Login request
    val scn = scenario("MamamSearch")
        .exec(http("Login")
            .post("/mamam/a/masteraccount/login")
            .headers(headers_6)
            .formParam("username", username)
            .formParam("password", password))


    //  Fetch and save data
    .exec(http("Keyframe_request")
            .get(uri1 + "/awsset/browse%3Bresource_type=media%3Boffset=1%3Blimit=9")
            .headers(headers_12)
            .check(jsonPath("$.resources[*].keyframeId").findAll.saveAs("kList"))
            )

    // added loop and conditions
    .doIf(session => session("Keyframe_request").validate[String].map(kList => !kList.contains("-1")))
    {
        foreach("${kList}", "keyId") {
            exec(http("Set_Keyframes")
                .get(uri1 + "/keyframes/${kList};width=185;height=103")
                .headers(headers_7))
        }       
    }   

    .exec(http("Logout")
        .get("/mam/logout")
        .headers(headers_80))       

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

Выдает следующую ошибку:

21345 [GatlingSystem-akka.actor.default-dispatcher-13] WARN  i.g.http.ahc.AsyncHandlerActor - Request 'Set_Keyframes' failed: status.find.in(200,304,201,202,203,204,205,206,207,208,209), but actually found 400
21346 [GatlingSystem-akka.actor.default-dispatcher-13] DEBUG i.g.http.ahc.AsyncHandlerActor - 
>>>>>>>>>>>>>>>>>>>>>>>>>>
Request:
Set_Keyframes: KO status.find.in(200,304,201,202,203,204,205,206,207,208,209), but actually found 400

21390 [GatlingSystem-akka.actor.default-dispatcher-4] INFO  io.gatling.http.ahc.HttpEngine - Sending request=Set_Keyframes uri=https://someurl/mamam/keyframes/Vector(167154,%20167035,%20167037,%20167040,%20167029,%20167024,%20167026,%20167022,%20167023);width=185;height=103:

person Peter    schedule 26.10.2016    source источник


Ответы (1)


Если я правильно понял, вы хотите взять значение из ответа и затем использовать его в следующем запросе. Во-первых, вы должны сохранить правильный keyframeId.

Что было неясно, так это то, хотите ли вы выбрать случайный keyframeId из своего списка или несколько ключевых кадров, я решил выбрать случайный.

Во-первых, мы должны применить некоторый jsonPath к нашему ответу JSON. Этот код .check(jsonPath("$.resources[?(@.keyframeId > -1)].keyframeId") вернет только список идентификаторов ключевых кадров, которые больше -1.

Затем мы выбираем случайный и сохраняем его в переменной.

//  Fetch and save data
.exec(http("Keyframe_request")
  .get(uri1 + "/awsset/browse%3Bresource_type=media%3Boffset=1%3Blimit=9")
  .headers(headers_12)
  .check(jsonPath("$.resources[?(@.keyframeId > -1)].keyframeId")
      .ofType[String]
      .findAll
      .transform(s => util.Random.shuffle(s).apply(1))
      .saveAs("keyframeId"))

Теперь вам просто нужно проверить, существует ли переменная сеанса keyframeId, и использовать ее для управления своим ответом с помощью ${keyframeId}

person Questioning    schedule 06.12.2016