How to retrieve all values for a particular key in karate - karate

How to retrieve partNumbers from below response. In below response
"10000061","10000062","10000063"
are dynamic in nature. I have to match these partNumbers with data table partnumbers.( In a response there could be more than 10 part numbers(based on input) and i have to validate them.)
{ "added": true, "lineItems": { "1111111": { "itemCore": { "partNumber":
"10000061" } }, "222222": { "itemCore": { "partNumber": "10000061" } },
"3333333": { "itemCore": { "partNumber": "10000063" } } } }
Tried below
def partNum= get[0] response..itemCore.partNumber[*] but getting empty array.
def partNum= get[0] response..itemCore.partNumber but getting empty value.
My below second approach also giving me empty value.
* def keys = function(obj){ return response.lineItems.keySet() }
* json dynamicValue= keys(response)
* print 'dynamic value '+dynamicValue
* def first = dynamicValue[0]
* print response.lineItems.dynamicValue[0].itemCore.partNumber
* print response.lineItems.first.itemCore.partNumber

For retrieving data for a particular key, you can use deep scan operator in jsonPath,
* def partNumbers = karate.jsonPath(response,"$..partNumber")

Here's another solution, using karate.forEach() which can also operate on a map, not just a list:
* def keys = []
* eval karate.forEach(response.lineItems, function(k){ keys.add(k) })
* print keys

Related

How to partially match a JSON key in Karate

I have a response that looks this
{
"metadata": {
"Customer_x0020_Folder": "Test"
}
}
I would like the assert key Customer_x0020_Folder is equal to 'Test'. However I don't care about the x0020 portion of they key and would like to ignore that part. I would like to do something like:
match response contains { metadata: {'Customer_' + '#ignore' + '_Folder': 'Test'} }
How can I perform this assertion in Karate?
Use karate.keysOf():
* def response = { "metadata": { "Customer_x0020_Folder": "Test" } }
* def keys = karate.keysOf(response.metadata)
* match keys[0] == '#regex Customer_.*_Folder'

Karate - Exception raises for invalid jsonpath

I have a Json response like below. The difference here is my Json body has a number as the parent node.
def response =
"""
{
"22388043":[
{
"firstName":"Romin",
"lastName":"Irani",
"phoneNumber":"408-1234567",
"emailAddress":"romin.k.irani#gmail.com"
}
]
}
"""
I want to return the mobileNumber attribute value from the response body. In this scenario I don't have that attribute in my response. So here I want to get a null value.
So when I use * def mobile = $.22388043[0].mobileNumber, I'm getting below error.
No results for path: $['22388043'][0]['mobileNumber']
Please advise on this.
Karate does give you a way to get the values of JSON keys.
Hopefully this example answers all your other questions as well:
* def response =
"""
{
"22388043":[
{
"firstName":"Romin",
"lastName":"Irani",
"phoneNumber":"408-1234567",
"emailAddress":"romin.k.irani#gmail.com"
}
]
}
"""
* def id = karate.keysOf(response)[0]
* match id == '22388043'
* def person = response[id][0]
* match person contains { firstName: 'Romin', lastName: 'Irani' }
* match person.mobileNumber == '#notpresent'

Using karate.forEach and karate.set to extract index of value from json array

I have the below json:
{
"id": [
"1A",
"2B"
],
"name": [
"rs",
"mk"
]
}
I want to extract the id value when name is 'rs' or 'mk'. There will be no duplication of name values and the size of id and name keys will always match.
So i have created the following scenario where:
- I iterate through the name array using forEach.
- Find if the value of name matches rs or mk and if it does, retrieve the index.
- Then use this index to find the retrieve the value from id key.
When I run this, the name_rs_idx and name_mk_idx are not being set and are blank.
Scenario: Using forEach and karate.set
* def vals = { id: ['1A', '2B'], name: ['rs', 'mk'] }
* def name_rs_idx = ''
* def rsFun =
"""
function(x, i) {
if(x == 'rs') {
karate.set(name_rs_idx, i);
}
}
"""
* karate.forEach(vals.name, rsFun)
* print 'RS Index - ' + name_rs_idx
* def name_rs_id = vals.id[name_rs_idx]
* print 'RS id -' + name_rs_id
* def name_mk_idx = ''
* def mkFun =
"""
function(x, i) {
if(x == 'mk') {
karate.set(name_mk_idx, i);
}
}
"""
* karate.forEach(vals.name, mkFun)
* print 'MK Index - ' + name_mk_idx
* def name_mk_id = vals.id[name_mk_idx]
* print 'MK id -' + name_mk_id
Maybe i am not using the forEach function correctly or logic is incorrect.
I think you are over-complicating things :) Here is my solution, take time to read and understand it, it will improve your Karate fundamentals ! To simplify things, we first combine the data into an array of { name: '', id: '' } pairs. Then things become much easier.
* def vals = { id: ['1A', '2B'], name: ['rs', 'mk'] }
* def fun = function(x, i){ return { name: vals.name[i], id: vals.id[i] } }
* def pairs = karate.map(vals.name, fun)
* def fun = function(x){ return x.name == 'rs' || x.name == 'mk' }
* def filtered = karate.filter(pairs, fun)

How to test the order of an array in Karate

I want to test that the array that I get back from an endpoint is in a particular order, based on a field in the object, using Karate. For example, I might have data that looks like this:
[
{ seconds: 20 },
{ seconds: 15 },
{ seconds: 12 }
]
My goal is to test that the objects are listed in descending order.
I have a successful implementation of this test, but I am looking for a better way of doing it, if possible. Here is what I did to test the order:
* def orderTest = function() { for(var i = 0; i < response.length; i++) { if(i !== 0 && response[i].seconds > response[i-1].seconds) return false; } return true; }
Then assert orderTest()
While this seems to work as expected, it is ugly. Is there a better way to test the array's order?
Yes ! It becomes simple if you extract the numbers alone into an array - which behind the scenes is just a Java List so you can apply the Collections methods on it:
* def Collections = Java.type('java.util.Collections')
* def response =
"""
[
{ seconds: 20 },
{ seconds: 15 },
{ seconds: 12 }
]
"""
* def before = $response[*].seconds
* copy after = before
* Collections.sort(after, Collections.reverseOrder())
* match before == after

karate: finding index of the particular element value from API response

my code for finding index as below
* def list = nestActual #this is API response value which is given at the end
* def searchFor = { category_name: 'books3'}
* def foundAt = []
* def fun = function(x, i){ if (karate.match(x, searchFor).pass) foundAt.add(i) }
* eval karate.forEach(list, fun)
* print "==========foundAt=======" +foundAt
i have tried the above code for finding index where im getting foundAt index as null.
Below is my response where i want to find index of "category_name":"books3"
[
{
"category_id":1, "parent_cat_id":0, "category_name":"books", "slug_name":"books_1", "popular":true,
}, {
"category_id":2, "parent_cat_id":1, "category_name":"books2", "slug_name":"books_2", "popular":false,
}, {
"category_id":3, "parent_cat_id":1, "category_name":"books3", "slug_name":"books3_2", "popular":false,
}, {
"category_id":4, "parent_cat_id":3, "category_name":"mp3", "slug_name":"mp_3", "popular":false, }, {
"category_id":5, "parent_cat_id":3, "category_name":"mp4", "slug_name":"humoristiska_deckare_mysi_deck_3", "popular":false, }, {
"category_id":6, "parent_cat_id":3, "category_name":"video", "slug_name":"video3", "popular":false,
} ]
Please let me know how to find index of "category_name":"books3" using karate
Guess what, there is a far simpler way, the trick is to convert your search target into an array of primitives. Then you can use the List.indexOf() Java method:
Scenario: using the java indexOf api (will change with graal)
* def response = [{ name: 'a' }, { name: 'b' }, { name: 'c' }]
* def names = $[*].name
* def index = names.indexOf('b')
* match index == 1