In a Postman pre-request-script, how can I read the actual value of a header that uses a variable - variables

I have a variable called token with a specific value myTokenValue
I try to make a call that includes that variable in a header, tokenHeader:{{token}}
I also have a pre-request-script that needs to change the request based on the value of the token header, but if I try to read the value pm.request.headers.get('tokenHeader') I get the literal value {{token}} instead of the interpolated myTokenValue
How do I get this value without having to look at the variable directly?

You can use the following function to replace any Postman variables in a string with their resolved values:
var resolveVariables = s => s.replace(/\{\{([^}]+)\}\}/g,
(match, capture) => pm.variables.get(capture));
In your example:
var token = resolveVariables(pm.request.headers.get('tokenHeader'));

Basically I was missing a function to interpolate a string, injecting variables from the environment
There are some workarounds:
write your own function, as in this comment by pomeh
function interpolate (value) {
return value.replace(/{{([^}]+)}}/g, function (match, $1) {
return pm.variables.get($1);
});
}
use Postman's own replaceSubstitutions, as in this comment by codenirvana
function interpolate (value) {
const {Property} = require('postman-collection');
let resolved = Property.replaceSubstitutions(value, pm.variables.toObject());
}
Either of these can be used as
const tokenHeader = interpolate(pm.request.headers.get('tokenHeader'));
but the second one is also null safe.

Related

Passing multiple parameters using karate.call

I am trying to call an API in second feature file , passing arguments from first feature file . Say token and current page value which is returned from a first API response.These has to be passed as a param for second API
* def activeDetails =
"""
function(times){
for(i=0;i<=times;i++){
karate.log('Run test round: '+(i+1));
karate.call('getActiveRouteDetails.feature', { token: token, currentPage: i });
}
java.lang.Thread.sleep(1*1000);
}
"""
* call activeDetails totalPages
In my second feature , I am able to print the values passed , but unable to pass in params . Can you please help me
And print currentPage
And print token
And param pageNumber = '#currentPage'
And param token = token
There is a subtle difference when you are in a JavaScript block. Please read this: https://github.com/intuit/karate#karate-expressions
Make this change:
var result = karate.call('examples/getDetails.feature', { token: token, currentPage, i });
And please don't have variable names like current page, take the help of a JavaScript programmer friend if needed for help.
Also note that the best practice is to avoid JS code and loops as far as possible: https://github.com/intuit/karate#loops

How to Set Variable from Request in Postman

I am trying to write some tests for Postman. Many of the requests require an API key that gets returned by an initial GET request.
To set something hard-coded that is not dynamic, it looks like the test code is of the form
let variable = pm.iterationData.get("variable");
console.log("Variable will be set to", variable);
How do I set a return value as a global variable and then set that as a header parameter?
#Example if you setting ApiToken that is dynamic.
Under Tests tab in postman.
Put the following code.
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("Token", jsonData.token);
Under specific environment put variable name as "Token" and current value will be set automatically.
access the variable using {{variable_name}}
#Example: {{token}}
You can specify that variable value in the request Headers by using the {{var_name}} syntax. Instead of any hardcoded value that you may have been using.
You would previously have had to set the value using the pm.globals.set()syntax.
If you do not have the SDK active (monthly payment required to Postman). You can retrieve the values through __environment and __globals.
//Use of environment
postman.setEnvironmentVariable("my_value", "This is a value");
//...
let myValueVar = postman.__environment["my_value"];
console.log("Variable value is:", myValueVar);
//shows: Variable value is: This is a value
//Use of Globals
postman.setGlobalVariable("my_value2", "This is a value of globals");
//...
let myValueVar2 = postman.__globals["my_value2"];
console.log("Variable value is:", myValueVar2);
//shows: Variable value is: This is a value of globals
Also you can see your globals variables in Environments->Globals of your Posmant client.

var within firebase set

I am trying to create some dynamic JSON based on a value of a name like below
this.merchantFirebase.child(firebase.auth().currentUser.uid).update({
this.props.data.name: {
status: this.state.productSwitch
}
});
I was thinking this would create something like
this.merchantFirebase.child(firebase.auth().currentUser.uid).update({
latte: {
status: this.state.productSwitch
}
});
but it is just given me an error of unexpected token
You'll need to use a different notation for this:
var updates = {};
updates[this.props.data.name] = { status: this.state.productSwitch };
this.merchantFirebase.child(firebase.auth().currentUser.uid).update(updates);
By using square-bracket notation, JavaScript "knows" that it needs to evaluate this.props.data.name as an expression, instead of using it as the literal name of the property (as it tries to do in your code).

Rename callback parameter for JSONP

Is there a way to rename the query string parameter that holds the name of callback function? Say, I've got a legacy app which sources I can't access, I want it to be switched to ServiceStack, but the app uses "function" query string parameter, while SS expects "callback".
You can do it with a response filter, inside AppHost.Configure():
ResponseFilters.Add((req, res, dto) =>
{
var func = req.QueryString.Get("function");
if (!func.isNullOrEmpty())
{
res.AddHeader("Content-Type", ContentType.Html);
res.Write("<script type='text/javascript'>{0}({1});</script>"
.FormatWith(func, dto.ToJson()));
res.Close();
}
});

Returning external data from a function in ActionScript

I have the following script that is calling a text file:
/* first create a new instance of the LoadVars object */
myVariables = new LoadVars();
myVariables.load("myFile.txt");
myVariables.onLoad = function(getreading):String{
var ODOMETER2:String=myVariables.ACADEMICWATER;
return ODOMETER2;
trace (ODOMETER2);
}
trace(getreading());
The text file contains the following:
ACADEMICWATER=3002&elec=89
I am able to import the value of 3002 into the function and I can trace it. However, I Should be able to trace it outside the function using trace(getreading()); as shown on the last line. This only returns an "UNDEFINED" value. I am stumped.
You are declaring an anonymous function (see AS3 Syntax and language / Functions) which can't be referenced by name. getreading is declared in your code as an untyped parameter of this function.
If you want to trace the result of this function, then you should declare a named function like this:
function getReading(): String {
var ODOMETER2:String=myVariables.ACADEMICWATER;
return ODOMETER2;
}
myVariables.onLoad = getReading;
trace(getReading());
getreading is not the name of the function in this case, but the name of a parameter to the anonymous function that is run on the onLoad event of the myVariables object.
Place the variable ODOMETER2 outside the function and set it's value inside the anonymous function. Then you will be able to access it outside the function as well.
/* first create a new instance of the LoadVars object */
var ODOMETER2:String;
myVariables = new LoadVars();
myVariables.load("myFile.txt");
myVariables.onLoad = function(){
ODOMETER2=myVariables.ACADEMICWATER;
}
trace(ODOMETER2);
LoadVars.onLoad is an event handler. It is called by LoadVars as soon as it finishes with the asynchronous load operation. It takes a boolean argument, indicating success or failure of the operation. It does not return anything.
LoadVars.onLoad documentation
In that function, you typically act upon the data you received, like storing and processing it. Here's a very simple example showing some basic use cases:
var ODOMETER2:String;
var myVariables = new LoadVars();
myVariables.load("myFile.txt");
myVariables.onLoad = function(success) {
trace(success);
ODOMETER2 = myVariables.ACADEMICWATER;
processResults();
}
function processResults() {
trace(ODOMETER2);
trace(myVariables.ACADEMICWATER);
}
// traces:
// true
// 3002
// 3002