Karate: compare csv data with api response

孤街浪徒 提交于 2020-08-09 09:24:06

问题


I have a use case where I want to assert on a API response and compare it with the csv data.

Step1:

Csv file: *test.csv*
id,date,fullname,cost,country,code
1,02-03-2002,user1,$200,Canada,CAN
2, 04-05-2016,user2,$1500,United States, USA

I read the csv file and store it in a variable

  • def var1 = read(test.csv)

So now, var1 is a list of jsons based on my csv

var1 = [
{
"id":1,
"date":"02-03-2002",
"fullname": "user1",
"cost": "$200",
"country": "Canada",
"code": "CAN"
},
{
"id":2,
"date":"04-05-2016",
"fullname": "user2",
"cost": "$1500",
"country": "United States",
"code": "USA"
}
]

Step2: I hit my api and get a response

Given url "https://dummyurl.com
Given path "/userdetails"
When method get
Then status 200
* def apiResponse = response

Step 3: My api returns a list response which is:

{
"id":1,
"date":"02-03-2002",
"fullname": "user1",
"cost": "$200",
"country": { 
  "name": "Canada",
  "code": "CAN"
  }
},
{
"id":2,
"date":"05-04-2012",
"fullname": "user2",
"cost": "$1500",
"country": { 
  "name": "United States",
  "code": "USA"
  }
},
...and more 100 records..
]

Step 4: So there are two assertions now which I wanted to perform

  1. Get the count of csvresponse and apiresponse and compare which I did using the .length operator

  2. Secondly, I want to confirm if each csv records are matching with each api response. And if possible in my case id key from csv and apiresponse is primary key, so if I can iterate on id and match the api response for any discrepancy.

Let me know if this is readable for you and if I was able to explain my use case. Thanks for your earlier response.


回答1:


Please read up on the match contains syntax, that's all you need: https://github.com/intuit/karate#match-contains

So this one line should be enough:

* match var1 contains response

Also look at this answer in case the new contains deep helps: https://stackoverflow.com/a/63103746/143475

Try to avoid iterating, it is not needed for most API tests. But you can certainly do it. Look at these answers:

https://stackoverflow.com/a/62567262/143475

Also read this - because I suspect you are trying to over-complicate your tests. Please don't. Write tests where your are 100% sure of the "shape" of the response as far as possible: https://stackoverflow.com/a/54126724/143475

And please please read the docs. It is worth it.



来源:https://stackoverflow.com/questions/63139613/karate-compare-csv-data-with-api-response

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!