[从Jsonfile驱动数据以随机化数据时,找不到JsonPath路径异常

问题描述 投票:0回答:1

下面的代码是否存在问题,基本上是从Jsonfile驱动数据,我在下面创建随机数,所以eventidStart和eventidEnd从Json文件中获取各自的值,如下所示

var idNumbers=(eventidStart to eventidEnd).iterator
def eventidStart: Int  = JsonPath.parse(nameDataSource).read("$. 
[0].eventIdStart")
def eventidEnd: Int  = JsonPath.parse(nameDataSource).read("$. 
[0].eventIdEnd")

def getNextOrgId()=
 {

 if(!idNumbers.hasNext)
  idNumbers=(eventidStart to eventidEnd).iterator
Map("orgId"->idNumbers.next())
 }

这里是JsonFile[ { "eventIdStart": 1000080, "eventIdEnd": 1000100 } ]

这是加特林控制台的错误:-

Exception in thread "main" com.jayway.jsonpath.PathNotFoundException: 
Filter: [0]['eventIdStart'] can only be applied to arrays. Current context 
is: RecordSeqFeederBuilder(Vector(Map(eventIdStart -> 1000080, eventIdEnd 
-> 1000100)),Random)
at com.jayway.jsonpath.internal.path.ArrayPathToken.checkArrayModel(ArrayPathToken.java:184)
at com.jayway.jsonpath.internal.path.ArrayPathToken.evaluate(ArrayPathToken.java:47)
at com.jayway.jsonpath.internal.path.RootPathToken.evaluate(RootPathToken.java:62)
at com.jayway.jsonpath.internal.path.CompiledPath.evaluate(CompiledPath.java:53)
at com.jayway.jsonpath.internal.path.CompiledPath.evaluate(CompiledPath.java:61)
at com.jayway.jsonpath.JsonPath.read(JsonPath.java:187)
at com.jayway.jsonpath.internal.JsonContext.read(JsonContext.java:102)
at com.jayway.jsonpath.internal.JsonContext.read(JsonContext.java:89)
at simulations.gamekeeper.eventidStart(gamekeeper.scala:46)
at simulations.gamekeeper.<init>(gamekeeper.scala:45)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at io.gatling.app.Runner.run0(Runner.scala:79)
at io.gatling.app.Runner.run(Runner.scala:64)
at io.gatling.app.Gatling$.start(Gatling.scala:63)
at io.gatling.app.Gatling$.fromMap(Gatling.scala:40)
at GatlingRunner$.main(GatlingRunner.scala:17)
at GatlingRunner.main(GatlingRunner.scala)
  Process finished with exit code 1

这里是完整代码供参考

package simulations

import baseConfig.BaseSimulation
import com.jayway.jsonpath.JsonPath
import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._
import scala.concurrent.forkjoin.ThreadLocalRandom
import scala.language.postfixOps
import scala.math._

import scala.concurrent.duration.DurationInt
import scala.io.Source

class GamekeeperWithJsonfileAsInputforRandomEvents extends BaseSimulation  
{

val uri03 = "https://api.platform.wizards.com"



  val headers_10 = Map("Content-Type" -> 
  "application/json","Authorization" -> "${token_type} + ${access_token}" 
)

   val usersDataSource=jsonFile("C:data/input-gamekeeper.json").circular
   val  nameDataSource=jsonFile("C:/input-StringBody.json").random
   var idNumbers=(eventidStart to eventidEnd).iterator
  def eventidStart: Int  = JsonPath.parse(nameDataSource).read("$. 
 [0].eventIdStart")
  def eventidEnd: Int  = JsonPath.parse(nameDataSource).read("$. 
 [0].eventIdEnd")




private def getProperty(propertyName: String, defaultValue: String) = {
  Option(System.getenv(propertyName))
    .orElse(Option(System.getProperty(propertyName)))
    .getOrElse(defaultValue)
   }
   // now specify the properties
    //def userCount: Int = getProperty("USERS", "100").toInt

  val source: String =  Source.fromFile("C:/input- 
 gamekeeper.json").getLines.mkString
 def userCount: Int  = JsonPath.parse(source).read("$.[0].user")
 def testDuration: Int  = JsonPath.parse(source).read("$. 
 [0].testDuration")
 def rampDuration: Int  = JsonPath.parse(source).read("$. 
 [0].rampDuration")


 // print out the properties at the start of the test
 before {
   println(s"Running test with ${userCount} users")
   println(s"Ramping users over ${rampDuration} seconds")
   println(s"Total Test duration: ${testDuration} seconds")
 }

  def getNextOrgId()=
  {

   if(!idNumbers.hasNext)
  idNumbers=(eventidStart to eventidEnd).iterator
   Map("orgId"->idNumbers.next())
  }



  val customFeeder=Iterator.continually(getNextOrgId())






  def createEventRound()={
    repeat(990000000){


      exec(flushHttpCache)
      feed(customFeeder)
      .exec(http("CreateEventGameKeeper")


      .post("https://api.cloud/dev/gamekeeper/Round")
      .headers(headers_10)


      .body(StringBody(
        """
          |{
          |  "eventId": ${orgId},
          |  "roundStart": "2019-04-16T18:22:50.388Z",
          |  "roundEnd": "2019-04-16T18:22:50.388Z",
          |  "currentTime": "2019-04-16T18:22:50.388Z",
          |  "roundNumber": 1,
          |  "matches": [
          |    {
          |      "matchId": 0,
          |      "isBye": true,
          |      "tableNumber": "string",
          |      "teams": [
          |        {
          |          "teamId": 0,
          |          "teamName": "string",
          |          "players": [
          |            {
          |              "personaId": "string",
          |              "displayName": "string"
          |            }
          |          ]
          |        }
          |      ]
          |    }
          |  ]
          |}
        """.stripMargin)).asJSON

      .check(status.in(200,201))//checkforaspecificstatus
      .check(jsonPath(path="$.roundNumber").is("1"))
      .check(jsonPath(path="$.eventId").saveAs(key="eventId")))

    .exec{session=>println(session);session}//parameterfortheorgIdgoeshere
    .pause(1)

    }
  }





  val scenario2 = scenario("Post Orgs ")
  .exec(http("Event-Web-Image-Login")
    .get("https://api.cloud/dev/event-reservations- 
    web/img/loading.dfbfd678.svg")
   .headers(headers_1)
   .resources(http("Http Header Token Authentication Url")
     .options(uri03 + "/auth/oauth/token")
     .headers(headers_7),
     http("Token Generation Url For Post")
       .post(uri03 + "/auth/oauth/token")
       .headers(headers_8)
       .formParam("grant_type", "password")
       .formParam("username", "[email protected]")
       .formParam("password", .basicAuth("")
      .check(jsonPath("$.access_token").exists.saveAs("access_token"))
      .check(jsonPath("$.token_type").exists.saveAs("token_type"))





  ))
.forever() { // add in the forever() method - users now loop forever
  exec(createEventRound())


}

 // setup the load profile
 // example command line: ./gradlew gatlingRun- 
 simulations.RuntimeParameters -DUSERS=10 -DRAMP_DURATION=5 -DDURATION=30
 setUp(

 scenario2.inject(
  nothingFor(5 seconds),
  rampUsers(userCount) over ( rampDuration ))
  .protocols(httpConf))


.maxDuration(testDuration)

}
scala gatling jsonpath
1个回答
0
投票

此答案与JAVA代码有关。错误:线程“ main” com.jayway.jsonpath.PathNotFoundException中的异常:过滤器:[0] ['eventIdStart']仅可应用于数组。

解决方案:1)创建一个文件对象,并在同一构造函数中传递“ sourcePath”。2)制作'DocumentContext'对象,并传递上述文件对象3)创建一个String / int对象(根据要求)以读取JSON内容。4)编写:documentContextObject.read(“ Step 3 Object”)

例如:用于从JSON文件读取int ::

File file = new file(“ SourcePathOfJSONFile”);DocumentContext jsonContext = JsonPath.parse(file);

String path =“ $ .abc.plm”;int lst = jsonContext.read(path);


  1. 列表项

© www.soinside.com 2019 - 2024. All rights reserved.