Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge branch 'master' of https://github.com/nrstott/bogart

  • Loading branch information...
commit 5d263e14bc4e9eaae52b5d9a35b221904beaeaf5 2 parents f5945ab + 398f29f
William Skinner authored
44 CHANGES.md
View
@@ -1,8 +1,52 @@
+## v0.3.36
+
+* Publishing v0.3.35 from windows seemed to cause issues when installing on unix. Therefore; I am republishing with only a version bump from linux.
+
+## v0.3.35
+
+* Back out change to package.json to add new CLI.
+
+## v0.3.34
+
+* Removed dependency on Q library.
+
+## v0.3.33
+
+* Changed the unit tests in the project from Expresso to Tap.
+
+## v0.3.32
+
+* Did not update package.json in my tag of 0.3.31, went to 0.3.32 for consistency.
+
+## v0.3.31
+
+* Fixed a bug where Parted middleware was not bubbling rejections.
+
+## v0.3.30
+
+* Fixed a bug causing before callbacks to cause errors.
+
+## v0.3.29
+
+* Missed a whenCall, same issue from v0.3.28.
+
+## v0.3.28
+
+* Added dependency on request 2.2.9.
+* Removed dependency on Deflate as Node.JS 0.6.x includes zlib.
+* Added gzip middleware to `bogart.batteries`
+* Added reject callbacks for all cases where whenCall is invoked as it tries to invoke the rejectCallback even if one is not provided.
+
+## v0.3.27
+
+* `bogart.middleware.session` assumed that `req.env` would be unique per request; however, it is not. Corrected issues caused by this.
+
## v0.3.26
* `bogart.middleware.bodyAdapter` now adapts responses that are of type Buffer or Stream to JSGI responses.
* Fixed a bug in `bogart.middleware.bodyAdatper` where Stream returns were not being handled properly.
* Added `bogart.config`. The default environment is 'development' and may be overridden with the BOGART_ENV environment variable.
+* Expose `DefaultIdProvider` and `DefaultDataProvider` as properties of `bogart.middleware.session`.
## v0.3.25
11 benchmarks/hello-world/hello-world.js
View
@@ -1,9 +1,8 @@
var bogart = require('../../lib/bogart');
-var config = function(show, create, update, destroy) {
- show('/hello/:name', function(req, name) {
- return bogart.html('Hello '+name);
- });
-};
+var router = bogart.router();
+router.get('/', function(req) {
+ return bogart.html('Hello World');
+});
-bogart.start(bogart.router(config));
+bogart.start(router);
2  benchmarks/run
View
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
-ABFLAGS=${ABFLAGS-"-n 500 -c 50 -k"}
+ABFLAGS=${ABFLAGS-"-n 5000 -c 500 -k"}
ADDR=${ADDR-http://0.0.0.0:8080/}
AB=${AB-ab}
16 lib/bogart.js
View
@@ -11,10 +11,20 @@ var
inherits = require('util').inherits,
EventEmitter = require('events').EventEmitter;
-exports.version = [0,3,25];
+exports.version = [0,3,36];
exports.q = Q;
+if (!Q.reject) {
+ Q.reject = function(err) {
+ var deferred = Q.defer();
+
+ deferred.reject(err);
+
+ return deferred.promise;
+ };
+}
+
/**
* Wraps a Node.JS style asynchronous function `function(err, result) {}`
* to return a `Promise`.
@@ -247,9 +257,11 @@ exports.router = function(config, notFoundApp) {
}
return resp;
+ }, function(err) {
+ throw err;
});
} catch (err) {
- return require('q').reject(err);
+ return Q.reject(err);
}
};
30 lib/middleware.js
View
@@ -64,7 +64,7 @@ exports.parseForm = exports.ParseForm = function(nextApp) {
};
exports.gzip = exports.Gzip = function(nextApp) {
- var deflate = require('deflate'),
+ var zlib = require('zlib'),
bogart = require('./bogart');
function acceptsGzip(req) {
@@ -85,14 +85,16 @@ exports.gzip = exports.Gzip = function(nextApp) {
if (acceptsGzip(req)) {
return Q.when(resp, function(resp) {
- var ds = deflate.createDeflateStream(new ForEachStream(resp.body.map(function(chunk) {
- return new Buffer(chunk);
- })));
- ds.readStream.pipe(ds);
-
+ var gzip = zlib.createGzip();
resp.headers['content-encoding'] = 'gzip';
+ if (resp.headers['content-length']) {
+ delete resp.headers['content-length'];
+ }
+
+ bogart.pump(resp.body, gzip);
- return bogart.pipe(ds, resp);
+ resp.body = toForEachable(gzip);
+ return resp;
});
} else {
return resp;
@@ -108,7 +110,7 @@ exports.methodOverride = exports.MethodOverride = function(nextApp) {
return function(request) {
if (request.body && typeof request.body == "object") {
if ((request.method == "POST") && (!request.headers["content-type"].match(/^multipart\/form-data/))) {
- method = request.headers[HTTP_METHOD_OVERRIDE_HEADER] || request.body[METHOD_OVERRIDE_PARAM_KEY];
+ var method = request.headers[HTTP_METHOD_OVERRIDE_HEADER] || request.body[METHOD_OVERRIDE_PARAM_KEY];
if (method && HTTP_METHODS[method.toUpperCase()] === true) {
request.env.original_method = request.method;
request.method = method.toUpperCase();
@@ -141,7 +143,7 @@ exports.parted = exports.Parted = function(nextApp, opts) {
fn(req, null, function() {
Q.when(nextApp(req), function(resp) {
deferred.resolve(resp);
- });
+ }, deferred.reject);
});
return deferred.promise;
@@ -233,6 +235,9 @@ exports.validateResponse = exports.ValidateResponse = function(nextApp) {
}
return resp;
+ }, function(err) {
+ // Workaround for fact that whenCall calls rejectCallback even if one is not provided.
+ throw err;
});
};
};
@@ -273,7 +278,7 @@ exports.directory = exports.Directory = function(root, nextApp) {
return nextApp(req);
}
}, function(err) {
- var notFoundMessaeg = "404 Not Found";
+ var notFoundMessage = "404 Not Found";
return nextApp ? nextApp(req) : {
"status": 404,
@@ -756,7 +761,7 @@ exports.cascade = function(accept /*, apps */) {
*
* Includes the following JSGI Chain:
*
- * error -> validateResponse -> directory -> parted -> methodOverride
+ * error -> validateResponse -> gzip -> directory -> parted -> methodOverride
* -> session -> flash -> bodyAdapter -> stringReturnAdapter -> nextApp
*
* @param {Object} config Optional configuration, if arity is two first parameter is config.
@@ -775,13 +780,14 @@ exports.batteries = function(config, nextApp) {
}
var stack = exports.Error(
+ exports.gzip(
exports.directory(root,
exports.Parted(
exports.MethodOverride(
exports.Session(
exports.Flash(
exports.bodyAdapter(
- exports.stringReturnAdapter(nextApp))))))));
+ exports.stringReturnAdapter(nextApp)))))))));
return stack;
};
68 lib/router.js
View
@@ -3,7 +3,8 @@ var
EventEmitter = require('events').EventEmitter,
Q = require('promised-io/lib/promise'),
when = Q.when,
- inherits = require('util').inherits;
+ inherits = require('util').inherits,
+ slice = Array.prototype.slice;
var
httpMethod = {
@@ -88,8 +89,13 @@ Router.prototype.after = function(cb) {
* @param {String} path Path for the route
* @param {Function} handler Function to execute when the route is accessed
*/
-Router.prototype.route = function(method, path, handler) {
- var paramNames, route, originalPath = path;
+Router.prototype.route = function(method, path /*, handlers... */) {
+ var paramNames, route, originalPath = path
+ , args = Array.prototype.slice.call(arguments);
+
+ method = args.shift();
+ path = args.shift();
+ apps = args;
if (path.constructor === String) {
paramNames = path.match(PATH_PARAMETERS) || [];
@@ -98,7 +104,7 @@ Router.prototype.route = function(method, path, handler) {
path = new RegExp("^"+path.replace(/\./, '\\.').replace(/\*/g, '(.+)').replace(PATH_PARAMETERS, PATH_PARAMETER_REPLACEMENT)+'$');
}
- route = { path: path, paramNames: paramNames, handler: handler, originalPath: originalPath };
+ route = { path: path, paramNames: paramNames, apps: apps, originalPath: originalPath };
this.emit(exports.bogartEvent.BEFORE_ADD_ROUTE, this, route);
@@ -163,45 +169,73 @@ Router.prototype.respond = function(reqPromise) {
Object.defineProperty(req, 'params', { value: util.merge({}, req.routeParams, req.search, req.body), enumerable: true, readonly: true });
- var args = [req].concat(routeParamValues || []);
-
/* Invoke all 'before' functions and save any promises. */
var promiseArray = [];
self.beforeCallbacks.forEach(function(cb) {
- promiseArray.push(cb.apply(self, args));
+ promiseArray.push(cb.call(self, req));
});
/* Wait until any promises have completed. */
return when(Q.all(promiseArray), function() {
return Q.whenCall(function() {
- return route.handler.apply(self, args);
+ var jsgiApp = stack.apply(stack, route.apps);
+ return jsgiApp(req);
}, function(resp) {
/* Invoke all 'after' functions and save any promises. */
var promiseArray = [];
self.afterCallbacks.forEach(function(cb) {
- promiseArray.push(cb.apply(self, args));
+ promiseArray.push(cb.call(self, req));
});
return when(Q.all(promiseArray), function() {
return resp;
});
+ }, function(err) {
+ // work around for issue in whenCall, it tries to call rejectCallback even if one is not provided
+ throw err;
});
});
});
};
-Router.prototype.show = Router.prototype.get = function(path, handler) {
- return this.route(restMethod.SHOW, path, handler);
+Router.prototype.show = Router.prototype.get = function(path /*, jsgiApps */) {
+ return this.route.apply(this, [ restMethod.SHOW ].concat(slice.call(arguments)));
};
-Router.prototype.create = Router.prototype.post = function(path, handler) {
- return this.route(restMethod.CREATE, path, handler);
+Router.prototype.create = Router.prototype.post = function(path /*, jsgiApps */) {
+ return this.route.apply(this, [ restMethod.CREATE ].concat(slice.call(arguments)));
};
-Router.prototype.update = Router.prototype.put = function(path, handler) {
- return this.route(restMethod.UPDATE, path, handler);
+Router.prototype.update = Router.prototype.put = function(path /*, jsgiApps */) {
+ return this.route.apply(this, [ restMethod.UPDATE ].concat(slice.call(arguments)));
};
-Router.prototype.destroy = Router.prototype.del = function(path, handler) {
- return this.route(restMethod.DESTROY, path, handler);
+Router.prototype.destroy = Router.prototype.del = function(path /*, jsgiApps */) {
+ return this.route.apply(this, [ restMethod.DESTROY ].concat(slice.call(arguments)));
};
+
+/**
+ * Takes a variadic number of JSGI applications and chains them together.
+ *
+ * A normal JSGI middleware has the signature `function(nextApp)` and is expected
+ * to return a function that takes a request and does something useful then calls
+ * the next application.
+ *
+ * Stack works with functions that have a signature of `function(req, nextApp)`.
+ *
+ * @returns {Function} A function that takes a request and executes a stack of JSGI applications.
+ */
+function stack(/* apps... */) {
+ var args = Array.prototype.slice.call(arguments);
+
+ function next(req) {
+ var jsgiApp = args.shift();
+ return jsgiApp(req, next);
+ }
+
+ return function(req) {
+ return next(req);
+ };
+}
+
+exports.stack = stack;
3  lib/view.js
View
@@ -66,6 +66,9 @@ ViewEngine.prototype.respond = function(view, opts) {
headers: opts.headers || { 'content-type': 'text/html', 'content-length': Buffer.byteLength(str, 'utf-8') },
body: [str]
};
+ }, function(err) {
+ // Workaround for issue where whenCall calls rejectCallback even if one is not provided.
+ throw err;
});
};
22 package.json
View
@@ -1,12 +1,17 @@
{
"name": "bogart",
"description": "Fast JSGI web framework taking inspiration from Sinatra",
- "version": "0.3.25",
+ "version": "0.3.36",
"keywords": ["bogart", "framework", "sinatra", "REST"],
- "author": "Nathan Stott",
+ "author": "Nathan Stott <nrstott@gmail.com>",
"email": "nathan.stott@whiteboard-it.com",
+ "homepage": "https://github.com/nrstott/bogart",
"main": "./lib/bogart",
"directories": { "lib": "./lib" },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/nrstott/bogart"
+ },
"bugs": {
"url": "https://github.com/nrstott/bogart/issues",
"email": "nrstott@gmail.com"
@@ -15,19 +20,20 @@
"promised-io": "v0.2.3",
"jsgi": ">=v0.2.2",
"mustache": "0.3.1-dev",
- "deflate": ">=1.0.3",
"underscore": ">=0.0.0",
"node-uuid": ">=1.2.0",
"parted": "=0.0.8",
- "q": "=0.7.2",
- "oauth": "=0.9.5"
+ "oauth": "=0.9.5",
+ "request": "=2.2.9",
+ "commander": "*",
+ "mkdirp": "*"
},
"devDependencies": {
- "expresso": ">= 0.8.1",
"haml": ">=0.4.2",
- "jade": ">=0.15.4"
+ "jade": ">=0.15.4",
+ "tap": "*"
},
"scripts": {
- "test": "expresso"
+ "test": "tap ./test/middleware.test.js ./test/response-builder.test.js ./test/response-helpers.test.js ./test/router.test.js ./test/stream.test.js ./test/util.test.js ./test/view.test.js"
}
}
333 test/middleware.test.js
View
@@ -1,12 +1,13 @@
var bogart = require('../lib/bogart')
, Q = require("promised-io/lib/promise")
- , assert = require('assert')
, path = require('path')
- , fs = require('fs')
+ , fs = require('fs')
, security = require("../lib/security")
- , util = require('util');
+ , util = require('util')
+ , test = require('tap').test
+ , plan = require('tap').plan;
-exports["test parses JSON"] = function(beforeExit) {
+test("test parses JSON", function(t) {
var forEachDeferred = Q.defer()
, app
, body
@@ -24,20 +25,20 @@ exports["test parses JSON"] = function(beforeExit) {
request.body = body;
app = bogart.middleware.ParseJson(function(req) {
- processedReq = req;
+ t.ok(req !== undefined);
+ t.equal('1', req.body.a, 'req.body.a should equal "1"');
});
- app(request);
-
+ process.nextTick(function() {
+ app(request);
+ });
+
forEachDeferred.resolve();
- beforeExit(function() {
- assert.ok(processedReq !== undefined);
- assert.equal('1', processedReq.body.a);
- })
-};
+ t.plan(2);
+});
-exports["test parses form"] = function(beforeExit) {
+test("test parses form", function(t) {
var forEachDeferred = Q.defer()
, app
, body
@@ -55,21 +56,21 @@ exports["test parses form"] = function(beforeExit) {
request.body = body;
app = bogart.middleware.ParseForm(function(req) {
- processedReq = req;
+ t.ok(req, 'req should not be falsey');
+ t.type(req.body, 'object', 'Body should be an object');
+ t.equal('1', req.body.a);
});
- app(request);
-
+ process.nextTick(function() {
+ app(request);
+ });
+
forEachDeferred.resolve();
- beforeExit(function() {
- assert.ok(processedReq !== undefined);
- assert.equal('object', typeof processedReq.body, 'Body should be an object');
- assert.equal('1', processedReq.body.a);
- });
-};
+ t.plan(3);
+});
-exports["test method override"] = function(beforeExit) {
+test("test method override", function(t) {
var request = { method: 'POST', env: {} }
, headers = { 'content-type': 'text/html' }
, app;
@@ -78,34 +79,34 @@ exports["test method override"] = function(beforeExit) {
request.headers = headers;
app = bogart.middleware.MethodOverride(function(req) {});
- app(request);
-
- beforeExit(function() {
- assert.equal('PUT', request.method, 'Should change method to PUT');
+ Q.when(app(request), function() {
+ t.equal('PUT', request.method, 'Should change method to PUT');
+ }, function(err) {
+ console.log('error', err);
+ t.end();
});
-};
-exports["test gzip"] = function(beforeExit) {
- var response = null;
-
+ t.plan(1);
+});
+
+test("test gzip", function(t) {
var app = bogart.middleware.Gzip(function(req) {
return bogart.html('Hello World');
});
var appPromise = app({ method: 'GET', env: {} });
- Q.when(appPromise, function(jsgiResp) {
- response = jsgiResp;
- });
-
- beforeExit(function() {
- assert.isNotNull(response, 'Response should not be null');
- assert.ok(response.body, 'Response should have a body');
+ Q.when(appPromise, function(resp) {
+ t.ok(resp, 'Response should not be falsey');
+ t.ok(resp.body, 'Response should have a body');
+ }, function(err) {
+ console.log('error', err);
+ t.end();
});
-};
-exports["test gzip downloads as text/html"] = function(beforeExit) {
- var response = null;
+ t.plan(2);
+});
+test("test gzip downloads as text/html", function(t) {
var router = bogart.router();
var viewEngine = bogart.viewEngine('mustache', path.join(__dirname, 'fixtures'));
@@ -117,32 +118,33 @@ exports["test gzip downloads as text/html"] = function(beforeExit) {
var app = Gzip(router);
Q.when(app({ method: 'GET', env: {}, headers: {}, pathInfo: '/' }), function(resp) {
- response = resp;
+ t.ok(resp, 'Response should not be falsey');
+ t.equal(resp.status, 200);
+ t.equal(resp.headers['content-type'], 'text/html');
+ }, function(err) {
+ console.log('error', err);
+ t.end();
});
- beforeExit(function() {
- assert.isNotNull(response, 'Responses should not be null');
- assert.equal(200, response.status);
- assert.equal('text/html', response.headers['content-type']);
- });
-};
+ t.plan(3);
+});
-exports["test error middleware has default response when error is thrown"] = function(beforeExit) {
- var response = null
- , app = new bogart.middleware.Error(function(req) { throw new Error('intentional'); });
+test("test error middleware has default response when error is thrown", function(t) {
+ var app = new bogart.middleware.Error(function(req) { throw new Error('intentional'); });
Q.when(app({ method: 'GET', env: {}, headers: {}, pathInfo: '/' }), function(resp) {
- response = resp;
+ t.ok(resp, 'Response should not be falsey');
+ t.equal(resp.status, 500);
+ t.equal(resp.headers['content-type'], 'text/html');
+ }, function(err) {
+ console.log('error', err);
+ t.end();
});
- beforeExit(function() {
- assert.isNotNull(response);
- assert.equal(500, response.status);
- assert.equal('text/html', response.headers['content-type']);
- });
-};
+ t.plan(3);
+});
-exports["test flash"] = function(beforeExit) {
+test("test flash", function(t) {
var app
, headers = { 'content-type': 'text/plain' }
, request = { headers: headers, body:[] }
@@ -164,104 +166,102 @@ exports["test flash"] = function(beforeExit) {
cookieStr = initialResp.headers["Set-Cookie"].join("").replace(/;$/, "");
// the first attempt to retrieve "foo" should be undefined
- assert.isUndefined(foo);
+ t.type(foo, 'undefined', 'Foo should be undefined');
request.headers.cookie = cookieStr;
- var secondResp = app(request);
- });
-
- beforeExit(function() {
- assert.eql(foo, "bar");
+ Q.when(app(request), function() {
+ t.equal(foo, 'bar', 'foo should equal bar');
+ });
});
-};
+ t.plan(2);
+});
-exports["test error middleware has default response when promise is rejected"] = function(beforeExit) {
- var response = null
- , app = new bogart.middleware.Error(function(req) { return require('q').reject('rejected'); });
+
+test("test error middleware has default response when promise is rejected", function(t) {
+ var app = new bogart.middleware.Error(function(req) { return bogart.Q.reject('rejected'); });
Q.when(app({ method: 'GET', env: {}, headers: {}, pathInfo: '/' }), function(resp) {
- response = resp;
+ t.ok(resp, 'Response should not be falsey');
+ t.equal(resp.status, 500);
+ t.equal(resp.headers['content-type'], 'text/html', 'Content-Type should be text/html');
});
- beforeExit(function() {
- assert.isNotNull(response);
- assert.equal(500, response.status);
- assert.equal('text/html', response.headers['content-type']);
- });
-};
+ t.plan(3);
+});
-exports["test parted json"] = function(beforeExit) {
- var request = null
- , parted = new bogart.middleware.Parted(function(req) { request = req; return {}; });
-
- response = parted({
+test("test parted json", function(t) {
+ var request = null
+ , parted = new bogart.middleware.Parted(function(req) { request = req; return {}; });
+
+ bogart.middleware.parted(function(req) {
+ t.ok(req, 'Request should not be falsey');
+ t.type(req.body, 'object', 'Request body should be an object');
+ t.equal(req.body.hello, 'world', 'req.body.hello should equal "world"');
+ })({
method: 'POST',
env: {},
headers: { 'content-type': 'application/json' },
body: [ '{ "hello": "world" }' ]
});
- beforeExit(function() {
- assert.isNotNull(request);
- assert.isNotNull(request.body);
- assert.equal('object', typeof request.body);
- assert.equal('world', request.body.hello);
- });
-};
+ t.plan(3);
+});
+
+test("test parted form", function(t) {
+ var body = {}
+ , bodyDefer = Q.defer()
+ , parted;
-exports["test parted form"] = function(beforeExit) {
- var request = null
- , parted = new bogart.middleware.Parted(function(req) { request = req; return {}; })
- , body = {}
- , bodyDefer = require('q').defer();
-
body.forEach = function(callback) {
callback('hello=one&hello=two');
return bodyDefer.promise;
- };
+ };
+
+ parted = new bogart.middleware.Parted(function(req) {
+ t.ok(req, 'Request should not be falsey');
+ t.ok(!!req.body);
+ t.ok(!!req.body.hello);
+ t.equal(req.body.hello.length, 2);
+ });
- response = parted({
+ parted({
method: 'POST',
env: {},
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: body
});
- bodyDefer.resolve();
-
- beforeExit(function() {
- assert.isNotNull(request);
- assert.ok(!!request.body);
- assert.ok(!!request.body.hello);
- assert.equal(2, request.body.hello.length);
+ process.nextTick(function() {
+ bodyDefer.resolve();
});
-};
-exports["test parted multipart"] = function(beforeExit) {
- var request = null
- , parted = new bogart.middleware.Parted(function(req) { request = req; return {}; });
+ t.plan(4);
+});
+
+test("test parted multipart", function(t) {
+ var parted;
- fs.readFileSync(path.join(__dirname, 'fixtures', 'chrome.part'));
+ parted = new bogart.middleware.Parted(function(req) {
+ t.ok(!!req.body);
+ t.ok(!!req.body.content, 'No file path');
+ });
- response = parted(multipartRequest(100, 'chrome'));
-
- beforeExit(function() {
- assert.ok(!!request.body);
- assert.ok(!!request.body.content, 'No file path');
+ process.nextTick(function() {
+ parted(multipartRequest(100, 'chrome'));
});
-};
+ t.plan(2);
+});
-exports["test session"] = function(beforeExit) {
+test("test session", function(t) {
var app
, headers = { 'content-type': 'text/plain' }
, request = { headers: headers, body:[] }
, values = []
, firstRequest = true;
-
app = bogart.middleware.Session({}, function(req) {
if(firstRequest) {
req.session("foo", "bar");
@@ -276,28 +276,27 @@ exports["test session"] = function(beforeExit) {
}
});
- var initialResp = app(request);
- var cookieStr = initialResp.headers["Set-Cookie"].join("").replace(/;$/, "");
+ Q.when(app(request), function(initialResp) {
+ var cookieStr = initialResp.headers["Set-Cookie"].join("").replace(/;$/, "");
- request.headers.cookie = cookieStr;
- var secondResp = app(request);
+ request.headers.cookie = cookieStr;
- beforeExit(function() {
- assert.equal(values.length, 2);
- values.forEach(function(val) {
- assert.equal(val, "bar");
- })
+ Q.when(app(request), function(resp) {
+ t.equal(values.length, 2);
+ values.forEach(function(val) {
+ t.ok(val, 'bar');
+ });
+ });
});
-
-};
-
-exports["test validate response"] = function(beforeExit) {
- var noResponse, noBody, notForEachable, forEachNotFunction, noStatus, statusNotNumber;
+ t.plan(3);
+});
+
+test("test validate response", function(t) {
bogart.middleware.validateResponse(function(req) {
return null;
- })().then(bogart.noop, function(err) {
- noResponse = err;
+ })().then(null, function(err) {
+ t.equal(err, 'Response must be an object.');
});
bogart.middleware.validateResponse(function(req) {
@@ -305,8 +304,8 @@ exports["test validate response"] = function(beforeExit) {
status: 200,
headers: {}
};
- })().then(bogart.noop, function(err) {
- noBody = err;
+ })().then(null, function(err) {
+ t.equal(err, 'Response must have a body property.');
});
bogart.middleware.validateResponse(function(req) {
@@ -315,8 +314,8 @@ exports["test validate response"] = function(beforeExit) {
headers: {},
body: {}
};
- })().then(bogart.noop, function(err) {
- notForEachable = err;
+ })().then(null, function(err) {
+ t.equal(err, 'Response body must have a forEach method.');
});
bogart.middleware.validateResponse(function(req) {
@@ -327,8 +326,8 @@ exports["test validate response"] = function(beforeExit) {
forEach: 'not a function'
}
};
- })().then(bogart.noop, function(err) {
- forEachNotFunction = err;
+ })().then(null, function(err) {
+ t.equal(err, 'Response body has a forEach method but the forEach method is not a function.');
});
bogart.middleware.validateResponse(function(req) {
@@ -336,8 +335,8 @@ exports["test validate response"] = function(beforeExit) {
headers: {},
body: []
};
- })().then(bogart.noop, function(err) {
- noStatus = err;
+ })().then(null, function(err) {
+ t.equal(err, 'Response must have a status property.');
});
bogart.middleware.validateResponse(function(req) {
@@ -346,23 +345,15 @@ exports["test validate response"] = function(beforeExit) {
body: [],
headers: {}
};
- })().then(bogart.noop, function(err) {
- statusNotNumber = err;
+ })().then(null, function(err) {
+ t.equal(err, 'Response has a status property but the status property must be a number.');
});
- beforeExit(function() {
- assert.equal('Response must be an object.', noResponse);
- assert.equal('Response must have a body property.', noBody);
- assert.equal('Response body must have a forEach method.', notForEachable);
- assert.equal('Response body has a forEach method but the forEach method is not a function.', forEachNotFunction);
- assert.equal('Response must have a status property.', noStatus);
- assert.equal('Response has a status property but the status property must be a number.', statusNotNumber);
- });
-};
+ t.plan(6);
+});
-exports["test bodyAdapter adapts Stream"] = function(beforeExit) {
- var Stream = require('stream').Stream
- , response;
+test("test bodyAdapter adapts Stream", function(t) {
+ var Stream = require('stream').Stream;
function TestReadStream() {
Stream.call(this);
@@ -371,14 +362,17 @@ exports["test bodyAdapter adapts Stream"] = function(beforeExit) {
, self = this;
process.nextTick(function emitData() {
- var x = args.pop();
- if (!x) { return; }
+ var x = args.shift();
+ if (x === undefined) {
+ self.emit('end');
+ return;
+ }
self.emit('data', x);
- process.nextTick(function() {
+ //process.nextTick(function() {
emitData();
- });
+ //});
});
this.readable = true;
@@ -391,22 +385,23 @@ exports["test bodyAdapter adapts Stream"] = function(beforeExit) {
});
Q.when(streamAdapter(), function(resp) {
- response = resp;
- });
+ var str = '';
- beforeExit(function() {
- assert.ok(response);
- assert.ok(response.body);
- assert.ok(response.body.forEach);
+ t.ok(resp, 'Response should not be falsey');
+ t.ok(resp.body, 'Response should have a body');
+ t.ok(resp.body.forEach, 'Response body should be forEachable');
- var str = '';
- response.body.forEach(function(x) {
+ return resp.body.forEach(function(x) {
str += x;
+ }).then(function() {
+ t.equal(str, 'hello world', 'should equal hello world');
+ t.end();
+ }, function(err) {
+ t.ok(false, err, 'found error');
+ t.end();
});
-
- assert.equal('hello world', str);
});
-};
+});
/**
* Create a mock request
68 test/response-builder.test.js
View
@@ -2,41 +2,37 @@ var bogart = require('../lib/bogart')
, assert = require('assert')
, Q = require('promised-io/lib/promise')
, fs = require('fs')
- , path = require('path');
+ , path = require('path')
+ , test = require('tap').test
+ , plan = require('tap').plan;
function identity(){};
-exports["test ResponseBuilder can be resolved"] = function(beforeExit) {
- var resolved = false
- , response = new bogart.ResponseBuilder();
+test("test ResponseBuilder can be resolved", function(t) {
+ var response = new bogart.ResponseBuilder();
response.then(function() {
- resolved = true;
+ t.ok(true);
});
response.resolve();
- beforeExit(function() {
- assert.ok(resolved, 'Should have resolved');
- });
-};
+ t.plan(1);
+});
-exports["test ResponseBuilder can be rejected"] = function(beforeExit) {
- var rejected = false
- , response = new bogart.ResponseBuilder();
+test("test ResponseBuilder can be rejected", function(t) {
+ var response = new bogart.ResponseBuilder();
- response.then(identity, function() {
- rejected = true;
+ response.then(null, function() {
+ t.ok(true);
});
response.reject();
- beforeExit(function() {
- assert.ok(rejected, 'Should have rejected');
- });
-};
+ t.plan(1);
+});
-exports["test ResponseBuilder send string"] = function(beforeExit) {
+test("test ResponseBuilder send string", function(t) {
var response = new bogart.ResponseBuilder()
, msg = 'Hello World'
, written = '';
@@ -47,16 +43,16 @@ exports["test ResponseBuilder send string"] = function(beforeExit) {
return resp.body.forEach(function(data) {
written += data;
});
+ }).then(function() {
+ t.equal(written, msg);
});
response.end();
- beforeExit(function() {
- assert.equal(msg, written);
- });
-};
+ t.plan(1);
+});
-exports["test ResponseBuilder send buffer"] = function(beforeExit) {
+exports["test ResponseBuilder send buffer"] = function(t) {
var response = new bogart.ResponseBuilder()
, msg = 'Hello World'
, buf = new Buffer(msg.length)
@@ -70,14 +66,14 @@ exports["test ResponseBuilder send buffer"] = function(beforeExit) {
return resp.body.forEach(function(data) {
written += data;
});
+ }).then(function() {
+ t.equal(written, msg);
});
- beforeExit(function() {
- assert.equal(msg, written);
- });
+ t.plan(1);
};
-exports["test ResponseBuilder send binary"] = function(beforeExit) {
+test("test ResponseBuilder send binary", function(t) {
var response = new bogart.ResponseBuilder()
, filePath = path.join(__dirname, 'fixtures', 'test.jpg')
, stat = fs.statSync(filePath)
@@ -85,19 +81,23 @@ exports["test ResponseBuilder send binary"] = function(beforeExit) {
, written = new Buffer(stat.size);
fs.readFile(filePath, 'binary', function(err, content) {
+ if (err) {
+ t.fail(err);
+ return;
+ }
fileContent = content;
response.send(content);
+ response.end();
});
- response.end();
-
response.then(function(resp) {
return resp.body.forEach(function(chunk) {
written.write(chunk, 'binary');
});
+ }).then(function() {
+ t.ok(fileContent !== null, 'fileContent should not be null');
+ t.equal(written.toString('binary'), fileContent);
});
- beforeExit(function() {
- assert.equal(fileContent, written.toString('binary'), 'not equal');
- });
-};
+ t.plan(2);
+});
121 test/response-helpers.test.js
View
@@ -1,95 +1,102 @@
var bogart = require('../lib/bogart')
- , assert = require('assert')
, Q = require('promised-io/lib/promise')
, when = Q.when
, path = require('path')
- , fs = require('fs');
+ , fs = require('fs')
+ , test = require('tap').test
+ , plan = require('tap').plan;
-
-exports["test json should have status 200"] = function() {
+test("test json should have status 200", function(t) {
var resp = bogart.json({});
- assert.equal(200, resp.status);
-};
+ t.equal(resp.status, 200);
+ t.end();
+});
-exports["test json should have status 403"] = function() {
+test("test json should have status 403", function(t) {
var status = 403
, resp = bogart.json({}, { status: status });
- assert.equal(status, resp.status);
-};
+ t.equal(resp.status, status);
+ t.end();
+});
-exports["test json should have body"] = function() {
+test("test json should have body", function(t) {
var bodyObj = { hello: "world" }
, resp = bogart.json(bodyObj);
- assert.equal(JSON.stringify(bodyObj), resp.body.join());
-};
+ t.equal(resp.body.join(), JSON.stringify(bodyObj));
+ t.end();
+});
-exports["test error should have status 500"] = function() {
+test("test error should have status 500", function(t) {
var resp = bogart.error();
- assert.equal(500, resp.status);
-};
+ t.equal(resp.status, 500);
+ t.end();
+});
-exports["test error should have status 403"] = function() {
+test("test error should have status 403", function(t) {
var resp = bogart.error("", { status: 403 });
- assert.equal(403, resp.status);
-};
+ t.equal(resp.status, 403);
+ t.end();
+});
-exports["test should have status 200"] = function() {
+test("test should have status 200", function(t) {
var resp = bogart.html();
- assert.equal(200, resp.status);
-};
+ t.equal(resp.status, 200);
+ t.end();
+});
-exports["test html should have status 404"] = function() {
+test("test html should have status 404", function(t) {
var resp = bogart.html("", { status: 404 });
- assert.equal(404, resp.status);
-};
+ t.equal(resp.status, 404);
+ t.end();
+});
-exports["test html should have HTML"] = function() {
-var str = "Hello World"
- , resp = bogart.html(str);
+test("test html should have HTML", function(t) {
+ var str = "Hello World"
+ , resp = bogart.html(str);
- assert.equal(str, resp.body.join());
-};
+ t.equal(str, resp.body.join());
+ t.end();
+});
-exports["test should be text/html"] = function() {
+test("test should be text/html", function(t) {
var resp = bogart.html();
- assert.equal("text/html", resp.headers["content-type"])
-};
+ t.equal(resp.headers["content-type"], "text/html");
+ t.end();
+});
-exports["test should have content-length 5"] = function() {
+test("test should have content-length 5", function(t) {
var str = "hello"
, resp = bogart.html(str);
- assert.equal(5, resp.headers["content-length"]);
-};
+ t.equal(resp.headers["content-length"], 5);
+ t.end();
+});
-exports["test pipe stream"] = function(beforeExit) {
+test("test pipe stream", function(t) {
var readStream = fs.createReadStream(path.join(__dirname, 'fixtures', 'text.txt'))
, pipe = bogart.pipe(readStream)
- , response = null
, written = '';
pipe.then(function(resp) {
- response = resp;
- resp.body.forEach(function(data) {
+ Q.when(resp.body.forEach(function(data) {
written += data;
+ }), function() {
+ t.equal(written, 'Hello World');
});
});
- beforeExit(function() {
- assert.isNotNull(response, 'Response should not be null');
- assert.equal('Hello World', written);
- });
-};
+ t.plan(1);
+});
-exports["test pipe forEachable"] = function(beforeExit) {
+test("test pipe forEachable", function(t) {
var forEachable = {}
, deferred = Q.defer()
, msg = 'Hello World'
@@ -109,30 +116,32 @@ exports["test pipe forEachable"] = function(beforeExit) {
return resp.body.forEach(function(data) {
written += data;
});
+ }).then(function() {
+ t.equal(written, msg);
});
- beforeExit(function() {
- assert.equal(msg, written);
- });
-};
+ t.plan(1);
+});
-exports["test bogart.redirect merges opts"] = function(beforeExit) {
+test("test bogart.redirect merges opts", function(t) {
var opts = {
hello: 'world'
};
var resp = bogart.redirect('/', opts);
- assert.equal('world', resp.hello);
-};
+ t.equal(resp.hello, 'world');
+ t.end();
+});
-exports["test bogart.redirect merges headers"] = function(beforeExit) {
+test("test bogart.redirect merges headers", function(t) {
var opts = {
headers: { hello: 'world' }
};
var resp = bogart.redirect('/', opts);
- assert.equal('world', resp.headers.hello);
- assert.ok('location' in resp.headers);
-};
+ t.equal(resp.headers.hello, 'world');
+ t.ok('location' in resp.headers);
+ t.end();
+});
333 test/router.test.js
View
@@ -1,17 +1,9 @@
var bogart = require('../lib/bogart')
- , assert = require('assert')
, Q = require('promised-io/lib/promise')
, when = Q.when
, jsgi = require('jsgi')
- , rootRequest = function() {
- return {
- headers: {},
- pathInfo: '/',
- method: 'GET',
- jsgi: { version: [0, 3] },
- env: {}
- };
- };
+ , test = require('tap').test
+ , plan = require('tap').plan;
function mockRequest(path) {
return {
@@ -23,6 +15,10 @@ function mockRequest(path) {
};
}
+function rootRequest() {
+ return mockRequest('/');
+}
+
/**
* Define a simple router that has a route that matches `path`
* @param {String} path The path to match
@@ -35,87 +31,74 @@ function simpleRouter(path) {
return router;
}
-exports['test matches parameter'] = function(beforeExit) {
- var
- name, req = rootRequest(), response,
- router = bogart.router(function(get) {
- get('/hello/:name', function(req) {
- name = req.params.name;
- return bogart.html("hello");
- });
- });
+test('matches parameter', function(t) {
+ var name
+ , req = rootRequest()
+ , router = bogart.router(function(get) {
+ get('/hello/:name', function(req) {
+ name = req.params.name;
+ return bogart.html("hello");
+ });
+ });
req.pathInfo = '/hello/nathan';
when(router(req), function(resp) {
- response = resp;
+ t.equal(resp.status, 200);
+ t.equal(name, 'nathan');
});
- beforeExit(function() {
- assert.equal(200, response.status);
- assert.equal("nathan", name);
- });
-};
-exports['test order of routes matching should be in order defined'] = function(){
- var
- name, req = rootRequest(),
- router = bogart.router(function(get) {
- get('/hello/:name', function(req) {
- name = req.params.name;
- assert.ok (true, "first route matched successfully");
- return bogart.html("hello");
- });
- get("/hello/:name/:something", function(req){
- name = req.params.name;
- return bogart.html("hello");
- assert.ok(false, "second route matched incorrectly")
- })
- });
+ t.plan(2);
+});
- req.pathInfo = '/hello/nathan/';
+test('order of routes matching should be in order defined', function(t) {
+ var name
+ , req = mockRequest('/hello/nathan')
+ , router = bogart.router(function(get) {
+ get('/hello/:name', function(req) {
+ t.ok(true);
+ });
+ get("/hello/:name/:something", function(req){
+ t.fail("second route matched incorrectly");
+ })
+ });
- return when(router(req), function(resp) {
- //do nothing
- });
+ router(req);
-};
+ t.plan(1);
+});
-exports['test should call notFoundApp'] = function(beforeExit) {
+test('should call notFoundApp', function(t) {
var called = false
, notFoundApp = function(req) {
called = true;
return { status: 409, body: [ '' ] };
}
, router = bogart.router(function() {}, notFoundApp)
- , respPromise = router(rootRequest())
- , response;
+ , respPromise = router(rootRequest());
when(respPromise, function(resp) {
- response = resp;
- });
-
- beforeExit(function() {
- assert.equal(409, response.status);
- assert.ok(called);
+ t.equal(resp.status, 409);
+ }, function() {
+ t.fail('Promise should not be rejected');
});
-};
+
+ t.plan(1);
+});
-exports['test should have default notFoundApp behavior of returning 404'] = function(beforeExit) {
+test('should have default notFoundApp behavior of returning 404', function(t) {
var router = bogart.router(function(){})
- , respPromise = router(rootRequest())
- , response;
+ , respPromise = router(rootRequest());
when(respPromise, function(resp) {
- response = resp;
+ t.equal(resp.status, 404);
});
- beforeExit(function() {
- assert.equal(404, response.status);
- });
-};
+ t.plan(1);
+});
-exports['test should not partially match route'] = function(beforeExit) {
+test('should not partially match route', function(t) {
var router = bogart.router(function(get) {
get('/partial', function(req) {
return {
@@ -124,24 +107,20 @@ exports['test should not partially match route'] = function(beforeExit) {
}
})
})
- , req = rootRequest()
- , response;
+ , req = rootRequest();
req.pathInfo = '/partial/path';
when(router(req), function(resp) {
- response = resp;
+ t.equal(resp.status, 404, 'Status should be 404');
});
- beforeExit(function() {
- assert.equal(404, response.status);
- })
-};
+ t.plan(1);
+});
-exports['test should not partially match route from beginning'] = function(beforeExit) {
+test('should not partially match route from beginning', function(t) {
var req = rootRequest()
- , router
- , response;
+ , router;
router = bogart.router(function(get) {
get('/:foo', function(req) {
@@ -155,18 +134,15 @@ exports['test should not partially match route from beginning'] = function(befor
req.pathInfo = '/hello/world';
when(router(req), function(resp) {
- response = resp;
+ t.equal(resp.status, 404, 'Status should be 404');
});
- beforeExit(function() {
- assert.equal(404, response.status);
- });
-};
+ t.plan(1);
+});
-exports['test should match route with querystring'] = function(beforeExit) {
+test('should match route with querystring', function(t) {
var req = rootRequest()
- , router
- , response;
+ , router;
router = bogart.router(function(get) {
get('/home', function(req) {
@@ -180,19 +156,19 @@ exports['test should match route with querystring'] = function(beforeExit) {
req.pathInfo = '/home';
req.queryString = "hello=world";
- when(router(req), function(resp) { response = resp; });
-
- beforeExit(function() {
- assert.isNotNull(response);
- assert.equal(200, response.status);
+ when(router(req), function(resp) {
+ t.equal(resp.status, 200, 'Status should be 200');
+ }, function(err) {
+ t.fail('Promise should not have been rejected');
});
-};
-exports['test regex route'] = function(beforeExit) {
+ t.plan(1);
+});
+
+test('regex route', function(t) {
var router
, req = rootRequest()
- , splat
- , response;
+ , splat;
req.pathInfo = '/hello/cruel/world';
@@ -204,53 +180,46 @@ exports['test regex route'] = function(beforeExit) {
});
when(router(req), function(resp) {
- response = resp;
+ t.equal(resp.status, 200, 'Status should be 200');
+ t.ok(splat, 'Should have set \'splat\'');
+ t.equal(splat[0], 'cruel', 'Should have correct value for splat[0]');
+ t.equal(splat[1], 'world', 'Should have correct value for splat[1]');
+ }, function() {
+ t.fail('Promise should not have been rejected');
});
- beforeExit(function() {
- assert.isNotNull(response);
- assert.equal(200, response.status);
- assert.ok(splat, "Should have set 'splat'");
- assert.equal(splat[0], 'cruel');
- assert.equal(splat[1], 'world');
- });
-};
+ t.plan(4);
+});
-exports['test handles encoded slashes'] = function(beforeExit) {
+test('handles encoded slashes', function(t) {
var router = bogart.router()
, called = false;
router.get('/:foo', function() {
- called = true;
+ t.ok(true, 'Should call route handler');
});
router(mockRequest('/foo%2Fbar'));
- beforeExit(function() {
- assert.ok(called);
- });
-};
+ t.plan(1);
+});
-exports['test matches a dot (".") as part of a named param'] = function(beforeExit) {
+test('matches a dot (".") as part of a named param', function(t) {
var router
, foo = null;
router = bogart.router();
router.get('/:foo/:bar', function(req) {
- foo = req.params.foo;
+ t.equal(req.params.foo, 'user@example.com', 'Named parameter should be matched correctly');
});
router(mockRequest('/user@example.com/name'));
- beforeExit(function() {
- assert.isNotNull(foo, 'Named parameter should not be null');
- assert.equal('user@example.com', foo);
- });
-};
+ t.plan(1);
+});
-exports['test matches empty `pathInfo` to "/" if no route is defined for ""'] = function(beforeExit) {
- var router
- , response;
+test('matches empty `pathInfo` to "/" if no route is defined for ""', function(t) {
+ var router;
router = bogart.router();
router.get('/', function(req) {
@@ -258,19 +227,15 @@ exports['test matches empty `pathInfo` to "/" if no route is defined for ""'] =
});
when(router(mockRequest('')), function(resp) {
- response = resp;
+ t.equal(resp.body.join(''), 'success', 'Should have matched "/" route');
});
- beforeExit(function() {
- assert.equal('success', response.body);
- });
-};
+ t.plan(1);
+});
+
+test('matches empty `pathInfo` to "" if a route is defined for ""', function(t) {
+ var router = bogart.router();
-exports['test matches empty `pathInfo` to "" if a route is defined for ""'] = function(beforeExit) {
- var router
- , response;
-
- router = bogart.router();
router.get('', function(req) {
return bogart.text('right');
});
@@ -280,103 +245,87 @@ exports['test matches empty `pathInfo` to "" if a route is defined for ""'] = fu
});
when(router(mockRequest('')), function(resp) {
- response = resp;
+ t.equal(resp.body.join(''), 'right');
});
- beforeExit(function() {
- assert.equal('right', response.body);
- });
-};
+ t.plan(1);
+});
-exports['test matches paths that include encoded spaces'] = function(beforeExit) {
- var router = bogart.router()
- , response;
+test('matches paths that include encoded spaces', function(t) {
+ var router = bogart.router();
router.get('/path with spaces', function(req) {
return bogart.text('spaces are cool');
});
when(router(mockRequest('/path%20with%20spaces')), function(resp) {
- response = resp;
+ t.equal(resp.body[0], 'spaces are cool');
+ }, function() {
+ t.fail('Promise should not have been rejected');
});
- beforeExit(function() {
- assert.ok(response);
- assert.equal('spaces are cool', response.body[0]);
- });
-};
+ t.plan(1);
+});
-exports['test matches dot (".") literally in paths'] = function(beforeExit) {
- var router = simpleRouter('/foo.bar')
- , response;
+test('matches dot (".") literally in paths', function(t) {
+ var router = simpleRouter('/foo.bar');
when(router(mockRequest('/foo.bar')), function(resp) {
- response = resp;
+ t.ok(resp);
+ }, function() {
+ t.fail('Promise should not have been rejected');
});
- beforeExit(function() {
- assert.ok(response);
- });
-};
+ t.plan(1);
+});
-exports['test supports splat ("*")'] = function(beforeExit) {
- var router = bogart.router()
- , response;
+test('supports splat ("*")', function(t) {
+ var router = bogart.router();
router.get('/foo/*', function(req) {
return bogart.text('splatted '+req.params.splat[0]);
});
when(router(mockRequest('/foo/hello/there')), function(resp) {
- response = resp;
+ t.equal(resp.body.join(''), 'splatted hello/there');
});
- beforeExit(function() {
- assert.ok(response);
- assert.equal('splatted hello/there', response.body.join(''));
- });
-};
+ t.plan(1);
+});
-exports['test supports multiple splat params'] = function(beforeExit) {
- var router = bogart.router()
- , response;
+test('supports multiple splat params', function(t) {
+ var router = bogart.router();
router.get('/download/*/*', function(req) {
return bogart.text(req.params.splat[0]+'/'+req.params.splat[1]);
});
when(router(mockRequest('/download/images/ninja-cat.jpg')), function(resp) {
- response = resp;
+ t.equal(resp.body.join(''), 'images/ninja-cat.jpg');
});
- beforeExit(function() {
- assert.ok(response);
- assert.equal('images/ninja-cat.jpg', response.body.join(''));
- });
-};
+ t.plan(1);
+});
-exports['test supports mixing named and splat parameters'] = function(beforeExit) {
- var router = bogart.router()
- , response;
+test('supports mixing named and splat parameters', function(t) {
+ var router = bogart.router();
router.get('/:foo/*', function(req) {
return bogart.text(req.params.foo+' '+req.params.splat[0]);
});
when(router(mockRequest('/foo/bar/baz')), function(resp) {
- response = resp;
+ t.equal(resp.body.join(''), 'foo bar/baz');
+ }, function() {
+ t.fail('Promise should not have been rejected');
});
- beforeExit(function() {
- assert.ok(response);
- assert.equal('foo bar/baz', response.body.join(''));
- });
-};
+ t.plan(1);
+});
-exports['test calls next app when handler returns `undefined`'] = function(beforeExit) {
+test('calls next app when handler returns `undefined`', function(t) {
var str = 'Hello from next app!'
- , router
- , response;
+ , router;
router = bogart.router(null, function(req) {
return bogart.text(str);
@@ -385,11 +334,29 @@ exports['test calls next app when handler returns `undefined`'] = function(befor
router.get('/', function(req) {});
when(router(mockRequest('/')), function(resp) {
- response = resp;
+ t.equal(resp.body[0], str);
+ }, function() {
+ t.fail('Promise should not have been rejected');
});
- beforeExit(function() {
- assert.ok(response);
- assert.equal(str, response.body[0]);
+ t.plan(1);
+});
+
+test('middleware in routes', function(t) {
+ var router = bogart.router();
+
+ router.get('/', function(req, next) {
+ req.hello = 'world';
+ return next(req);
+ }, function(req) {
+ return bogart.text(req.hello);
});
-};
+
+ router(mockRequest('/')).then(function(resp) {
+ t.equal(resp.body[0], 'world');
+ }, function() {
+ t.fail('Promise should not have been rejected');
+ });
+
+ t.plan(1);
+});
45 test/server.test.js
View
@@ -1,45 +0,0 @@
-var bogart = require('../lib/bogart')
- , q = require('promised-io/lib/promise')
- , when = q.when
- , assert = require('assert')
- , jsgi = require('jsgi')
- , rootRequest = {
- headers: {},
- pathInfo: '/',
- method: 'GET',
- jsgi: { version: [0, 3] },
- env: {}
- };
-
-exports["test should have middleware"] = function(beforeExit) {
- var response = null
- , server = new bogart.build(function() {
- this.use(function(nextApp) {
- return function(req) {
- return when(nextApp(req), function(resp) {
- resp.headers["custom-header"] = "xyz";
- return resp;
- });
- }
- });
-
- this.use(bogart.router, function(get) {
- get("/", function() {
- return {
- status: 200,
- headers: {},
- body: []
- }
- });
- });
- });
-
- when(server(rootRequest), function(resp) {
- response = resp;
- });
-
- beforeExit(function() {
- assert.ok(response.headers);
- assert.equal("xyz", response.headers["custom-header"]);
- });
-};
88 test/stream.test.js
View
@@ -1,43 +1,68 @@
var bogart = require('../lib/bogart')
+ , test = require('tap').test
+ , plan = require('tap').plan
, Q = require('promised-io/lib/promise')
- , assert = require('assert')
, fs = require('fs')
, ForEachStream = require('../lib/forEachStream')
- , deflate = require('deflate');
+ , zlib = require('zlib');
-exports["test foreachstream pipe to file stream"] = function(beforeExit) {
+test("test foreachstream pipe to file stream", function(t) {
var source = ['Hello ','World']
, stream = new ForEachStream(source)
, filename = 'hello-world.txt';
stream.pipe(fs.createWriteStream(filename));
- beforeExit(function() {
+ stream.on('end', function() {
var stat = fs.statSync(filename);
- assert.isNotNull(stat);
- assert.ok(stat.isFile(), 'Should be a file');
-
- assert.equal('Hello World', fs.readFileSync(filename, 'utf8'));
+ t.ok(stat);
+ t.ok(stat.isFile(), 'Should be a file');
+ t.equal('Hello World', fs.readFileSync(filename, 'utf8'));
+ t.end();
});
-};
+});
-exports["test foreachstream pipe to deflateStream"] = function(beforeExit) {
- var source = ['Hello',' ','World'].map(function(x) { return new Buffer(x); })
- , stream = deflate.createDeflateStream(new ForEachStream(source))
- , filename = 'hello-world.dat';
+test("test foreachstream pipe to deflateStream", function(t) {
+ var source = [ 'Hello', ' ', 'World' ]
+ , srcStream = new ForEachStream(source)
+ , stream = zlib.createDeflateRaw()
+ , filename = 'hello-world.dat';
- stream.pipe(fs.createWriteStream(filename));
+ srcStream.pipe(stream).pipe(fs.createWriteStream(filename));
- beforeExit(function() {
+ stream.on('end', function() {
var stat = fs.statSync(filename);
- assert.isNotNull(stat);
- assert.ok(stat.isFile(), 'Should be a file');
+ t.ok(stat);
+ t.ok(stat.isFile(), 'Should be a file');
+
+ process.nextTick(function() {
+ var readStream = fs.createReadStream(filename)
+ , inflateStream = zlib.createInflateRaw()
+ , buf = new Buffer(0);
+
+ readStream.pipe(inflateStream);
+
+ inflateStream.on('data', function(data) {
+ var oldBuf = buf;
+
+ buf = new Buffer(oldBuf.length + data.length);
+ oldBuf.copy(buf, 0, 0);
+ data.copy(buf, oldBuf.length, 0);
+ });
+
+ inflateStream.on('error', function(err) {
+ t.fail(err);
+ });
- assert.equal('Hello World', deflate.inflate(fs.readFileSync(filename)).toString('utf8'));
+ inflateStream.on('end', function() {
+ t.equal(buf.toString('utf-8'), 'Hello World');
+ t.end();
+ });
+ });
});
-};
+});
exports["test pump ForEachStrean to file stream"] = function(beforeExit) {
var seed = ['Hello',' ','World'].map(function(x) { return new Buffer(x); })
@@ -47,25 +72,30 @@ exports["test pump ForEachStrean to file stream"] = function(beforeExit) {
bogart.pump(src, dest);
- beforeExit(function() {
+ src.on('end', function() {
var stat = fs.statSync(filename);
- assert.ok(stat.isFile());
- assert.equal('Hello World', fs.readFileSync(filename, 'utf-8'));
+ t.ok(stat.isFile());
+ t.equal('Hello World', fs.readFileSync(filename, 'utf-8'));
+ t.end();
});
};
exports["test pump forEachable to file stream"] = function(beforeExit) {
var src = ['Hello',' ','World']
, filename = 'forEachableToFileStream.txt'
- , dest = fs.createWriteStream(filename);
-
- bogart.pump(src, dest);
+ , dest = fs.createWriteStream(filename)
+ , destEnd = dest.end;
+
+ dest.end = function() {
+ destEnd.apply(dest, Array.prototype.slice.call(arguments));
- beforeExit(function() {
var stat = fs.statSync(filename);
- assert.ok(stat.isFile());
- assert.equal('Hello World', fs.readFileSync(filename, 'utf-8'));
- });
+ t.ok(stat.isFile());
+ t.equal('Hello World', fs.readFileSync(filename, 'utf-8'));
+ t.end();
+ };
+
+ bogart.pump(src, dest);
};
84 test/util.test.js
View
@@ -1,38 +1,40 @@
-var bogart = require('../lib/bogart'),
- Q = require("promised-io/lib/promise"),
- assert = require('assert'),
- path = require('path'),
- security = require("../lib/security");
+var bogart = require('../lib/bogart')
+ , Q = require("promised-io/lib/promise")
+ , path = require('path')
+ , security = require("../lib/security")
+ , test = require('tap').test
+ , plan = require('tap').plan;
-exports["security"] = function(beforeExit) {
- var key = "667016c4-1a2e-11e1-8db4-836d74549718";
- var key2 = "THIS is a Secret -- key == C!@#$%^&*())_%3D%2F";
- var key3 = "0ce05d12-1a33-11e1-a436-0019e34411d1";
- var plain = "this is a very long string of text with random characters {}[[]\!@#$%^&*()_+!@#$%^&*()_+%3D%44%5Z,this is a very long string of text with random characters {}[[]\!@#$%^&*()_+!@#$%^&*()_+%3D%44%5Z,this is a very long string of text with random characters {}[[]\!@#$%^&*()_+!@#$%^&*()_+%3D%44%5Z,this is a very long string of text with random characters {}[[]\!@#$%^&*()_+!@#$%^&*()_+%3D%44%5Z";
+test("security", function(t) {
+ var key = "667016c4-1a2e-11e1-8db4-836d74549718";
+ var key2 = "THIS is a Secret -- key == C!@#$%^&*())_%3D%2F";
+ var key3 = "0ce05d12-1a33-11e1-a436-0019e34411d1";
+ var plain = "this is a very long string of text with random characters {}[[]\!@#$%^&*()_+!@#$%^&*()_+%3D%44%5Z,this is a very long string of text with random characters {}[[]\!@#$%^&*()_+!@#$%^&*()_+%3D%44%5Z,this is a very long string of text with random characters {}[[]\!@#$%^&*()_+!@#$%^&*()_+%3D%44%5Z,this is a very long string of text with random characters {}[[]\!@#$%^&*()_+!@#$%^&*()_+%3D%44%5Z";
- // test default key
- var enc1 = security.encrypt(plain);
- var dec1 = security.decrypt(enc1);
- assert.equal(dec1, plain);
+ // test default key
+ var enc1 = security.encrypt(plain);
+ var dec1 = security.decrypt(enc1);
+ t.equal(dec1, plain);
- // test provided key 1
- var enc2 = security.encrypt(plain, key2);
- var dec2 = security.decrypt(enc2, key2);
- assert.equal(dec2, plain);
+ // test provided key 1
+ var enc2 = security.encrypt(plain, key2);
+ var dec2 = security.decrypt(enc2, key2);
+ t.equal(dec2, plain);
- // test uuid key
- var enc3 = security.encrypt(plain, key3);
- var dec3 = security.decrypt(enc3, key3);
- assert.equal(dec3, plain);
+ // test uuid key
+ var enc3 = security.encrypt(plain, key3);
+ var dec3 = security.decrypt(enc3, key3);
+ t.equal(dec3, plain);
- // test uri encoding, just to be safe
- var enc4 = encodeURIComponent(security.encrypt(plain, key2));
- var dec4 = security.decrypt(decodeURIComponent(enc4), key2);
- assert.equal(dec4, plain);
-};
+ // test uri encoding, just to be safe
+ var enc4 = encodeURIComponent(security.encrypt(plain, key2));
+ var dec4 = security.decrypt(decodeURIComponent(enc4), key2);
+ t.equal(dec4, plain);
+ t.end();
+});
-exports['bogart.promisify handles success'] = function(beforeExit) {
- var p, asyncFn, actualVal, expectedVal = 1;
+test('bogart.promisify handles success', function(t) {
+ var p, asyncFn, expectedVal = 1;
asyncFn = function(cb) {
process.nextTick(function() {
@@ -42,15 +44,14 @@ exports['bogart.promisify handles success'] = function(beforeExit) {
p = bogart.promisify(asyncFn)();
p.then(function(val) {
- actualVal = val;
+ t.equal(val, expectedVal);
+ t.end();
+ }, function(err) {
+ t.fail(err);
});
+});
- beforeExit(function() {
- assert.equal(expectedVal, actualVal);
- });
-};
-
-exports['bogart.promisify handles rejection'] = function(beforeExit) {
+test('bogart.promisify handles rejection', function(t) {
var p, asyncFn, expected, actual;
asyncFn = function(cb) {
@@ -60,11 +61,8 @@ exports['bogart.promisify handles rejection'] = function(beforeExit) {
};
p = bogart.promisify(asyncFn)();
- p.then(bogart.noop, function(err) {
- actual = err;
- });
-
- beforeExit(function() {
- assert.equal(expected, actual);
+ p.then(null, function(err) {
+ t.equal(err, expected);
+ t.end();
});
-};
+});
35 test/view.test.js
View
@@ -2,32 +2,29 @@ var bogart = require('../lib/bogart')
, view = require('../lib/view')
, jsgi = require('jsgi')
, when = require('promised-io/lib/promise').when
- , assert = require('assert')
, path = require('path')
+ , test = require('tap').test
+ , plan = require('tap').plan
, fixturesPath = path.join(__dirname, 'fixtures');
-exports['test render mustache'] = function(beforeExit) {
- var viewEngine = bogart.viewEngine('mustache', fixturesPath)
- , renderedText;
+test('test render mustache', function(t) {
+ var viewEngine = bogart.viewEngine('mustache', fixturesPath);
when(viewEngine.render('index.mustache', { layout: false }), function(str) {
- renderedText = str;
+ t.equal(str, '<h1>Hello World from Mustache</h1>');;
+ t.end();
+ }, function(err) {
+ t.fail(err);
});
+});
- beforeExit(function() {
- assert.equal(renderedText, '<h1>Hello World from Mustache</h1>');
- });
-};
-
-exports['test render mustache with partials'] = function(beforeExit) {
- var viewEngine = bogart.viewEngine('mustache', fixturesPath)
- , renderedText;
+test('test render mustache with partials', function(t) {
+ var viewEngine = bogart.viewEngine('mustache', fixturesPath);
when(viewEngine.render('partial-test.mustache', { layout: false, locals: { greeting: {} }, partials: { greeting: 'greeting.mustache' } }), function(str) {
- renderedText = str;
- });
-
- beforeExit(function() {
- assert.equal(renderedText, '<h1>Hello World from Mustache</h1><p>With Partial</p>');
+ t.equal(renderedText, '<h1>Hello World from Mustache</h1>');
+ t.end();
+ }, function(err) {
+ t.fail(err);
});
-};
+});
Please sign in to comment.
Something went wrong with that request. Please try again.