Using Postman How to write a test to check for duplicate ids - postman

I would like to write a test in Postman that validates there are no duplicate values in the array of objects. Here is an example response:
This is my json response :
{
"content": [
{
"id": "88848990-c4c8-4e7d-b708-3e69e684085b",
"name": "UPDATED",
},
{
"id": "42c37e1d-eed3-4f5c-b76a-7b915c05b0bf",
"name": "Swoop ",
},
{
"id": "88848990-c4c8-4e7d-b708-3e69e684085b",
"name": "United Test Airlines",
},
I can see 2 ids that are the same I want to write a test in postman to identify any duplicates in my results. If the test picks up duplicates then it must fail, if it does not pick up any duplicates it should pass. Note I am new to postman api testing.

The short and esay solution might be:
Save all id in an array
Create a set from this array
Compare size of the array and the set. If it equals, then no duplication. If not, there is a duplication.
const res = pm.response.json();
const ids = _.map(res.content, "id");
pm.test("check duplicate id", () => {
const setIds = new Set(ids);
pm.expect(ids.length).eql(setIds.size);
})

Related

Get keys from Json with regex Jmeter

I'm hustling with regex, and trying to get the id's from this body.
But only the id´s in the members list, and not the id in the verified key. :)
To clarify, I'm using Regular Expression Extractor in JMeter
{
"id": "9c40ffca-0f1a-4f93-b068-1f6332707d02", //<--not this
"me": {
"id": "38a2b866-c8a9-424f-a5d4-93b379f080ce", //<--not this
"isMe": true,
"user": {
"verified": {
"id": "257e30f4-d001-47b3-9e7f-5772e591970b" //<--not this
}
}
},
"members": [
{
"id": "88a2b866-c8a9-424f-a5d4-93b379f780ce", //<--this
"isMe": true,
"user": {
"verified": {
"id": "223e30f4-d001-47b3-9e7f-5772e781970b" //<--not this
}
}
},
{
"id": "53cdc218-4784-4e55-a784-72e6a3ffa9bc", //<--this
"isMe": false,
"user": {
"unverified": {
"verification": "XYZ"
}
}
}
]
}
at the moment I have this regex :
("id": )("[\w-]+")
But as you can see here it returns every guid
Any ideas on how to go on?
Thanks in advance.
Since the input data type is JSON, it is recommended to use the JMeter's JSON Path Extractor Plugin.
Once you add it, use the
$.members[*].id
JSON path expression to match all id values of each members in the document that are the top nodes.
If you may have nested memebers, you may get them all using
$..members[*].id
You may test these expressions at https://jsonpath.com/, see a test:

jsonPath expression expected value but return list of values

I want to check response "class_type" value has "REGION".
I test springboot API using mockMvc.
the MockHttpServletResponse is like this.
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body =
{"result":true,
"code":200,
"desc":"OK",
"data":{"total_count":15567,
"items": ...
}}
this is whole response object.
Let's take a closer look, especially items.
"items": [
{
"id": ...,
"class_type": "REGION",
"region_type": "MULTI_CITY",
"class": "com.model.Region",
"code": "AE-65GQ6",
...
},
{
"id": "...",
"class_type": "REGION",
"region_type": "CITY",
"class": "com.model.Region",
"code": "AE-AAN",
...
},
I tried using jsonPath.
#When("User wants to get list of regions, query is {string} page is {int} pageSize is {int}")
public void userWantsToGetListOfRegionsQueryIsPageIsPageSizeIs(String query, int page, int pageSize) throws Exception {
mockMvc().perform(get("/api/v1/regions" ))
.andExpect(status().is2xxSuccessful())
.andDo(print())
.andExpect(jsonPath("$.data", is(notNullValue())))
.andExpect(jsonPath("$.data.total_count").isNumber())
.andExpect(jsonPath("$.data.items").isArray())
.andExpect(jsonPath("$.data.items[*].class_type").value("REGION"));
log.info("지역 목록");
}
but
jsonPath("$.data.items[*].class_type").value("REGION")
return
java.lang.AssertionError: Got a list of values ["REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION"] instead of the expected single value REGION
I want to just check "$.data.items[*].class_type" has "REGION".
How can I change this?
One option would be to check whether you have elements in your array which have the class_type equal to 'REGION':
public static final String REGION = "REGION";
mockMvc().perform(get("/api/v1/regions"))
.andExpect(jsonPath("$.data.items[?(#.class_type == '" + REGION + "')]").exists());

Azure Cosmos query to convert into List

This is my JSON data, which is stored into cosmos db
{
"id": "e064a694-8e1e-4660-a3ef-6b894e9414f7",
"Name": "Name",
"keyData": {
"Keys": [
"Government",
"Training",
"support"
]
}
}
Now I want to write a query to eliminate the keyData and get only the Keys (like below)
{
"userid": "e064a694-8e1e-4660-a3ef-6b894e9414f7",
"Name": "Name",
"Keys" :[
"Government",
"Training",
"support"
]
}
So far I tried the query like
SELECT c.id,k.Keys FROM c
JOIN k in c.keyPhraseBatchResult
Which is not working.
Update 1:
After trying with the Sajeetharan now I can able to get the result, but the issue it producing another JSON inside the Array.
Like
{
"id": "ee885fdc-9951-40e2-b1e7-8564003cd554",
"keys": [
{
"serving": "Government"
},
{
"serving": "Training"
},
{
"serving": "support"
}
]
}
Is there is any way that extracts only the Array without having key value pari again?
{
"userid": "e064a694-8e1e-4660-a3ef-6b894e9414f7",
"Name": "Name",
"Keys" :[
"Government",
"Training",
"support"
]
}
You could try this one,
SELECT C.id, ARRAY(SELECT VALUE serving FROM serving IN C.keyData.Keys) AS Keys FROM C
Please use cosmos db stored procedure to implement your desired format based on the #Sajeetharan's sql.
function sample() {
var collection = getContext().getCollection();
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
'SELECT C.id,ARRAY(SELECT serving FROM serving IN C.keyData.Keys) AS keys FROM C',
function (err, feed, options) {
if (err) throw err;
if (!feed || !feed.length) {
var response = getContext().getResponse();
response.setBody('no docs found');
}
else {
var response = getContext().getResponse();
var map = {};
for(var i=0;i<feed.length;i++){
var keyArray = feed[i].keys;
var array = [];
for(var j=0;j<keyArray.length;j++){
array.push(keyArray[j].serving)
}
feed[i].keys = array;
}
response.setBody(feed);
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
Output:

Run a Postman request multiple times using an array from a previous step

I am working on some test scripts and data cleanup scripts using postman, and was wondering if it were possible to run a request on an array result produced in a previous step.
For example, I have an API that returns tasks as a JSON like so:
[
{
"active": true,
"_id": "5b2101244651a04a4907b094",
"name": "Test Task",
"updatedAt": "2018-06-13T11:33:56.911Z",
"createdAt": "2018-06-13T11:33:56.911Z"
},
{
"active": true,
"_id": "5b2101244651a04a4907b067",
"name": "Test Task 2",
"updatedAt": "2018-06-13T11:33:56.911Z",
"createdAt": "2018-06-13T11:33:56.911Z"
}
]
So in the Tests scripts I run this to collect an array of the IDs:
var jsonData = JSON.parse(responseBody)
postman.setEnvironmentVariable('task_id_list', jsonData.map((i) => i._id))
The next request is to delete a task, but the API only deletes one at a time. I am trying to do something like:
http://localhost:3000/api/v1/tasks/{{task_id_list}}
I was hoping that Postman would see that task_id_list was an array and simple "work", but that doesn't seem to be the case. Is it possible to have a step run multiple times based on an array input?
Solution from this article
Get array of ID's in test script of first request (I prefer to store it in JSON to avoid bugs):
let JsonData = pm.response.json();
let iDs = JsonData.map((i) => i._id)));
pm.environment.set("IdArray", JSON.stringify(iDs);
//and now check, if there was no objects returned, stop runner
if(iDs.length === 0)
{
postman.setNextRequest(null);//next request will not be sent
}
else
{
pm.environment.set("count", 0);
}
In pre-request script of 2 request:
var count = +pm.environment.get("count");
var iDs = JSON.parse(pm.environment.get("IdArray"));
pm.variables.set("task_id_list", iDs[count]); //like one-request environment variable
count = count + 1; //next iteration
if(count < iDs.length)
{
postman.setNextRequest("NAME OF THIS REQUEST");
}
else
{
postman.setNextRequest(null); // or next request name
}
pm.environment.set("count", count)
So you should understand my idea.

How to get JSONobject from JSONArray in postman

I am trying to automize a registration scenario in postman using test scripts
I have the following JsonArray as a response:
[
{
"id": 1,
"name": "user_A",
"cntkp": "martin",
"company": "kreativ",
"tel": "12345678",
"email": "user_A#gmail.com"
"street": "str. 0001",
"city": "DEF",
}
......
......
......
{
"id": 4,
"name": "user_B",
"cntkp": "martin",
"company": "kreativ",
"tel": "12345678",
"email": "user_B#gmail.com"
"street": "str. 0002",
"city": "NJ",
}
......
......
......
{
"id": 10,
"name": "User_C",
"cntkp": "martin",
"company": "kreativ",
"tel": "12345678",
"email": "user_C#gmail.com"
"street": "str. 0003",
"city": "ABC",
}
......
]
the array length can be dynamic and changed (in this sample is 10) and want to find the object with special email (somewhere in the array) and then get the ID from that object and make the assertion based on JsonData from this object (catch elements e.g. check name).
how can I do that?
thanks for the support.
I send a GETrequest to get all Data from Registration DB.
as response I get a JsonArray
from Json Array I need the specific Object for the assertion (e.g. object with email user_B in sample) .
I know my Email address and base on it I have to findout the ID from Object .
I can do it when I know which ID is my ID but in case it is dynamic I don't know how to search an array for it in postman to get ID
For example, to assert the company name
pm.expect(jsonData[0].company).to.equal(pm.environment.get("regDB_new_company"))
but if I dont know the ID ( only know my email) I have first to find out the ID of Object then I can asser it.
e.g.
in this case first, find the object with email "user_B#gmail.com"
then from that object get ID element (in this case 4)
then I want to assert for all data from the object
Thanks Danny, I found the solution
var arr = pm.response.json()
for(i = 0; i < arr.length; i++) {
if (arr[i].email == "userB#gmail.com") {
pm.environment.set("personID", arr[i].id)
}
}