How to skip first/current request in newman through data file? - postman

I have a column called 'value' in my data.csv file. When its value is 1, I want to run only the request with ID "1" (and skip request ID "2") and when it is 2, request ID "2" should run (and skip request ID "1").
I tried the following already:
Collection pre-request script:
var valueFromData = pm.iterationData.get("value");
if(valueFromData === 1) {
postman.setNextRequest("1");
}
if(valueFromData === 2) {
postman.setNextRequest("2");
}
Request "1" pre-request script:
var valueFromData = pm.iterationData.get("value");
if(valueFromData === 1) {
postman.setNextRequest(null);
}
if(valueFromData === 2) {
postman.setNextRequest("2");
}
Request "2" pre-request script:
var valueFromData = pm.iterationData.get("value");
if(valueFromData === 1) {
postman.setNextRequest(null);
}
if(valueFromData === 2) {
postman.setNextRequest(null);
}
Actual result:
When value = 1, RequestId "1" is called. RequestId "2" is skipped due to the next request being set as null. This is fine.
When value = 2, RequestId "1" is not expected to be called. But it is called! RequestId "2" is called after that.
Expected result:
When value = 1, only RequestId "1" should be called. RequestId "2" should be skipped
When value = 2, only RequestId "2" should be called. RequestId "1" should be skipped
In short, the first request of collection is always called irrespective of setting next requests. May I know how to skip the first/current request conditionally please?

Method name is setNextRequest()
I allways use it in test segment to set next request, not current in pre-request segment.
My proposition:
delete collection script as pointless
add empty/neutral request "0"
set next request here:
if(valueFromData === 1) {
postman.setNextRequest("1");
}
if(valueFromData === 2) {
postman.setNextRequest("2");
}
in test script in "1" set:
if(valueFromData === 1) {
postman.setNextRequest(null); }
delete script inside "2" as pointless
This solution isn't elegnt but should work.

Related

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.

Alexa aws lambda function prompting an error when creating a new object

I am starting to learn how to create a lambda function. I wanted to implement a lambda function that can control a led on an arduino uno device. I found this code on GitHub.
I copied and pasted it and got the following error:
"errorMessage": "Exception: TypeError: Cannot read property 'new' of
undefined".
I searched on StackOverflow and I found this similar question but the answer did not help a lot.
Please I need help in fixing this code. I do not know if it matters but the variable endpoint that contains links for a cloud (sparkfun) is out of service.
Thank you so much for your time and consideration!
Below is the code:
var https = require('https'); //include https
var http = require('http');
exports.handler = (event, context) => {
try {
if (event.session.new) {
// New Session
console.log("NEW SESSION"); //log this for debugging
}
switch (event.request.type) {
case "LaunchRequest":
// Launch Request
console.log(`LAUNCH REQUEST`)
context.succeed(
generateResponse(
buildSpeechletResponse("Welcome to the ForceTronics Home Automation Skill, say turn light on or turn light off", true), //response for Alexa if you just call the skill without intent
{}
)
)
break;
case "IntentRequest":
// Intent Request
console.log(`INTENT REQUEST`)
switch(event.request.intent.name) { //switch statement to select the right intent
case "TurnLightOn": //if you told alexa to turn the light on this will be true
var endpoint = "https://data.sparkfun.com/input/1nlZrX0NbdfwxgrY0zA0?private_key=0mDlvAkdoRIq976eakpa&lightstate=1" //https string to log data to phant phant
https.get(endpoint, function (result) { //use https get request to send data to phant
console.log('Success, with: ' + result.statusCode);
context.succeed(
generateResponse( //if you succeeded allow Alexa to tell you state of light
buildSpeechletResponse("The light is turned on", true),
{}
)
)
}).on('error', function (err) {
console.log('Error, with: ' + err.message);
context.done("Failed");
});
break;
case "TurnLightOff": //the turn light off intent
var endpoint2 = "https://data.sparkfun.com/input/1nlZrX0NbdfwxgrY0zA0?private_key=0mDlvAkdoRIq976eakpa&lightstate=0"; // phant string to set light state to off
https.get(endpoint2, function (result) {
console.log('Success, with: ' + result.statusCode);
context.succeed(
generateResponse( //Alexa response if successful
buildSpeechletResponse("The light is turned off", true),
{}
)
);
}).on('error', function (err) {
console.log('Error, with: ' + err.message);
context.done("Failed");
});
break;
case "IsWasherRunning": //check the state of the washer
var endpoint3 = "http://data.sparkfun.com/output/pw8EWVl18zUgW9OYzJNv.csv?page=1"; // phant csv file page
http.get(endpoint3, function (response) { //http get request, data is returned to response
response.setEncoding('utf8');
response.on('data', function (body) { //now let's go through response data from phant cloud
//following variables are getting hour and date info to ensure data is new and not old
var lHour = Date().substr(16,2); //hour from amazon server
var dHour = body.substr(35,2); //hour from phant cloud data
var lDate = Date().substr(8,2);
var dDate = body.substr(32,2);
if(checkTime(lHour, dHour, lDate, dDate)===1) { //if this is true data from phant is fresh
var s = body.substr(22,1); //read washer state data from phant string
if (s=='1') { //if it is 1 then washer is on
context.succeed(
generateResponse( //if you succeeded allow Alexa to tell you state of light
buildSpeechletResponse("The washer is running", true),
{}
)
);
}
else if (s=='0') { //if it is 0 then washer is off
context.succeed(
generateResponse( //if you succeeded allow Alexa to tell you state of light
buildSpeechletResponse("The washer is off", true),
{}
)
);
}
else { //if this is true then there is an issue getting data from phant
context.succeed(
generateResponse( //if you succeeded allow Alexa to tell you state of light
buildSpeechletResponse("There was an error checking washer state", true),
{}
)
);
}
}
else { //if this is true the data is old and there maybe something wrong with the hardware
console.log("didn't pass date and time test");
context.succeed(
generateResponse( //if you succeeded allow Alexa to tell you state of light
buildSpeechletResponse("No recent washer state data available", true),
{}
)
);
}
});
response.on('error', console.error);
});
break;
default:
throw "Invalid intent";
}
break;
case "SessionEndedRequest":
// Session Ended Request
console.log(`SESSION ENDED REQUEST`);
break;
default:
context.fail(`INVALID REQUEST TYPE: ${event.request.type}`)
}
} catch(error) { context.fail(`Exception: ${error}`) }
}
// builds an Alexa response
buildSpeechletResponse = (outputText, shouldEndSession) => {
return {
outputSpeech: {
type: "PlainText",
text: outputText
},
shouldEndSession: shouldEndSession
}
};
//plays Alexa reponse
generateResponse = (speechletResponse, sessionAttributes) => {
return {
version: "1.0",
sessionAttributes: sessionAttributes,
response: speechletResponse
}
};
//this function checks to see if data from phant cloud is relitively new
function checkTime(lTime, dTime, lDay, dDay) {
//turn hour and date strings into ints
var lT = parseInt(lTime);
var dT = parseInt(dTime);
var lD = parseInt(lDay);
var dD = parseInt(dDay);
if(lD===dD && lT===dT) { //if it is same day and hour then data is good
return 1;
}
else if(lD===dD && (lT - 1)===dT) { //if day is the same and hour is only off by one then data is good
return 1;
}
else if((lD - 1)===dD && lT===0 && dT===23) { //if date is one off but time is around midnight then data is good
return 1;
}
else return 0; //if none of the above if statements are true then data is old
}
It means the object 'event' (look at your line exports.handler) does not have a key called 'session'. Everything after that is non consequential until you fix that. I cannot know what you wanted to accomplish with that call.
Do this:
console.log(event);
You can also look up 'event' in the AWS documentation.
Then you can look for whatever you thought 'session' was and move forward from there. Good luck. Post details of what you thought 'session' was if you get stuck. I don't think you need that though. I can't know for sure from what you posted.

Extracting global variable value from brackets

I am sending a POST request, which I'm getting in the response an attribute named "value" that its value is a number with brackets. I need to use the number without the brackets for my next API request.
Here is what I get in the response of my request:
{
"additionalAttributes": {
"map": [
{
"key": "RESULT_IDS",
"value": "[26913648997439042205288611421953968843]"
}
]
}
Here is what I've updated in Tests tab of the request in order to save it as a global variable:
tests["Status code is 200"] = responseCode.code === 200;
if (responseCode.code === 200) {
try {
var campaign_data = JSON.parse(responseBody),
campaignValue = campaign_data.additionalAttributes.map[0].value;
} catch(e) {
console.log(e);
}
postman.setGlobalVariable("campaignValue",campaignValue);
}
Can you explain please how can I have the value 26913648997439042205288611421953968843 without the brackets saved into a global variable?
Many thanks.
You can use the integrated lodash lib of the Postman sandbox:
var campaignValueRaw = campaign_data.additionalAttributes.map[0].value;
var campaignValue = _.trimRight(_.trimLeft(campaignValueRaw, '[') , ']');