Karate: Get all users and delete with the reference id - karate

After my tests are completed, I would like to delete all the users that were created. I am able to delete one user at a time. Can we do this using conditional logic?
Feature file:
Given path 'users'
And header Authorization = authId
And header Accept = 'application/json;version=2'
When method Get
Then status 200
Then print 'Response Time: '+ responseTime + ' milliseconds'
* def resp = $
* def size = karate.sizeOf(resp)
* print 'Number of users: ' + size
This gives me below response:
[
{
"firstName": "Edit User",
"lastName": "API Test",
"emailAddress": "edituserapitesting#gmail.com",
"ada": true,
"isDeleted": false,
"alerts": [],
"links": [
{
"href": "https://someurl/api/users/0219360d-5ca6-42af-9e9c-10be1e32d219",
"rel": "self"
}
]
},
{
"firstName": "Create",
"lastName": "Test",
"emailAddress": "api#test.com",
"ada": true,
"isDeleted": false,
"alerts": [],
"links": [
{
"href": "https://someurl/api/users/5e3c9be1-2863-4a2d-85e9-966582b127ac",
"rel": "self"
}
]
},
{
"firstName": "Create",
"lastName": "Test",
"emailAddress": "api#test.com",
"ada": true,
"isDeleted": false,
"alerts": [],
"links": [
{
"href": "https://someurl/api/users/b6feb126-bca2-43e6-ba2d-87aaae81fef0",
"rel": "self"
}
]
},
{
"firstName": "Create",
"lastName": "Test",
"emailAddress": "api#test.com",
"ada": true,
"isDeleted": false,
"alerts": [],
"links": [
{
"href": "https://someurl/api/users/4f07f234-9606-4cf5-94ce-3a42fb11a6d7",
"rel": "self"
}
]
}
]
I have to get the id [Eg:4f07f234-9606-4cf5-94ce-3a42fb11a6d7] from each json and pass it to delete path.

Please read about transforms: https://github.com/intuit/karate#json-transforms
Now in one line you can get an array of ids:
* def ids = karate.map(response, function(x){ var link = x.links[0].href; return link.substring(link.lastIndexOf('/') + 1) })
Now you can use this in a loop or data driven test and do what you want.

Related

JSON element extraction from response based on scenario outline examples or external file

This is my api response. Want to extract the value of the Id based on the displayNumber. This display number is a given in the list of values in examples/csv file.
{
"Acc": [
{
"Id": "2b765368696b3441673633325",
"code": "SGD",
"val": 406030.83,
"displayNumber": "8957",
"curval": 406030.83
},
{
"Id": "4e676269685a73787472355776764b50717a4",
"code": "GBP",
"val": 22.68,
"displayNumber": "1881",
"curval": 22.68
},
{
"Id": "526e666d65366e67626244626e6266467",
"code": "SGD",
"val": 38404.44,
"displayNumber": "1004",
"curval": 38404.44
},
],
"combinations": [
{
"displayNumber": "3444",
"Code": "SGD",
"Ids": [
{
"Id": "2b765368696b34416736333254462"
},
{
"Id": "4e676269685a7378747235577"
},
{
"Id": "526e666d65366e6762624d"
}
],
"destId": "3678434b643530456962435272d",
"curval": 3.85
},
{
"displayNumber": "8957",
"code": "SGD",
"Ids": [
{
"Id": "3678434b6435304569624357"
},
{
"Id": "4e676269685a73787472355776764b50717a4"
},
{
"Id": "526e666d65366e67626244626e62664679"
}
],
"destId": "2b765368696b344167363332544",
"curval": 406030.83
},
{
"displayNumber": "1881",
"code": "GBP",
"Ids": [
{
"Id": "3678434b643530456962435275"
},
{
"Id": "2b765368696b3441673"
},
{
"Id": "526e666d65366e67626244626e626"
}
],
"destId": "4e676269685a7378747d",
"curval": 22.68
},
]
}
Examples
|displayNumber|
|8957|
|3498|
|4943|
Below expression works if i give the value
* def tempid = response
* def fromAccount = get[0] tempid.Acc[?(#.displayNumber==8957].Id
I'm not sure how to make this comparison value (i.e. 1881) as a variable which can be read from examples (scenario outline) or a csv file. Went through the documentation, which recommends, karate filters or maps. However, not able to follow how to implement.
You almost got it :-). This is the way you want to solve this
Scenario Outline: Testing SO question for Navneeth
* def tempid = response
* def fromAccount = get[0] tempid.Acc[?(#.displayNumber == <displayNumber>)]
* print fromAccount
Examples:
|displayNumber|
|8957|
|1881|
|3444|
You need to pass the placeholder in examples as -
'<displayNumber>'

Unable to access data in Postgres query where clause

I am dealing with the following JSON in a Postgres database column called steps in a table called tCampaign :
[
{
"name":"Step 1",
"stepReference":"01e9f7c0-bc79-11eb-ab6f-2fa1cb676e38",
"rewardConditions": [
{
"conditionDefinitions": [
{
"instanceId":"01805260-0818-4e99-e5b1-5820d1b133cd",
"type":"registration",
"properties": null,
"name": "Registration"
},
{
"instanceId":"01e115c3-5e56-437a-5d13-6c04281e9588",
"type":"optIn",
"properties": null,
"name":"Opt In"
}
],
"rewardDefinitions":[
{
"instanceId":"01c82190-1d56-44f9-474a-513732302e28",
"type":"sportsReward",
"properties": {"activation": {"type": "onReward"}, "betFlavour": "SPORTS", "channels": ["__use_campaign_restrictions__"], "expiry": {"offset": {"days": "02", "hours": "00", "minutes": "00", "seconds": "00"}, "type": "relative"}, "inRunning": "-", "maxReward": {"USD": "1"}, "minimumOdds": "", "oddsInput": {"minimumOdds": {"american": "", "european": ""}}, "retail": "offBetBuild", "returnStakeOnPayout": "false"},
"name":"Freebet",
"calculator":{"type":"fixed","value":"100"}
}
]
}
]
},
{
"name" : "Step 2",
"stepReference" : "01daa4a0-bc79-11eb-ab6f-2fa1cb676e38",
"rewardConditions": [
{
"conditionDefinitions": [
{
"instanceId" : "01fb15ae-01d0-49e1-966a-8ff438e9a191",
"type" : "genericSportsBet",
"properties" : {"betFlavour": "SPORTS", "betTrackEventThreshold": "10", "betTypes": [ "SGL" ], "builderBetOption": "ALL", "channels": [ "__use_campaign_restrictions__" ], "currencyThresholdMap": { "USD": "1" }, "eventHierarchySelection": { "categories": [], "classes": [], "events": [], "marketTemplates": [], "markets": [ "5824" ], "retrobetEventIds": [ "1200" ], "selections": [], "selectionsMarket": [], "types": [] }, "eventHierarchySelectionUI": { "markets": [ { "id": 5824, "mapping": [], "name": "Match Result", "parentId": 1200, "parentParentId": 5, "path": [ "Category: |England|", "Class: |England Premier League|", "Type: |GK Team K| |vs| |GK Team L|" ], "selectionMapper": false, "settled": "N", "startTime": "2021-05-31 11:15:00", "status": "A" } ] }, "inRunning": "-", "legTypes": [ "WIN" ], "metOnSettlement": false, "minOdds": "", "oddsInput": { "minOdds": { "american": "", "european": "" } }, "priceTypes": [ "LP" ]},
"name" : "Sports Bet"
}
],
"rewardDefinitions":[
{
"instanceId" : "0110eb70-44f9-4d57-40bb-09ff4169136c",
"type" : "sportsReward",
"properties" : {"activation": {"type": "onReward"}, "betFlavour": "SPORTS", "channels": ["__use_campaign_restrictions__"], "expiry": {"offset": {"days": "02", "hours": "00", "minutes": "00", "seconds": "00"}, "type": "relative"}, "inRunning": "-", "maxReward": {"USD": "2"}, "minimumOdds": "", "oddsInput": {"minimumOdds": {"american": "", "european": ""}}, "retail": "offBetBuild", "returnStakeOnPayout": "false"},
"name" : "Freebet",
"calculator" : {"type":"fixed","value":"100"}
}
]
}
]
}
]
and have written the following query to extract properties from conditionDefinitions :
select conditionDefinitions->'properties' as properties from tcampaign cmp
LEFT JOIN LATERAL json_array_elements(steps) singleStep ON true
LEFT JOIN LATERAL json_array_elements(singleStep->'rewardConditions') rewardConditions on TRUE
LEFT JOIN LATERAL json_array_elements(rewardConditions->'conditionDefinitions') conditionDefinitions on TRUE
where properties is not null ;
but I get the following error :
ERROR: column "properties" does not exist
LINE 5: where properties is null ;
If I remove the where clause the query runs fine. Why do I not have access to properties in the where clause? Because I can see results coming back if I remove the WHERE clause, so the query does have results

Graph API doesn't restore a mail message, instead it is creating a new message with CreateDateTime automatically updated to present date

When I am performing restore of an email message via graph API with a Post request, instead of restoring it is creating a new message with the same data. Because in the JSON createDateTime is being updated although I am passing previous createDataTime.
To elaborate more: I want to restore below mail message which got created in 2018 ( "createdDateTime": "2018-12-31T14:49:42Z") but when I am posting same JSON for restore, createDateTime is being updated automatically to the present date. Which is problem because it's not the restore, it is just like creating new message.
{
"#odata.type": "#microsoft.graph.eventMessageResponse",
"#odata.etag": "W/\"DAAAABYAAABjFtMyIejaSbuRSeM/auJwAAGfpJnO\"",
"id": "AAMkAGZiNGI0MWM4LTQ0NjUtNDUyMy1hOTI2LWNopaTZiMGYxZTBkNQBGAAAAAACaBIVNrajXSj6AQcjiAFBwBjFtMyIejaSbuRSeM-auJwAAAAAAEJAABjFtMyIejaSbuRSeM-auJwAAGf4eRfAAA=",
"createdDateTime": "2018-12-31T14:49:42Z",
"lastModifiedDateTime": "2020-12-31T14:49:46Z",
"changeKey": "DopskAkslaAABjFtMyIejaSbuRSeM/auJwAAGfpJnO",
"categories": [],
"receivedDateTime": "2020-12-31T14:49:43Z",
"sentDateTime": "2020-12-31T14:49:42Z",
"hasAttachments": false,
"internetMessageId": "<MA1PR0101MB207oPF15907003958DB7A58BDD60#MA1PR0101MB2070.INDPRD01.PROD.OUTLOOK.COM>",
"subject": "Accepted: New Year Party",
"bodyPreview": "",
"importance": "normal",
"parentFolderId": "AQMkAGZiNGI0MWM4LTQ0ADY1LTQ1MjMtYTkyNi1jZGU2YjBmMWUwZDUALgAAA5oEhU2tqNdKuqPoBByOIAlkallspspspspspppAAAIBCQAAAA==",
"conversationId": "AAQkAGZiNGI0MWM4LTQ0NjUtNDUyMy1hOTI2LWNkZTZiMGYxZTBkNQAQAEJ5AU8Tk1nklXE3E0XGh2w=",
"conversationIndex": "AQHW34QsrZ0Wy3deoU2Bn2byefNABQ==",
"isDeliveryReceiptRequested": null,
"isReadReceiptRequested": false,
"isRead": true,
"isDraft": false,
"inferenceClassification": "focused",
"meetingMessageType": "meetingAccepted",
"type": "singleInstance",
"isOutOfDate": false,
"isAllDay": false,
"isDelegated": false,
"responseType": "accepted",
"recurrence": null,
"body": {
"contentType": "text",
"content": ""
},
"sender": {
"emailAddress": {
"name": "Mark Rober",
"address": "mark#securemigration.in"
}
},
"from": {
"emailAddress": {
"name": "Mark Rober",
"address": "mark#securemigration.in"
}
},
"toRecipients": [
{
"emailAddress": {
"name": "#Class Yammer",
"address": "ClassYammer#securemigration.in"
}
}
],
"ccRecipients": [],
"bccRecipients": [],
"replyTo": [],
"flag": {
"flagStatus": "notFlagged"
},
"startDateTime": {
"dateTime": "2020-12-31T15:00:00.0000000",
"timeZone": "UTC"
},
"endDateTime": {
"dateTime": "2020-12-31T15:30:00.0000000",
"timeZone": "UTC"
}
}
Please help me with it.

Karate: Is it possible to compare two service responses & exclude some keys in comparison

I am trying to compare responses from two service call(for Migration project) using Karate.
Is it possible to exclude or ignore some keys while comparing whole response at one go for following cases:
1)There are few elements in response where the values is different(marked in bold).
2)There are few elements which is not present in one response but present in other(marked in bold).
Service 1 response -
{
"userKey": "string",
"enabled": true,
"locked": true,
"profile": {},
"roles": [
{
"roleKey": 3,
"name": "Role",
**"links": []**
}
],
"links": [
{
"rel": "self",
**"href": "https://starhub1.com"**
},
{
"rel": "self",
**"href": "https://singtel1.com"**
}
]
}
Service 2 response -
{
"userKey": "string",
"enabled": true,
"locked": true,
"profile": {},
"roles": [
{
"roleKey": 3,
"name": "Role"
}
],
"links": [
{
"rel": "self",
**"href": "https://starhub22.com"**
},
{
"rel": "self",
**"href": "https://singtel22.com"**
}`enter code here`
]
}
Yes Karate is pretty good at this. Just do a transform on one payload before comparison.
Please see this answer for details: https://stackoverflow.com/a/53120851/143475
For your specifc example maybe all you need to do is change one "side" to #string and then do the comparison.
* def response1 = { foo: 'hello' }
* def response2 = { foo: 'world' }
* response2.foo = '#string'
* match response1 == response2

Issue when sending Query with Arabic characters through API

I can't send Query with Arabic characters through API. I am trying to send the query from CS-Cart to Quickbooks Online.
I tried to send the query using the arabic letters as the following:
select * from Customer Where DisplayName = 'احمد عبدالعزيز'
it returns:
{
"responseHeader": {
"status": 400,
"message": "Bad Request",
"intuitTid": "2dbec1fd-5dc1-3a14-4a12-7c338db0ee2a",
"realmID": "123146420719144"
},
"response": {
"Fault": {
"Error": [
{
"Message": "Error parsing query",
"Detail": "QueryParserError: Invalid content. Lexical error at line 1, column 45. Encountered: \"\\u0627\" (1575), after : \"\\'\"",
"code": "4000"
}
],
"type": "ValidationFault"
},
"time": "2019-07-04T07:09:03.026-07:00"
}
}
And if I try it after encoding the name and send the query as the following:
select * from Customer Where DisplayName = '%D8%A7%D8%AD%D9%85%D8%AF+%D8%B9%D8%A8%D8%AF%D8%A7%D9%84%D8%B9%D8%B2%D9%8A%D8%B2'
it returns nothing:
{
"QueryResponse": {},
"time": "2019-07-04T07:09:42.698-07:00"
}
I am expecting to get like:
{
"QueryResponse": {
"Customer": [
{
"Taxable": false,
"BillAddr": {
"Id": "924",
"Country": "Saudi Arabia"
},
"ShipAddr": {
"Id": "925",
"Country": "Saudi Arabia"
},
"Job": false,
"BillWithParent": false,
"Balance": 157.5,
"BalanceWithJobs": 157.5,
"CurrencyRef": {
"value": "SAR",
"name": "Saudi Riyal"
},
"PreferredDeliveryMethod": "None",
"IsProject": false,
"domain": "QBO",
"sparse": false,
"Id": "577",
"SyncToken": "0",
"MetaData": {
"CreateTime": "2019-07-01T06:37:32-07:00",
"LastUpdatedTime": "2019-07-01T06:37:33-07:00"
},
"GivenName": "Ramil",
"FamilyName": "Gilaev",
"FullyQualifiedName": "Ramil Gilaev",
"DisplayName": "Ramil Gilaev",
"PrintOnCheckName": "Ramil Gilaev",
"Active": true,
"PrimaryPhone": {
"FreeFormNumber": "123456789"
}
}
],
"startPosition": 1,
"maxResults": 1
},
"time": "2019-07-05T02:12:35.562-07:00"
}
Also I noticed even if the Query is in English name, it results the same.
select * from Customer Where DisplayName = 'Ahmed Al-Khuraisir'
it results:
{
"QueryResponse": {},
"time": "2019-07-05T03:31:11.149-07:00"
}
Please check attached images.
Screenshot 1
Screenshot 2