Skip to content

Commit

Permalink
document test-server harness
Browse files Browse the repository at this point in the history
  • Loading branch information
jamestalmage committed Jul 4, 2015
1 parent 3604c0b commit e2bb4af
Showing 1 changed file with 30 additions and 13 deletions.
43 changes: 30 additions & 13 deletions test/lib/test-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,23 @@ var https = require('https');
var assert = require('assert');

module.exports = function(defaultPorts) {
// set default ports for each protocol i.e. {http: 80, https: 443}
defaultPorts = defaultPorts || {};
var cache = [];
var servers = [];

/**
* Starts a server
*
* If options is a function, uses that the request handler for a `http` server on the default port.
* options.protocol - the protocol to use (`http` or `https`). Defaults to `http`.
* options.port - the port to use, will fall back to defaultPorts[protocol].
* options.app - the request handler passed to http|https.createServer
*
* the options object will also be passed to as the https config for https servers
*
* @param options
* @returns {Promise} that resolves when the server successfully started
*/
function start(options) {
return Promise.fromNode(function(callback) {
if (typeof options === 'function') {
Expand All @@ -19,32 +33,35 @@ module.exports = function(defaultPorts) {
assert(typeof options.app, 'function', 'app');
var server, port;
var protocol = options.protocol;
if (!protocol || protocol.match(/^http(:)?$/)) {
if (!protocol || protocol.trim().match(/^http(:)?$/)) {
server = http.createServer(options.app);
port = options.port || defaultPorts.http;
} else if (protocol.match(/^https(:)?$/)) {
} else if (protocol.trim().match(/^https(:)?$/)) {
server = https.createServer(options, options.app);
port = options.port || defaultPorts.https;
}
assert(typeof port, 'number', 'port');
addServer(server);
servers.push(server);
server.listen(port, callback);
});
}

/**
* Stops all the currently running servers previously created with `start`
* @returns {Promise} that resolves when all servers have successfully shut down.
*/
function stop() {
return Promise.all(cache.map(function(_stop){return _stop();})).finally(function(){
cache = [];
});
return Promise.all(servers.map(stopServer)).finally(clearServers);
}

function addServer(server) {
cache.push(function () {
return Promise.fromNode(function(callback) {
server.close(callback);
});
function stopServer(server) {
return Promise.fromNode(function(callback) {
server.close(callback);
});
return server;
}

function clearServers() {
servers = [];
}

return {
Expand Down

0 comments on commit e2bb4af

Please sign in to comment.