Tests for cdb request

This commit is contained in:
Raul Ochoa 2015-03-30 16:28:37 +02:00
parent 1fc0545b5a
commit f1e8c9a709
2 changed files with 66 additions and 6 deletions

View File

@ -1,25 +1,25 @@
function CdbRequest() {
this.RE_USER_FROM_HOST = new RegExp(global.environment.user_from_host ||
'^([^\\.]+)\\.' // would extract "strk" from "strk.cartodb.com"
);
}
module.exports = CdbRequest;
var RE_USER_FROM_HOST = new RegExp(global.environment.user_from_host ||
'^([^\\.]+)\\.' // would extract "strk" from "strk.cartodb.com"
);
CdbRequest.prototype.userByReq = function(req) {
var host = req.headers.host;
if (req.params.user) {
return req.params.user;
}
var mat = host.match(RE_USER_FROM_HOST);
var mat = host.match(this.RE_USER_FROM_HOST);
if ( ! mat ) {
console.error("Pattern '" + RE_USER_FROM_HOST + "' does not match hostname '" + host + "'");
console.error("Pattern '" + this.RE_USER_FROM_HOST + "' does not match hostname '" + host + "'");
return;
}
// console.log("Matches: "); console.dir(mat);
if ( mat.length !== 2 ) {
console.error("Pattern '" + RE_USER_FROM_HOST + "' gave unexpected matches against '" + host + "': ", mat);
console.error("Pattern '" + this.RE_USER_FROM_HOST + "' gave unexpected matches against '" + host + "': ", mat);
return;
}
return mat[1];

View File

@ -0,0 +1,60 @@
require('../../support/test_helper');
var assert = require('assert');
var CdbRequest = require('../../../lib/cartodb/models/cdb_request');
describe('req2params', function() {
function createRequest(host, userParam) {
var req = {
params: {},
headers: {
host: host
}
};
if (userParam) {
req.params.user = userParam;
}
return req;
}
it('extracts name from host header', function() {
var cdbRequest = new CdbRequest();
var user = cdbRequest.userByReq(createRequest('localhost'));
assert.equal(user, 'localhost');
});
it('extracts name from subdomain host header in case of no config', function() {
var userFromHostConfig = global.environment.user_from_host;
global.environment.user_from_host = null;
var cdbRequest = new CdbRequest();
var user = cdbRequest.userByReq(createRequest('development.localhost.lan'));
global.environment.user_from_host = userFromHostConfig;
assert.equal(user, 'development');
});
it('considers user param before headers', function() {
var cdbRequest = new CdbRequest();
var user = cdbRequest.userByReq(createRequest('localhost', 'development'));
assert.equal(user, 'development');
});
it('returns undefined when it cannot extract username', function() {
var userFromHostConfig = global.environment.user_from_host;
global.environment.user_from_host = null;
var cdbRequest = new CdbRequest();
var user = cdbRequest.userByReq(createRequest('localhost'));
global.environment.user_from_host = userFromHostConfig;
assert.equal(user, undefined);
});
});