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

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]

Related

How to Print Index value for matching JSON data using Karate

I would like to print the index value for matching JSON data using Karate.
For below code the expected answer should be 2, but I got -1, not sure what I am missing
[
{"aaa": 101},
{"bbb": 102},
{"ccc": 103}
]
Feature: Rough
Scenario: Rough
* def myData = read('roughTestData.json')
* print "Index ->>", myData.indexOf('ccc')
You have a JSON object within an array (not a plain string), and the complication here is you are interested in keys not values, so you need to do this instead:
* def response = [{"aaa":101},{"bbb":102},{"ccc":103}]
* def keys = response.map(x => Object.keys(x)[0])
* def index = keys.indexOf('ccc')
* match index == 2
We are using JS array methods such as map(), Object.keys() and indexOf() above
That said, I personally think you are over-complicating things because Karate allows you to match without caring about the order. For example:
* def response = [{"aaa":101},{"bbb":102},{"ccc":103}]
* def expected = [{ccc:'#number'},{bbb:'#number'},{aaa:'#number'}]
* match response contains only expected
So read the docs, and be creative: https://github.com/karatelabs/karate#json-arrays

Modified variable name in karate framework [duplicate]

This question already has an answer here:
Karate Http request add param conditionally
(1 answer)
Closed 1 year ago.
I want to modified param variable for my request(GET/POST) dynamically. As I have 2 different environment which takes different parameters for same request.
I tried below code, but not able to replace param variable(name).
I can replace param value successfully.
This function generate the dynamic param name for different enviornment
public static String paramDynamicVariable(String env, String param) {
String paramValue;
if (env.equals("test")) {
paramValue = '$' + param;
} else {
paramValue = param;
}
return paramValue;
}
Now when I am using paramValue in my test--
Scenario: xyz
Given path URLOfRequest
* print paramDynamicVariable(karate.env,'nameParam')
And param random.paramDynamicVariable(karate.env,'nameParam') = 10
It prints correct value, but in the next line it is not replacing for param name.
Please suggest if any solution is there to dynamic param name.
Please do something like this:
* def nameParam = paramDynamicVariable(karate.env, 'nameParam')
* def paramValues = {}
* paramValues[nameParam] = 10
And then:
* params paramValues
Since params accepts any JSON, all you need to do is create the JSON. Since the key is dynamic, it requires you to do a little more work.

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

Expression with String placeholder in the filter part of JsonPath using karate

I am trying to filter my response using JSON Path where one of the condition using a value from a variable but I am not able to map variable properly, so my filter not working properly.
Sample response JSON:
{
"response":[
{
"id":"1234",
"confirmationCode":"abcd"
}
]
}
I am using the below script where I am using variable 'code':
* def Code = 'abcd'
* def value = karate.jsonPath($.response[?(#.confirmationCode == ' + Code +')])
Read the docs carefully please:
* def value = karate.jsonPath(response, "$.response[?(#.confirmationCode=='" + Code + "')]")

How to convert objectid to string

I want to get the string character from an ObjectId object. I use pymongo.
eg: ObjectId("543b591d91b9e510a06a42e2"), I want to get "543b591d91b9e510a06a42e2".
I see the doc, It says ObjectId.toString(), ObjectId.valueOf().
So I make this code: from bson.objectid import ObjectId.
But when I use ObjectId.valueOf(), It shows:
'ObjectId' object has no attribute 'valueOf'.
How can I get it? Thanks.
ObjectId.toString() and ObjectId.valueOf() are in Mongo JavaScript API.
In Python API (with PyMongo) proper way is to use pythonic str(object_id) as you suggested in comment, see documentation on ObjectId.
ObjectId.toString() returns the string representation of the ObjectId() object.
In pymongo str(o) get a hex encoded version of ObjectId o.
Check this link.
What works for me is to "sanitize" the output so Pydantic doesn't get indigestion from an _id that is of type ObjectId...here's what works for me...
I'm converting _id to a string before returning the output...
# Get One
#router.get("/{id}")
def get_one(id):
query = {"_id": ObjectId(id)}
resp = db.my_collection.find_one(query)
if resp:
resp['_id'] = str(resp['_id'])
return resp
else:
raise HTTPException(status_code=404, detail=f"Unable to retrieve record")
Use str(ObjectId), as already mentined in the comment by #Simon.
#app.route("/api/employee", methods=['POST'])
def create_employee():
json = request.get_json()
result = employee.insert_employee(json)
return { "id": str(result.inserted_id) }
This is an old thread, but as the existing answers didn't help me:
Having run
new_object = collection.insert_one(doc)
I was able to get the ObjectID with the inserted_id property:
print(f"{new_object.inserted_id}")
In python (Pymongo) there's no inbuilt method to do it so iterate over the result you fetched from db and then typecast _id to str(_id)
result = collection.find({query})
for docs in result:
docs[_id] = str(docs[_id])
first you have to assign the Object Id value to a variable
for example:
let objectId = ObjectId("543b591d91b9e510a06a42e2");
then use the toString method like this
let id = objectId.toString();