Karate match two json files(expected json and API response) irrespective of the order of array elements - karate

Expected Response:
{"data":{
{"assignments":[{"locationId":"1186755","locationName":"X.11.11"},{"locationId":"1186756","locationName":"X.11.12"}]}}}
Response:
{"data":{
{"assignments":[{"locationId":"1186756","locationName":"X.11.12"},{"locationId":"1186755","locationName":"X.11.11"}]}}}
I saw a SO post stating to use karate.sort(response, x=>x.locationId), when i tried it's giving me empty response. Is there any simple way i can achieve do the comparison of whole response file irrespective of order?
Note: I even tried contains only, but it's failing the assertion.

Just use contains deep: https://stackoverflow.com/a/64373344/143475
* def response = {"assignments":[{"locationId":"1186755","locationName":"X.11.11"},{"locationId":"1186756","locationName":"X.11.12"}]}}}
* match response contains deep {"assignments":[{"locationId":"1186756","locationName":"X.11.12"},{"locationId":"1186755","locationName":"X.11.11"}]}}}

Related

Karate netty/mock schema match not working [duplicate]

I have a request that is hitting my mock server... the request is in json, but one of the values is a string of about 2,000+ characters.. I am wanting to match the request if the string value (of 2,000+ characters) contains a specific substring value...
for example:
Scenario:
pathMatches('/callService') &&
methodIs('post') && request.clientDescription contains 'blue eyes'
(request.clientDescription = string of 2,000+ characters)
It seems that it does not like the key word contains and I can't seem to find any information on the syntax I would use to search through a given string in a request and see if it contains a specific value.
I understand that I could try to match the entire string value using '==', but I am looking for a way to only match if it contains a substring.
Here's a tip, whatever you see on the right of Scenario: is pure JavaScript, and methodIs() etc. happen to be pre-defined for your convenience.
So this should work, using String.includes()
Scenario: request.clientDescription.includes('blue eyes')
Also please refer this answer for other ideas: https://stackoverflow.com/a/57463815/143475
And one more: https://stackoverflow.com/a/63708918/143475
It did not seem to like when I added "&& request.clientDescription.includes('blue eyes')" in the Scenario, but it did lead me in the right direction, and I did find a solution. thanks!
Error : after adding String.includes to Scenario:
com.intuit.karate - scenario match evaluation failed: evaluation (js) failed: pathMatches('/callService') &&
methodIs('post') && request.clientDescription.includes('blue eyes'), javax.script.ScriptException: TypeError: request.clientDescription.includes is not a function in at line number 2
stack trace: jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470)
A Solution:
defined a function in the background using karate.match
Code Example of Solution:
Background:
* def isBlueEyed = function(){return karate.match("request.clientDescription contains 'Blue Eyes'").pass}
Scenario:
pathMatches('/callService') &&
methodIs('post') && isBlueEyed()
* def response = read('./***/***/**')

Want to assert that the values are not duplicated in the list

I'm asserting a response like this using karate.
"Ids": ["123456","123456","123457"]
Now I want to assert that my list doesn't contain the duplicate values (If there is a duplicate value, it should fail the test-case), is there any in built function which is supported by Karate or is there any JS who does the trick?
Here you go: https://github.com/karatelabs/karate#karate-distinct
* def response = ["123456","123456","123457"]
* match response == karate.distinct(response)

ORDS: Removing escaping char from json in ORDS OUT param

I am using the OUT parameter in the ORDS parameters to send a response which is already in JSON and this stored as CLOB in the DB. When I send this out in the response from the ORDS, ORDS is actually adding lot of back spaces to the response.
Can someone help me to understand how I can remove the escaping chars here(all the backslashes). I had tried a different approach explained by Jeff in another thread to try to use an alias for the JSON key, but it did not work for me.
Over here I have mentioned the response as OUT parameter in my code.
eg payload:
{
"response": "{\n\"Order\":{\n\"OriginalShipmentID\":1\n,\"orderNumber\":1\n,\"orgID\":1\n,\"orderShipmentNumber\":1\n,\"oracleShipSet\":\"1\"\n,\"OeHeaderId\":1\n,\"GsHeaderId\":1\n,\"CustomerPoNumber\":\"1\"\n,\"PaymentTerms\":1\n,\"FreightTerms\":\"PAID\"\n,\"CurrencyCode\":\"USD\"\n,\"BillToSiteUseID\":1\n,\"ShipToSiteUseID\":1\n,\"SalesChannel\":\"DIRECT\"\n,\"HeaderKeyCode\":\"1 1\"\n,\"OrigSysDocumentRef\":\"1\"\n,\"OrderTypeCode\":\"XYZ yXYZ\"\n,\"OrderTypeID\":1\n,\"SalesRepID\":-3\n,\"IsAtgOrder\":\"N\"\n,\"OrderSource\":\"MCP\"\n,\"OdiDocSet\":\"PO\"\n,\"CsServiceSymbol\":\"XYZ\"\n,\"CsServiceFriendlyName\":\"XYZ\"\n,\"CsShipper\":\"NDC_MX\"\n,\"GsShipToAddressID\":1\n,\"GsBillFrtAddressID\":-1\n,\"BillingMethod\":\"DoNotBillFreight\"\n,\"ReasonForNoInvoice\":\"NA\"\n,\"ShippedBy\":\"NA\"\n,\"ManifestID\":1771748\n,\"IsVoided\":\"N\"\n,\"CustomerNumber\":\"1\"\n,\"OrderLines\":[\n]\n,\"HeaderShortNotes\":{\n}\n}\n}\n"
}
Some more details:
SELECT get_json ( :ordernumber,
:warehouseid,
:shipset,
:ordershipmentno,
:gsshipmentid,
:countrycode,
:shipperid,
:fromcurrency,
:tocurrency,
:groupid,
:optionvalues,
:linehaul,
:servicename,
:sigid,
:lineid,
:customerid) "{}Order"
INTO l_response_clob
FROM DUAL;
This function returns a CLOB with a JSON format data and l_response_clob is defined as STRING output parameter on the ORDS.
Essentially, I want to stop ORDS from again converting JSON to JSON.
Been banging head over this from some time but can't seem to make it work.
Thanks for the help I can get here.

Asserting Against Large Dynamic Response

I have a very large response array I want to assert against, but without knowing the order. I have a variable with the expected response values so I can do a single giant comparison, but I'm unable to load the entire response and compare it with the entire expected response variable at the same time.
* def obligationsQuery = Java.type("tests.account.sql.Obligations").getObligations(division, account)
* def getObligations = db.readRows(obligationsQuery)
Given path "account", "v1", "accounts", systemId, "obligations"
And header api-key = gatewayKey
When method GET
Then status 200
And match $.data != null
And match $.data[*].transactionType contains any "<transactionTypeResponse>"
And match $.data[*] contains only getObligations
Examples:
| description | transactionType | transactionTypeResponse |
| Invoice | 001 | invoice
The error I get is:
get_obligations_collection.feature:49 - path: $.data[*][*], actual: [{"object1"}, {"object2"}, {"etc"}], expected: {"object1"}, reason: actual value does not contain expected
I've also tried:
And match each $.data[*] contains only getObligations
But then I get:
get_obligations_collection.feature:49 - path: $[0], actual: [{"object1"}, expected: [{"object1"}, {"object2"}, {"etc"}, reason: actual value is not list-like
I assume $.data is a JSON array so no need to use json-path to again get the data into another array by calling as $.data[*].
so,
And match $.data contains only getObligations
should work.
If this still not working, please provide some proper response and getObligations values to investigate further.
I assumed that contains only would show the complete value of my variable, but smartly, it only shows the object that fails to match the api response object. Was able to verify that through a simpler assert, and then checking the error message saw that an ID was missing padding that the API adds, but the DB does not.
As usual, just looking more closely at the data returned provides a simple explanation.

Can Karate generate multiple query parameters with the same name?

I need to pass multiple query parameters with the same name in a URL, but I am having problems getting it to work with Karate. In my case, the URL should look like this:
http://mytestapi.com/v1/orders?sort=order.orderNumber&sort=order.customer.name,DESC
Notice 2 query parameters named "sort". I attempted to create these query string parameters with Karate, but only the last "sort" parameter gets created in the query string. Here are the ways I tried to do this:
Given path 'v1/orders'
And param sort = 'order.orderNumber'
And param sort = 'order.customer.name,DESC'
And header Authorization = authInfo.token
And method get
Then status 200
And:
Given path 'v1/orders'
And params sort = { sort: 'order.orderNumber', sort: 'order.customer.name,DESC' }
And header Authorization = authInfo.token
And method get
Then status 200
And:
Given path 'v1/order?sort=order.orderNumber&sort=order.customer.name,DESC'
And header Authorization = authInfo.token
And method get
Then status 200
The first two ways provide the same query string result: ?sort=order.customer.name%2CDESC
The last example does not work because the ? get encoded, which was expected and explained in this post - Karate API Tests - Escaping '?' in the url in a feature file
It's clear that the second "sort" param is overriding the first and only one parameter is being added to the URL. I have gone through the Karate documentation, which is very good, but I have not found a way to add multiple parameters with the same name.
So, is there a way in Karate to set multiple URL query parameters with the same name?
Yes you can generate multiple query parameters with the same name in karate
All values of similar key should be provided in an array.
Given path 'v1/orders'
And params {"sort":["order.orderNumber","order.customer.name,DESC"]}
And header Authorization = authInfo.token
And method get
Then status 200
And for setting single parameter using param it will be like
And param sort = ["order.orderNumber","order.customer.name,DESC"]