I have a pre-request Script in my postmancollections.json file which does the following:
const executedOnce = pm.environment.get('executedOnce');
if(executedOnce == 0)
{
console.log("Getting Access Token");
const tokenUrl = pm.environment.get('tokenUrl');
const webApiClientId = pm.environment.get('webApiClientId');
const scope = pm.environment.get('scope');
const username = pm.environment.get('username');
const password = pm.environment.get('password');
const getTokenRequest = {
method: 'POST',
url: tokenUrl,
body: {
mode: 'formdata',
formdata:[
{key: 'client_id', value: webApiClientId},
{key: 'scope', value: scope},
{key: 'grant_type', value: 'password'},
{key: 'username', value: username},
{key: 'password', value: password}
]
}
};
pm.sendRequest(getTokenRequest, (err, response) => {
const jsonResponse = response.json();
const newAccessToken = jsonResponse.access_token;
pm.environment.set('accessToken', newAccessToken);
pm.environment.set('executedOnce', 1)
console.log("Access Token Obtained");
});
From my newman, I pass the username and password which are my environment variables. The access Token is getting generated, but is not getting set to the environment variable, because of which my test scripts in collection is failing.
How to update the environment variable accessToken which is dynamically generated after passing username and password in newman?
Some answers suggest an export command at the end of newman run like below:
newman run testscripts_postman.json -e localenvironment.json --env-var "username=ABC" --env-var "password=abc" --export-environment localenvironment.json
But how will this run in Azure DevOps pipeline if I add an export?
Using
pm.variables()all other varaibles andpm.environment()forpasswordandusername.it use to define a local variable within a collection. Newman can using it without environmental variables handling.
Demo I will use Keycloak v19(docker image is
quay.io/keycloak/keycloak:legacy) for getting an access token Then call to get user list with that token.In
Pre-request ScripttabNote, Keycloak needs
mode: 'urlencoded'If your POST body mode isformdata, to use it.In
AuthorizationtabIn
TesttabTest run in Postman
Export collection (JSON) and environment variables(JSON)
Run by
newmanfrom terminalTeststab insteadPre-request Scripttab in hereIt is more easy due to just get token by separate API then all other API using it.