[dist] Complete JSHint compliance except for too many var statements

This commit is contained in:
indexzero 2012-07-22 03:14:01 -04:00
parent 46c184cb08
commit 36226daa2e
10 changed files with 166 additions and 156 deletions

View File

@ -79,9 +79,9 @@ exports.createServer = function () {
case 'number': port = arg; break; case 'number': port = arg; break;
case 'object': options = arg || {}; break; case 'object': options = arg || {}; break;
case 'function': callback = arg; handlers.push(callback); break; case 'function': callback = arg; handlers.push(callback); break;
}; }
}); });
// //
// Helper function to create intelligent error message(s) // Helper function to create intelligent error message(s)
// for the very liberal arguments parsing performed by // for the very liberal arguments parsing performed by
@ -90,36 +90,35 @@ exports.createServer = function () {
function validArguments() { function validArguments() {
var conditions = { var conditions = {
'port and host': function () { 'port and host': function () {
return port && host; return port && host;
}, },
'options.target or options.router': function () { 'options.target or options.router': function () {
return options && (options.router || return options && (options.router ||
(options.target && options.target.host && options.target.port)); (options.target && options.target.host && options.target.port));
}, },
'or proxy handlers': function () { 'or proxy handlers': function () {
return handlers && handlers.length; return handlers && handlers.length;
} }
} };
var missing = Object.keys(conditions).filter(function (name) { var missing = Object.keys(conditions).filter(function (name) {
return !conditions[name](); return !conditions[name]();
}); });
if (missing.length === 3) { if (missing.length === 3) {
message = 'Cannot proxy without ' + missing.join(', '); message = 'Cannot proxy without ' + missing.join(', ');
return false; return false;
} }
return true; return true;
} }
if (!validArguments()) { if (!validArguments()) {
// //
// If `host`, `port` and `options` are all not passed (with valid // If `host`, `port` and `options` are all not passed (with valid
// options) then this server is improperly configured. // options) then this server is improperly configured.
// //
throw new Error(message); throw new Error(message);
return;
} }
// //
@ -130,7 +129,7 @@ exports.createServer = function () {
options.target = options.target || {}; options.target = options.target || {};
options.target.port = options.target.port || port; options.target.port = options.target.port || port;
options.target.host = options.target.host || host; options.target.host = options.target.host || host;
if (options.target && options.target.host && options.target.port) { if (options.target && options.target.host && options.target.port) {
// //
// If an explicit `host` and `port` combination has been passed // If an explicit `host` and `port` combination has been passed
@ -148,31 +147,31 @@ exports.createServer = function () {
// we have to assume that this is a "go-anywhere" Proxy (i.e. a `RoutingProxy`). // we have to assume that this is a "go-anywhere" Proxy (i.e. a `RoutingProxy`).
// //
proxy = new RoutingProxy(options); proxy = new RoutingProxy(options);
if (options.router) { if (options.router) {
// //
// If a routing table has been supplied than we assume // If a routing table has been supplied than we assume
// the user intends us to add the "proxy" middleware layer // the user intends us to add the "proxy" middleware layer
// for them // for them
// //
handlers.push(function (req, res) { handlers.push(function (req, res) {
proxy.proxyRequest(req, res); proxy.proxyRequest(req, res);
}); });
proxy.on('routes', function (routes) { proxy.on('routes', function (routes) {
server.emit('routes', routes); server.emit('routes', routes);
}); });
} }
} }
// //
// Create the `http[s].Server` instance which will use // Create the `http[s].Server` instance which will use
// an instance of `httpProxy.HttpProxy`. // an instance of `httpProxy.HttpProxy`.
// //
handler = handlers.length > 1 handler = handlers.length > 1
? exports.stack(handlers, proxy) ? exports.stack(handlers, proxy)
: function (req, res) { handlers[0](req, res, proxy) }; : function (req, res) { handlers[0](req, res, proxy) };
server = options.https server = options.https
? https.createServer(options.https, handler) ? https.createServer(options.https, handler)
: http.createServer(handler); : http.createServer(handler);
@ -184,8 +183,8 @@ exports.createServer = function () {
if (!callback) { if (!callback) {
// //
// If an explicit callback has not been supplied then // If an explicit callback has not been supplied then
// automagically proxy the request using the `HttpProxy` // automagically proxy the request using the `HttpProxy`
// instance we have created. // instance we have created.
// //
server.on('upgrade', function (req, socket, head) { server.on('upgrade', function (req, socket, head) {
proxy.proxyWebSocketRequest(req, socket, head); proxy.proxyWebSocketRequest(req, socket, head);
@ -222,7 +221,7 @@ exports.createServer = function () {
// //
exports.buffer = function (obj) { exports.buffer = function (obj) {
var events = [], var events = [],
onData, onData,
onEnd; onEnd;
obj.on('data', onData = function (data, encoding) { obj.on('data', onData = function (data, encoding) {
@ -240,11 +239,11 @@ exports.buffer = function (obj) {
}, },
destroy: function () { destroy: function () {
this.end(); this.end();
this.resume = function () { this.resume = function () {
console.error("Cannot resume buffer after destroying it."); console.error("Cannot resume buffer after destroying it.");
}; };
onData = onEnd = events = obj = null; onData = onEnd = events = obj = null;
}, },
resume: function () { resume: function () {
this.end(); this.end();
@ -278,10 +277,10 @@ exports.setMaxSockets = function (value) {
// //
// ### function stack (middlewares, proxy) // ### function stack (middlewares, proxy)
// #### @middlewares {Array} Array of functions to stack. // #### @middlewares {Array} Array of functions to stack.
// #### @proxy {HttpProxy|RoutingProxy} Proxy instance to // #### @proxy {HttpProxy|RoutingProxy} Proxy instance to
// Iteratively build up a single handler to the `http.Server` // Iteratively build up a single handler to the `http.Server`
// `request` event (i.e. `function (req, res)`) by wrapping // `request` event (i.e. `function (req, res)`) by wrapping
// each middleware `layer` into a `child` middleware which // each middleware `layer` into a `child` middleware which
// is in invoked by the parent (i.e. predecessor in the Array). // is in invoked by the parent (i.e. predecessor in the Array).
// //
// adapted from https://github.com/creationix/stack // adapted from https://github.com/creationix/stack
@ -295,17 +294,17 @@ exports.stack = function stack (middlewares, proxy) {
if (err) { if (err) {
if (res._headerSent) { if (res._headerSent) {
res.destroy(); res.destroy();
} }
else { else {
res.statusCode = 500; res.statusCode = 500;
res.setHeader('Content-Type', 'text/plain'); res.setHeader('Content-Type', 'text/plain');
res.end('Internal Server Error'); res.end('Internal Server Error');
} }
console.error('Error in middleware(s): %s', err.stack); console.error('Error in middleware(s): %s', err.stack);
return; return;
} }
if (child) { if (child) {
child(req, res); child(req, res);
} }
@ -344,7 +343,7 @@ exports._getAgent = function _getAgent (options) {
if (!options || !options.host) { if (!options || !options.host) {
throw new Error('`options.host` is required to create an Agent.'); throw new Error('`options.host` is required to create an Agent.');
} }
if (!options.port) { if (!options.port) {
options.port = options.https ? 443 : 80; options.port = options.https ? 443 : 80;
} }
@ -352,21 +351,21 @@ exports._getAgent = function _getAgent (options) {
var Agent = options.https ? https.Agent : http.Agent, var Agent = options.https ? https.Agent : http.Agent,
agent; agent;
agent = new Agent({ agent = new Agent({
host: options.host, host: options.host,
port: options.port port: options.port
}); });
agent.maxSockets = options.maxSockets || maxSockets; agent.maxSockets = options.maxSockets || maxSockets;
return agent; return agent;
} };
// //
// ### function _getProtocol (options) // ### function _getProtocol (options)
// #### @options {Object} Options for the proxy target. // #### @options {Object} Options for the proxy target.
// Returns the appropriate node.js core protocol module (i.e. `http` or `https`) // Returns the appropriate node.js core protocol module (i.e. `http` or `https`)
// based on the `options` supplied. // based on the `options` supplied.
// //
exports._getProtocol = function _getProtocol (options) { exports._getProtocol = function _getProtocol (options) {
return options.https ? https : http; return options.https ? https : http;
@ -382,7 +381,7 @@ exports._getProtocol = function _getProtocol (options) {
// //
exports._getBase = function _getBase (options) { exports._getBase = function _getBase (options) {
var result = function () {}; var result = function () {};
if (options.https && typeof options.https === 'object') { if (options.https && typeof options.https === 'object') {
['ca', 'cert', 'key'].forEach(function (key) { ['ca', 'cert', 'key'].forEach(function (key) {
if (options.https[key]) { if (options.https[key]) {

View File

@ -222,9 +222,10 @@ HttpProxy.prototype.proxyRequest = function (req, res, buffer) {
// origin of the host header to the target URL! Please // origin of the host header to the target URL! Please
// don't revert this without documenting it! // don't revert this without documenting it!
// //
if(this.changeOrigin) if (this.changeOrigin) {
outgoing.headers.host = this.target.host + ':' + this.target.port; outgoing.headers.host = this.target.host + ':' + this.target.port;
}
// //
// Open new HTTP request to internal resource with will act // Open new HTTP request to internal resource with will act
// as a reverse proxy pass // as a reverse proxy pass
@ -287,12 +288,13 @@ HttpProxy.prototype.proxyRequest = function (req, res, buffer) {
// already been called and the 'error' event listener // already been called and the 'error' event listener
// removed. // removed.
// //
var ended = false var ended = false;
response.on('close', function () { response.on('close', function () {
if(!ended) response.emit('end') if (!ended) { response.emit('end') }
}) });
response.on('end', function () { response.on('end', function () {
ended = true ended = true;
if (!errState) { if (!errState) {
reverseProxy.removeListener('error', proxyError); reverseProxy.removeListener('error', proxyError);
@ -566,11 +568,11 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, head, buffer)
proxySocket.end(); proxySocket.end();
detach(); detach();
}); });
}; }
function getPort (port) { function getPort (port) {
port = port || 80; port = port || 80;
return port - 80 === 0 ? '' : ':' + port return port - 80 === 0 ? '' : ':' + port;
} }
// //

View File

@ -165,7 +165,7 @@ ProxyTable.prototype.getProxyLocation = function (req) {
} }
var target = req.headers.host.split(':')[0]; var target = req.headers.host.split(':')[0];
if (this.hostnameOnly == true) { if (this.hostnameOnly === true) {
if (this.router.hasOwnProperty(target)) { if (this.router.hasOwnProperty(target)) {
var location = this.router[target].split(':'), var location = this.router[target].split(':'),
host = location[0], host = location[0],

View File

@ -167,6 +167,8 @@ RoutingProxy.prototype.close = function () {
// //
RoutingProxy.prototype.proxyRequest = function (req, res, options) { RoutingProxy.prototype.proxyRequest = function (req, res, options) {
options = options || {}; options = options || {};
var location;
// //
// Check the proxy table for this instance to see if we need // Check the proxy table for this instance to see if we need
@ -237,6 +239,10 @@ RoutingProxy.prototype.proxyRequest = function (req, res, options) {
RoutingProxy.prototype.proxyWebSocketRequest = function (req, socket, head, options) { RoutingProxy.prototype.proxyWebSocketRequest = function (req, socket, head, options) {
options = options || {}; options = options || {};
var location,
proxy,
key;
if (this.proxyTable && !options.host) { if (this.proxyTable && !options.host) {
location = this.proxyTable.getProxyLocation(req); location = this.proxyTable.getProxyLocation(req);
@ -248,8 +254,7 @@ RoutingProxy.prototype.proxyWebSocketRequest = function (req, socket, head, opti
options.host = location.host; options.host = location.host;
} }
var key = this._getKey(options), key = this._getKey(options);
proxy;
if (!this.proxies[key]) { if (!this.proxies[key]) {
this.add(options); this.add(options);
@ -270,11 +275,10 @@ RoutingProxy.prototype._getKey = function (options) {
if (!options || ((!options.host || !options.port) if (!options || ((!options.host || !options.port)
&& (!options.target || !options.target.host || !options.target.port))) { && (!options.target || !options.target.host || !options.target.port))) {
throw new Error('options.host and options.port or options.target are required.'); throw new Error('options.host and options.port or options.target are required.');
return;
} }
return [ return [
options.host || options.target.host, options.host || options.target.host,
options.port || options.target.port options.port || options.target.port
].join(':'); ].join(':');
} };

View File

@ -5,7 +5,7 @@
* MIT LICENCE * MIT LICENCE
* *
*/ */
var assert = require('assert'), var assert = require('assert'),
http = require('http'), http = require('http'),
https = require('https'), https = require('https'),
@ -20,7 +20,7 @@ var assert = require('assert'),
// #### @options {Object} Options to create target and proxy server. // #### @options {Object} Options to create target and proxy server.
// #### @callback {function} Continuation to respond to when complete. // #### @callback {function} Continuation to respond to when complete.
// //
// Creates http target and proxy servers // Creates http target and proxy servers
// //
exports.createServerPair = function (options, callback) { exports.createServerPair = function (options, callback) {
async.series([ async.series([
@ -51,7 +51,7 @@ exports.createServerPair = function (options, callback) {
// //
exports.createServer = function (options, callback) { exports.createServer = function (options, callback) {
// //
// Request handler to use in either `http` // Request handler to use in either `http`
// or `https` server. // or `https` server.
// //
function requestHandler(req, res) { function requestHandler(req, res) {
@ -60,16 +60,16 @@ exports.createServer = function (options, callback) {
assert.equal(req.headers[key], options.headers[key]); assert.equal(req.headers[key], options.headers[key]);
}); });
} }
res.writeHead(200, { 'Content-Type': 'text/plain' }); res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write(options.output || 'hello proxy'); res.write(options.output || 'hello proxy');
res.end(); res.end();
} }
var server = protocols.target === 'https' var server = protocols.target === 'https'
? https.createServer(helpers.https, requestHandler) ? https.createServer(helpers.https, requestHandler)
: http.createServer(requestHandler); : http.createServer(requestHandler);
server.listen(options.port, function () { server.listen(options.port, function () {
callback(null, this); callback(null, this);
}); });
@ -91,7 +91,7 @@ exports.createProxyServer = function (options, callback) {
if (protocols.proxy === 'https') { if (protocols.proxy === 'https') {
options.proxy.https = helpers.https; options.proxy.https = helpers.https;
} }
return httpProxy return httpProxy
.createServer(options.proxy) .createServer(options.proxy)
.listen(options.port, function () { .listen(options.port, function () {
@ -99,12 +99,15 @@ exports.createProxyServer = function (options, callback) {
}); });
} }
var proxy = options.routing var server,
proxy;
proxy = options.routing
? new httpProxy.RoutingProxy(options.proxy) ? new httpProxy.RoutingProxy(options.proxy)
: new httpProxy.HttpProxy(options.proxy); : new httpProxy.HttpProxy(options.proxy);
// //
// Request handler to use in either `http` // Request handler to use in either `http`
// or `https` server. // or `https` server.
// //
function requestHandler(req, res) { function requestHandler(req, res) {
@ -115,15 +118,15 @@ exports.createProxyServer = function (options, callback) {
// Setup options dynamically for `RoutingProxy.prototype.proxyRequest` // Setup options dynamically for `RoutingProxy.prototype.proxyRequest`
// or `HttpProxy.prototype.proxyRequest`. // or `HttpProxy.prototype.proxyRequest`.
// //
buffer = options.routing ? { buffer: buffer } : buffer buffer = options.routing ? { buffer: buffer } : buffer;
proxy.proxyRequest(req, res, buffer); proxy.proxyRequest(req, res, buffer);
}, options.latency); }, options.latency);
} }
var server = protocols.proxy === 'https' server = protocols.proxy === 'https'
? https.createServer(helpers.https, requestHandler) ? https.createServer(helpers.https, requestHandler)
: http.createServer(requestHandler); : http.createServer(requestHandler);
server.listen(options.port, function () { server.listen(options.port, function () {
callback(null, this); callback(null, this);
}); });
@ -132,14 +135,14 @@ exports.createProxyServer = function (options, callback) {
// //
// ### function assignPortsToRoutes (routes) // ### function assignPortsToRoutes (routes)
// #### @routes {Object} Routing table to assign ports to // #### @routes {Object} Routing table to assign ports to
// //
// Assigns dynamic ports to the `routes` for runtime testing. // Assigns dynamic ports to the `routes` for runtime testing.
// //
exports.assignPortsToRoutes = function (routes) { exports.assignPortsToRoutes = function (routes) {
Object.keys(routes).forEach(function (source) { Object.keys(routes).forEach(function (source) {
routes[source] = routes[source].replace('{PORT}', helpers.nextPort); routes[source] = routes[source].replace('{PORT}', helpers.nextPort);
}); });
return routes; return routes;
}; };
@ -148,14 +151,14 @@ exports.assignPortsToRoutes = function (routes) {
// #### @options {Object} Options to use when parsing routes // #### @options {Object} Options to use when parsing routes
// #### @protocol {string} Protocol to use in the routes // #### @protocol {string} Protocol to use in the routes
// #### @routes {Object} Routes to parse. // #### @routes {Object} Routes to parse.
// //
// Returns an Array of fully-parsed URLs for the source and // Returns an Array of fully-parsed URLs for the source and
// target of `options.routes`. // target of `options.routes`.
// //
exports.parseRoutes = function (options) { exports.parseRoutes = function (options) {
var protocol = options.protocol || 'http', var protocol = options.protocol || 'http',
routes = options.routes; routes = options.routes;
return Object.keys(routes).map(function (source) { return Object.keys(routes).map(function (source) {
return { return {
source: url.parse(protocol + '://' + source), source: url.parse(protocol + '://' + source),

View File

@ -28,7 +28,7 @@ Object.defineProperty(exports, 'https', {
// //
// @protocols {Object} // @protocols {Object}
// Returns an object representing the desired protocols // Returns an object representing the desired protocols
// for the `proxy` and `target` server. // for the `proxy` and `target` server.
// //
Object.defineProperty(exports, 'protocols', { Object.defineProperty(exports, 'protocols', {
get: function () { get: function () {
@ -37,11 +37,11 @@ Object.defineProperty(exports, 'protocols', {
target: exports.argv.target || 'http', target: exports.argv.target || 'http',
proxy: exports.argv.proxy || 'http' proxy: exports.argv.proxy || 'http'
}; };
} }
}); });
// //
// @nextPort {number} // @nextPort {number}
// Returns an auto-incrementing port for tests. // Returns an auto-incrementing port for tests.
// //
Object.defineProperty(exports, 'nextPort', { Object.defineProperty(exports, 'nextPort', {
@ -53,7 +53,7 @@ Object.defineProperty(exports, 'nextPort', {
}); });
// //
// @nextPortPair {Object} // @nextPortPair {Object}
// Returns an auto-incrementing pair of ports for tests. // Returns an auto-incrementing pair of ports for tests.
// //
Object.defineProperty(exports, 'nextPortPair', { Object.defineProperty(exports, 'nextPortPair', {
@ -66,22 +66,22 @@ Object.defineProperty(exports, 'nextPortPair', {
}); });
// //
// ### function describe(prefix) // ### function describe(prefix)
// #### @prefix {string} Prefix to use before the description // #### @prefix {string} Prefix to use before the description
// //
// Returns a string representing the protocols that this suite // Returns a string representing the protocols that this suite
// is testing based on CLI arguments. // is testing based on CLI arguments.
// //
exports.describe = function (prefix, base) { exports.describe = function (prefix, base) {
prefix = prefix || ''; prefix = prefix || '';
base = base || 'http' base = base || 'http';
function protocol(endpoint) { function protocol(endpoint) {
return exports.protocols[endpoint] === 'https' return exports.protocols[endpoint] === 'https'
? base + 's' ? base + 's'
: base; : base;
} }
return [ return [
'node-http-proxy', 'node-http-proxy',
prefix, prefix,

View File

@ -5,7 +5,7 @@
* MIT LICENCE * MIT LICENCE
* *
*/ */
var assert = require('assert'), var assert = require('assert'),
https = require('https'), https = require('https'),
async = require('async'), async = require('async'),
@ -22,7 +22,7 @@ var assert = require('assert'),
// #### @proxy {Object} Options for the proxy server. // #### @proxy {Object} Options for the proxy server.
// #### @callback {function} Continuation to respond to when complete. // #### @callback {function} Continuation to respond to when complete.
// //
// Creates http target and proxy servers // Creates http target and proxy servers
// //
exports.createServerPair = function (options, callback) { exports.createServerPair = function (options, callback) {
async.series([ async.series([
@ -30,7 +30,7 @@ exports.createServerPair = function (options, callback) {
// 1. Create the target server // 1. Create the target server
// //
function createTarget(next) { function createTarget(next) {
exports.createServer(options.target, next); exports.createServer(options.target, next);
}, },
// //
// 2. Create the proxy server // 2. Create the proxy server
@ -42,7 +42,7 @@ exports.createServerPair = function (options, callback) {
}; };
// //
// ### function createServer (options, callback) // ### function createServer (options, callback)
// #### @options {Object} Options for creating the socket.io or ws server. // #### @options {Object} Options for creating the socket.io or ws server.
// #### @raw {boolean} Enables ws.Websocket server. // #### @raw {boolean} Enables ws.Websocket server.
// //
@ -55,20 +55,20 @@ exports.createServer = function (options, callback) {
}; };
// //
// ### function createSocketIoServer (options, callback) // ### function createSocketIoServer (options, callback)
// #### @options {Object} Options for creating the socket.io server // #### @options {Object} Options for creating the socket.io server
// #### @port {number} Port to listen on // #### @port {number} Port to listen on
// #### @input {string} Input to expect from the only socket // #### @input {string} Input to expect from the only socket
// #### @output {string} Output to send the only socket // #### @output {string} Output to send the only socket
// //
// Creates a socket.io server on the specified `options.port` which // Creates a socket.io server on the specified `options.port` which
// will expect `options.input` and then send `options.output`. // will expect `options.input` and then send `options.output`.
// //
exports.createSocketIoServer = function (options, callback) { exports.createSocketIoServer = function (options, callback) {
var server = protocols.target === 'https' var server = protocols.target === 'https'
? io.listen(options.port, helpers.https, callback) ? io.listen(options.port, helpers.https, callback)
: io.listen(options.port, callback); : io.listen(options.port, callback);
server.sockets.on('connection', function (socket) { server.sockets.on('connection', function (socket) {
socket.on('incoming', function (data) { socket.on('incoming', function (data) {
assert.equal(data, options.input); assert.equal(data, options.input);
@ -78,25 +78,25 @@ exports.createSocketIoServer = function (options, callback) {
}; };
// //
// ### function createWsServer (options, callback) // ### function createWsServer (options, callback)
// #### @options {Object} Options for creating the ws.Server instance // #### @options {Object} Options for creating the ws.Server instance
// #### @port {number} Port to listen on // #### @port {number} Port to listen on
// #### @input {string} Input to expect from the only socket // #### @input {string} Input to expect from the only socket
// #### @output {string} Output to send the only socket // #### @output {string} Output to send the only socket
// //
// Creates a ws.Server instance on the specified `options.port` which // Creates a ws.Server instance on the specified `options.port` which
// will expect `options.input` and then send `options.output`. // will expect `options.input` and then send `options.output`.
// //
exports.createWsServer = function (options, callback) { exports.createWsServer = function (options, callback) {
var server, var server,
wss; wss;
if (protocols.target === 'https') { if (protocols.target === 'https') {
server = https.createServer(helpers.https, function (req, res) { server = https.createServer(helpers.https, function (req, res) {
req.writeHead(200); req.writeHead(200);
req.end(); req.end();
}).listen(options.port, callback); }).listen(options.port, callback);
wss = new ws.Server({ server: server }); wss = new ws.Server({ server: server });
} }
else { else {

View File

@ -26,7 +26,7 @@ vows.describe(helpers.describe('routing-table')).addBatch({
} }
}), }),
"using RegExp": macros.http.assertProxiedToRoutes({ "using RegExp": macros.http.assertProxiedToRoutes({
routes: { routes: {
"foo.com": "127.0.0.1:{PORT}", "foo.com": "127.0.0.1:{PORT}",
"bar.com": "127.0.0.1:{PORT}", "bar.com": "127.0.0.1:{PORT}",
"baz.com/taco": "127.0.0.1:{PORT}", "baz.com/taco": "127.0.0.1:{PORT}",

View File

@ -5,7 +5,7 @@
* MIT LICENCE * MIT LICENCE
* *
*/ */
var assert = require('assert'), var assert = require('assert'),
fs = require('fs'), fs = require('fs'),
async = require('async'), async = require('async'),
@ -34,7 +34,7 @@ exports.assertRequest = function (options) {
if (options.assert.body) { if (options.assert.body) {
assert.equal(body, options.assert.body); assert.equal(body, options.assert.body);
} }
if (options.assert.statusCode) { if (options.assert.statusCode) {
assert.equal(res.statusCode, options.assert.statusCode); assert.equal(res.statusCode, options.assert.statusCode);
} }
@ -47,7 +47,7 @@ exports.assertRequest = function (options) {
// #### @options {Object} Options for this test // #### @options {Object} Options for this test
// #### @latency {number} Latency in milliseconds for the proxy server. // #### @latency {number} Latency in milliseconds for the proxy server.
// #### @ports {Object} Ports for the request (target, proxy). // #### @ports {Object} Ports for the request (target, proxy).
// #### @output {string} Output to assert from. // #### @output {string} Output to assert from.
// #### @forward {Object} Options for forward proxying. // #### @forward {Object} Options for forward proxying.
// //
// Creates a complete end-to-end test for requesting against an // Creates a complete end-to-end test for requesting against an
@ -55,22 +55,22 @@ exports.assertRequest = function (options) {
// //
exports.assertProxied = function (options) { exports.assertProxied = function (options) {
options = options || {}; options = options || {};
var ports = options.ports || helpers.nextPortPair, var ports = options.ports || helpers.nextPortPair,
output = options.output || 'hello world from ' + ports.target, output = options.output || 'hello world from ' + ports.target,
protocol = helpers.protocols.proxy, protocol = helpers.protocols.proxy,
req = options.request || {}; req = options.request || {};
req.uri = req.uri || protocol + '://127.0.0.1:' + ports.proxy; req.uri = req.uri || protocol + '://127.0.0.1:' + ports.proxy;
return { return {
topic: function () { topic: function () {
// //
// Create a target server and a proxy server // Create a target server and a proxy server
// using the `options` supplied. // using the `options` supplied.
// //
helpers.http.createServerPair({ helpers.http.createServerPair({
target: { target: {
output: output, output: output,
port: ports.target, port: ports.target,
headers: req.headers headers: req.headers
@ -109,14 +109,14 @@ exports.assertProxied = function (options) {
// //
exports.assertInvalidProxy = function (options) { exports.assertInvalidProxy = function (options) {
options = options || {}; options = options || {};
var ports = options.ports || helpers.nextPortPair, var ports = options.ports || helpers.nextPortPair,
req = options.request || {}, req = options.request || {},
protocol = helpers.protocols.proxy; protocol = helpers.protocols.proxy;
req.uri = req.uri || protocol + '://127.0.0.1:' + ports.proxy; req.uri = req.uri || protocol + '://127.0.0.1:' + ports.proxy;
return { return {
topic: function () { topic: function () {
// //
@ -152,13 +152,13 @@ exports.assertInvalidProxy = function (options) {
// //
exports.assertForwardProxied = function (options) { exports.assertForwardProxied = function (options) {
var forwardPort = helpers.nextPort; var forwardPort = helpers.nextPort;
return { return {
topic: function () { topic: function () {
helpers.http.createServer({ helpers.http.createServer({
output: 'hello from forward', output: 'hello from forward',
port: forwardPort port: forwardPort
}, this.callback) }, this.callback);
}, },
"and a valid forward target": exports.assertProxied({ "and a valid forward target": exports.assertProxied({
forward: { forward: {
@ -176,7 +176,7 @@ exports.assertForwardProxied = function (options) {
}; };
// //
// ### function assertProxiedtoRoutes (options, nested) // ### function assertProxiedtoRoutes (options, nested)
// #### @options {Object} Options for this ProxyTable-based test // #### @options {Object} Options for this ProxyTable-based test
// #### @routes {Object|string} Routes to use for the proxy. // #### @routes {Object|string} Routes to use for the proxy.
// #### @hostnameOnly {boolean} Enables hostnameOnly routing. // #### @hostnameOnly {boolean} Enables hostnameOnly routing.
@ -186,25 +186,25 @@ exports.assertForwardProxied = function (options) {
// http proxy using `options.routes`: // http proxy using `options.routes`:
// //
// 1. Creates target servers for all routes in `options.routes.` // 1. Creates target servers for all routes in `options.routes.`
// 2. Creates a proxy server. // 2. Creates a proxy server.
// 3. Ensure requests to the proxy server for all route targets // 3. Ensure requests to the proxy server for all route targets
// returns the unique expected output. // returns the unique expected output.
// //
exports.assertProxiedToRoutes = function (options, nested) { exports.assertProxiedToRoutes = function (options, nested) {
// //
// Assign dynamic ports to the routes to use. // Assign dynamic ports to the routes to use.
// //
options.routes = helpers.http.assignPortsToRoutes(options.routes); options.routes = helpers.http.assignPortsToRoutes(options.routes);
// //
// Parse locations from routes for making assertion requests. // Parse locations from routes for making assertion requests.
// //
var locations = helpers.http.parseRoutes(options), var locations = helpers.http.parseRoutes(options),
port = helpers.nextPort, port = helpers.nextPort,
protocol = helpers.protocols.proxy, protocol = helpers.protocols.proxy,
context, context,
proxy; proxy;
if (options.filename) { if (options.filename) {
// //
// If we've been passed a filename write the routes to it // If we've been passed a filename write the routes to it
@ -217,19 +217,19 @@ exports.assertProxiedToRoutes = function (options, nested) {
// //
// Otherwise just use the routes themselves. // Otherwise just use the routes themselves.
// //
proxy = { proxy = {
hostnameOnly: options.hostnameOnly, hostnameOnly: options.hostnameOnly,
router: options.routes router: options.routes
}; };
} }
// //
// Set the https options if necessary // Set the https options if necessary
// //
if (helpers.protocols.target === 'https') { if (helpers.protocols.target === 'https') {
proxy.target = { https: true }; proxy.target = { https: true };
} }
// //
// Create the test context which creates all target // Create the test context which creates all target
// servers for all routes and a proxy server. // servers for all routes and a proxy server.
@ -237,13 +237,13 @@ exports.assertProxiedToRoutes = function (options, nested) {
context = { context = {
topic: function () { topic: function () {
var that = this; var that = this;
async.waterfall([ async.waterfall([
// //
// 1. Create all the target servers // 1. Create all the target servers
// //
async.apply( async.apply(
async.forEach, async.forEach,
locations, locations,
function createRouteTarget(location, next) { function createRouteTarget(location, next) {
helpers.http.createServer({ helpers.http.createServer({
@ -256,8 +256,8 @@ exports.assertProxiedToRoutes = function (options, nested) {
// 2. Create the proxy server // 2. Create the proxy server
// //
async.apply( async.apply(
helpers.http.createProxyServer, helpers.http.createProxyServer,
{ {
port: port, port: port,
latency: options.latency, latency: options.latency,
routing: true, routing: true,
@ -271,14 +271,14 @@ exports.assertProxiedToRoutes = function (options, nested) {
that.proxyServer = server; that.proxyServer = server;
that.callback(); that.callback();
}); });
// //
// 4. Assign the port to the context for later use // 4. Assign the port to the context for later use
// //
this.port = port; this.port = port;
}, },
// //
// Add an extra assertion to a route which // Add an extra assertion to a route which
// should respond with 404 // should respond with 404
// //
"a request to unknown.com": exports.assertRequest({ "a request to unknown.com": exports.assertRequest({
@ -291,7 +291,7 @@ exports.assertProxiedToRoutes = function (options, nested) {
} }
}) })
}; };
// //
// Add test assertions for each of the route locations. // Add test assertions for each of the route locations.
// //
@ -307,8 +307,8 @@ exports.assertProxiedToRoutes = function (options, nested) {
body: 'hello from ' + location.source.href body: 'hello from ' + location.source.href
} }
}); });
}); });
// //
// If there are any nested vows to add to the context // If there are any nested vows to add to the context
// add them before returning the full context. // add them before returning the full context.
@ -318,6 +318,6 @@ exports.assertProxiedToRoutes = function (options, nested) {
context[key] = nested[key]; context[key] = nested[key];
}); });
} }
return context; return context;
}; };

View File

@ -5,8 +5,10 @@
* MIT LICENCE * MIT LICENCE
* *
*/ */
var assert = require('assert'), var assert = require('assert'),
fs = require('fs'),
async = require('async'),
io = require('socket.io-client'), io = require('socket.io-client'),
WebSocket = require('ws'), WebSocket = require('ws'),
helpers = require('../helpers/index'); helpers = require('../helpers/index');
@ -16,11 +18,11 @@ var assert = require('assert'),
// #### @options {Object} Options for creating this assertion. // #### @options {Object} Options for creating this assertion.
// #### @raw {boolean} Enables raw `ws.WebSocket`. // #### @raw {boolean} Enables raw `ws.WebSocket`.
// #### @uri {string} URI of the proxy server. // #### @uri {string} URI of the proxy server.
// #### @input {string} Input to assert sent to the target ws server. // #### @input {string} Input to assert sent to the target ws server.
// #### @output {string} Output to assert from the taget ws server. // #### @output {string} Output to assert from the taget ws server.
// //
// Creates a `socket.io` or raw `WebSocket` connection and asserts that // Creates a `socket.io` or raw `WebSocket` connection and asserts that
// `options.input` is sent to and `options.output` is received from the // `options.input` is sent to and `options.output` is received from the
// connection. // connection.
// //
exports.assertSendReceive = function (options) { exports.assertSendReceive = function (options) {
@ -34,9 +36,9 @@ exports.assertSendReceive = function (options) {
"should send input and receive output": function (_, data) { "should send input and receive output": function (_, data) {
assert.equal(data, options.output); assert.equal(data, options.output);
} }
} };
} }
return { return {
topic: function () { topic: function () {
var socket = new WebSocket(options.uri); var socket = new WebSocket(options.uri);
@ -48,15 +50,15 @@ exports.assertSendReceive = function (options) {
"should send input and recieve output": function (_, data, flags) { "should send input and recieve output": function (_, data, flags) {
assert.equal(data, options.output); assert.equal(data, options.output);
} }
} };
} };
// //
// ### function assertProxied (options) // ### function assertProxied (options)
// #### @options {Object} Options for this test // #### @options {Object} Options for this test
// #### @latency {number} Latency in milliseconds for the proxy server. // #### @latency {number} Latency in milliseconds for the proxy server.
// #### @ports {Object} Ports for the request (target, proxy). // #### @ports {Object} Ports for the request (target, proxy).
// #### @input {string} Input to assert sent to the target ws server. // #### @input {string} Input to assert sent to the target ws server.
// #### @output {string} Output to assert from the taget ws server. // #### @output {string} Output to assert from the taget ws server.
// #### @raw {boolean} Enables raw `ws.Server` usage. // #### @raw {boolean} Enables raw `ws.Server` usage.
// //
@ -65,18 +67,18 @@ exports.assertSendReceive = function (options) {
// //
exports.assertProxied = function (options) { exports.assertProxied = function (options) {
options = options || {}; options = options || {};
var ports = options.ports || helpers.nextPortPair, var ports = options.ports || helpers.nextPortPair,
input = options.input || 'hello world to ' + ports.target, input = options.input || 'hello world to ' + ports.target,
output = options.output || 'hello world from ' + ports.target, output = options.output || 'hello world from ' + ports.target,
protocol = helpers.protocols.proxy; protocol = helpers.protocols.proxy;
if (options.raw) { if (options.raw) {
protocol = helpers.protocols.proxy === 'https' protocol = helpers.protocols.proxy === 'https'
? 'wss' ? 'wss'
: 'ws'; : 'ws';
} }
return { return {
topic: function () { topic: function () {
helpers.ws.createServerPair({ helpers.ws.createServerPair({
@ -109,7 +111,7 @@ exports.assertProxied = function (options) {
}; };
// //
// ### function assertProxiedtoRoutes (options, nested) // ### function assertProxiedtoRoutes (options, nested)
// #### @options {Object} Options for this ProxyTable-based test // #### @options {Object} Options for this ProxyTable-based test
// #### @raw {boolean} Enables ws.Server usage. // #### @raw {boolean} Enables ws.Server usage.
// #### @routes {Object|string} Routes to use for the proxy. // #### @routes {Object|string} Routes to use for the proxy.
@ -120,18 +122,18 @@ exports.assertProxied = function (options) {
// http proxy using `options.routes`: // http proxy using `options.routes`:
// //
// 1. Creates target servers for all routes in `options.routes.` // 1. Creates target servers for all routes in `options.routes.`
// 2. Creates a proxy server. // 2. Creates a proxy server.
// 3. Ensure Websocket connections to the proxy server for all route targets // 3. Ensure Websocket connections to the proxy server for all route targets
// can send input and recieve output. // can send input and recieve output.
// //
exports.assertProxiedToRoutes = function (options, nested) { exports.assertProxiedToRoutes = function (options, nested) {
// //
// Assign dynamic ports to the routes to use. // Assign dynamic ports to the routes to use.
// //
options.routes = helpers.http.assignPortsToRoutes(options.routes); options.routes = helpers.http.assignPortsToRoutes(options.routes);
// //
// Parse locations from routes for making assertion requests. // Parse locations from routes for making assertion requests.
// //
var locations = helpers.http.parseRoutes(options), var locations = helpers.http.parseRoutes(options),
protocol = helpers.protocols.proxy, protocol = helpers.protocols.proxy,
@ -144,7 +146,7 @@ exports.assertProxiedToRoutes = function (options, nested) {
? 'wss' ? 'wss'
: 'ws'; : 'ws';
} }
if (options.filename) { if (options.filename) {
// //
// If we've been passed a filename write the routes to it // If we've been passed a filename write the routes to it
@ -157,12 +159,12 @@ exports.assertProxiedToRoutes = function (options, nested) {
// //
// Otherwise just use the routes themselves. // Otherwise just use the routes themselves.
// //
proxy = { proxy = {
hostnameOnly: options.hostnameOnly, hostnameOnly: options.hostnameOnly,
router: options.routes router: options.routes
}; };
} }
// //
// Create the test context which creates all target // Create the test context which creates all target
// servers for all routes and a proxy server. // servers for all routes and a proxy server.
@ -170,13 +172,13 @@ exports.assertProxiedToRoutes = function (options, nested) {
context = { context = {
topic: function () { topic: function () {
var that = this; var that = this;
async.waterfall([ async.waterfall([
// //
// 1. Create all the target servers // 1. Create all the target servers
// //
async.apply( async.apply(
async.forEach, async.forEach,
locations, locations,
function createRouteTarget(location, next) { function createRouteTarget(location, next) {
helpers.ws.createServer({ helpers.ws.createServer({
@ -191,8 +193,8 @@ exports.assertProxiedToRoutes = function (options, nested) {
// 2. Create the proxy server // 2. Create the proxy server
// //
async.apply( async.apply(
helpers.http.createProxyServer, helpers.http.createProxyServer,
{ {
port: port, port: port,
latency: options.latency, latency: options.latency,
routing: true, routing: true,
@ -206,14 +208,14 @@ exports.assertProxiedToRoutes = function (options, nested) {
that.proxyServer = server; that.proxyServer = server;
that.callback(); that.callback();
}); });
// //
// 4. Assign the port to the context for later use // 4. Assign the port to the context for later use
// //
this.port = port; this.port = port;
} }
}; };
// //
// Add test assertions for each of the route locations. // Add test assertions for each of the route locations.
// //
@ -224,7 +226,7 @@ exports.assertProxiedToRoutes = function (options, nested) {
input: 'hello to ' + location.source.href, input: 'hello to ' + location.source.href,
raw: options.raw raw: options.raw
}); });
}); });
return context; return context;
}; };