Postman Test - If/else if clause stuck on 1st IF - if-statement

I am trying to verify that the language from "accept-language" is taking the correct information (aka correct translations).
since the language in the header is like: en, de, es and the translations fed to the request body are: german, english, spanish, I was thinking of the below, but all the responses are compared to the first if, that's it.
Can someone help me and tell me what I am doing wrong?
if (responseData = "english") {
pm.test("Check that the response language is EN, same as the Pre-request one, PASSED", () => {
pm.expect((pm.environment.get("language"))).to.be.equal("en")
})
} else if (responseData = "german") {
pm.test("Check that the response language is DE, same as the Pre-request one, PASSED", () => {
pm.expect((pm.environment.get("language"))).to.be.equal("de")
})
} else if (responseData = "spanish") {
pm.test("Check that the response language is ES, same as the Pre-request one, PASSED", () => {
pm.expect((pm.environment.get("language"))).to.be.equal("es")
})
} else if (responseData = "portuguese") {
pm.test("Check that the response language is PT, same as the Pre-request one, PASSED", () => {
pm.expect((pm.environment.get("language"))).to.be.equal("pt")
})
} else if (responseData = "islandic") {
pm.test("Check that the response language is IS, same as the Pre-request one, PASSED", () => {
pm.expect((pm.environment.get("language"))).to.be.equal("is")
})
}

Related

testing multiple http request using mocha

I've been trying to solve this issue for days;
create the test for this case using mocha:
app.post('/approval', function(req, response){
request.post('https://git.ecommchannel.com/api/v4/users/' + req.body.content.id + '/' + req.body.content.state + '?private_token=blabla', function (error, resp, body) {
if (resp.statusCode == 201) {
//do something
} else {
response.send("failed"), response.end();
}
});
} else {
response.send("failed"), response.end();
}
});
});
I've tried several ways, using supertest to test the '/approval' and using nock to test the post request to git api. But it always turn "statusCode" is undefined. I think that's because the request to git api in index.js is not inside a certain function(?)
So I can't implement something like this :
https://codeburst.io/testing-mocking-http-requests-with-nock-480e3f164851 or
https://scotch.io/tutorials/nodejs-tests-mocking-http-requests
const nockingGit = () => {
nock('https://git.ecommchannel.com/api/v4/users')
.post('/1/yes', 'private_token=blabla')
.reply(201, { "statusCode": 201 });
};
it('approval', (done) => {
let req = {
content: {
id: 1,
state: 'yes'
},
_id: 1
}
request(_import.app)
.post('/approval')
.send(req)
.expect(200)
.expect('Content-Type', /html/)
.end(function (err, res) {
if (!err) {
nockingGit();
} else {
done(err);
}
});
done();
})
Then I tried to use supertest as promise
it('approve-block-using-promise', () => {
return promise(_import.app)
.post('/approval')
.send(req = {
content: {
id: 1,
state: 'yes'
},
_id: 1
})
.expect(200)
.then(function(res){
return promise(_import.app)
.post("https://git.ecommchannel.com/api/v4/users/")
.send('1/yes', 'private_token=blabla')
.expect(201);
})
})
But it gives error: ECONNEREFUSED: Connection refused. I didn't find any solution to solve the error. Some sources said that it needs done() .. but it gives another error message, 'ensure "done()" is called" >.<
So then I've found another way, using async (https://code-examples.net/en/q/141ce32)
it('should respond to only certain methods', function(done) {
async.series([
function(cb) { request(_import.app).post('/approval')
.send(req = {
content: {
id: 1,
state: 'yes'
},
_id: 1
})
.expect(200, cb); },
function(cb) { request(_import.app).post('/https://git.ecommchannel.com/api/v4/users/').send('1/yes', 'private_token=blabla').expect(201, cb); },
], done);
});
and it gives this error : expected 201 "Created", got 404 "Not Found". Well, if I open https://git.ecommchannel.com/api/v4/users/1/yes?private_token=blabla in the browser it does return 404. But what I expect is I've injected the response to 201 from the unit test; so whatever the actual response is, the statusCode suppose to be 201, right?
But then since it gives that error, is it means the unit test really send the request to the api?
Pls help me to solve this; how to test the first code I shared.
I really new into unit test.
There are a few things wrong with your posted code, I'll try to list them out but I'm also including a full, passing example below.
First off, your call to git.ecommchannel in the controller, it's a POST with no body. While this isn't causing the errors you're seeing and is technically not incorrect, it is odd. So you should double check what the data you should be sending is.
Next, I'm assuming this was a copy/paste issue when you created the question, but the callback for the request in your controller is not valid JS. The brackets don't match up and the send "failed" is there twice.
Your Nock setup had two issues. First the argument to nock should only have origin, none of the path. So /api/v4/users had to be moved into the first argument of the post method. The other issue was with the second argument passed to post that is an optional match of the POST body. As stated above, you aren't currently sending a body so Nock will always fail to match and replace that request. In the example below, the private_token has been moved to match against the query string of the request, as that what was shown as happening.
The calling of nockingGit was happening too late. Nock needs to register the mock before you use Supertest to call your Express app. You have it being called in the end method, by that time it's too late.
The test labeled approve-block-using-promise has an issue with the second call to the app. It's calling post via Supertest on the Express app, however, the first argument to that post method is the path of the request you're making to your app. It has nothing to do with the call to git.ecommchannel. So in that case your Express app should have returned a 404 Not Found.
const express = require('express')
const nock = require('nock')
const request = require('request')
const supertest = require('supertest')
const app = express()
app.use(express.json())
app.post('/approval', function(req, response) {
const url = 'https://git.ecommchannel.com/api/v4/users/' + req.body.content.id + '/' + req.body.content.state
request.post({
url,
qs: {private_token: 'blabla'}
// body: {} // no body?
},
function(error, resp, body) {
if (error) {
response.status(500).json({message: error.message})
} else if (resp.statusCode === 201) {
response.status(200).send("OK")
} else {
response.status(500).send("failed").end();
}
});
});
const nockingGit = () => {
nock('https://git.ecommchannel.com')
.post('/api/v4/users/1/yes')
.query({private_token: 'blabla'})
.reply(201, {"data": "hello world"});
};
it('approval', (done) => {
const reqPayload = {
content: {
id: 1,
state: 'yes'
},
_id: 1
}
nockingGit();
supertest(app)
.post('/approval')
.send(reqPayload)
.expect(200)
.expect('Content-Type', /html/)
.end(function(err) {
done(err);
})
})

Cant refresh JWT Token "Signature has expired."

I am using django-rest-framework-jwt and react-redux for my SPA.
Need refresh token that expires in 5 minutes.
Refresh works during the 5 minutes.
After it does not work, console show this error:
POST http://localhost:8000/auth/api-token-refresh/ 400 (Bad Request)
createError.js:17 Uncaught (in promise) Error: Request failed with status code 400
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:78)
and postman show this:
{
"non_field_errors": [
"Signature has expired."
]
}
there's the middleware's code
import axios from "axios";
import * as urls from "../helpers/url";
import { authUpdateToken } from "../actions/auth";
const jwthunk = ({ dispatch, getState }: any) => (next: any) => (action: any) => {
if (typeof action === 'function') {
if (getState().auth && getState().auth.token) {
const currentToken = getState().auth.token;
verifyToken(currentToken)
.then((tokenVerified: any) => {
refreshToken(tokenVerified, dispatch)
})
.catch(() => {
refreshToken(currentToken, dispatch)
})
} else {
console.log('Not Auth');
}
}
return next(action);
}
export default jwthunk;
const verifyToken = async (token: any) => {
const body = { token };
let verifiedToken = '';
await axios.post('http://localhost:8000/auth/api-token-verify/', body)
.then(({ data: { code, expires, token } }: any) => {
verifiedToken = token;
});
return verifiedToken;
}
const refreshToken = async (token: any, dispatch: any) => {
const body = { token }
await axios.post('http://localhost:8000/auth/api-token-refresh/', body)
.then((response: any) => {
dispatch(authUpdateToken({ token }));
})
}
django-rest-framework-jwt send an unique token, without refresh-token
I assume that there library have a flaw.
You cant refresh expired token..
Solution
1) Do a monkey patch in your code (Check the below commit code)
https://github.com/jpadilla/django-rest-framework-jwt/pull/348
2)Switch to different library
3)you need to run a timer in you application(front end) and request for access token every 5 minutes before expiry. (which is not ideal way)

axios post for multiple data with flask and vuejs

All I want to do is get context_answers and treatment_answers from my web user inputs and bring it on the Flask. (I am very new to this, sorry that I am a vague about what I am doing)
`context_answers = {"a":[1], "b":[2], "c":[3], "d":[4]}
treatment_answers = {"y":[10]}`
I was able to get context_answers doing following:
`methods: {
handleSubmit() {
axios.post("/submit_survey", this.context_answers)
}
}`
and on the Flask
`#app.route("/submit_survey", methods=["POST"])
def submit_survey():
context = request.get_json(force=True)
context_df = pd.DataFrame.from_dict(context)`
But how do you get this.treatments_answers in the same axios post method? and in the submit_survey?
I want to create a data frame that has following:
a b c d y
1 2 3 4 10
Thank you so much!
If do you want past many params you can do this:
methods: {
handleSubmit() {
axios.post("/submit_survey", {context_answers: this.context_answers,
treatments_answers: this.treatments_answers})
.then(
(response) => { console.log(response) },
(error) => { console.log(error) }
)
}
}
or try this:
methods: {
handleSubmit() {
axios.post("/submit_survey", {context_answers: this.context_answers,
treatments_answers: this.treatments_answers})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
});
}

AWS Lamda/API Gateway Every Second Call Results in Internal Server Error

I'm need to 'Nodejs' and 'Serveless'. I've created a 'Serverless' API and deployed to AWS. Everything works as expected. The issue i have and i can't seem to find anything about this is, on every second call i get an internal server error. the first call is, returns data as expected.
I've deployed to AWS only in a dev stage. I'm wondering if there is some configuration i'm missing or something?
If you need the 'Serverless' config or code examples i can provide.
Thanks.
ANSWER
I think there was an issue with the DB call not returning data in time for the callback, therefore i was finding inconsistent results.
So basically what i did was create a Database class returning Promises like so...
'use strict';
const mysql = require('mysql');
/**
* Database
*/
class Database {
constructor(config) {
if (!this.dbConnection) {
console.log('connect to DB');
this.dbConnection = mysql.createPool(config);
this.dbConnection.on('connection', (connection) => {
console.info('Connection Made!');
});
}
}
query(sql, args) {
return new Promise((resolve, reject) => {
this.dbConnection.query(sql, args, (err, rows) => {
if (err) {
reject(err);
}
resolve(rows);
})
});
}
close() {
return new Promise((resolve, reject) => {
this.dbConnection.end((error) => {
if (error) {
reject(error);
}
resolve();
});
});
}
}
module.exports = Database;
So when i made my query there was a result ready for the callback.
'use strict';
const Database = require('./lib/Database');
const {successResponse, errorResponse} = require('./lib/response');
const CategoryResource = require('./resource/Category');
module.exports.list = (event, context, callback) => {
let sql = 'SELECT * FROM categories AS c WHERE c.company_id = ? AND c.parent_id IS NULL AND c.status = 1 LIMIT ?, ?;';
const company = parseInt(event.queryStringParameters.company);
let page = 1;
let limit = 20;
if (null != event.queryStringParameters) {
if ('page' in event.queryStringParameters) {
page = parseInt(event.queryStringParameters.page);
}
if ('limit' in event.queryStringParameters) {
limit = parseInt(event.queryStringParameters.limit);
}
}
let start = (page - 1) * limit;
if (isNaN(company)) {
callback(null, errorResponse(400, 'Company ID Required', 'Parameter company_id is required.', []));
return;
}
let Category = new Database();
let categoryResource = [];
Category
.query(sql, [company, start, limit])
.then(response => {
Category.close();
response.forEach((category) => {
categoryResource.push(CategoryResource(category));
});
callback(null, successResponse(200, {
"total": response.length,
"perPage": limit,
"currentPage": page,
"data": categoryResource
}));
})
.catch((error) => {
callback(null, errorResponse(error.code, error.sqlMessage, error.sql, {
code: error.errno,
field: error.sqlMessage,
message: error.sqlMessage
}));
Category.close();
});
};
I hope that helps anyone that may have run into the same issue.
If every other time you get an internal server error, that means your code is syntactically sound but has some sort of logic error. It's impossible to help without example code, but some of the more common errors I've seen that only sometimes occur can be:
race conditions (if you're doing parallel access of the same array, for example)
array access errors (length+1 instead of length-1, less-than-zero, or your iterators are jumping someplace in memory they shouldn't)
simply mentioning the wrong variable (putting an i instead of a j, for example)
Unfortunately, without specific examples, the best we can offer is wild speculation and personal experience. Have you tried looking at AWS's CloudWatch and what it says about your execution? There should be some errors logged in there too.
I think there was an issue with the DB call not returning data in time for the callback, therefore i was finding inconsistent results.
So basically what i did was create a Database class returning Promises like so...
'use strict';
const mysql = require('mysql');
/**
* Database
*/
class Database {
constructor(config) {
if (!this.dbConnection) {
console.log('connect to DB');
this.dbConnection = mysql.createPool(config);
this.dbConnection.on('connection', (connection) => {
console.info('Connection Made!');
});
}
}
query(sql, args) {
return new Promise((resolve, reject) => {
this.dbConnection.query(sql, args, (err, rows) => {
if (err) {
reject(err);
}
resolve(rows);
})
});
}
close() {
return new Promise((resolve, reject) => {
this.dbConnection.end((error) => {
if (error) {
reject(error);
}
resolve();
});
});
}
}
module.exports = Database;
So when i made my query there was a result ready for the callback.
'use strict';
const Database = require('./lib/Database');
const {successResponse, errorResponse} = require('./lib/response');
const CategoryResource = require('./resource/Category');
module.exports.list = (event, context, callback) => {
let sql = 'SELECT * FROM categories AS c WHERE c.company_id = ? AND c.parent_id IS NULL AND c.status = 1 LIMIT ?, ?;';
const company = parseInt(event.queryStringParameters.company);
let page = 1;
let limit = 20;
if (null != event.queryStringParameters) {
if ('page' in event.queryStringParameters) {
page = parseInt(event.queryStringParameters.page);
}
if ('limit' in event.queryStringParameters) {
limit = parseInt(event.queryStringParameters.limit);
}
}
let start = (page - 1) * limit;
if (isNaN(company)) {
callback(null, errorResponse(400, 'Company ID Required', 'Parameter company_id is required.', []));
return;
}
let Category = new Database();
let categoryResource = [];
Category
.query(sql, [company, start, limit])
.then(response => {
Category.close();
response.forEach((category) => {
categoryResource.push(CategoryResource(category));
});
callback(null, successResponse(200, {
"total": response.length,
"perPage": limit,
"currentPage": page,
"data": categoryResource
}));
})
.catch((error) => {
callback(null, errorResponse(error.code, error.sqlMessage, error.sql, {
code: error.errno,
field: error.sqlMessage,
message: error.sqlMessage
}));
Category.close();
});
};
I hope that helps anyone that may have run into the same issue.

DRF lowercase header key

Is it possible to use lowercase HTTP header key "content-type" with django rest framework parsers?
HTTP headers are case insensitive, but it doesn't seem to work with DRF 3.3.2. My frontend (emberjs) sends request with lowercase header name by ember-network(Fetch API).
Yes, it is. But ember-network or Fetch API doesn't return success and error callback.
Instead:
fetch(url, {/options/}).then(
(success) => {
//
},
(error) => {
//
});
use:
fetch(url, {/options/}).then(
(response) => {
if (response.status >= 400) {
//error
} else {
//success
}
}
);
Note response.json() returns a promise, my code is:
function request(url, type, data){
return new Ember.RSVP.Promise((resolve, reject) => {
let headers = {...};
let credentials = 'include';
fetch(url, {
method: type,
body: JSON.stringify(data),
headers: headers,
credentials: credentials
}).then((response) => {
response.json().then(
(json) => {
if (response.status >= 400) {
reject(json);
} else {
resolve(json);
}
})
});
}