Postman test automation - verify json array response - postman

I have a simple api GET request and the response body is just like below. I'm using Postman API automation and I want to validate the response and check whether below conditions are met using a Postman test.
Response array size should always be 2
In each of the array item, the “build.time” value should be a date time.
In each of the array item, the “build.artifact” value should be equals to “main_component”.
“build.name” value of the 1st array item should equals to “web app”
“build.name” value of the 2nd array item should equals to “back-end”.
[
{
"build.time": "2020-01-24 02:07:03 UTC",
"build.artifact": "main_component",
"build.name": "web app",
"build.version": "1.0.0"
},
{
"build.time": "2019-07-10 15:26:18 UTC",
"build.artifact": "main_component",
"build.name": "back-end",
"build.version": "1.0.1"
}
]

It was difficult for me to get around this UTC format, so I just converted it to string. Did the job, but will not fit all situations.
// Import moment.js for date validation
var moment = require('moment');
// Load response into object
const jsonData = pm.response.json();
// Test HTTP status code
pm.test("Check if HTTP status code is 200", () => {
pm.response.to.have.status(200);
});
// Check if response contains an array
pm.test("Check if response contains an array", () => {
pm.expect(jsonData).to.be.an("array");
});
// Response array size should always be 2
pm.test("Check if response array size is 2", () => {
pm.expect(Object.keys(pm.response.json()).length).to.eql(2);
});
// In each of the array item, the “build.time” value should be a date time.
pm.test("Check in each of the array item, the “build.time” value is of type datetime",
() => {
pm.expect(jsonData[0]).to.have.property("build.time");
pm.expect(jsonData[1]).to.have.property("build.time");
});
// In each of the array item, the “build.time” value should be a date time.
// Get full timestamp
var timestamp = jsonData[0]["build.time"];
// Get time
var time = timestamp.substring(0,19);
// Get timezone
var timezone = timestamp.toString().substring(20);
// Test the time format
pm.test("Check in each of the array item, the “build.time” value is of type datetime",
() => {
pm.expect(moment(new Date(time)).format("YYYY-MM-DD HH:mm:ss") == time);
});
pm.test("Timezone is valid", () => {
pm.expect(timezone).eql("UTC");
});
// In each of the array item, the “build.artifact” value should be equal to
“main_component”.
pm.test("Check in each of the array item, the “build.artifact” value equals
“main_component”", () => {
pm.expect(jsonData[0]["build.artifact"]).to.eql("main_component");
pm.expect(jsonData[1]["build.artifact"]).to.eql("main_component");
});
// “build.name” value of the 1st array item must equal to “web app”
pm.test("Check if “build.name” value of the 1st array item equals 'web app'", () => {
pm.expect(jsonData[0]["build.name"]).to.eql("web app");
});
// “build.name” value of the 2nd array item equals to “back-end”.
pm.test("Check if “build.name” value of the 2nd array item equals 'web app'", () => {
pm.expect(jsonData[1]["build.name"]).to.eql("back-end");
});

Related

Postman = To assert that the array in the response body contains a string value in all its elements

I'm new to Postman. My Postman is failing to match test criteria. Could anyone please help! It is returning true even if there is no match
pm.test('Hourly metrics report generated to only 1 building', () => {
_.each(jsonData.attributes, (item) => {
pm.expect(item.building_ref_id).to.include('Mounting_View-EN-1-Internal_Alpha')
})
})
{
"id": "423317",
"type": "space",
"attributes": {
"name": "RM_05_030",
"space_ref_id": "RM_05_030",
"building_ref_id": "80_Fen",
"floor_ref_id": "5"
}
}
I assume that the code above is incomplete and that the response is actually and array of objects and that jsonData contains the parsed response body as a JavaScript array of objects.
The _.each() function takes an array as its first parameter, so you should not pass jsonData.attributes. This is the reason that your test passed; jsonData.attributes isn't an array, your callback will never get executed and no failing assertions means a succeeding test.
You can iterate over jsonData and assert that every item has a nested attribute item.attributes.building_ref_id containing your string:
jsonData = pm.response.json()
pm.test('Hourly metrics report generated to only 1 building', () => {
_.each(jsonData, (item) => {
pm.expect(item.attributes.building_ref_id).to.include('Mounting_View-EN-1-Internal_Alpha')
})
})

SuiteScript - Map/Reduce summarize

I am writing a map/reduce script to search for a custom record and create a CSV file from its results.
Firstly, in the getInputData() creating a search and returning its results.
After that comes the map function where I am using JSON.parse to parse the result values.
I have an array declared globally as var data = '' in which I am pushing the values I get in map function.
But when all the looping ends in map() and it enters summarize(), the data array becomes empty again.
I want that data array to be called in summarize() where I can use file.create() function to create the csv file.
I used return data; in map() but it is showing as empty when in summarize().
You have to use context.write at the end of map to send data to the next stage.
context.write({
key: key,
value: value
});
Adding a simple script to show how to access values in the summarize stage:
/**
*#NApiVersion 2.x
*#NScriptType MapReduceScript
*/
define([],
function () {
function getInputData() {
return [{
id: 1,
value: 'abc'
}, {
id: 2,
value: 'def'
}];
}
function map(context) {
var value = JSON.parse(context.value);
context.write({
key: value.id,
value: value.value
});
}
function summarize(context) {
var values = [];
context.output.iterator().each(function (key, value) {
log.debug({
title: 'Output for key ' + key,
details: value
});
values.push(value);
return true;
});
log.debug({
title: 'Summary',
details: JSON.stringify(values)
});
}
return {
getInputData: getInputData,
map: map,
summarize: summarize
}
});

How to stop next request execution in postman on a condition when a variable does not contain any value?

I have a test scenario in postman where I have to stop the execution of next request if an envrionment variable value is null. Below is the piece of code and collection description:
Collection details: I have two request in a collection test1 & test2. If in below scenario variable "document" has value then I want request "test2" to be executed otherwise request "test1" should keep on executing as per the data being passed from the csv sheet.
pm.test("Verify the the: " + data.value + " exist in " + data.source, function() {
_.each(pm.response.json(), (arrItem) => {
pm.expect(arrItem.id).to.be.equal(data.value);
pm.expect(arrItem.source).to.be.equal(data.source);
findDocument(arrItem);
})
})
function findDocument(arr) {
arr.links.forEach(a => {
if (a.id.indexOf('A90') > 0) {
pm.environment.set('document', a.id)
} else
postman.setNextRequest(null)
});
}

using axios post from react to django rest framework got 400 ( bad request) when posting objects contains empty strings

I don't get it why this is happening
as long as i post an object with an empty string value in it will cause an error
and the code snippet is the function that I called for posting values
result from posting with empty string:
https://i.ibb.co/jfhcQY8/1.png
post with arbitrary values:
https://i.ibb.co/CtZ2CKB/2.png
addToServer(e) {
console.log("item: " + this._input.value)
if (this._input.value !== "") {
var newItem = {
"title": this._input.value,
"content": "", //===>if it's empty string it will get a 400 error, however if i change to any non empty value, it will work
"complete": false,
};
console.log("item: " + newItem.title)
console.log(newItem)
axios.post("http://localhost:8000/api/todo/", newItem)
.then(res => this.axiosGet())
.catch( err => console.log(err))
}
this._input.value = "";
this._input.focus();
e.preventDefault();
}

Postman API testing: Unable to assert a value is true

I am testing an API with a GET request that returns the following data:
{
"Verified": true,
"VerifiedDate": 2018-10-08
}
I am trying to test that the first field comes back true, and the second field has a value. I have the following code:
pm.test("Verified should be true", function () {
var Status = pm.response.json();
pm.expect(Status.Verified).to.be.true;
});
pm.test("Returns a verified date", function () {
var Status = pm.response.json();
pm.expect(Status.VerifiedDate).to.not.eql(null);
});
The assert on true is failing for the following reason:
Verified should be true | AssertionError: expected undefined to be true
Why is the first test failing?
I am running the same test on a post command without any issues.
Any ideas?
thanks
Root cause:
Your result is an array but your test is verifying an object. Thus, the postman will throw the exception since it could not compare.
Solution:
Use exactly value of an item in the list with if else command to compare.
var arr = pm.response.json();
console.log(arr.length)
for (var i = 0; i < arr.length; i++)
{
if(arr[i].Verified === true){
pm.test("Verified should be true", function () {
pm.expect(arr[i].Verified).to.be.true;
});
}
if(arr[i].Verified === false){
pm.test("Verified should be false", function () {
pm.expect(arr[i].Verified).to.be.false;
});
}
}
Hope it help you.
You could also just do this:
pm.test('Check the response body properties', () => {
_.each(pm.response.json(), (item) => {
pm.expect(item.Verified).to.be.true
pm.expect(item.VerifiedDate).to.be.a('string').and.match(/^\d{4}-\d{2}-\d{2}$/)
})
})
The check will do a few things for you, it will iterate over the whole array and check that the Verified property is true and also check that the VerifiedDate is a string and matches the YYYY-MM-DD format, like in the example given in your question.