本文介绍了空手道:比较CSV数据和api响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例,我想对API响应进行断言,并将其与csv数据进行比较.

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

第一步:

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

我读取了csv文件并将其存储在变量中

I read the csv file and store it in a variable

  • def var1 =读取(test.csv)

所以现在,var1是基于我的csv的json列表

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"
}
]

第2步:我打了我的api并得到了回应

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

第3步:我的api返回一个列表响应,即:

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..
]

第4步:因此,我现在要执行两个断言

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

  1. 获取csvresponse和apiresponse的计数,并使用 .length 运算符

其次,我想确认每个csv记录是否与每个api响应匹配.如果可能的话,来自csv和apiresponse的 id 键是主键,因此,如果我可以迭代id并匹配api响应以解决任何差异.

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.

推荐答案

请阅读match contains语法,这就是您所需要的: https://github.com/intuit/karate#match-contains

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

所以这一行就足够了:

* match var1 contains response

如果新的contains deep有帮助,也请查看以下答案: https://stackoverflow.com/a/63103746/143475

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

尽量避免重复,大多数API测试都不需要它.但是您当然可以做到.查看以下答案:

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

也请阅读此内容-因为我怀疑您正在尝试使测试过于复杂.请不要.在100%确定形状"正确的地方编写测试.尽可能多的响应: https://stackoverflow.com/a/54126724/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.

这篇关于空手道:比较CSV数据和api响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 20:35