Targeted Request in postman.setNextRequest() can't set Environment Variables - postman

I use postman.setNextRequest("login") to call login request. Inside login test I set environment variables from token login response. It's not work. Login testing is success, but environment variable token not exists.
Pre Request Script in Collection:
var email = "foo#bar.com";
var password = "mypassword";
pm.environment.set("email", email); // success to set env variable
pm.environment.set("password", password); // success to set env variable
postman.setNextRequest("login");
postman.setNextRequest(null);
Test Script in login request:
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
var dt = pm.response.json();
pm.environment.set("token", dt.token); // failed to set env variable
});

I resolve this problem by enabled Persist Variables checkbox in Collection Runner before run collection.

Related

Are API keys and Google Cloud Platform service account credentials safe to store as environment variables in Netlify deploy settings?

I have this app https://github.com/ChristianOConnor/google-cloudfunction-callfromreactapp. It works by simply calling some text via a button press. The text is delivered by a Netlify function. I set up the Netlify function by adding a netlify.toml file to the root directory:
netlify.toml:
[functions]
directory = "functions/"
and adding this file:
functions/hello-netlify.js:
exports.handler = async (event) => {
return {
statusCode: 200,
body: process.env.GREETING_TEST,
};
};
I added GREETING_TEST environmental variable in Netlify's deploy settings and set it to "this variable is now working":
The app works perfectly after deploying:
I have a default python Google Cloud Function that simply prints "Hello World!"
The question is, if I replace the test Netlify function that spits out "this variable is now working," with this,
import { JWT } from "google-auth-library";
exports.handler = async (event) => {
const client = new JWT({
email: process.env.CLIENT_EMAIL,
key: process.env.PRIVATE_KEY
});
const url = process.env.RUN_APP_URL;
const res = await client.request({url});
const resData = res.data
return {
statusCode: 200,
body: resData,
};
};
set the CLIENT_EMAIL and PRIVATE_KEY to that of my relevant Google Cloud Function service account, and set RUN_APP_URL to the Google Cloud Function's trigger url, would that be safe? My secret environment variables like PRIVATE_KEY would never be visible right?

Postman Test with comparison to global variable

I want to orchestrate two requests in Postman. The first response will give me a variable. I save this id to a global variable id. In Postman this variable is usually accessible via {{id}}.
Then I send a second request with this id (like GET foo.bar/{{id}}). Now I want to check, if the id is in the result as well.
This is what I tried in the test code:
var jsonData = pm.response.json();
pm.expect(jsonData.id).to.eql({{id}});
where idis the variable from the first response (e.g. 72b302bf297a228a75730123efef7c41).
The response for the second request looks sth. like this:
{
"id": "72b302bf297a228a75730123efef7c41"
}
Here some examples which did not work either:
var jsonData = pm.response.json();
pm.expect(jsonData.id).to.eql("{{id}}");
var jsonData = pm.response.json();
var myId = {{id}};
pm.expect(jsonData.id).to.eql(myId);
My excpectation is, that the test will be positive and the `id from the request will be found in the response.
Do you have an idea how to solve this problem?
Thanks for the help.
The {{...}} syntax cannot be used like that, in the sandbox environment, you would need to access it this way.
pm.expect(jsonData.id).to.eql(pm.globals.get('id'))
The test syntax would be:
pm.test("IDs equal?", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.id).to.eql(pm.globals.get('id'))
});

loopback's User Model (login & logout) methods usage in middleware

Is there a way to use the User(model) methods like (login & logout) in our code? Like in my case I want to use the User.login(....) method in the middle-ware that is defined in the route phase of middle-ware.
I tried to import the User model in this way in the middle-ware file.
var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
var User = app.models.user;
It gives me the error that "app is undefined".
Kindly let me know is there a way to use the login etc methods in my middle-ware.
Thank you
'use strict';
var mysql = require('mysql')
var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};
// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) throw err;
// start the server if $ node server.js
if (require.main === module)
app.start();
});
You need to bootstrap the application in advance before using the models
var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
boot(app, __dirname, function(err) {
// You can start your application here
app.start();
// Models have been loaded to app object after boot(). You can use it here if you want
var User = app.models.user;
});
From their official document
The LoopBack bootstrapper, loopback-boot, performs application
initialization (also called bootstrapping). When an application
starts, the bootstrapper:
Configures data sources.
Defines custom models Configures models and attaches models to data-sources.
Configures application settings
Runs boot scripts in the /server/boot directory.
You may want to look at their sample server.js for better reference

how to setup csrf cookie name and header from protractor to make post request to django server to setup fixture to test angular app?

I need to make a post request to django server to insert fixture for my protractor test. To make post request to django, i need to change xsrf setting. i know how to do this in my app :
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}]);
I don't know how to access $httpProvider within protractor.
my_app_module is where i setup xsrf information. I simply include it in the array as below so that my_api_service can have the desired setup.
// in my test
it('something',function(){
//insert fixture
browser.executeAsyncScript(function(data,callback) {
var api = angular.injector(['ng','my_api_module','my_app_module']).get('my_api_service');
api.insert_new(data).then( function(data){ callback(data);} )
},my_fixture)
.then(function (output) { console.log(output); });
//continue my test ...
})

Unable to set a localStorage/cookie in unit testing

Good afternoon to you all,
Just want to ask how to properly set the value of localStorage/cookie in unit testing. I have this code below where I set a cookie then tried to get the value of that cookie but it always disply null.
This snippet of code is the one that I'm trying to test:
scope.$on("$locationChangeSuccess", function(event, next, current)
{
if(location.path() === '/home') {
if(!Utils.isBlank(session.get('token'))) {
var usertype = session.get('usertype');
// console.log('landed home');
if(usertype === 'player') location.path('/user/dashboard');
if(usertype === 'broadcaster') location.path('/broadcaster/dashboard');
if(usertype === 'quizmaster') location.path('/quizmaster/dashboard');
}
}
});
My controllerSpec.js
describe('MainCtrl', function() {
var scope, api, security, clearAll, location, redirect, session, utility;
beforeEach(inject(function($rootScope, $controller ,$location, Api, Security, Utils, localStorageService){
scope = $rootScope.$new();
location = $location;
session = localStorageService
utility = Utils;
$controller("MainCtrl", {
$scope : scope,
localStorageService : session,
Api : Api,
$location : location,
Utility : utility
});
}));
it('should expect player to be redirected to /user/dashboard', function() {
//set the location to home
var home = spyOn(location, 'path');
var addSession = spyOn(session, 'add');
var token = 'testToken';
location.path('/home');
scope.$on('$locationChangeSuccess', {})
expect(home).toHaveBeenCalledWith('/home');
//mock a session
session.add('token',token);
expect(addSession).toHaveBeenCalled();
expect(session.get('token')).toEqual('testToken');
});
Error:
Chrome 24.0 (Linux) controllers MainCtrl MainCtrl should expect player to be redirected to /user/dashboard FAILED
Expected null to equal 'testToken'.
Even though I already set the token "session.add('token', token)" it still showing token is null. I added a spyOn to check if the session.add method was called and it did.
Please help.
You mocked the method add in the service. If you want to call it while spying it, you need to use andCallThrough()
var addSession = spyOn(session, 'add').andCallThrough();
This might not be obvious if you are new to Jasmine. There was an issue (couldn't find it, sorry) where people complained that this should be the default functionality of spyOn. IMHO, it's good the way it is, as you are supposed to only do Unit Tests, not expect your controller do a full integration test (i.e remove the session.get expect, you are not testing the session to work, that has to be in the library test).
Update Answering your comment, to test the url based on a token stored in local storage just do something like this:
spyOn(session, 'get').andReturn(token); //Remember, you are not testing the service, you assume it works.
Depending on what the value of token, you can do expect(location.path()).toBe('/registeredUserOnly')