How to convert "Number" into number In karate [duplicate] - api

This question already has an answer here:
Is there numeric value comparison available in Karate testing framework?
(1 answer)
Closed 2 years ago.
How to convert this "2203" to 2203
Tried with some given examples, no Luck
Jobid="2203"
* def Jobid = response # Jobid="2203"
* def intJobid = function(x){ x.Jobid = ~~x.Jobid; return x }
* def results = karate.map(intJobid, Jobid)
* match results == #number

Use parseInt() to convert string to number. An alternative is to just multiply the string with 1. e.g.
* def foo = '10'
* string json = { bar: '#(1 * foo)' }
* match json == '{"bar":10.0}'
* string json = { bar: '#(parseInt(foo))' }
* match json == '{"bar":10.0}'
Source: https://intuit.github.io/karate/#floats-and-integers

Related

Karate API Converting String from JSON Response into UPPERCASE [duplicate]

This question already has an answer here:
How to extract value in double quotes from a response header in karate
(1 answer)
Closed 1 year ago.
JSON Response has __typename in the response.
I am defining and storing it so I can use this in the next graphQL Request
def contentType1 = response.data.getPublicList.items[0].__typename
__typename comes back as "Movie"
The next Request requires "Movie" to be "MOVIE"
query {
getContentById(id: "", contentType: "MOVIE") {
Is there a way I can convert/define the entire string value as UPPERCASE?
That should be easy, behind the scenes it is a "Java" string, so there are methods you can use:
* def contentType1 = 'Movie'
* def after = contentType1.toUpperCase()
* match after == 'MOVIE'
EDIT: If you want to convert "in place", just do JS-style operations:
* def data = { foo: 'bar' }
* data.foo = data.foo.toUpperCase()
* match data == { foo: 'BAR' }
If you need more sophistication, please look at the docs for JSON transforms: https://github.com/karatelabs/karate#json-transforms

Karate : Trying to convert array to string using js method toString() in karate [duplicate]

This question already has an answer here:
Change type from string to float/double for a key value of any json object in an array
(1 answer)
Closed 1 year ago.
I'm trying to convert an Array to string using a simple js function placed in the reusable feature file. I don't see any reason why the array is not getting converted to a string when I try to run the same function on the console it works without any issue.
Can anyone suggest a way to get this issue sorted?
"""
* def formatter = function(str){
var formatstring = str.toString();
return formatstring
}
"""
feature file
* def format = call read('../common/resuable.feature)
* def result = format.formatter(value)
* print result
Input = ["ID3:Jigglypuff(NORMAL)"]
Actual result = ["ID3:Jigglypuff(NORMAL)"]
Expected result = ID3:Jigglypuff(NORMAL)
[![When tried same on console][1]][1]
[1]: https://i.stack.imgur.com/tAcIz.png
Sorry, if you print an array, it will have square-brackets and all, that's just how it is.
Please unpack arrays if you want the plain string / content:
* def input = ["ID3:Jigglypuff(NORMAL)"]
* def expected = input[0]

Convert all ints to double in Json [duplicate]

I am getting a JSON response with JSONArray having leading zeros. Example, registrationnumber = ["0000012345", "0000001234", "000123456"]
I want to remove these zeros and compare with another json response where I get the registrationNumber =["12345", "1234", "123456"]
I am trying to do this with my automation in karate-dsl.
Can someone help?
Thanks.
To convert to a number just multiply by 1. You should read the docs: https://github.com/intuit/karate#type-conversion
* def data = ["0000012345", "0000001234", "000123456"]
* def nums = karate.map(data, function(x){ return parseInt(x) })
* match nums == [12345, 1234, 123456]

Change type from string to float/double for a key value of any json object in an array

i have a json as follows:
* def first = [{"country":"X","code":"XY","cityName":"XYZN","city":"XYZ","timezone":"XYZT","latitude":"57.0928","name":"XYZN","longitude":"9.8492"}, {"country":"A","code":"AB","cityName":"ABCN","city":"ABC","timezone":"ABCT","latitude":"1.234","name":"ABCN","longitude":"29.8482"}]
def second = [{"country":"X","code":"XY","cityName":"XYZN","city":"XYZ","timezone":"XYZT","latitude":57.0928,"name":"XYZN","longitude":9.8492}, {"country":"A","code":"AB","cityName":"ABCN","city":"ABC","timezone":"ABCT","latitude":1.234,"name":"ABCN","longitude":29.8482}]
i want to compare these two, but its failing because the first json has longitude and latitude as string while second json has them as numbers.
Also, i dont want to change second json and has to be used as it is.
Please suggest how can i change the type from string to number in first?
I tried https://github.com/intuit/karate#floats-and-integers
but it didnt work out for object array.
Sample Code:
Feature:
Scenario:
* def first = [{"country":"X","code":"XY","cityName":"XYZN","city":"XYZ","timezone":"XYZT","latitude":"57.0928","name":"XYZN","longitude":"9.8492"}, {"country":"A","code":"AB","cityName":"ABCN","city":"ABC","timezone":"ABCT","latitude":"1.234","name":"ABCN","longitude":"29.8482"}]
* def second = [{"country":"X","code":"XY","cityName":"XYZN","city":"XYZ","timezone":"XYZT","latitude":57.0928,"name":"XYZN","longitude":9.8492}, {"country":"A","code":"AB","cityName":"ABCN","city":"ABC","timezone":"ABCT","latitude":1.234,"name":"ABCN","longitude":29.8482}]
* def first_formatted = []
* def fun = function(x){x.latitude = Number(x.latitude); x.longitude = Number(x.longitude); karate.appendTo(first_formatted, x); }
* karate.forEach(first, fun)
* print first_formatted
* match first_formatted == second

Unable to Parse the variable value to the array variable

I was trying to pass the variable 'i' value to a array index 'locations[i]' using below karate code. but throwing an error saying unable to parse. Please suggest be for any changes.
Feature: Verify Branches
Background: For loop implementation
Given url ''
When method GET
Then status 200
* def i = 0
* def z = $.locations[i].zip
* def p = $.locations[i].phone
* def fun =
"""
function(locations){
for (var i = 0; i < locations.length; i++)
{
print(i)
print('Element at Location ' + i +':' + p)
}
}
"""
Scenario: Validate the locations
Given url ''
When method GET
Then status 200
* call fun p
It is hard to make out anything since you have not provided the value of the response. There are many things wrong here. But I'll try.
Take this line:
* def z = $.locations[i].zip
This will not work, Karate does not support variables within JsonPath by default, refer the docs: https://github.com/intuit/karate#jsonpath-filters
And I think you are un-necessarily using JsonPath where normal JavaScript would have been sufficient:
* def z = response.locations[i].zip
Also it seems you are just trying to loop over an array and call a feature. Please refer to the documentation on Data Driven Features.
Take some time and read the docs and examples please, it will be worth your time. One more tip - before I leave you to understand Karate a little better. There is a way to convert a JSON array into another JSON array should you need it:
* def fun = function(x){ return { value: x } }
* def list = [1, 2, 3]
* def res = karate.map(list, fun)
* match res == [{ value: 1 }, { value: 2 }, { value: 3 }]
So there should never be a need for you to manually do a for loop at all.