Postman - Can you use the {{...}} syntax within a Test script? - postman

I have an environment variable called "url", the value is a combination of several other variables in the same environment.
Here is the bulk environment variable definition:
scheme:http
server:localhost
port::55881
application:/
url:{{scheme}}://{{server}}{{port}}{{application}}
As you can see, url contains other variables.
This works great in the actual request (I'm using {{url}} when addressing my service), but when I try to use the same variable in my scripted tests (In the Tests tab), I'm getting the un-evaluated version.
var serviceUrl = pm.variables.get("url");
console.log(serviceUrl); //Yields {{scheme}}://{{server}}{{port}}{{application}}
Is there a way to get the evaluated value inside my tests?
Thanks!
Complete test for more insight:
var jsonData = JSON.parse(responseBody);
tests["Status code is 200"] = responseCode.code === 200;
var ordrereferanse = jsonData.Ordrereferanse;
tests.OrdreReferanse = ordrereferanse.length > 0;
//Have to do this
var scheme = pm.variables.get("scheme");
var server = pm.variables.get("server");
var port = pm.variables.get("port");
var application = pm.variables.get("application");
var api_key = pm.variables.get("api_key");
var serviceUrl = scheme + "://" + server + port + application;
//Instead of this - an environment variable defined like this "{{scheme}}://{{server}}{{port}}{{application}}"
//var serviceUrl = pm.variables.get("url");
//remaining test - go to url to verify that the resource is created and the order reference is set
var infoUrl = serviceUrl + "ordreinformasjon/" + ordrereferanse + "?format=json&api_key=" + api_key;
pm.sendRequest(infoUrl, function (err, response) {
var info = response.json();
console.log(info);
tests.OrdreInformasjonOrdreReferanse = info.OrdreReferanse === ordrereferanse;
});

This would work but I'm not sure what you're trying to achieve:
var scheme = pm.variables.get("scheme")
var server = pm.variables.get("server")
var port = pm.variables.get("port")
var application = pm.variables.get("application")
console.log(`${scheme}://${server}${port}${application}`)
That would log out http://localhost:55881/ to the console.
The {{...}} syntax doesn't work in the way that you had it in the environment file. As it's just storing everything as a string so that's why you would get that output.
You could use {{scheme}}://{{server}}{{port}}{{application}} as the URL but not in the tests using the same syntax.
UPDATE
After seeing the update to the question - Could you not combine the separate variables into a single url variable and construct the infoUrl variable in the following way:
var infoUrl = `${pm.variables.get("url")}ordreinformasjon/${ordrereferanse}?format=json&api_key=${pm.variables.get("api_key")}`
Then use a different environment file with the same url key but with a different value if you need to point the request at a staging or production URL.
I've also noticed that you're using the older tests syntax rather than the newer pm.test() syntax, that might clean up some of the code for you.

Related

Cannot set global variable in postman script

When I log in to a Fortinet device via API, It returns a variable called fpc-sid. This is their version of an authtoken.
When I attempt to put this on a global variable on the test section in the login request it returns the fpc-sid and then I get:
"ReferenceError: sid is not defined"
For some reason, I think it doesn't like the "-", but not sure.
How can I set fps-sid as a global variable?
var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("fpc-sid", jsonData.fpc-sid);
var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("fpc-sid", jsonData.fpc-sid);
Property cannot be accessed like that when it is not a valid identifier. use it by name as :
var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("fpc-sid", jsonData['fpc-sid']);
Read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
Also use the pm object pm.globals.set() for setting variable as Danny mentioned. This is the new syntax, this will make it more future proof

Trying to get two postman.setNextRequest (not chained) or two Actions in Workspace

I’m quite new to postman (and coding) and was trying to find and piece together many snippets of scripts to make it work the way I want.
What I want is very simple: I have a list of IDs that I want to make a POST in each of them, get one of the responseBody as a variable and do another POST. I think I’m close but I can’t manage to get it to work.
I’ve tried:
Two POST request in the same Collection and running the collection.
In the first request I have a POST to
https://APIADDRESS/?order_id{{orderid}}&contract[copy_order_data]=true
On the Pre-request Script tab:
var orderids = pm.environment.get(“orderids”);
if (!orderids) {
orderids = [“bc46bf79-2846-44ed-ac4d-78c77c92ccc8”,“81aacc33-1ade-41a3-b23e-06b03b526b8f”];
}
var currentOrderId = orderids.shift();
pm.environment.set(“orderid”, currentOrderId);
pm.environment.set(“orderids”, orderids);
On the Tests tab:
var orderids = pm.environment.get(“orderids”);
if (orderids && orderids.length > 0) {
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable(“invoice.id”, jsonData.invoice.id);
postman.setNextRequest(“Create invoice”);
} else {
postman.setNextRequest(null);
}
invoice.id is a environment variable populated with the response body of the first action/post and then using the variable on the second action/post.
And then the second request would be a POST to
https://APIADDRESS/invoices/{{invoice.id}}/finalize.json
Of course this doesn’t work. Either it doesn't run the second request in the collection or it doesn't do the loope to more than 1 ID on the list.
So I thought that putting the second POST inside the first one would solve it. But I had no luck.
Can please someone help me?
I have tried mentioned use case with sample API's provided by POSTMAN.
Can you try it?
First POST Method Request : https://postman-echo.com/post
Pre-request Script of first POST method
var orderids = pm.environment.get("orderids");
if(!orderids ){
orderids = ["bc46bf79-2846-44ed-ac4d-78c77c92ccc8","81aacc33-1ade-41a3-b23e-06b03b526b8f"];
}
var currentOrderId = orderids.shift();
pm.environment.set("orderid", currentOrderId);
pm.environment.set("orderids", orderids);
Tests Tab of first POST Method
var orderids = pm.environment.get("orderids");
if (orderids && orderids.length > 0) {
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("invoice.id", jsonData.headers.host);
postman.setNextRequest("Test1");
} else {
postman.setNextRequest(null);
}
Second POST Method Reqeust: https://postman-echo.com/post?key={{invoice.id}}
After executing the above collection it will set orederids and invoice.id value in environment variables and then it will call next POST Method.
Hope this will help you.
Thanks #HalfBloodPrince, from the Postman Echo it worked but in my case it doesn't :S
What I manage to get it working was using a Json file as a list of Orderids.
In that case I've separated all requests.
Request1 - https://APIADDRESS/?order_id{{orderid}}&contract[copy_order_data]=true
Tests tab:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("invoice.id", jsonData.invoice.id);
Request2 - https://APIADDRESS/invoices/{{invoice.id}}/finalize.json
That way everything is in a neat and organized way.
Thanks

How to extract the values from the response body in postman

After posting the request, API return response body as string
Response body look like
{ UniqueID = 93243434,birthGender = M,birthDate = 11/1/2018 5:51:18
PM, familyNames = James, givenNames = Test }
when I try to set the environment variable using the below code
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("currentUniqueId", data.UniqueId);
I got the below error on test results
Error message:
There was an error in evaluating the test script: JSONError:
Unexpected token 'U' at 1:3 { UniqueID = 93243434,birthGender =
M,birthDate = 11/1/2018 5:51:18 PM, family ^
my goal is I need to extract the value 93243434 and assign to environment variable.
Hi you are using the correct way but you can try this version
var jsonData = pm.response.json();
pm.environment.set("UNIQUE_ID", jsonData.UniqueID);
The set("UNIQUE_ID" will help you save it in variable and you can name it as you want and jsonData.uniqueID will extract what you want to get from the Json response
If you view my approach I am extracting Access code and company id and saving it in variable and calling it in all next api's
You are using a notation pattern that is deprecated.
Instead of set your variable using:
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("currentUniqueId", data.UniqueId);
Try to set your variable this way:
pm.environment.set('currentUniqueId', pm.response.json().UniqueID);
To get more information, try: https://learning.getpostman.com/docs/postman/scripts/test_examples/

Base64 Encoding for multi Variables

I have a list of 3 environment variables that I want to bind and encode them (Key +value) in base64.
fro examples,
the 3 Variable now are stored as key-value variables and what i need to have is a base64 encode on this:
{
"VAR1": "313",
"VAR2": "33344",
"VAR3": "rovkssj",
}
I guess that should use the script to create the json and encode it.
appreciate your help
Ronen
Postman uses the built-in module CryptoJS. This could be used to get you close to a solution.
If you add this into the Pre-request Script or Tests tab and send a request, you will see the output of the Base64 conversation in the Postman Console. In the example I'm getting the 'VAR1' environment variable and using this as the value to convert.
var CryptoJS = require("crypto-js")
//Encrypt
var rawStr = CryptoJS.enc.Utf8.parse(pm.environment.get('VAR1'))
var base64 = CryptoJS.enc.Base64.stringify(rawStr)
console.log(`Encrypted value: ${base64}`)
//Decrypt
var parsedWord = CryptoJS.enc.Base64.parse(base64)
var parsedStr = parsedWord.toString(CryptoJS.enc.Utf8)
console.log(`Decrypted value: ${parsedStr}`)
Postman Console output:
This is probably not the exact solution that you need but hopefully this brings you closer to achieving what you need to do.
I see that, in the answer given by #danny-dainton he is importing a JS library. That is unnecessary.
You can just use the btoa and atob functions. Reference
In postman this would be (In your Tests / Pre-request Script tab)
var str = "Hello World!";
var encodedValue = btoa(str);
var decodedValue = atob(encodedValue);
So in your case to decode { "VAR1": "313", "VAR2": "33344", "VAR3": "rovkssj", }
you can just do
var str = "{ \"VAR1\": \"313\", \"VAR2\": \"33344\", \"VAR3\": \"rovkssj\", }";
var encodedValue = btoa(str);
PS: I just want to add that your JSON { "VAR1": "313", "VAR2": "33344", "VAR3": "rovkssj", } is not valid as there is an extra , at the end.

Twitter Typeahead remote

I am trying to use Twitter typeahead but I am facing a problem. I don't know how typeahead passes the string to the server. Is it through a GET parameter? If so, what is the name of the parameter?
Easiest through a GET parameter, you can choose whatever parameter you want.
In JS:
$('#search').typeahead({
name: 'Search',
remote: '/search.php?query=%QUERY' // you can change anything but %QUERY, it's Typeahead default for the string to pass to backend
});
In PHP (or whatever backend you have):
$query = $_GET['query'];
Hope you get the basic idea.
You might want to consider something like this, it is a very basic remote datasource example. The get parameter in this example is 'q'
// Get your data source
var dataSource = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: 'path/to/your/url/json/datasource/?q=%QUERYSTRING',
wildcard: '%QUERYSTRING'
}
});
// initialize your element
var $typehead = $('#form input').typeahead(null, {
source: dataSource
});
// fire a select event, what you want once a user has selected an item
$typehead.on('typeahead:select', function(obj, datum, name) {
//your code here
});
////////////////////////////////////
# in python (django) we get a query string using the request object passed through a view like this
query = request.GET.get('q') or ""
//the caveat [or ""] is just to prevent null exceptions
///////////////////////////////////
# using php
$query = ($_GET['q']) ? $_GET['q'] : "";