Skip to content

tests: connection refactor. #148

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 29, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 27 additions & 28 deletions lib/common/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@

'use strict';

var events = require('events');
var fs = require('fs');
var GAPIToken = require('gapitoken');
var nodeutil = require('util');
var req = require('request');

/** @type {module:common/util} */
Expand Down Expand Up @@ -91,14 +93,15 @@ module.exports.Token = Token;
* var conn = new Connection({ scopes: SCOPES });
*/
function Connection(opts) {
events.EventEmitter.call(this);

this.opts = opts || {};

this.credentials = null;
this.scopes = opts.scopes || [];
this.token = null; // existing access token, if exists

this.isConnecting = false;
this.waitQueue = [];

if (opts.credentials) {
if (opts.credentials.client_email && opts.credentials.private_key) {
Expand All @@ -110,27 +113,29 @@ function Connection(opts) {
}
}

nodeutil.inherits(Connection, events.EventEmitter);

/**
* Retrieve a token to authorize requests.
*
* @todo Connect should be context aware, it should not require an email and
* key, if it's running on Google Compute Engine.
*
* @param {function} callback - The callback function.
*
* @example
* conn.connect(function(err) {});
* conn.connect();
*/
Connection.prototype.connect = function(callback) {
Connection.prototype.connect = function() {
var that = this;
this.isConnecting = true;
// retrieves an access token
this.fetchToken(function(err, token) {
if (!err) {
that.token = token;
}
that.isConnecting = false;
callback(err);
if (err) {
that.emit('connected', err);
return;
}
that.token = token;
that.emit('connected');
});
};

Expand Down Expand Up @@ -246,30 +251,24 @@ Connection.prototype.createAuthorizedReq = function(reqOpts, callback) {
reqOpts.headers['User-Agent'] = USER_AGENT;
}

if (this.isConnected()) {
return callback(null, this.authorizeReq(reqOpts));
function onConnected(err) {
if (err) {
callback(err);
return;
}
callback(null, that.authorizeReq(reqOpts));
}
if (this.isConnecting) {
this.waitQueue = this.waitQueue || [];
this.waitQueue.push({ req: reqOpts, cb: callback });

if (this.isConnected()) {
onConnected();
return;
}
this.connect(function(err) {
that.waitQueue.push({ req: reqOpts, cb: callback });
that.waitQueue.forEach(function(v) {
if (!v.cb) {
return;
}

if (err) {
v.cb(err);
return;
}
this.once('connected', onConnected);

v.cb(null, that.authorizeReq(v.req));
});
that.waitQueue = [];
});
if (!this.isConnecting) {
this.connect();
}
};

/**
Expand Down
72 changes: 37 additions & 35 deletions test/common/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ describe('Connection', function() {
conn = new connection.Connection({
keyFilename: path.join(__dirname, '../testdata/privateKeyFile.json')
});
conn.requester = function(opts, callback) {
callback(null);
};
});

it('should use a private key json file', function(done) {
Expand Down Expand Up @@ -62,70 +65,69 @@ describe('Connection', function() {
});
});


describe('Token', function() {
var tokenNeverExpires = new connection.Token('token', new Date(3000, 0, 0));
var tokenExpired = new connection.Token('token', new Date(2011, 0, 0));

it('should fetch a new token if token expires', function(done) {
var c = new connection.Connection({
email: 'x@provider',
privateKey: '/some/path',
scopes: ['scope1', 'scope2']
});
c.token = tokenExpired;
c.fetchToken = function() {
conn.token = tokenExpired;
conn.fetchToken = function() {
done();
};
c.requester = function(opts, callback) {
callback(null);
conn.req({ uri: 'https://someuri' }, function() {});
});

it('should pass error to callback', function(done) {
var error = new Error('Something terrible happened.');
conn.fetchToken = function(cb) {
cb(error);
};
c.req({ uri: 'https://someuri' }, function() {});
conn.req({}, function(err) {
assert.equal(error, err);
done();
});
});

it('should make other requests wait while connecting', function(done) {
var numTokenFetches = 0;
var c = new connection.Connection({
email: 'x@provider',
privateKey: '/some/path',
scopes: ['scope1', 'scope2']
});
c.fetchToken = function(cb) {
var requestedUris = [];
conn.fetchToken = function(cb) {
numTokenFetches++;
setImmediate(function() {
cb(null, tokenNeverExpires);
});
};
c.requester = function(opts, callback) {
conn.requester = function(opts, callback) {
requestedUris.push(opts.uri);
callback(null);
};

async.parallel([
function(done) { c.req({ uri: 'https://someuri' }, done); },
function(done) { c.req({ uri: 'https://someuri' }, done); },
function(done) { c.req({ uri: 'https://someuri' }, done); }
function(next) {
assert.strictEqual(conn.isConnecting, false);
conn.req({ uri: '1' }, next);
},
function(next) {
assert.strictEqual(conn.isConnecting, true);
conn.req({ uri: '2' }, next);
},
function(next) {
conn.req({ uri: '3' }, next);
}
], function(err) {
assert.equal(err, null);
assert.ifError(err);
assert.equal(numTokenFetches, 1);
assert.equal(c.token, tokenNeverExpires);
assert.equal(conn.token, tokenNeverExpires);
assert.deepEqual(requestedUris, ['1', '2', '3']);
done();
});
});

it('should fetch a new token if token is invalid', function(done) {
var c = new connection.Connection({
email: 'x@provider',
privateKey: '/some/path',
scopes: ['scope1', 'scope2']
});
c.token = new connection.Token();
c.fetchToken = function() {
conn.token = new connection.Token();
conn.fetchToken = function() {
done();
};
c.requester = function(opts, callback) {
callback(null);
};
c.req({ uri: 'https://someuri' }, function() {});
conn.req({ uri: 'https://someuri' }, function() {});
});
});
});