switched out assertion library with should.js... I really should have written my own baby util library since that was the third time I've done that...

This commit is contained in:
Spencer Alger
2013-12-23 15:33:53 -07:00
parent 3d0b2fde4e
commit 2b3734a081
32 changed files with 828 additions and 987 deletions

View File

@ -2,9 +2,6 @@ var unitTests = ['test/unit/test_*.js'];
var integrationTests = ['test/integration/yaml_suite/index.js']; var integrationTests = ['test/integration/yaml_suite/index.js'];
module.exports = { module.exports = {
options: {
require: ['should']
},
unit: { unit: {
src: unitTests src: unitTests
}, },

View File

@ -17,7 +17,6 @@
"mocha": "~1.14.0", "mocha": "~1.14.0",
"async": "~0.2.9", "async": "~0.2.9",
"moment": "~2.4.0", "moment": "~2.4.0",
"should": "~2.1.0",
"js-yaml": "~2.1.3", "js-yaml": "~2.1.3",
"optimist": "~0.6.0", "optimist": "~0.6.0",
"browserify": "~2.35.1", "browserify": "~2.35.1",
@ -45,7 +44,8 @@
"grunt-prompt": "~0.1.2", "grunt-prompt": "~0.1.2",
"grunt-mocha-cov": "~0.1.1", "grunt-mocha-cov": "~0.1.1",
"grunt-open": "~0.2.2", "grunt-open": "~0.2.2",
"glob": "~3.2.7" "glob": "~3.2.7",
"expect.js": "~0.2.0"
}, },
"license": "Apache 2.0", "license": "Apache 2.0",
"dependencies": { "dependencies": {
@ -65,11 +65,25 @@
], ],
"harness": "mocha", "harness": "mocha",
"browsers": { "browsers": {
"ie": [ 9, 10, 11 ], "ie": [
"firefox": [ 24, "nightly" ], 9,
"chrome": [ 30, "canary" ], 10,
"safari": [ 5.1 ], 11
"opera": [ 12 ] ],
"firefox": [
24,
"nightly"
],
"chrome": [
30,
"canary"
],
"safari": [
5.1
],
"opera": [
12
]
} }
}, },
"scripts": { "scripts": {

View File

@ -75,7 +75,7 @@ if (argv['check-upstream']) {
if (argv.unit) { if (argv.unit) {
if (argv.server) { if (argv.server) {
commands.push(['./node_modules/.bin/mocha', 'test/unit/test_*.js', '--require should']); commands.push(['./node_modules/.bin/mocha', 'test/unit/test_*.js']);
} }
if (argv.browsers) { if (argv.browsers) {
commands.push(['./node_modules/.bin/testling', '.']); commands.push(['./node_modules/.bin/testling', '.']);
@ -88,7 +88,6 @@ if (argv.integration) {
'./node_modules/.bin/mocha', './node_modules/.bin/mocha',
'test/integration/yaml_suite/index.js', 'test/integration/yaml_suite/index.js',
// '-b', // '-b',
'--require', 'should',
'--host', argv.host, '--host', argv.host,
'--port', argv.port '--port', argv.port
].filter(Boolean)); ].filter(Boolean));

View File

@ -86,7 +86,7 @@ ConnectionPool.prototype.select = function (cb) {
this.selector(this._conns.alive, cb); this.selector(this._conns.alive, cb);
} else { } else {
try { try {
_.nextTick(cb, null, this.selector(this._conns.alive)); _.nextTick(cb, void 0, this.selector(this._conns.alive));
} catch (e) { } catch (e) {
cb(e); cb(e);
} }
@ -94,7 +94,7 @@ ConnectionPool.prototype.select = function (cb) {
} else if (this._timeouts.length) { } else if (this._timeouts.length) {
this._selectDeadConnection(cb); this._selectDeadConnection(cb);
} else { } else {
_.nextTick(cb, null); _.nextTick(cb, void 0);
} }
}; };
@ -210,7 +210,7 @@ ConnectionPool.prototype._selectDeadConnection = function (cb) {
process.nextTick(function next() { process.nextTick(function next() {
var timeout = orderedTimeouts.shift(); var timeout = orderedTimeouts.shift();
if (!timeout) { if (!timeout) {
cb(null); cb(void 0);
return; return;
} }
@ -225,11 +225,11 @@ ConnectionPool.prototype._selectDeadConnection = function (cb) {
log.warning('Unable to revive connection: ' + timeout.conn.id); log.warning('Unable to revive connection: ' + timeout.conn.id);
process.nextTick(next); process.nextTick(next);
} else { } else {
cb(null, timeout.conn); cb(void 0, timeout.conn);
} }
}); });
} else { } else {
cb(null, timeout.conn); cb(void 0, timeout.conn);
} }
}); });
}; };

View File

@ -284,7 +284,7 @@ Transport.prototype.request = function (params, cb) {
if (connection) { if (connection) {
sendReqWithConnection(null, connection); sendReqWithConnection(void 0, connection);
} else { } else {
self.connectionPool.select(sendReqWithConnection); self.connectionPool.select(sendReqWithConnection);
} }

View File

@ -8,7 +8,7 @@
module.exports = YamlDoc; module.exports = YamlDoc;
var _ = require('../../../src/lib/utils'); var _ = require('../../../src/lib/utils');
var should = require('should'); var expect = require('expect.js');
var clientManager = require('./client_manager'); var clientManager = require('./client_manager');
/** /**
@ -42,7 +42,7 @@ function getVersionFromES(done) {
if (err) { if (err) {
throw new Error('unable to get info about ES'); throw new Error('unable to get info about ES');
} }
should(resp.version.number).match(versionRE); expect(resp.version.number).to.match(versionRE);
ES_VERSION = versionToComparableString(versionRE.exec(resp.version.number)[1]); ES_VERSION = versionToComparableString(versionRE.exec(resp.version.number)[1]);
done(); done();
}); });
@ -77,7 +77,7 @@ function versionToComparableString(version) {
*/ */
function rangeMatchesCurrentVersion(rangeString, done) { function rangeMatchesCurrentVersion(rangeString, done) {
function doWork() { function doWork() {
should(rangeString).match(versionRangeRE); expect(rangeString).to.match(versionRangeRE);
var range = versionRangeRE.exec(rangeString); var range = versionRangeRE.exec(rangeString);
range = _.map(_.last(range, 2), versionToComparableString); range = _.map(_.last(range, 2), versionToComparableString);
@ -114,7 +114,7 @@ function YamlDoc(doc, file) {
var method = self['do_' + action.name]; var method = self['do_' + action.name];
// check that it's a function // check that it's a function
should(method).have.type('function'); expect(method).to.have.type('function');
if (_.isPlainObject(action.args)) { if (_.isPlainObject(action.args)) {
action.name += ' ' + _.keys(action.args).join(', '); action.name += ' ' + _.keys(action.args).join(', ');
@ -317,7 +317,7 @@ YamlDoc.prototype = {
params[paramName] = (typeof val === 'string' && val[0] === '$') ? this.get(val) : val; params[paramName] = (typeof val === 'string' && val[0] === '$') ? this.get(val) : val;
}, {}, this); }, {}, this);
should(clientAction || clientActionName).have.type('function'); expect(clientAction || clientActionName).to.be.a('function');
if (typeof clientAction === 'function') { if (typeof clientAction === 'function') {
if (_.isNumeric(catcher)) { if (_.isNumeric(catcher)) {
@ -332,11 +332,11 @@ YamlDoc.prototype = {
if (catcher) { if (catcher) {
if (catcher instanceof RegExp) { if (catcher instanceof RegExp) {
// error message should match the regexp // error message should match the regexp
should(error.message).match(catcher); expect(error.message).to.match(catcher);
error = null; error = null;
} else if (typeof catcher === 'function') { } else if (typeof catcher === 'function') {
// error should be an instance of // error should be an instance of
should(error).be.an.instanceOf(catcher); expect(error).to.be.a(catcher);
error = null; error = null;
} else { } else {
return done(new Error('Invalid catcher ' + catcher)); return done(new Error('Invalid catcher ' + catcher));
@ -380,7 +380,7 @@ YamlDoc.prototype = {
* @return {undefined} * @return {undefined}
*/ */
do_is_true: function (path) { do_is_true: function (path) {
should(Boolean(this.get(path))).equal(true, 'path: ' + path); expect(Boolean(this.get(path))).to.be(true, 'path: ' + path);
}, },
/** /**
@ -391,7 +391,7 @@ YamlDoc.prototype = {
* @return {undefined} * @return {undefined}
*/ */
do_is_false: function (path) { do_is_false: function (path) {
should(Boolean(this.get(path))).equal(false, 'path: ' + path); expect(Boolean(this.get(path))).to.be(false, 'path: ' + path);
}, },
/** /**
@ -405,7 +405,7 @@ YamlDoc.prototype = {
if (val[0] === '$') { if (val[0] === '$') {
val = this.get(val); val = this.get(val);
} }
should(this.get(path)).eql(val, 'path: ' + path); expect(this.get(path)).to.eql(val, 'path: ' + path);
}, this); }, this);
}, },
@ -417,7 +417,7 @@ YamlDoc.prototype = {
*/ */
do_lt: function (args) { do_lt: function (args) {
_.forOwn(args, function (num, path) { _.forOwn(args, function (num, path) {
should(this.get(path)).be.below(num, 'path: ' + path); expect(this.get(path)).to.be.below(num, 'path: ' + path);
}, this); }, this);
}, },
@ -429,7 +429,7 @@ YamlDoc.prototype = {
*/ */
do_gt: function (args) { do_gt: function (args) {
_.forOwn(args, function (num, path) { _.forOwn(args, function (num, path) {
should(this.get(path)).be.above(num, 'path: ' + path); expect(this.get(path)).to.be.above(num, 'path: ' + path);
}, this); }, this);
}, },
@ -442,7 +442,7 @@ YamlDoc.prototype = {
*/ */
do_length: function (args) { do_length: function (args) {
_.forOwn(args, function (len, path) { _.forOwn(args, function (len, path) {
should(_.size(this.get(path))).eql(len, 'path: ' + path); expect(_.size(this.get(path))).to.eql(len, 'path: ' + path);
}, this); }, this);
} }
}; };

View File

@ -1,14 +1,14 @@
/* jshint browser:true */ /* jshint browser:true */
/* global angular */ /* global angular */
var should = require('should'); var expect = require('expect.js');
var Client = require('../../src/lib/client'); var Client = require('../../src/lib/client');
describe('Angular esFactory', function () { describe('Angular esFactory', function () {
before(function (done) { before(function (done) {
// inject angular // inject angular
var scr = document.createElement('script'); var scr = document.createElement('script');
scr.src = '/test/unit/angular-1.2.5.js'; scr.src = '//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.5/angular.js';
scr.async = true; scr.async = true;
scr.onload = function () { scr.onload = function () {
require('../../src/elasticsearch.angular.js'); require('../../src/elasticsearch.angular.js');
@ -37,7 +37,7 @@ describe('Angular esFactory', function () {
it('is available in the elasticsearch module', function (done) { it('is available in the elasticsearch module', function (done) {
directive(function (esFactory) { directive(function (esFactory) {
return function () { return function () {
esFactory.should.have.type('function'); expect(esFactory).to.be.a('function');
done(); done();
}; };
}); });
@ -45,8 +45,8 @@ describe('Angular esFactory', function () {
it('has Transport and ConnectionPool properties', function (done) { it('has Transport and ConnectionPool properties', function (done) {
directive(function (esFactory) { directive(function (esFactory) {
return function () { return function () {
esFactory.should.have.property('Transport'); expect(esFactory).to.have.property('Transport');
esFactory.should.have.property('ConnectionPool'); expect(esFactory).to.have.property('ConnectionPool');
done(); done();
}; };
}); });
@ -54,7 +54,7 @@ describe('Angular esFactory', function () {
it('returns a new client when it is called', function (done) { it('returns a new client when it is called', function (done) {
directive(function (esFactory) { directive(function (esFactory) {
return function () { return function () {
esFactory({ log: null }).should.be.an.instanceOf(Client); expect(esFactory({ log: null })).to.be.a(Client);
done(); done();
}; };
}); });

View File

@ -1,62 +0,0 @@
/* jshint browser:true */
/* global angular */
var should = require('should');
var Client = require('../../src/lib/client');
describe('Angular esFactory', function () {
before(function (done) {
// inject angular
var scr = document.createElement('script');
scr.src = '/test/unit/angular-1.2.5.js';
scr.async = true;
scr.onload = function () {
require('../../src/elasticsearch.angular.js');
done();
};
scr.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(scr);
});
var uuid = (function () { var i = 0; return function () { return ++i; }; }());
function directive(makeDirective) {
var root = document.createElement('div');
var id = uuid();
root.setAttribute('test-directive-' + id, 'test-directive');
document.body.appendChild(root);
after(function () {
document.body.removeChild(root);
root = null;
});
angular.module('mod' + id, ['elasticsearch']).directive('testDirective' + id, makeDirective);
angular.bootstrap(root, ['mod' + id]);
}
it('is available in the elasticsearch module', function (done) {
directive(function (esFactory) {
return function () {
esFactory.should.have.type('function');
done();
};
});
});
it('has Transport and ConnectionPool properties', function (done) {
directive(function (esFactory) {
return function () {
esFactory.should.have.property('Transport');
esFactory.should.have.property('ConnectionPool');
done();
};
});
});
it('returns a new client when it is called', function (done) {
directive(function (esFactory) {
return function () {
esFactory({ log: null }).should.be.an.instanceOf(Client);
done();
};
});
});
});

View File

@ -1,4 +1,5 @@
module.exports = function (makeLogger) { module.exports = function (makeLogger) {
var expect = require('expect.js');
var stub = require('./auto_release_stub').make(); var stub = require('./auto_release_stub').make();
var fs = require('fs'); var fs = require('fs');
var once = require('events').EventEmitter.prototype.once; var once = require('events').EventEmitter.prototype.once;
@ -34,8 +35,8 @@ module.exports = function (makeLogger) {
exitHandler.call(process); exitHandler.call(process);
// the first line is sent immediately to _write and there is nothing we can do about that // the first line is sent immediately to _write and there is nothing we can do about that
flushedOutput.should.match(new RegExp(line)); expect(flushedOutput).to.match(new RegExp(line));
flushedOutput.match(new RegExp(line, 'g')).length.should.eql(9); expect(flushedOutput.match(new RegExp(line, 'g'))).to.have.property('length', 9);
}); });
} else { } else {
it('does not fall apart with non streams2 streams', function () { it('does not fall apart with non streams2 streams', function () {
@ -49,10 +50,10 @@ module.exports = function (makeLogger) {
var logger = makeLogger(); var logger = makeLogger();
(function () { expect(function () {
// call the event handler // call the event handler
exitHandler.call(process); exitHandler.call(process);
}).should.not.throw(); }).to.not.throw();
}); });
} }
}); });

View File

@ -1,3 +1,4 @@
var expect = require('expect.js');
var Log = require('../../src/lib/log'); var Log = require('../../src/lib/log');
var LoggerAbstract = require('../../src/lib/logger'); var LoggerAbstract = require('../../src/lib/logger');
var TracerLogger = require('../../src/lib/loggers/tracer'); var TracerLogger = require('../../src/lib/loggers/tracer');
@ -19,12 +20,12 @@ module.exports = function (makeLogger) {
parent.close(); parent.close();
logger = makeLogger(parent); logger = makeLogger(parent);
logger.setupListeners.callCount.should.eql(1); expect(logger.setupListeners).to.have.property('callCount', 1);
}); });
it('listens for the loggers\' "closing" event', function () { it('listens for the loggers\' "closing" event', function () {
var logger = makeLogger(parent); var logger = makeLogger(parent);
parent.listenerCount('closing').should.eql(1); expect(parent.listenerCount('closing')).to.eql(1);
}); });
}); });
@ -33,56 +34,56 @@ module.exports = function (makeLogger) {
var logger = makeLogger(); var logger = makeLogger();
stub(logger, 'cleanUpListeners'); stub(logger, 'cleanUpListeners');
logger.setupListeners([]); logger.setupListeners([]);
logger.cleanUpListeners.callCount.should.eql(1); expect(logger.cleanUpListeners).to.have.property('callCount', 1);
}); });
it('listens to just error when log is explicitly error', function () { it('listens to just error when log is explicitly error', function () {
var logger = makeLogger(parent, 'error'); var logger = makeLogger(parent, 'error');
parent.listenerCount('error').should.eql(1); expect(parent.listenerCount('error')).to.eql(1);
parent.listenerCount('warning').should.eql(0); expect(parent.listenerCount('warning')).to.eql(0);
parent.listenerCount('info').should.eql(0); expect(parent.listenerCount('info')).to.eql(0);
parent.listenerCount('debug').should.eql(0); expect(parent.listenerCount('debug')).to.eql(0);
parent.listenerCount('trace').should.eql(0); expect(parent.listenerCount('trace')).to.eql(0);
}); });
it('listens for all the events when level is "trace"', function () { it('listens for all the events when level is "trace"', function () {
var logger = makeLogger(parent, 'trace'); var logger = makeLogger(parent, 'trace');
parent.listenerCount('error').should.eql(1); expect(parent.listenerCount('error')).to.eql(1);
parent.listenerCount('warning').should.eql(1); expect(parent.listenerCount('warning')).to.eql(1);
parent.listenerCount('info').should.eql(1); expect(parent.listenerCount('info')).to.eql(1);
parent.listenerCount('debug').should.eql(1); expect(parent.listenerCount('debug')).to.eql(1);
parent.listenerCount('trace').should.eql(1); expect(parent.listenerCount('trace')).to.eql(1);
}); });
it('listens for specific events when level is an array', function () { it('listens for specific events when level is an array', function () {
var logger = makeLogger(parent, ['error', 'trace']); var logger = makeLogger(parent, ['error', 'trace']);
parent.listenerCount('error').should.eql(1); expect(parent.listenerCount('error')).to.eql(1);
parent.listenerCount('warning').should.eql(0); expect(parent.listenerCount('warning')).to.eql(0);
parent.listenerCount('info').should.eql(0); expect(parent.listenerCount('info')).to.eql(0);
parent.listenerCount('debug').should.eql(0); expect(parent.listenerCount('debug')).to.eql(0);
parent.listenerCount('trace').should.eql(1); expect(parent.listenerCount('trace')).to.eql(1);
}); });
it('sets the logLevel property to the new levels', function () { it('sets the logLevel property to the new levels', function () {
var logger = makeLogger(); var logger = makeLogger();
var levels = ['error']; var levels = ['error'];
logger.setupListeners(levels); logger.setupListeners(levels);
logger.listeningLevels.should.eql(levels).and.not.be.exactly(levels); expect(logger.listeningLevels).to.eql(levels).and.not.be(levels);
levels = ['warning', 'trace']; levels = ['warning', 'trace'];
logger.setupListeners(levels); logger.setupListeners(levels);
logger.listeningLevels.should.eql(levels).and.not.be.exactly(levels); expect(logger.listeningLevels).to.eql(levels).and.not.be(levels);
levels = ['debug', 'debug']; levels = ['debug', 'debug'];
logger.setupListeners(levels); logger.setupListeners(levels);
logger.listeningLevels.should.eql(levels).and.not.be.exactly(levels); expect(logger.listeningLevels).to.eql(levels).and.not.be(levels);
}); });
it('rejects listening levels it can not listen to', function () { it('rejects listening levels it can not listen to', function () {
var logger = makeLogger(); var logger = makeLogger();
(function () { expect(function () {
logger.setupListeners(['scream']); logger.setupListeners(['scream']);
}).should.throw(/unable to listen/i); }).to.throwError(/unable to listen/i);
}); });
it('emits events because something is listening', function () { it('emits events because something is listening', function () {
@ -90,19 +91,19 @@ module.exports = function (makeLogger) {
stub(parent, 'emit'); stub(parent, 'emit');
parent.error(new Error('error message')); parent.error(new Error('error message'));
parent.emit.lastCall.args[0].should.eql('error'); expect(parent.emit.lastCall.args[0]).to.eql('error');
parent.warning('warning'); parent.warning('warning');
parent.emit.lastCall.args[0].should.eql('warning'); expect(parent.emit.lastCall.args[0]).to.eql('warning');
parent.info('info'); parent.info('info');
parent.emit.lastCall.args[0].should.eql('info'); expect(parent.emit.lastCall.args[0]).to.eql('info');
parent.debug('debug'); parent.debug('debug');
parent.emit.lastCall.args[0].should.eql('debug'); expect(parent.emit.lastCall.args[0]).to.eql('debug');
parent.trace('GET', {}, '', '', 200); parent.trace('GET', {}, '', '', 200);
parent.emit.lastCall.args[0].should.eql('trace'); expect(parent.emit.lastCall.args[0]).to.eql('trace');
}); });
}); });
@ -110,7 +111,7 @@ module.exports = function (makeLogger) {
it('returns in the right format', function () { it('returns in the right format', function () {
stub.autoRelease(sinon.useFakeTimers(now.getTime())); stub.autoRelease(sinon.useFakeTimers(now.getTime()));
var logger = makeLogger(); var logger = makeLogger();
logger.timestamp().should.eql('2013-03-01T00:00:00Z'); expect(logger.timestamp()).to.eql('2013-03-01T00:00:00Z');
}); });
}); });
@ -118,7 +119,7 @@ module.exports = function (makeLogger) {
it('returns a single string with the message indented', function () { it('returns a single string with the message indented', function () {
stub.autoRelease(sinon.useFakeTimers(now.getTime())); stub.autoRelease(sinon.useFakeTimers(now.getTime()));
var logger = makeLogger(); var logger = makeLogger();
logger.format('LABEL', 'MSG').should.eql( expect(logger.format('LABEL', 'MSG')).to.eql(
'LABEL: 2013-03-01T00:00:00Z\n' + 'LABEL: 2013-03-01T00:00:00Z\n' +
' MSG\n' + ' MSG\n' +
'\n' '\n'
@ -128,7 +129,7 @@ module.exports = function (makeLogger) {
it('properly indents multi-line messages', function () { it('properly indents multi-line messages', function () {
stub.autoRelease(sinon.useFakeTimers(now.getTime())); stub.autoRelease(sinon.useFakeTimers(now.getTime()));
var logger = makeLogger(); var logger = makeLogger();
logger.format('LABEL', 'MSG\nwith\nseveral lines').should.eql( expect(logger.format('LABEL', 'MSG\nwith\nseveral lines')).to.eql(
'LABEL: 2013-03-01T00:00:00Z\n' + 'LABEL: 2013-03-01T00:00:00Z\n' +
' MSG\n' + ' MSG\n' +
' with\n' + ' with\n' +
@ -142,21 +143,21 @@ module.exports = function (makeLogger) {
it('uses the Error name when it is not just "Error"', function () { it('uses the Error name when it is not just "Error"', function () {
var logger = makeLogger(); var logger = makeLogger();
stub(logger, 'write', function (label, msg) { stub(logger, 'write', function (label, msg) {
label.should.eql('TypeError'); expect(label).to.eql('TypeError');
}); });
logger.onError(new TypeError('Typerr')); logger.onError(new TypeError('Typerr'));
logger.write.callCount.should.eql(1); expect(logger.write.callCount).to.eql(1);
}); });
it('uses "ERROR" when the error name is "Error"', function () { it('uses "ERROR" when the error name is "Error"', function () {
var logger = makeLogger(); var logger = makeLogger();
stub(logger, 'write', function (label, msg) { stub(logger, 'write', function (label, msg) {
label.should.eql('ERROR'); expect(label).to.eql('ERROR');
}); });
logger.onError(new Error('thing')); logger.onError(new Error('thing'));
logger.write.callCount.should.eql(1); expect(logger.write.callCount).to.eql(1);
}); });
}); });
@ -164,20 +165,20 @@ module.exports = function (makeLogger) {
it('uses the "WARNING" label', function () { it('uses the "WARNING" label', function () {
var logger = makeLogger(); var logger = makeLogger();
stub(logger, 'write', function (label, msg) { stub(logger, 'write', function (label, msg) {
label.should.eql('WARNING'); expect(label).to.eql('WARNING');
}); });
logger.onWarning('message'); logger.onWarning('message');
logger.write.callCount.should.eql(1); expect(logger.write.callCount).to.eql(1);
}); });
it('echos the message', function () { it('echos the message', function () {
var logger = makeLogger(); var logger = makeLogger();
stub(logger, 'write', function (label, msg) { stub(logger, 'write', function (label, msg) {
msg.should.eql('message'); expect(msg).to.eql('message');
}); });
logger.onWarning('message'); logger.onWarning('message');
logger.write.callCount.should.eql(1); expect(logger.write.callCount).to.eql(1);
}); });
}); });
@ -185,20 +186,20 @@ module.exports = function (makeLogger) {
it('uses the "INFO" label', function () { it('uses the "INFO" label', function () {
var logger = makeLogger(); var logger = makeLogger();
stub(logger, 'write', function (label, msg) { stub(logger, 'write', function (label, msg) {
label.should.eql('INFO'); expect(label).to.eql('INFO');
}); });
logger.onInfo('message'); logger.onInfo('message');
logger.write.callCount.should.eql(1); expect(logger.write.callCount).to.eql(1);
}); });
it('echos the message', function () { it('echos the message', function () {
var logger = makeLogger(); var logger = makeLogger();
stub(logger, 'write', function (label, msg) { stub(logger, 'write', function (label, msg) {
msg.should.eql('message'); expect(msg).to.eql('message');
}); });
logger.onInfo('message'); logger.onInfo('message');
logger.write.callCount.should.eql(1); expect(logger.write.callCount).to.eql(1);
}); });
}); });
@ -206,20 +207,20 @@ module.exports = function (makeLogger) {
it('uses the "DEBUG" label', function () { it('uses the "DEBUG" label', function () {
var logger = makeLogger(); var logger = makeLogger();
stub(logger, 'write', function (label, msg) { stub(logger, 'write', function (label, msg) {
label.should.eql('DEBUG'); expect(label).to.eql('DEBUG');
}); });
logger.onDebug('message'); logger.onDebug('message');
logger.write.callCount.should.eql(1); expect(logger.write.callCount).to.eql(1);
}); });
it('echos the message', function () { it('echos the message', function () {
var logger = makeLogger(); var logger = makeLogger();
stub(logger, 'write', function (label, msg) { stub(logger, 'write', function (label, msg) {
msg.should.eql('message'); expect(msg).to.eql('message');
}); });
logger.onDebug('message'); logger.onDebug('message');
logger.write.callCount.should.eql(1); expect(logger.write.callCount).to.eql(1);
}); });
}); });
@ -227,10 +228,10 @@ module.exports = function (makeLogger) {
it('uses the "TRACE" label', function () { it('uses the "TRACE" label', function () {
var logger = makeLogger(); var logger = makeLogger();
stub(logger, 'write', function (label, msg) { stub(logger, 'write', function (label, msg) {
label.should.eql('TRACE'); expect(label).to.eql('TRACE');
}); });
logger.onTrace('message'); logger.onTrace('message');
logger.write.callCount.should.eql(1); expect(logger.write.callCount).to.eql(1);
}); });
it('joins the message and curl call with a newline', function () { it('joins the message and curl call with a newline', function () {
@ -239,11 +240,11 @@ module.exports = function (makeLogger) {
// tracer logger has custom trace logic... // tracer logger has custom trace logic...
if (!(logger instanceof TracerLogger)) { if (!(logger instanceof TracerLogger)) {
stub(logger, 'write', function (label, msg) { stub(logger, 'write', function (label, msg) {
msg.should.eql('curlcall\nmessage'); expect(msg).to.eql('curlcall\nmessage');
}); });
logger.onTrace('message', 'curlcall'); logger.onTrace('message', 'curlcall');
logger.write.callCount.should.eql(1); expect(logger.write.callCount).to.eql(1);
} }
}); });
}); });

View File

@ -1,30 +0,0 @@
/* jshint browser:true */
// hard requires so that browserify can grab them
require('./test_abstract_logger');
require('./test_client');
require('./test_client_action');
require('./test_connection_abstract');
require('./test_connection_pool');
require('./test_console_logger');
require('./test_errors');
// require('./test_file_logger');
require('./test_host');
// require('./test_http_connector');
require('./test_json_serializer');
require('./test_log');
require('./test_nodes_to_host_callback');
require('./test_random_selector');
require('./test_round_robin_selector');
// require('./test_stdio_logger');
// require('./test_stream_logger');
// require('./test_tracer_logger');
require('./test_transport');
// require('./test_transport_with_server');
require('./test_utils');
// browser build tests
require('./browser_test_generic_build');
require('./browser_test_angular_build');
require('./browser_test_jquery_build');

View File

@ -1,5 +1,5 @@
describe('Logger Abstract', function () { describe('Logger Abstract', function () {
var expect = require('expect.js');
var sinon = require('sinon'); var sinon = require('sinon');
var Log = require('../../src/lib/log'); var Log = require('../../src/lib/log');
var LoggerAbstract = require('../../src/lib/logger'); var LoggerAbstract = require('../../src/lib/logger');
@ -23,10 +23,10 @@ describe('Logger Abstract', function () {
describe('#write', function () { describe('#write', function () {
it('requires that it is overwritten', function () { it('requires that it is overwritten', function () {
(function () { expect(function () {
var logger = makeLogger(); var logger = makeLogger();
logger.write(); logger.write();
}).should.throw(/overwritten/); }).to.throwError(/overwritten/);
}); });
}); });

View File

@ -1,7 +1,7 @@
var es = require('../../src/elasticsearch');
var api = require('../../src/lib/api');
describe('Client instances creation', function () { describe('Client instances creation', function () {
var es = require('../../src/elasticsearch');
var api = require('../../src/lib/api');
var expect = require('expect.js');
var client; var client;
beforeEach(function () { beforeEach(function () {
@ -12,20 +12,21 @@ describe('Client instances creation', function () {
}); });
it('throws an error linking to the es module when you try to instanciate the exports', function () { it('throws an error linking to the es module when you try to instanciate the exports', function () {
(function () { var Es = es;
var client = new es(); expect(function () {
}).should.throw(/previous "elasticsearch" module/); var client = new Es();
}).to.throwError(/previous "elasticsearch" module/);
}); });
it('Succeeds even not called with new', function () { it('Succeeds even not called with new', function () {
var client = es.Client(); var client = es.Client();
client.bulk.should.eql(api.bulk); expect(client.bulk).to.eql(api.bulk);
client.cluster.nodeStats.should.eql(api.cluster.prototype.nodeStats); expect(client.cluster.nodeStats).to.eql(api.cluster.prototype.nodeStats);
}); });
it('inherits the api', function () { it('inherits the api', function () {
client.bulk.should.eql(api.bulk); expect(client.bulk).to.eql(api.bulk);
client.cluster.nodeStats.should.eql(api.cluster.prototype.nodeStats); expect(client.cluster.nodeStats).to.eql(api.cluster.prototype.nodeStats);
}); });
it('closing the client causes it\'s transport to be closed', function () { it('closing the client causes it\'s transport to be closed', function () {
@ -34,14 +35,14 @@ describe('Client instances creation', function () {
called = true; called = true;
}; };
client.close(); client.close();
called.should.be.exactly(true); expect(called).to.be(true);
}); });
it('creates a warning level logger by default', function () { it('creates a warning level logger by default', function () {
client.transport.log.listenerCount('error').should.eql(1); expect(client.transport.log.listenerCount('error')).to.eql(1);
client.transport.log.listenerCount('warning').should.eql(1); expect(client.transport.log.listenerCount('warning')).to.eql(1);
client.transport.log.listenerCount('info').should.eql(0); expect(client.transport.log.listenerCount('info')).to.eql(0);
client.transport.log.listenerCount('debug').should.eql(0); expect(client.transport.log.listenerCount('debug')).to.eql(0);
client.transport.log.listenerCount('trace').should.eql(0); expect(client.transport.log.listenerCount('trace')).to.eql(0);
}); });
}); });

View File

@ -1,5 +1,5 @@
var ca = require('../../src/lib/client_action'); var ca = require('../../src/lib/client_action');
var should = require('should'); var expect = require('expect.js');
var _ = require('lodash'); var _ = require('lodash');
var when = require('when'); var when = require('when');
@ -64,7 +64,7 @@ describe('Client Action runner', function () {
// note: the first arg is the callback // note: the first arg is the callback
action(function (err, params) { action(function (err, params) {
params.query.should.eql({}); expect(params.query).to.eql({});
done(); done();
}); });
}); });
@ -76,9 +76,9 @@ describe('Client Action runner', function () {
throw new Error('proxy function called'); throw new Error('proxy function called');
}); });
(function () { expect(function () {
action({}, function () {}); action({}, function () {});
}).should.throw('proxy function called'); }).to.throwError('proxy function called');
}); });
it('provides the proper context', function (done) { it('provides the proper context', function (done) {
@ -91,15 +91,15 @@ describe('Client Action runner', function () {
}); });
action({}, function (err, params) { action({}, function (err, params) {
client.transport.request.should.be.type('function'); expect(client.transport.request).to.be.a('function');
done(); done();
}); });
}); });
it('handles passing just the callback', function () { it('handles passing just the callback', function () {
var action = makeClientActionProxy(function (params, cb) { var action = makeClientActionProxy(function (params, cb) {
should(_.isObject(params)).be.ok; expect(_.isObject(params)).to.be.ok;
cb.should.be.type('function'); expect(cb).to.be.a('function');
}); });
action(function () {}); action(function () {});
@ -107,7 +107,7 @@ describe('Client Action runner', function () {
it('supports a param transformation function', function () { it('supports a param transformation function', function () {
var action = makeClientActionProxy(function (params, cb) { var action = makeClientActionProxy(function (params, cb) {
params.should.have.property('transformed'); expect(params).to.have.property('transformed');
}, { }, {
transform: function (params) { transform: function (params) {
params.transformed = true; params.transformed = true;
@ -123,7 +123,7 @@ describe('Client Action runner', function () {
return football; return football;
}); });
action().should.be.exactly(football); expect(action()).to.be(football);
}); });
}); });
@ -155,9 +155,9 @@ describe('Client Action runner', function () {
three: '15m' three: '15m'
}, function (err, params) { }, function (err, params) {
if (err) { throw err; } if (err) { throw err; }
params.query.one.should.eql(1500); expect(params.query.one).to.eql(1500);
params.query.two.should.eql('500'); expect(params.query.two).to.eql('500');
params.query.three.should.eql('15m'); expect(params.query.three).to.eql('15m');
done(); done();
}); });
@ -167,7 +167,7 @@ describe('Client Action runner', function () {
action({ action({
one: new Date() one: new Date()
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -177,7 +177,7 @@ describe('Client Action runner', function () {
one: ['one'], one: ['one'],
two: [ 1304 ] two: [ 1304 ]
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -186,7 +186,7 @@ describe('Client Action runner', function () {
action({ action({
one: { but: 'duration' } one: { but: 'duration' }
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -210,7 +210,7 @@ describe('Client Action runner', function () {
three: ['some', 'strings'], three: ['some', 'strings'],
}, function (err, params) { }, function (err, params) {
if (err) { throw err; } if (err) { throw err; }
params.query.should.eql({ expect(params.query).to.eql({
one: 'some,strings', one: 'some,strings',
two: 1430, two: 1430,
three: 'some,strings' three: 'some,strings'
@ -223,7 +223,7 @@ describe('Client Action runner', function () {
action({ action({
one: /regexp!/g one: /regexp!/g
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -234,7 +234,7 @@ describe('Client Action runner', function () {
pasta: 'sauce' pasta: 'sauce'
} }
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -254,7 +254,7 @@ describe('Client Action runner', function () {
one: 'opt' one: 'opt'
}, function (err, params) { }, function (err, params) {
if (err) { throw err; } if (err) { throw err; }
params.query.one.should.eql('opt'); expect(params.query.one).to.eql('opt');
done(); done();
}); });
}); });
@ -264,7 +264,7 @@ describe('Client Action runner', function () {
one: 150 one: 150
}, function (err, params) { }, function (err, params) {
if (err) { throw err; } if (err) { throw err; }
params.query.one.should.be.exactly('150'); expect(params.query.one).to.be('150');
done(); done();
}); });
}); });
@ -273,7 +273,7 @@ describe('Client Action runner', function () {
action({ action({
one: 'not an opt' one: 'not an opt'
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -301,10 +301,10 @@ describe('Client Action runner', function () {
four: '' four: ''
}, function (err, params) { }, function (err, params) {
if (err) { throw err; } if (err) { throw err; }
should(params.query.one).be.exactly(false); expect(params.query.one).to.be(false);
should(params.query.two).be.exactly(false); expect(params.query.two).to.be(false);
should(params.query.three).be.exactly(false); expect(params.query.three).to.be(false);
should(params.query.four).be.exactly(false); expect(params.query.four).to.be(false);
done(); done();
}); });
}); });
@ -319,12 +319,12 @@ describe('Client Action runner', function () {
six: {} six: {}
}, function (err, params) { }, function (err, params) {
if (err) { throw err; } if (err) { throw err; }
should(params.query.one).be.exactly(true); expect(params.query.one).to.be(true);
should(params.query.two).be.exactly(true); expect(params.query.two).to.be(true);
should(params.query.three).be.exactly(true); expect(params.query.three).to.be(true);
should(params.query.four).be.exactly(true); expect(params.query.four).to.be(true);
should(params.query.five).be.exactly(true); expect(params.query.five).to.be(true);
should(params.query.six).be.exactly(true); expect(params.query.six).to.be(true);
done(); done();
}); });
}); });
@ -354,12 +354,12 @@ describe('Client Action runner', function () {
six: 0xFFF six: 0xFFF
}, function (err, params) { }, function (err, params) {
if (err) { throw err; } if (err) { throw err; }
params.query.one.should.equal(42); expect(params.query.one).to.be(42);
params.query.two.should.equal(-69); expect(params.query.two).to.be(-69);
params.query.three.should.equal(15); expect(params.query.three).to.be(15);
params.query.four.should.equal(-100); expect(params.query.four).to.be(-100);
params.query.five.should.equal(255); expect(params.query.five).to.be(255);
params.query.six.should.equal(4095); expect(params.query.six).to.be(4095);
done(); done();
}); });
}); });
@ -374,12 +374,12 @@ describe('Client Action runner', function () {
six: '123e-2', six: '123e-2',
}, function (err, params) { }, function (err, params) {
if (err) { throw err; } if (err) { throw err; }
params.query.one.should.equal(-1.6); expect(params.query.one).to.be(-1.6);
params.query.two.should.equal(4.536); expect(params.query.two).to.be(4.536);
params.query.three.should.equal(-2.6); expect(params.query.three).to.be(-2.6);
params.query.four.should.equal(3.1415); expect(params.query.four).to.be(3.1415);
params.query.five.should.equal(800000); expect(params.query.five).to.be(800000);
params.query.six.should.equal(1.23); expect(params.query.six).to.be(1.23);
done(); done();
}); });
}); });
@ -388,7 +388,7 @@ describe('Client Action runner', function () {
action({ action({
one: new Date() one: new Date()
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -396,7 +396,7 @@ describe('Client Action runner', function () {
action({ action({
one: {} one: {}
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -404,7 +404,7 @@ describe('Client Action runner', function () {
action({ action({
one: [] one: []
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -412,7 +412,7 @@ describe('Client Action runner', function () {
action({ action({
one: /pasta/g one: /pasta/g
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -442,12 +442,12 @@ describe('Client Action runner', function () {
six: 0xFFF six: 0xFFF
}, function (err, params) { }, function (err, params) {
if (err) { throw err; } if (err) { throw err; }
params.query.one.should.equal('42'); expect(params.query.one).to.be('42');
params.query.two.should.equal('-69'); expect(params.query.two).to.be('-69');
params.query.three.should.equal('15'); expect(params.query.three).to.be('15');
params.query.four.should.equal('-100'); expect(params.query.four).to.be('-100');
params.query.five.should.equal('0xFF'); expect(params.query.five).to.be('0xFF');
params.query.six.should.equal('4095'); expect(params.query.six).to.be('4095');
done(); done();
}); });
}); });
@ -456,7 +456,7 @@ describe('Client Action runner', function () {
action({ action({
one: new Date() one: new Date()
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -464,7 +464,7 @@ describe('Client Action runner', function () {
action({ action({
one: {} one: {}
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -472,7 +472,7 @@ describe('Client Action runner', function () {
action({ action({
one: [] one: []
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -480,7 +480,7 @@ describe('Client Action runner', function () {
action({ action({
one: /pasta/g one: /pasta/g
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -511,11 +511,11 @@ describe('Client Action runner', function () {
five: new Date('2013-03-01T01:10:00Z') five: new Date('2013-03-01T01:10:00Z')
}, function (err, params) { }, function (err, params) {
if (err) { throw err; } if (err) { throw err; }
params.query.one.should.equal('42'); expect(params.query.one).to.be('42');
params.query.two.should.equal('-69'); expect(params.query.two).to.be('-69');
params.query.three.should.equal('15'); expect(params.query.three).to.be('15');
params.query.four.should.equal('' + now.getTime()); expect(params.query.four).to.be('' + now.getTime());
params.query.five.should.equal('1362100200000'); expect(params.query.five).to.be('1362100200000');
done(); done();
}); });
}); });
@ -524,7 +524,7 @@ describe('Client Action runner', function () {
action({ action({
one: {} one: {}
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -532,7 +532,7 @@ describe('Client Action runner', function () {
action({ action({
one: [] one: []
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -540,7 +540,7 @@ describe('Client Action runner', function () {
action({ action({
one: /pasta/g one: /pasta/g
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -554,7 +554,7 @@ describe('Client Action runner', function () {
}); });
action({}, function (err, params) { action({}, function (err, params) {
params.bulkBody.should.be.exactly(true); expect(params.bulkBody).to.be(true);
done(); done();
}); });
}); });
@ -565,7 +565,7 @@ describe('Client Action runner', function () {
}); });
action({}, function (err, params) { action({}, function (err, params) {
params.castExists.should.be.exactly(true); expect(params.castExists).to.be(true);
done(); done();
}); });
}); });
@ -580,7 +580,7 @@ describe('Client Action runner', function () {
var body = '{"JSON":"PLEASE"}'; var body = '{"JSON":"PLEASE"}';
action({ body: body }, function (err, params) { action({ body: body }, function (err, params) {
params.body.should.be.exactly(body); expect(params.body).to.be(body);
done(); done();
}); });
}); });
@ -589,7 +589,7 @@ describe('Client Action runner', function () {
action().then(function () { action().then(function () {
done(new Error('Error should have been raised')); done(new Error('Error should have been raised'));
}, function (err) { }, function (err) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -602,7 +602,7 @@ describe('Client Action runner', function () {
}); });
action({method: 'get'}, function (err, params) { action({method: 'get'}, function (err, params) {
params.method.should.be.exactly('GET'); expect(params.method).to.be('GET');
done(); done();
}); });
}); });
@ -613,7 +613,7 @@ describe('Client Action runner', function () {
}); });
action({}, function (err, params) { action({}, function (err, params) {
params.method.should.be.exactly('POST'); expect(params.method).to.be('POST');
done(); done();
}); });
}); });
@ -623,7 +623,7 @@ describe('Client Action runner', function () {
it('passes ignore as an array', function (done) { it('passes ignore as an array', function (done) {
var action = makeClientAction({}); var action = makeClientAction({});
action({ ignore: 404 }, function (err, params) { action({ ignore: 404 }, function (err, params) {
params.ignore.should.eql([404]); expect(params.ignore).to.eql([404]);
done(); done();
}); });
}); });
@ -636,7 +636,7 @@ describe('Client Action runner', function () {
}); });
action({}, function (err, params) { action({}, function (err, params) {
params.requestTimeout.should.be.exactly(100); expect(params.requestTimeout).to.be(100);
done(); done();
}); });
}); });
@ -647,7 +647,7 @@ describe('Client Action runner', function () {
}); });
action({ requestTimeout: 3000 }, function (err, params) { action({ requestTimeout: 3000 }, function (err, params) {
params.requestTimeout.should.be.exactly(3000); expect(params.requestTimeout).to.be(3000);
done(); done();
}); });
}); });
@ -656,7 +656,7 @@ describe('Client Action runner', function () {
var action = makeClientAction({}); var action = makeClientAction({});
action({}, function (err, params) { action({}, function (err, params) {
should(params.requestTimeout).be.exactly(void 0); expect(params.requestTimeout).be(void 0);
done(); done();
}); });
}); });
@ -695,7 +695,7 @@ describe('Client Action runner', function () {
action({ action({
type: ['type1', 'type2'] type: ['type1', 'type2']
}, function (err, params) { }, function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });
@ -706,7 +706,7 @@ describe('Client Action runner', function () {
id: '1' id: '1'
}, function (err, params) { }, function (err, params) {
if (err) { throw err; } if (err) { throw err; }
params.path.should.be.exactly('/index1/_all/1/'); expect(params.path).to.be('/index1/_all/1/');
done(); done();
}); });
}); });
@ -719,7 +719,7 @@ describe('Client Action runner', function () {
thing: 'poo' thing: 'poo'
}, function (err, params) { }, function (err, params) {
if (err) { throw err; } if (err) { throw err; }
params.path.should.be.exactly('/index1%2Cindex2/_all%2C-pizza/123/poo'); expect(params.path).to.be('/index1%2Cindex2/_all%2C-pizza/123/poo');
done(); done();
}); });
}); });
@ -741,7 +741,7 @@ describe('Client Action runner', function () {
}, },
function (err, params) { function (err, params) {
if (err) { throw err; } if (err) { throw err; }
params.query.should.eql({ expect(params.query).to.eql({
a: 'pizza', a: 'pizza',
b: '1M' b: '1M'
}); });
@ -757,7 +757,7 @@ describe('Client Action runner', function () {
}, },
function (err, params) { function (err, params) {
if (err) { throw err; } if (err) { throw err; }
params.query.should.eql({ expect(params.query).to.eql({
a: 'pizza', a: 'pizza',
b: '3w', b: '3w',
c: 'popular' c: 'popular'
@ -773,7 +773,7 @@ describe('Client Action runner', function () {
}, },
function (err, params) { function (err, params) {
if (err) { throw err; } if (err) { throw err; }
params.query.should.eql({ expect(params.query).to.eql({
a: 'pizza' a: 'pizza'
}); });
done(); done();
@ -792,7 +792,7 @@ describe('Client Action runner', function () {
}, },
function (err, params) { function (err, params) {
if (err) { throw err; } if (err) { throw err; }
params.query.should.eql({ expect(params.query).to.eql({
a: 'pizza', a: 'pizza',
b: '3w', b: '3w',
q: 'beep' q: 'beep'
@ -806,7 +806,7 @@ describe('Client Action runner', function () {
b: '3w' b: '3w'
}, },
function (err, params) { function (err, params) {
err.should.be.an.instanceOf(TypeError); expect(err).to.be.a(TypeError);
done(); done();
}); });
}); });

View File

@ -1,7 +1,7 @@
var ConnectionAbstract = require('../../src/lib/connection'); var ConnectionAbstract = require('../../src/lib/connection');
var Host = require('../../src/lib/host'); var Host = require('../../src/lib/host');
var sinon = require('sinon'); var sinon = require('sinon');
var should = require('should'); var expect = require('expect.js');
var _ = require('lodash'); var _ = require('lodash');
var errors = require('../../src/lib/errors'); var errors = require('../../src/lib/errors');
@ -12,24 +12,24 @@ describe('Connection Abstract', function () {
it('constructs with defaults for host, and bound', function () { it('constructs with defaults for host, and bound', function () {
var conn = new ConnectionAbstract(host); var conn = new ConnectionAbstract(host);
conn.host.should.be.exactly(host); expect(conn.host).to.be(host);
}); });
it('requires a valid host', function () { it('requires a valid host', function () {
(function () { expect(function () {
new ConnectionAbstract(); new ConnectionAbstract();
}).should.throw(TypeError); }).to.throwError(TypeError);
(function () { expect(function () {
new ConnectionAbstract({}); new ConnectionAbstract({});
}).should.throw(TypeError); }).to.throwError(TypeError);
}); });
it('required that the request method is overridden', function () { it('required that the request method is overridden', function () {
(function () { expect(function () {
var conn = new ConnectionAbstract(host); var conn = new ConnectionAbstract(host);
conn.request(); conn.request();
}).should.throw(/overwrit/); }).to.throwError(/overwrit/);
}); });
describe('#ping', function () { describe('#ping', function () {
@ -38,18 +38,18 @@ describe('Connection Abstract', function () {
stub(conn, 'request'); stub(conn, 'request');
var cb = function () {}; var cb = function () {};
conn.ping(cb); conn.ping(cb);
conn.request.callCount.should.eql(1); expect(conn.request.callCount).to.eql(1);
conn.request.lastCall.args[0].should.have.type('object'); expect(conn.request.lastCall.args[0]).to.be.a('object');
conn.request.lastCall.args[1].should.have.type('function'); expect(conn.request.lastCall.args[1]).to.be.a('function');
}); });
it('accpets just params', function () { it('accpets just params', function () {
var conn = new ConnectionAbstract(host); var conn = new ConnectionAbstract(host);
stub(conn, 'request'); stub(conn, 'request');
conn.ping({}); conn.ping({});
conn.request.callCount.should.eql(1); expect(conn.request.callCount).to.eql(1);
conn.request.lastCall.args[0].should.have.type('object'); expect(conn.request.lastCall.args[0]).to.be.a('object');
conn.request.lastCall.args[1].should.have.type('function'); expect(conn.request.lastCall.args[1]).to.be.a('function');
}); });
it('allows overriding the requestTimeout, method, and path', function () { it('allows overriding the requestTimeout, method, and path', function () {
@ -61,9 +61,9 @@ describe('Connection Abstract', function () {
requestTimeout: 10000 requestTimeout: 10000
}; };
conn.ping(params); conn.ping(params);
conn.request.callCount.should.eql(1); expect(conn.request.callCount).to.eql(1);
conn.request.lastCall.args[0].should.include(params); expect(conn.request.lastCall.args[0]).to.eql(params);
conn.request.lastCall.args[1].should.have.type('function'); expect(conn.request.lastCall.args[1]).to.be.a('function');
}); });
it('calls it\'s own request method', function () { it('calls it\'s own request method', function () {
@ -71,7 +71,7 @@ describe('Connection Abstract', function () {
var football = {}; var football = {};
stub(conn, 'request'); stub(conn, 'request');
conn.ping(); conn.ping();
conn.request.callCount.should.eql(1); expect(conn.request.callCount).to.eql(1);
}); });
it('sets a timer for the request', function (done) { it('sets a timer for the request', function (done) {
@ -81,7 +81,7 @@ describe('Connection Abstract', function () {
stub(conn, 'request', function (params, cb) { stub(conn, 'request', function (params, cb) {
setTimeout(function () { setTimeout(function () {
should(++order).eql(2); expect(++order).to.eql(2);
cb(); cb();
}, 10001); }, 10001);
}); });
@ -89,8 +89,8 @@ describe('Connection Abstract', function () {
conn.ping({ conn.ping({
requestTimeout: 100 requestTimeout: 100
}, function (err) { }, function (err) {
should(++order).eql(1); expect(++order).to.eql(1);
err.should.be.an.instanceOf(errors.RequestTimeout); expect(err).to.be.an(errors.RequestTimeout);
}); });
process.nextTick(function () { process.nextTick(function () {
@ -107,20 +107,20 @@ describe('Connection Abstract', function () {
stub(conn, 'request', function (params, cb) { stub(conn, 'request', function (params, cb) {
setTimeout(function () { setTimeout(function () {
should(++order).eql(3); expect(++order).to.eql(3);
cb(); cb();
}, 10001); }, 10001);
return function () { return function () {
should(++order).eql(1); expect(++order).to.eql(1);
}; };
}); });
conn.ping({ conn.ping({
requestTimeout: 100 requestTimeout: 100
}, function (err) { }, function (err) {
should(++order).eql(2); expect(++order).to.eql(2);
err.should.be.an.instanceOf(errors.RequestTimeout); expect(err).to.be.an(errors.RequestTimeout);
}); });
process.nextTick(function () { process.nextTick(function () {
@ -130,6 +130,7 @@ describe('Connection Abstract', function () {
done(); done();
}); });
}); });
it('ignores the response from the request if it already aborted'); it('ignores the response from the request if it already aborted');
}); });
@ -146,90 +147,15 @@ describe('Connection Abstract', function () {
}; };
conn.setStatus('closed'); conn.setStatus('closed');
emitted.name.should.eql('status set'); expect(emitted.name).to.eql('status set');
emitted.args.should.eql(['closed', null, conn]); expect(emitted.args).to.eql(['closed', undefined, conn]);
}); });
it('stores the status in this.status', function () { it('stores the status in this.status', function () {
var conn = new ConnectionAbstract(host); var conn = new ConnectionAbstract(host);
conn.setStatus('closed'); conn.setStatus('closed');
conn.status.should.eql('closed'); expect(conn.status).to.eql('closed');
}); });
// it('sets a timeout when set to dead, and removed when alive', function () {
// var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
// stub.autoRelease(clock);
// var conn = new ConnectionAbstract(host);
// var start = _.size(clock.timeouts);
// conn.setStatus('dead');
// _.size(clock.timeouts).should.be.eql(start + 1);
// conn.setStatus('alive');
// _.size(clock.timeouts).should.eql(start);
// clock.restore();
// });
}); });
// describe('#resuscitate', function () {
// it('should not ping the connection unless it is still dead', function () {
// var conn = new ConnectionAbstract(host);
// conn.setStatus('alive');
// stub(conn, 'ping', function () {
// throw new Error('ping should not have been called');
// });
// conn.resuscitate();
// });
// it('should ping the connection after the deadTimeout, and set the status to "alive" on pong', function (done) {
// var conn = new ConnectionAbstract(host);
// var clock;
// stub.autoRelease(clock = sinon.useFakeTimers('setTimeout', 'clearTimeout'));
// // schedules the resuscitate
// conn.setStatus('dead');
// // override the ping method to just callback without an error
// stub(conn, 'ping', function (cb) {
// cb();
// });
// // will be called after the ping calls back
// stub(conn, 'setStatus', function (status) {
// status.should.eql('alive');
// done();
// });
// // fast forward the clock
// clock.tick(conn.deadTimeout);
// });
// it('should ping the connection after the deadTimeout, and set the status to "dead" on error', function (done) {
// var conn = new ConnectionAbstract(host);
// var clock;
// stub.autoRelease(clock = sinon.useFakeTimers('setTimeout', 'clearTimeout'));
// // schedules the resuscitate
// conn.setStatus('dead');
// // override the ping method to just callback without an error
// stub(conn, 'ping', function (cb) {
// cb(new Error('server still down'));
// });
// // will be called after the ping calls back
// stub(conn, 'setStatus', function (status) {
// status.should.eql('dead');
// done();
// });
// // fast forward the clock
// clock.tick(conn.deadTimeout);
// });
// });
}); });

View File

@ -4,7 +4,7 @@ var errors = require('../../src/lib/errors');
var ConnectionAbstract = require('../../src/lib/connection'); var ConnectionAbstract = require('../../src/lib/connection');
var _ = require('lodash'); var _ = require('lodash');
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var should = require('should'); var expect = require('expect.js');
var sinon = require('sinon'); var sinon = require('sinon');
var stub = require('./auto_release_stub').make(); var stub = require('./auto_release_stub').make();
@ -37,13 +37,13 @@ describe('Connection Pool', function () {
}); });
it('#addConnection only adds the connection if it doesn\'t already exist', function () { it('#addConnection only adds the connection if it doesn\'t already exist', function () {
_.keys(pool.index).length.should.eql(0); expect(_.keys(pool.index).length).to.eql(0);
pool.addConnection(connection); pool.addConnection(connection);
_.keys(pool.index).should.eql([host.toString()]); expect(_.keys(pool.index)).to.eql([host.toString()]);
pool._conns.alive.should.eql([connection]); expect(pool._conns.alive).to.eql([connection]);
pool._conns.dead.should.eql([]); expect(pool._conns.dead).to.eql([]);
}); });
describe('#removeConnection', function () { describe('#removeConnection', function () {
@ -51,28 +51,28 @@ describe('Connection Pool', function () {
pool.addConnection(connection); pool.addConnection(connection);
pool.removeConnection(connection2); pool.removeConnection(connection2);
pool._conns.alive.should.eql([connection]); expect(pool._conns.alive).to.eql([connection]);
pool._conns.dead.should.eql([]); expect(pool._conns.dead).to.eql([]);
_.keys(pool.index).length.should.eql(1); expect(_.keys(pool.index).length).to.eql(1);
}); });
it('closes the connection when it removes it', function () { it('closes the connection when it removes it', function () {
pool.addConnection(connection); pool.addConnection(connection);
connection.status.should.eql('alive'); expect(connection.status).to.eql('alive');
listenerCount(connection, 'status set').should.eql(1); expect(listenerCount(connection, 'status set')).to.eql(1);
pool.removeConnection(connection); pool.removeConnection(connection);
connection.status.should.eql('closed'); expect(connection.status).to.eql('closed');
listenerCount(connection, 'status set').should.eql(0); expect(listenerCount(connection, 'status set')).to.eql(0);
}); });
}); });
it('#setHosts syncs the list of Hosts with the connections in the index', function () { it('#setHosts syncs the list of Hosts with the connections in the index', function () {
// there should now be two connections // there should now be two connections
pool.setHosts([host, host2]); pool.setHosts([host, host2]);
pool._conns.alive.length.should.eql(2); expect(pool._conns.alive.length).to.eql(2);
pool._conns.dead.length.should.eql(0); expect(pool._conns.dead.length).to.eql(0);
// get the new connections // get the new connections
connection = pool.index[host.toString()]; connection = pool.index[host.toString()];
@ -80,16 +80,16 @@ describe('Connection Pool', function () {
// should remove the second connection // should remove the second connection
pool.setHosts([host]); pool.setHosts([host]);
pool._conns.alive.should.eql([connection]); expect(pool._conns.alive).to.eql([connection]);
pool._conns.dead.length.should.eql(0); expect(pool._conns.dead.length).to.eql(0);
// should skip the first, but create a new for the second // should skip the first, but create a new for the second
pool.setHosts([host, host2]); pool.setHosts([host, host2]);
pool._conns.alive.length.should.eql(2); expect(pool._conns.alive.length).to.eql(2);
pool._conns.dead.length.should.eql(0); expect(pool._conns.dead.length).to.eql(0);
// a new connection should have been created // a new connection should have been created
pool.index[host2.toString()].should.not.be.exactly(connection2); expect(pool.index[host2.toString()]).to.not.be(connection2);
}); });
}); });
@ -110,7 +110,7 @@ describe('Connection Pool', function () {
it('detects if the selector is async', function (done) { it('detects if the selector is async', function (done) {
pool.selector = function (list, cb) { pool.selector = function (list, cb) {
cb.should.have.type('function'); expect(cb).to.be.a('function');
cb(); cb();
}; };
@ -122,7 +122,7 @@ describe('Connection Pool', function () {
it('detects if the selector is not async', function (done) { it('detects if the selector is not async', function (done) {
pool.selector = function (list) { pool.selector = function (list) {
arguments.should.have.length(1); expect(arguments.length).to.be(1);
}; };
pool.select(function (err) { pool.select(function (err) {
@ -140,12 +140,12 @@ describe('Connection Pool', function () {
pool.select(function (err, selection) { pool.select(function (err, selection) {
if (err) { throw err; } if (err) { throw err; }
selection.host.should.be.exactly(host); expect(selection.host).to.be(host);
selected = selection; selected = selection;
done(); done();
}); });
should(selected).be.exactly(null); expect(selected).to.be(null);
}); });
it('should catch errors in sync selectors', function (done) { it('should catch errors in sync selectors', function (done) {
@ -154,7 +154,7 @@ describe('Connection Pool', function () {
}; };
pool.select(function (err, selection) { pool.select(function (err, selection) {
should(err).be.an.instanceOf(Error); expect(err).be.an(Error);
done(); done();
}); });
}); });
@ -185,7 +185,7 @@ describe('Connection Pool', function () {
cb = params; cb = params;
} }
var expectedConn = pingQueue.shift(); var expectedConn = pingQueue.shift();
conn.should.be.exactly(expectedConn); expect(conn).to.be(expectedConn);
if (pingQueue.length) { if (pingQueue.length) {
process.nextTick(function () { process.nextTick(function () {
cb(new Error('keep trying')); cb(new Error('keep trying'));
@ -202,10 +202,10 @@ describe('Connection Pool', function () {
pool.select(function (err, selection) { pool.select(function (err, selection) {
clock.restore(); clock.restore();
selection.should.be.exactly(expectedSelection); expect(selection).to.be(expectedSelection);
pingQueue.should.have.length(0); expect(pingQueue.length).to.be(0);
pool.setHosts([]); pool.setHosts([]);
should.not.exist(err); expect(err).to.be(undefined);
done(); done();
}); });
}); });
@ -228,8 +228,8 @@ describe('Connection Pool', function () {
connection = pool.index[host.toString()]; connection = pool.index[host.toString()];
connection2 = pool.index[host2.toString()]; connection2 = pool.index[host2.toString()];
pool._conns.alive.should.have.length(2); expect(pool._conns.alive.length).to.be(2);
pool._conns.dead.should.have.length(0); expect(pool._conns.dead.length).to.be(0);
}); });
afterEach(function () { afterEach(function () {
@ -239,21 +239,21 @@ describe('Connection Pool', function () {
it('moves an alive connection to dead', function () { it('moves an alive connection to dead', function () {
connection.setStatus('dead'); connection.setStatus('dead');
pool._conns.alive.should.have.length(1); expect(pool._conns.alive.length).to.be(1);
pool._conns.dead.should.have.length(1); expect(pool._conns.dead.length).to.be(1);
}); });
it('clears and resets the timeout when a connection redies', function () { it('clears and resets the timeout when a connection redies', function () {
var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout'); var clock = sinon.useFakeTimers('setTimeout', 'clearTimeout');
connection.setStatus('dead'); connection.setStatus('dead');
_.size(clock.timeouts).should.eql(1); expect(_.size(clock.timeouts)).to.eql(1);
var id = _(clock.timeouts).keys().first(); var id = _(clock.timeouts).keys().first();
// it re-dies // it re-dies
connection.setStatus('dead'); connection.setStatus('dead');
_.size(clock.timeouts).should.eql(1); expect(_.size(clock.timeouts)).to.eql(1);
_(clock.timeouts).keys().first().should.not.eql(id); expect(_(clock.timeouts).keys().first()).to.not.eql(id);
clock.restore(); clock.restore();
}); });
@ -261,26 +261,26 @@ describe('Connection Pool', function () {
var last = pool._conns.alive[pool._conns.alive.length - 1]; var last = pool._conns.alive[pool._conns.alive.length - 1];
var first = pool._conns.alive[0]; var first = pool._conns.alive[0];
last.should.not.be.exactly(first); expect(last).to.not.be(first);
// first re-alives // first re-alives
first.setStatus('alive'); first.setStatus('alive');
pool._conns.alive[0].should.be.exactly(first); expect(pool._conns.alive[0]).to.be(first);
pool._conns.alive[pool._conns.alive.length - 1].should.be.exactly(last); expect(pool._conns.alive[pool._conns.alive.length - 1]).to.be(last);
// last re-alives // last re-alives
last.setStatus('alive'); last.setStatus('alive');
pool._conns.alive[0].should.be.exactly(first); expect(pool._conns.alive[0]).to.be(first);
pool._conns.alive[pool._conns.alive.length - 1].should.be.exactly(last); expect(pool._conns.alive[pool._conns.alive.length - 1]).to.be(last);
}); });
it('removes all its connection when it closes, causing them to be closed', function () { it('removes all its connection when it closes, causing them to be closed', function () {
pool.close(); pool.close();
pool._conns.alive.should.have.length(0); expect(pool._conns.alive.length).to.be(0);
pool._conns.dead.should.have.length(0); expect(pool._conns.dead.length).to.be(0);
connection.status.should.eql('closed'); expect(connection.status).to.eql('closed');
connection2.status.should.eql('closed'); expect(connection2.status).to.eql('closed');
}); });
}); });
@ -295,10 +295,10 @@ describe('Connection Pool', function () {
} }
var result = pool.getConnections(); var result = pool.getConnections();
result.should.have.length(1000); expect(result.length).to.be(1000);
_.reduce(result, function (sum, num) { expect(_.reduce(result, function (sum, num) {
return sum += num; return sum += num;
}, 0).should.eql(499500); }, 0)).to.eql(499500);
}); });
}); });
@ -307,42 +307,42 @@ describe('Connection Pool', function () {
var pool = new ConnectionPool({ var pool = new ConnectionPool({
calcDeadTimeout: 'flat' calcDeadTimeout: 'flat'
}); });
pool.calcDeadTimeout.should.be.exactly(ConnectionPool.calcDeadTimeoutOptions.flat); expect(pool.calcDeadTimeout).to.be(ConnectionPool.calcDeadTimeoutOptions.flat);
pool.close(); pool.close();
}); });
it('"flat" always returns the base timeout', function () { it('"flat" always returns the base timeout', function () {
var pool = new ConnectionPool({ var pool = new ConnectionPool({
calcDeadTimeout: 'flat' calcDeadTimeout: 'flat'
}); });
pool.calcDeadTimeout(0, 1000).should.eql(1000); expect(pool.calcDeadTimeout(0, 1000)).to.eql(1000);
pool.calcDeadTimeout(10, 5000).should.eql(5000); expect(pool.calcDeadTimeout(10, 5000)).to.eql(5000);
pool.calcDeadTimeout(25, 10000).should.eql(10000); expect(pool.calcDeadTimeout(25, 10000)).to.eql(10000);
}); });
it('"exponential" always increases the timeout based on the attempts', function () { it('"exponential" always increases the timeout based on the attempts', function () {
var pool = new ConnectionPool({ var pool = new ConnectionPool({
calcDeadTimeout: 'exponential' calcDeadTimeout: 'exponential'
}); });
pool.calcDeadTimeout(0, 1000).should.eql(1000); expect(pool.calcDeadTimeout(0, 1000)).to.eql(1000);
pool.calcDeadTimeout(10, 5000).should.be.above(5000); expect(pool.calcDeadTimeout(10, 5000)).to.be.greaterThan(5000);
pool.calcDeadTimeout(25, 10000).should.be.above(10000); expect(pool.calcDeadTimeout(25, 10000)).to.be.greaterThan(10000);
}); });
it('"exponential" produces predicatable results', function () { it('"exponential" produces predicatable results', function () {
var pool = new ConnectionPool({ var pool = new ConnectionPool({
calcDeadTimeout: 'exponential' calcDeadTimeout: 'exponential'
}); });
pool.calcDeadTimeout(0, 1000).should.eql(1000); expect(pool.calcDeadTimeout(0, 1000)).to.eql(1000);
pool.calcDeadTimeout(4, 10000).should.eql(40000); expect(pool.calcDeadTimeout(4, 10000)).to.eql(40000);
// maxes out at 30 minutes by default // maxes out at 30 minutes by default
pool.calcDeadTimeout(25, 30000).should.eql(18e5); expect(pool.calcDeadTimeout(25, 30000)).to.eql(18e5);
}); });
it('"exponential" repects config.maxDeadtimeout', function () { it('"exponential" repects config.maxDeadtimeout', function () {
var pool = new ConnectionPool({ var pool = new ConnectionPool({
calcDeadTimeout: 'exponential', calcDeadTimeout: 'exponential',
maxDeadTimeout: 10000 maxDeadTimeout: 10000
}); });
pool.calcDeadTimeout(0, 1000).should.eql(1000); expect(pool.calcDeadTimeout(0, 1000)).to.eql(1000);
pool.calcDeadTimeout(10, 1000).should.eql(10000); expect(pool.calcDeadTimeout(10, 1000)).to.eql(10000);
pool.calcDeadTimeout(100, 1000).should.eql(10000); expect(pool.calcDeadTimeout(100, 1000)).to.eql(10000);
}); });
}); });
}); });

View File

@ -1,6 +1,7 @@
var Log = require('../../src/lib/log'); var Log = require('../../src/lib/log');
var ConsoleLogger = require('../../src/lib/loggers/console'); var ConsoleLogger = require('../../src/lib/loggers/console');
var sinon = require('sinon'); var sinon = require('sinon');
var expect = require('expect.js');
var parentLog; var parentLog;
beforeEach(function () { beforeEach(function () {
@ -33,7 +34,7 @@ describe('Console Logger', function () {
var logger = makeLogger(); var logger = makeLogger();
logger.onWarning('message'); logger.onWarning('message');
console.log.callCount.should.eql(1); expect(console.log.callCount).to.be(1);
console.warn = _warning; console.warn = _warning;
console.log.restore(); console.log.restore();

View File

@ -1,4 +1,5 @@
var errors = require('../../src/lib/errors'); var errors = require('../../src/lib/errors');
var expect = require('expect.js');
var _ = require('lodash'); var _ = require('lodash');
_.each(errors, function (CustomError, name) { _.each(errors, function (CustomError, name) {
@ -6,8 +7,9 @@ _.each(errors, function (CustomError, name) {
describe(name, function () { describe(name, function () {
it('extend the ErrorAbstract and Error classes', function () { it('extend the ErrorAbstract and Error classes', function () {
var err = new CustomError(); var err = new CustomError();
err.message.length.should.be.above(7); expect(err.message.length).to.be.greaterThan(7);
err.should.be.an.instanceOf(Error).and.an.instanceOf(errors._Abstract); expect(err).to.be.an(Error);
expect(err).to.be.an(errors._Abstract);
}); });
}); });
} }
@ -20,6 +22,6 @@ describe('Error Abstract', function () {
var err = new errors._Abstract(); var err = new errors._Abstract();
process.browser = isBrowser; process.browser = isBrowser;
err.stack.should.be.exactly(''); expect(err.stack).to.be('');
}); });
}); });

View File

@ -1,40 +1,40 @@
var Log = require('../../src/lib/log');
var FileLogger = require('../../src/lib/loggers/file');
var once = require('events').EventEmitter.prototype.once;
var _ = require('lodash');
var parentLog;
var logger;
var fs = require('fs');
beforeEach(function () {
parentLog = new Log();
});
afterEach(function () {
parentLog.close();
if (logger
&& logger.stream
&& logger.stream._writableState
&& logger.stream._writableState.buffer.length
) {
// empty the buffer manually
logger.stream._writableState.buffer.splice(0);
}
});
function makeLogger(parent, levels) {
parent = parent || parentLog;
logger = new FileLogger(parent, {
levels: Log.parseLevels(levels || 'trace'),
path: 'test.log'
});
return logger;
}
var stub = require('./auto_release_stub').make();
describe('File Logger', function () { describe('File Logger', function () {
var Log = require('../../src/lib/log');
var FileLogger = require('../../src/lib/loggers/file');
var once = require('events').EventEmitter.prototype.once;
var _ = require('lodash');
var parentLog;
var logger;
var expect = require('expect.js');
var fs = require('fs');
var stub = require('./auto_release_stub').make();
beforeEach(function () {
parentLog = new Log();
});
afterEach(function () {
parentLog.close();
if (logger
&& logger.stream
&& logger.stream._writableState
&& logger.stream._writableState.buffer.length
) {
// empty the buffer manually
logger.stream._writableState.buffer.splice(0);
}
});
function makeLogger(parent, levels) {
parent = parent || parentLog;
logger = new FileLogger(parent, {
levels: Log.parseLevels(levels || 'trace'),
path: 'test.log'
});
return logger;
}
require('./generic_logger_tests')(makeLogger); require('./generic_logger_tests')(makeLogger);
describe('buffer flush', function () { describe('buffer flush', function () {
@ -67,8 +67,8 @@ describe('File Logger', function () {
exitHandler.call(process); exitHandler.call(process);
// the first line is sent immediately to _write and there is nothing we can do about that // the first line is sent immediately to _write and there is nothing we can do about that
flushedOutput.should.match(new RegExp(line)); expect(flushedOutput).to.match(new RegExp(line));
flushedOutput.match(new RegExp(line, 'g')).length.should.eql(9); expect(flushedOutput.match(new RegExp(line, 'g')).length).to.be(9);
}); });
} else { } else {
it('does not fall apart with non streams2 streams', function () { it('does not fall apart with non streams2 streams', function () {
@ -82,10 +82,10 @@ describe('File Logger', function () {
var logger = makeLogger(); var logger = makeLogger();
(function () { expect(function () {
// call the event handler // call the event handler
exitHandler.call(process); exitHandler.call(process);
}).should.not.throw(); }).to.not.throw();
}); });
} }
}); });

View File

@ -1,12 +1,13 @@
var Host = require('../../src/lib/host'); var Host = require('../../src/lib/host');
var _ = require('lodash'); var _ = require('lodash');
var expect = require('expect.js');
var url = require('url'); var url = require('url');
describe('Host class', function () { describe('Host class', function () {
describe('construction', function () { describe('construction', function () {
it('properly sets the defaults', function () { it('properly sets the defaults', function () {
var host = new Host(); var host = new Host();
host.should.eql({ expect(host).to.eql({
protocol: 'http', protocol: 'http',
host: 'localhost', host: 'localhost',
port: 9200, port: 9200,
@ -19,7 +20,7 @@ describe('Host class', function () {
it('accepts a string for query', function () { it('accepts a string for query', function () {
var host = new Host({ query: 'beep=boop'}); var host = new Host({ query: 'beep=boop'});
host.query.should.eql({ expect(host.query).to.eql({
beep: 'boop' beep: 'boop'
}); });
}); });
@ -28,14 +29,14 @@ describe('Host class', function () {
var headers = { 'X-Special-Routing-Header': 'pie' }; var headers = { 'X-Special-Routing-Header': 'pie' };
var host = new Host({ headers: headers }); var host = new Host({ headers: headers });
host.headers.should.be.exactly(headers); expect(host.headers).to.be(headers);
}); });
describe('from a string', function () { describe('from a string', function () {
it('accepts a string for the entire url', function () { it('accepts a string for the entire url', function () {
var host = new Host('john:dude@pizza.com:420/pizza/cheese?shrooms=true'); var host = new Host('john:dude@pizza.com:420/pizza/cheese?shrooms=true');
host.should.eql({ expect(host).to.eql({
protocol: 'http', protocol: 'http',
host: 'pizza.com', host: 'pizza.com',
port: 420, port: 420,
@ -51,14 +52,14 @@ describe('Host class', function () {
var host; var host;
host = new Host('https://google.com'); host = new Host('https://google.com');
host.port.should.eql(443); expect(host.port).to.be(443);
host = new Host('http://google.com'); host = new Host('http://google.com');
host.port.should.eql(80); expect(host.port).to.be(80);
Host.defaultPorts.trift = 9300; Host.defaultPorts.trift = 9300;
host = new Host('thrift://google.com'); host = new Host('thrift://google.com');
host.port.should.eql(9200); expect(host.port).to.be(9200);
delete Host.defaultPorts.trift; delete Host.defaultPorts.trift;
}); });
}); });
@ -68,37 +69,33 @@ describe('Host class', function () {
var parsedUrl = url.parse('pizza.com:888'); var parsedUrl = url.parse('pizza.com:888');
// I imagine most people don't expect // I imagine most people don't expect
parsedUrl.should.include({ expect(parsedUrl.protocol).to.eql('pizza.com:');
protocol: 'pizza.com:', expect(parsedUrl.host).to.eql('888');
host: '888',
});
var host = new Host(parsedUrl); var host = new Host(parsedUrl);
host.protocol.should.eql('pizza.com'); expect(host.protocol).to.eql('pizza.com');
host.host.should.eql('888'); expect(host.host).to.eql('888');
}); });
it('will cause extra properties', function () { it('will cause extra properties', function () {
var host = new Host(url.parse('https://joe:diner@pizza.com:888/path?query=yes')); var host = new Host(url.parse('https://joe:diner@pizza.com:888/path?query=yes'));
host.should.include({ expect(host.protocol).to.eql('https');
protocol: 'https', expect(host.host).to.eql('pizza.com');
host: 'pizza.com', expect(host.port).to.eql(888);
port: 888, expect(host.path).to.eql('/path');
path: '/path', expect(host.auth).to.eql('joe:diner');
auth: 'joe:diner', expect(host.query).to.eql({
query: { query: 'yes'
query: 'yes'
}
}); });
_.keys(host).should.include('slashes', 'hash', 'href', 'search'); expect(host).to.include.keys('slashes', 'hash', 'href', 'search');
}); });
}); });
it('ignores anything that\'s not a string or object-y', function () { it('ignores anything that\'s not a string or object-y', function () {
var host = new Host(1234); var host = new Host(1234);
host.should.eql({ expect(host).to.eql({
protocol: 'http', protocol: 'http',
host: 'localhost', host: 'localhost',
port: 9200, port: 9200,
@ -118,39 +115,39 @@ describe('Host class', function () {
} }
}); });
host.makeUrl({ expect(host.makeUrl({
path: '/this and that', path: '/this and that',
query: { query: {
param: 1 param: 1
}, },
auth: 'user:pass' auth: 'user:pass'
}).should.eql('http://user:pass@localhost:9200/prefix/this and that?param=1&user_id=123'); })).to.be('http://user:pass@localhost:9200/prefix/this and that?param=1&user_id=123');
}); });
it('ensures that path starts with a forward-slash', function () { it('ensures that path starts with a forward-slash', function () {
var host = new Host(); var host = new Host();
host.path = 'prefix'; host.path = 'prefix';
host.makeUrl({ path: '/this and that'}) expect(host.makeUrl({ path: '/this and that'}))
.should.eql('http://localhost:9200/prefix/this and that'); .to.be('http://localhost:9200/prefix/this and that');
}); });
it('does not try to prevent double forward-slashes', function () { it('does not try to prevent double forward-slashes', function () {
var host = new Host({ path: 'prefix/' }); var host = new Host({ path: 'prefix/' });
host.makeUrl({ path: '/this and that'}) expect(host.makeUrl({ path: '/this and that'}))
.should.eql('http://localhost:9200/prefix//this and that'); .to.be('http://localhost:9200/prefix//this and that');
}); });
it('creates proper url without any params', function () { it('creates proper url without any params', function () {
var host = new Host({}); var host = new Host({});
host.makeUrl().should.eql('http://localhost:9200/'); expect(host.makeUrl()).to.be('http://localhost:9200/');
host = new Host({ host: 'john', port: 80 }); host = new Host({ host: 'john', port: 80 });
host.makeUrl().should.eql('http://john/'); expect(host.makeUrl()).to.be('http://john/');
host = new Host({ host: 'italy', path: '/pie', auth: 'user:pass'}); host = new Host({ host: 'italy', path: '/pie', auth: 'user:pass'});
host.makeUrl().should.eql('http://user:pass@italy:9200/pie'); expect(host.makeUrl()).to.be('http://user:pass@italy:9200/pie');
}); });
}); });
@ -161,7 +158,7 @@ describe('Host class', function () {
host: 'google.com' host: 'google.com'
}); });
host.toString().should.eql(host.makeUrl()); expect(host.toString()).to.eql(host.makeUrl());
}); });
}); });

View File

@ -1,6 +1,6 @@
describe('Http Connector', function () { describe('Http Connector', function () {
var should = require('should'); var expect = require('expect.js');
var Host = require('../../src/lib/host'); var Host = require('../../src/lib/host');
var errors = require('../../src/lib/errors'); var errors = require('../../src/lib/errors');
var HttpConnection = require('../../src/lib/connectors/http'); var HttpConnection = require('../../src/lib/connectors/http');
@ -41,13 +41,13 @@ describe('Http Connector', function () {
describe('Constructor', function () { describe('Constructor', function () {
it('creates an object that extends ConnectionAbstract', function () { it('creates an object that extends ConnectionAbstract', function () {
var con = new HttpConnection(new Host()); var con = new HttpConnection(new Host());
con.should.be.an.instanceOf(ConnectionAbstract); expect(con).to.be.a(ConnectionAbstract);
}); });
it('sets certain defaults', function () { it('sets certain defaults', function () {
var con = new HttpConnection(new Host()); var con = new HttpConnection(new Host());
con.hand.should.be.exactly(require('http')); expect(con.hand).to.be(require('http'));
// con.requestTimeout // con.requestTimeout
// maxSockets // maxSockets
// maxFreeSockets // maxFreeSockets
@ -56,9 +56,9 @@ describe('Http Connector', function () {
}); });
it('expects one the host to have a protocol of http or https', function () { it('expects one the host to have a protocol of http or https', function () {
(function () { expect(function () {
var con = new HttpConnection(new Host('thrifty://es.com/stuff')); var con = new HttpConnection(new Host('thrifty://es.com/stuff'));
}).should.throw(/invalid protocol/i); }).to.throwError(/invalid protocol/i);
}); });
}); });
@ -68,7 +68,7 @@ describe('Http Connector', function () {
var con = new HttpConnection(host, {}); var con = new HttpConnection(host, {});
var reqParams = con.makeReqParams(); var reqParams = con.makeReqParams();
reqParams.should.eql({ expect(reqParams).to.eql({
method: 'GET', method: 'GET',
protocol: 'http:', protocol: 'http:',
auth: 'john:dude', auth: 'john:dude',
@ -93,9 +93,7 @@ describe('Http Connector', function () {
} }
}); });
reqParams.should.include({ expect(reqParams.path).to.eql('/?user_id=123&jvm=yes');
path: '/?user_id=123&jvm=yes'
});
}); });
it('merges the path prefex', function () { it('merges the path prefex', function () {
@ -108,7 +106,7 @@ describe('Http Connector', function () {
} }
}); });
reqParams.should.eql({ expect(reqParams).to.eql({
method: 'GET', method: 'GET',
protocol: 'https:', protocol: 'https:',
auth: null, auth: null,
@ -131,7 +129,7 @@ describe('Http Connector', function () {
} }
}); });
reqParams.should.eql({ expect(reqParams).to.eql({
method: 'PUT', method: 'PUT',
protocol: 'http:', protocol: 'http:',
auth: null, auth: null,
@ -151,7 +149,7 @@ describe('Http Connector', function () {
path: '/stuff' path: '/stuff'
}); });
reqParams.should.eql({ expect(reqParams).to.eql({
method: 'PUT', method: 'PUT',
protocol: 'http:', protocol: 'http:',
auth: null, auth: null,
@ -173,8 +171,8 @@ describe('Http Connector', function () {
it('calls http based on the host', function (done) { it('calls http based on the host', function (done) {
var con = new HttpConnection(new Host('http://google.com')); var con = new HttpConnection(new Host('http://google.com'));
con.request({}, function () { con.request({}, function () {
http.request.callCount.should.eql(1); expect(http.request.callCount).to.eql(1);
https.request.callCount.should.eql(0); expect(https.request.callCount).to.eql(0);
done(); done();
}); });
}); });
@ -182,8 +180,8 @@ describe('Http Connector', function () {
it('calls https based on the host', function (done) { it('calls https based on the host', function (done) {
var con = new HttpConnection(new Host('https://google.com')); var con = new HttpConnection(new Host('https://google.com'));
con.request({}, function () { con.request({}, function () {
http.request.callCount.should.eql(0); expect(http.request.callCount).to.eql(0);
https.request.callCount.should.eql(1); expect(https.request.callCount).to.eql(1);
done(); done();
}); });
}); });
@ -202,14 +200,14 @@ describe('Http Connector', function () {
con.request({}, function (err) { con.request({}, function (err) {
// error should have been sent to the // error should have been sent to the
err.message.should.eql('actual error'); expect(err.message).to.eql('actual error');
// logged the error and the trace log // logged the error and the trace log
con.log.trace.callCount.should.eql(1); expect(con.log.trace.callCount).to.eql(1);
con.log.error.callCount.should.eql(0); expect(con.log.error.callCount).to.eql(0);
con.log.info.callCount.should.eql(0); expect(con.log.info.callCount).to.eql(0);
con.log.warning.callCount.should.eql(0); expect(con.log.warning.callCount).to.eql(0);
con.log.debug.callCount.should.eql(0); expect(con.log.debug.callCount).to.eql(0);
done(); done();
}); });
@ -224,10 +222,10 @@ describe('Http Connector', function () {
con.request({}, function (err) { con.request({}, function (err) {
// error should have been sent to the // error should have been sent to the
err.message.should.eql('actual error'); expect(err.message).to.eql('actual error');
// logged the error // logged the error
con.log.error.callCount.should.eql(0); expect(con.log.error.callCount).to.eql(0);
done(); done();
}); });
}); });
@ -254,7 +252,7 @@ describe('Http Connector', function () {
stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody()); stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody());
con.request({}, function (err, resp, status) { con.request({}, function (err, resp, status) {
con.log.error.callCount.should.eql(0); expect(con.log.error.callCount).to.eql(0);
done(); done();
}); });
}); });
@ -264,8 +262,8 @@ describe('Http Connector', function () {
stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody(new Error('no more message :('))); stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody(new Error('no more message :(')));
con.request({}, function (err, resp, status) { con.request({}, function (err, resp, status) {
should.exist(err); expect(err).to.be.an(Error);
err.message.should.eql('no more message :('); expect(err.message).to.eql('no more message :(');
done(); done();
}); });
}); });
@ -275,7 +273,7 @@ describe('Http Connector', function () {
stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody()); stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody());
con.request({}, function (err, resp, status) { con.request({}, function (err, resp, status) {
should.not.exist(resp); expect(resp).to.be(undefined);
done(); done();
}); });
}); });
@ -285,7 +283,7 @@ describe('Http Connector', function () {
stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody()); stub(https, 'request', makeStubReqWithMsgWhichErrorsMidBody());
con.request({}, function (err, resp, status) { con.request({}, function (err, resp, status) {
should.not.exist(status); expect(status).to.be(undefined);
done(); done();
}); });
}); });
@ -305,9 +303,9 @@ describe('Http Connector', function () {
method: 'GET', method: 'GET',
path: '/users/1' path: '/users/1'
}, function (err, resp, status) { }, function (err, resp, status) {
should.not.exist(err); expect(err).to.be(undefined);
resp.should.eql(body); expect(resp).to.eql(body);
status.should.eql(200); expect(status).to.eql(200);
server.done(); server.done();
done(); done();
}); });
@ -327,9 +325,9 @@ describe('Http Connector', function () {
method: 'GET', method: 'GET',
path: '/users/1' path: '/users/1'
}, function (err, resp, status) { }, function (err, resp, status) {
should.not.exist(err); expect(err).to.be(undefined);
resp.should.eql(body); expect(resp).to.eql(body);
status.should.eql(200); expect(status).to.eql(200);
done(); done();
}); });
}); });
@ -342,8 +340,8 @@ describe('Http Connector', function () {
var server = nock('http://localhost').get('/').reply(200); var server = nock('http://localhost').get('/').reply(200);
con.request({}, function (err, resp, status) { con.request({}, function (err, resp, status) {
http.ClientRequest.prototype.setNoDelay.callCount.should.eql(1); expect(http.ClientRequest.prototype.setNoDelay.callCount).to.eql(1);
http.ClientRequest.prototype.setNoDelay.lastCall.args[0].should.eql(true); expect(http.ClientRequest.prototype.setNoDelay.lastCall.args[0]).to.eql(true);
server.done(); server.done();
done(); done();
}); });
@ -355,13 +353,13 @@ describe('Http Connector', function () {
var server = nock('http://localhost').get('/').reply(200); var server = nock('http://localhost').get('/').reply(200);
var body = 'pasta and 𝄞'; var body = 'pasta and 𝄞';
body.length.should.eql(12); // nope expect(body.length).to.eql(12); // nope
Buffer.byteLength(body, 'utf8').should.eql(14); // yep expect(Buffer.byteLength(body, 'utf8')).to.eql(14); // yep
con.request({ con.request({
body: body body: body
}, function (err, resp, status) { }, function (err, resp, status) {
http.ClientRequest.prototype.setHeader.lastCall.args.should.eql(['Content-Length', 14]); expect(http.ClientRequest.prototype.setHeader.lastCall.args).to.eql(['Content-Length', 14]);
server.done(); server.done();
done(); done();
}); });

View File

@ -1,7 +1,6 @@
var JsonSerializer = require('../../src/lib/serializers/json');
var should = require('should');
describe('JSON serializer', function () { describe('JSON serializer', function () {
var JsonSerializer = require('../../src/lib/serializers/json');
var expect = require('expect.js');
var stub = require('./auto_release_stub').make(); var stub = require('./auto_release_stub').make();
function makeSerializer() { function makeSerializer() {
@ -13,20 +12,20 @@ describe('JSON serializer', function () {
stub(JSON, 'stringify'); stub(JSON, 'stringify');
var ser = makeSerializer(); var ser = makeSerializer();
ser.serialize({ some: 'object' }); ser.serialize({ some: 'object' });
JSON.stringify.callCount.should.eql(1); expect(JSON.stringify.callCount).to.eql(1);
}); });
it('does not modify strings', function () { it('does not modify strings', function () {
var ser = makeSerializer(); var ser = makeSerializer();
var thing = 'pretend that I am serialized'; var thing = 'pretend that I am serialized';
ser.serialize(thing).should.be.exactly(thing); expect(ser.serialize(thing)).to.be(thing);
}); });
it('returns nothing for invalid values', function () { it('returns nothing for invalid values', function () {
var ser = makeSerializer(); var ser = makeSerializer();
should.not.exist(ser.serialize(null)); expect(ser.serialize(null)).to.be(undefined);
should.not.exist(ser.serialize(false)); expect(ser.serialize(false)).to.be(undefined);
}); });
it('throws serialization errors', function () { it('throws serialization errors', function () {
@ -34,9 +33,9 @@ describe('JSON serializer', function () {
var thing = { name: 'thing' }; var thing = { name: 'thing' };
thing.self = thing; thing.self = thing;
(function () { expect(function () {
ser.serialize(thing); ser.serialize(thing);
}).should.throw(); }).to.throwError();
}); });
}); });
@ -45,22 +44,22 @@ describe('JSON serializer', function () {
stub(JSON, 'parse'); stub(JSON, 'parse');
var ser = makeSerializer(); var ser = makeSerializer();
ser.deserialize('{ "some": "JSON" }'); ser.deserialize('{ "some": "JSON" }');
JSON.parse.callCount.should.eql(1); expect(JSON.parse.callCount).to.eql(1);
}); });
it('ignores non string values', function () { it('ignores non string values', function () {
var ser = makeSerializer(); var ser = makeSerializer();
var thing = ['pretend that I am not here']; var thing = ['pretend that I am not here'];
should.not.exist(ser.deserialize(thing)); expect(ser.deserialize(thing)).to.be(undefined);
should.not.exist(ser.deserialize(null)); expect(ser.deserialize(null)).to.be(undefined);
should.not.exist(ser.deserialize(false)); expect(ser.deserialize(false)).to.be(undefined);
}); });
it('catches serialization errors, returns nothing', function () { it('catches serialization errors, returns nothing', function () {
var ser = makeSerializer(); var ser = makeSerializer();
var thing = '{ name: \'thing\' }'; var thing = '{ name: \'thing\' }';
should.not.exist(ser.deserialize(thing)); expect(ser.deserialize(thing)).to.be(undefined);
}); });
}); });
@ -73,27 +72,27 @@ describe('JSON serializer', function () {
it('creates a string out of an array of obejcts', function () { it('creates a string out of an array of obejcts', function () {
var ser = makeSerializer(); var ser = makeSerializer();
ser.bulkBody(body).should.eql(bulk); expect(ser.bulkBody(body)).to.eql(bulk);
}); });
it('adds a newline to the end of strings', function () { it('adds a newline to the end of strings', function () {
var ser = makeSerializer(); var ser = makeSerializer();
ser.bulkBody(bulk.substr(0, bulk.length - 1)).should.eql(bulk); expect(ser.bulkBody(bulk.substr(0, bulk.length - 1))).to.eql(bulk);
}); });
it('throws an error for anything else', function () { it('throws an error for anything else', function () {
var ser = makeSerializer(); var ser = makeSerializer();
(function () { expect(function () {
ser.bulkBody({}); ser.bulkBody({});
}).should.throw(); }).to.throwError();
(function () { expect(function () {
ser.bulkBody(null); ser.bulkBody(null);
}).should.throw(); }).to.throwError();
(function () { expect(function () {
ser.bulkBody(false); ser.bulkBody(false);
}).should.throw(); }).to.throwError();
}); });
}); });
}); });

View File

@ -1,10 +1,11 @@
var Log = require('../../src/lib/log'); var Log = require('../../src/lib/log');
var _ = require('lodash'); var _ = require('lodash');
var expect = require('expect.js');
describe('Log class', function () { describe('Log class', function () {
describe('::parseLevels', function () { describe('::parseLevels', function () {
it('accepts a string and returns it and the other levels below it', function () { it('accepts a string and returns it and the other levels below it', function () {
Log.parseLevels('trace').should.eql([ expect(Log.parseLevels('trace')).to.eql([
'error', 'error',
'warning', 'warning',
'info', 'info',
@ -14,19 +15,19 @@ describe('Log class', function () {
}); });
it('accepts and validates an array of levels', function () { it('accepts and validates an array of levels', function () {
Log.parseLevels(['warning', 'info']).should.eql(['warning', 'info']); expect(Log.parseLevels(['warning', 'info'])).to.eql(['warning', 'info']);
}); });
it('throws an error when an invalid string is supplied', function () { it('throws an error when an invalid string is supplied', function () {
(function () { expect(function () {
Log.parseLevels('INVALID'); Log.parseLevels('INVALID');
}).should.throw(/invalid logging level/); }).to.throwError(/invalid logging level/);
}); });
it('throws an error when an invalid string is supplied in side an array', function () { it('throws an error when an invalid string is supplied in side an array', function () {
(function () { expect(function () {
Log.parseLevels(['error', 'INVALID']); Log.parseLevels(['error', 'INVALID']);
}).should.throw(/invalid logging level/); }).to.throwError(/invalid logging level/);
}); });
}); });
@ -42,7 +43,7 @@ describe('Log class', function () {
}); });
it('returns the newly created logger', function () { it('returns the newly created logger', function () {
log.addOutput({ type: 'stub' }).should.be.an.instanceOf(Log.loggers.stub); expect(log.addOutput({ type: 'stub' })).to.be.a(Log.loggers.stub);
}); });
it('Accepts a config object with `level: "{{level}}"`', function () { it('Accepts a config object with `level: "{{level}}"`', function () {
@ -51,11 +52,9 @@ describe('Log class', function () {
level: 'warning' level: 'warning'
}); });
logger.config.should.include({ expect(logger.config.levels).to.eql([
levels: [ 'error', 'warning'
'error', 'warning' ]);
]
});
}); });
it('Accepts a config object with `level: ["{{level}}"]`', function () { it('Accepts a config object with `level: ["{{level}}"]`', function () {
@ -64,11 +63,9 @@ describe('Log class', function () {
level: ['warning'] level: ['warning']
}); });
logger.config.should.include({ expect(logger.config.levels).to.eql([
levels: [ 'warning'
'warning' ]);
]
});
}); });
@ -78,11 +75,9 @@ describe('Log class', function () {
levels: 'warning' levels: 'warning'
}); });
logger.config.should.include({ expect(logger.config.levels).to.eql([
levels: [ 'error', 'warning'
'error', 'warning' ]);
]
});
}); });
it('Accepts a config object with `levels: ["{{level}}"]`', function () { it('Accepts a config object with `levels: ["{{level}}"]`', function () {
@ -91,20 +86,18 @@ describe('Log class', function () {
level: ['warning'] level: ['warning']
}); });
logger.config.should.include({ expect(logger.config.levels).to.eql([
levels: [ 'warning'
'warning' ]);
]
});
}); });
}); });
describe('#join', function () { describe('#join', function () {
it('joins strings together with spaces', function () { it('joins strings together with spaces', function () {
Log.join(['foo', 'bar']).should.eql('foo bar'); expect(Log.join(['foo', 'bar'])).to.eql('foo bar');
}); });
it('stringifies objects', function () { it('stringifies objects', function () {
Log.join([{ foo: 'bar' }]).should.eql('{ foo: \'bar\' }\n'); expect(Log.join([{ foo: 'bar' }])).to.eql('{ foo: \'bar\' }\n');
}); });
}); });
@ -157,103 +150,103 @@ describe('Log class', function () {
it('should emit an "error" event with an Error object arg', function () { it('should emit an "error" event with an Error object arg', function () {
var err = new Error('error'); var err = new Error('error');
log.error(err); log.error(err);
call.event.should.eql('error'); expect(call.event).to.eql('error');
call.args[0].should.be.exactly(err); expect(call.args[0]).to.be(err);
call = void 0; call = void 0;
log.error('error'); log.error('error');
call.event.should.eql('error'); expect(call.event).to.eql('error');
call.args[0].should.be.an.instanceOf(Error); expect(call.args[0]).to.be.a(Error);
call.args[0].message.should.eql('error'); expect(call.args[0].message).to.eql('error');
}); });
it('should emit a "warning" event with a single message arg for #warning calls', function () { it('should emit a "warning" event with a single message arg for #warning calls', function () {
log.warning('shit!'); log.warning('shit!');
call.event.should.eql('warning'); expect(call.event).to.eql('warning');
call.args.should.have.length(1); expect(call.args.length).to.be(1);
call.args[0].should.eql('shit!'); expect(call.args[0]).to.eql('shit!');
}); });
it('should emit a "info" event with a single message arg for #info calls', function () { it('should emit a "info" event with a single message arg for #info calls', function () {
log.info('look out!'); log.info('look out!');
call.event.should.eql('info'); expect(call.event).to.eql('info');
call.args.should.have.length(1); expect(call.args.length).to.be(1);
call.args[0].should.eql('look out!'); expect(call.args[0]).to.eql('look out!');
}); });
it('should emit a "debug" event with a single message arg for #debug calls', function () { it('should emit a "debug" event with a single message arg for #debug calls', function () {
log.debug('here'); log.debug('here');
call.event.should.eql('debug'); expect(call.event).to.eql('debug');
call.args.should.have.length(1); expect(call.args.length).to.be(1);
call.args[0].should.eql('here'); expect(call.args[0]).to.eql('here');
}); });
it('should emit a trace event for trace events, with message and curlCall args', function () { it('should emit a trace event for trace events, with message and curlCall args', function () {
log.trace('GET', 'http://localhost:9200/_cluster/nodes', '', '', 200); log.trace('GET', 'http://localhost:9200/_cluster/nodes', '', '', 200);
call.event.should.eql('trace'); expect(call.event).to.eql('trace');
call.args.should.have.length(2); expect(call.args.length).to.be(2);
call.args[0].should.match(/^<- 200/); expect(call.args[0]).to.match(/^<- 200/);
call.args[1].should.match(/^curl /); expect(call.args[1]).to.match(/^curl /);
}); });
}); });
describe('constructor', function () { describe('constructor', function () {
it('looks for output config options at config.log', function () { it('looks for output config options at config.log', function () {
var log = new Log({ log: { type: process.browser ? 'console' : 'stdio', level: 'error' } }); var log = new Log({ log: { type: process.browser ? 'console' : 'stdio', level: 'error' } });
log.listenerCount('error').should.eql(1); expect(log.listenerCount('error')).to.eql(1);
log.listenerCount('warning').should.eql(0); expect(log.listenerCount('warning')).to.eql(0);
log.listenerCount('info').should.eql(0); expect(log.listenerCount('info')).to.eql(0);
log.listenerCount('debug').should.eql(0); expect(log.listenerCount('debug')).to.eql(0);
log.listenerCount('trace').should.eql(0); expect(log.listenerCount('trace')).to.eql(0);
}); });
it('accepts a string and treat it as a log level', function () { it('accepts a string and treat it as a log level', function () {
var log = new Log({ log: 'error' }); var log = new Log({ log: 'error' });
log.listenerCount('error').should.eql(1); expect(log.listenerCount('error')).to.eql(1);
log.listenerCount('warning').should.eql(0); expect(log.listenerCount('warning')).to.eql(0);
log.listenerCount('info').should.eql(0); expect(log.listenerCount('info')).to.eql(0);
log.listenerCount('debug').should.eql(0); expect(log.listenerCount('debug')).to.eql(0);
log.listenerCount('trace').should.eql(0); expect(log.listenerCount('trace')).to.eql(0);
}); });
it('accepts an array of strings and treat it as a log level config', function () { it('accepts an array of strings and treat it as a log level config', function () {
var log = new Log({ log: ['error', 'trace'] }); var log = new Log({ log: ['error', 'trace'] });
log.listenerCount('error').should.eql(1); expect(log.listenerCount('error')).to.eql(1);
log.listenerCount('warning').should.eql(0); expect(log.listenerCount('warning')).to.eql(0);
log.listenerCount('info').should.eql(0); expect(log.listenerCount('info')).to.eql(0);
log.listenerCount('debug').should.eql(0); expect(log.listenerCount('debug')).to.eql(0);
log.listenerCount('trace').should.eql(1); expect(log.listenerCount('trace')).to.eql(1);
}); });
it('accepts an array of output config objects', function () { it('accepts an array of output config objects', function () {
var log = new Log({ log: [{ level: 'error' }, { level: 'trace'}] }); var log = new Log({ log: [{ level: 'error' }, { level: 'trace'}] });
log.listenerCount('error').should.eql(2); expect(log.listenerCount('error')).to.eql(2);
log.listenerCount('warning').should.eql(1); expect(log.listenerCount('warning')).to.eql(1);
log.listenerCount('info').should.eql(1); expect(log.listenerCount('info')).to.eql(1);
log.listenerCount('debug').should.eql(1); expect(log.listenerCount('debug')).to.eql(1);
log.listenerCount('trace').should.eql(1); expect(log.listenerCount('trace')).to.eql(1);
}); });
it('rejects numbers and other truthy data-types', function () { it('rejects numbers and other truthy data-types', function () {
(function () { expect(function () {
var log = new Log({ log: 1515 }); var log = new Log({ log: 1515 });
}).should.throw(/invalid logging output config/i); }).to.throwError(/invalid logging output config/i);
(function () { expect(function () {
var log = new Log({ log: /regexp/ }); var log = new Log({ log: /regexp/ });
}).should.throw(/invalid logging output config/i); }).to.throwError(/invalid logging output config/i);
(function () { expect(function () {
var log = new Log({ log: new Date() }); var log = new Log({ log: new Date() });
}).should.throw(/invalid logging output config/i); }).to.throwError(/invalid logging output config/i);
(function () { expect(function () {
var log = new Log({ log: [1515] }); var log = new Log({ log: [1515] });
}).should.throw(/invalid logging output config/i); }).to.throwError(/invalid logging output config/i);
(function () { expect(function () {
var log = new Log({ log: [/regexp/] }); var log = new Log({ log: [/regexp/] });
}).should.throw(/invalid logging output config/i); }).to.throwError(/invalid logging output config/i);
(function () { expect(function () {
var log = new Log({ log: [new Date()] }); var log = new Log({ log: [new Date()] });
}).should.throw(/invalid logging output config/i); }).to.throwError(/invalid logging output config/i);
}); });
}); });
}); });

View File

@ -1,13 +1,14 @@
describe('Nodes to host callback', function () { describe('Nodes to host callback', function () {
var callback = require('../../src/lib/nodes_to_host'); var callback = require('../../src/lib/nodes_to_host');
var expect = require('expect.js');
// example node list that would come back from "GET _cluster/nodes" // example node list that would come back from "GET _cluster/nodes"
var nodes = require('../fixtures/short_node_list.json'); var nodes = require('../fixtures/short_node_list.json');
it('properly creates host objects', function () { it('properly creates host objects', function () {
var hosts = callback(nodes); var hosts = callback(nodes);
hosts.should.have.lengthOf(2); expect(hosts.length).to.be(2);
hosts[0].should.eql({ expect(hosts[0]).to.eql({
host: '10.10.10.100', host: '10.10.10.100',
port: 9205, port: 9205,
_meta: { _meta: {
@ -17,7 +18,7 @@ describe('Nodes to host callback', function () {
version: '0.90.5' version: '0.90.5'
} }
}); });
hosts[1].should.eql({ expect(hosts[1]).to.eql({
host: '10.10.10.101', host: '10.10.10.101',
port: 9205, port: 9205,
_meta: { _meta: {

View File

@ -1,7 +1,8 @@
var randomSelector = require('../../src/lib/selectors/random');
var _ = require('lodash');
describe('Random Selector', function () { describe('Random Selector', function () {
var randomSelector = require('../../src/lib/selectors/random');
var _ = require('lodash');
var expect = require('expect.js');
it('chooses a selection by random', function () { it('chooses a selection by random', function () {
var log = { a: 0, b: 0, c: 0 }; var log = { a: 0, b: 0, c: 0 };
var choices = _.keys(log); var choices = _.keys(log);
@ -11,9 +12,9 @@ describe('Random Selector', function () {
log[choice]++; log[choice]++;
}); });
_.filter(log, function (count) { expect(_.filter(log, function (count) {
return count < 200 || count > 400; return count < 200 || count > 400;
}).should.have.length(0); })).to.have.length(0);
}); });
}); });

View File

@ -1,7 +1,8 @@
var selector = require('../../src/lib/selectors/round_robin');
var _ = require('lodash');
describe('Round Robin Selector', function () { describe('Round Robin Selector', function () {
var selector = require('../../src/lib/selectors/round_robin');
var _ = require('lodash');
var expect = require('expect.js');
it('chooses options in order', function () { it('chooses options in order', function () {
var options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; var options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
var expected = _.clone(options); var expected = _.clone(options);
@ -11,6 +12,6 @@ describe('Round Robin Selector', function () {
selections.push(selector(options)); selections.push(selector(options));
}); });
selections.should.eql(expected); expect(selections).to.eql(expected);
}); });
}); });

View File

@ -1,28 +1,29 @@
var Log = require('../../src/lib/log');
var StdioLogger = require('../../src/lib/loggers/stdio');
var sinon = require('sinon');
var parentLog;
beforeEach(function () {
parentLog = new Log();
});
afterEach(function () {
parentLog.close();
});
function makeLogger(parent, levels) {
parent = parent || parentLog;
var config = {
levels: Log.parseLevels(levels || 'trace')
};
return new StdioLogger(parent, config);
}
var stub = require('./auto_release_stub').make();
describe('Stdio Logger', function () { describe('Stdio Logger', function () {
var Log = require('../../src/lib/log');
var StdioLogger = require('../../src/lib/loggers/stdio');
var expect = require('expect.js');
var sinon = require('sinon');
var parentLog;
beforeEach(function () {
parentLog = new Log();
});
afterEach(function () {
parentLog.close();
});
function makeLogger(parent, levels) {
parent = parent || parentLog;
var config = {
levels: Log.parseLevels(levels || 'trace')
};
return new StdioLogger(parent, config);
}
var stub = require('./auto_release_stub').make();
require('./generic_logger_tests')(makeLogger); require('./generic_logger_tests')(makeLogger);
describe('colorizing', function () { describe('colorizing', function () {
@ -39,7 +40,7 @@ describe('Stdio Logger', function () {
it('uses colors when it\'s supported', function () { it('uses colors when it\'s supported', function () {
var logger = makeLogger(); var logger = makeLogger();
var hasColor = require('chalk').supportsColor; var hasColor = require('chalk').supportsColor;
logger.color.should.be.exactly(hasColor); expect(logger.color).to.be(hasColor);
}); });
it('obeys the logger.color === false', function () { it('obeys the logger.color === false', function () {
@ -49,7 +50,7 @@ describe('Stdio Logger', function () {
logger.color = false; logger.color = false;
logger.onInfo('something'); logger.onInfo('something');
process.stdout.write.lastCall.args[0].should.eql(withoutColor); expect(process.stdout.write.lastCall.args[0]).to.eql(withoutColor);
}); });
it('obeys the logger.color === true', function () { it('obeys the logger.color === true', function () {
@ -60,8 +61,8 @@ describe('Stdio Logger', function () {
logger.color = true; logger.color = true;
logger.onTrace('msg', 'curl'); logger.onTrace('msg', 'curl');
process.stdout.write.lastCall.args[0].should.not.eql(withoutColor); expect(process.stdout.write.lastCall.args[0]).to.not.eql(withoutColor);
chalk.stripColor(process.stdout.write.lastCall.args[0]).should.eql(withoutColor); expect(chalk.stripColor(process.stdout.write.lastCall.args[0])).to.eql(withoutColor);
}); });
}); });

View File

@ -1,39 +1,40 @@
var Log = require('../../src/lib/log');
var StreamLogger = require('../../src/lib/loggers/stream');
var MockWritableStream = require('../mocks/writable_stream');
var once = require('events').EventEmitter.prototype.once;
var stream = new MockWritableStream();
var _ = require('lodash');
var parentLog;
var stub = require('./auto_release_stub').make();
beforeEach(function () {
stub(stream, 'write');
stub(stream, 'end');
parentLog = new Log();
});
afterEach(function () {
parentLog.close();
if (stream._writableState && stream._writableState.buffer.length) {
// empty the buffer manually
stream._writableState.buffer.splice(0);
}
});
function makeLogger(parent, levels) {
parent = parent || parentLog;
var config = {
levels: Log.parseLevels(levels || 'trace'),
stream: stream
};
return new StreamLogger(parent, config);
}
describe('Stream Logger', function () { describe('Stream Logger', function () {
var Log = require('../../src/lib/log');
var StreamLogger = require('../../src/lib/loggers/stream');
var MockWritableStream = require('../mocks/writable_stream');
var once = require('events').EventEmitter.prototype.once;
var stream = new MockWritableStream();
var _ = require('lodash');
var expect = require('expect.js');
var parentLog;
var stub = require('./auto_release_stub').make();
beforeEach(function () {
stub(stream, 'write');
stub(stream, 'end');
parentLog = new Log();
});
afterEach(function () {
parentLog.close();
if (stream._writableState && stream._writableState.buffer.length) {
// empty the buffer manually
stream._writableState.buffer.splice(0);
}
});
function makeLogger(parent, levels) {
parent = parent || parentLog;
var config = {
levels: Log.parseLevels(levels || 'trace'),
stream: stream
};
return new StreamLogger(parent, config);
}
require('./generic_logger_tests')(makeLogger); require('./generic_logger_tests')(makeLogger);
describe('buffer flush', function () { describe('buffer flush', function () {
@ -67,8 +68,8 @@ describe('Stream Logger', function () {
console.error.restore(); console.error.restore();
// the first line is sent immediately to _write and there is nothing we are not going to worry about it // the first line is sent immediately to _write and there is nothing we are not going to worry about it
flushedOutput.should.match(new RegExp(line)); expect(flushedOutput).to.match(new RegExp(line));
flushedOutput.match(new RegExp(line, 'g')).length.should.eql(9); expect(flushedOutput.match(new RegExp(line, 'g'))).to.have.length(9);
}); });
} else { } else {
it('does not fall apart with non streams2 streams', function () { it('does not fall apart with non streams2 streams', function () {
@ -82,10 +83,10 @@ describe('Stream Logger', function () {
var logger = makeLogger(); var logger = makeLogger();
(function () { expect(function () {
// call the event handler // call the event handler
exitHandler.call(process); exitHandler.call(process);
}).should.not.throw(); }).to.not.throw();
}); });
} }
}); });

View File

@ -1,28 +1,30 @@
var Log = require('../../src/lib/log');
var TracerLogger = require('../../src/lib/loggers/tracer');
var sinon = require('sinon');
var parentLog;
beforeEach(function () {
parentLog = new Log();
});
afterEach(function () {
parentLog.close();
});
function makeLogger(parent, levels) {
parent = parent || parentLog;
var config = {
levels: Log.parseLevels(levels || 'trace')
};
return new TracerLogger(parent, config);
}
var stub = require('./auto_release_stub').make();
describe('Tracer Logger', function () { describe('Tracer Logger', function () {
var Log = require('../../src/lib/log');
var TracerLogger = require('../../src/lib/loggers/tracer');
var sinon = require('sinon');
var expect = require('expect.js');
var parentLog;
beforeEach(function () {
parentLog = new Log();
});
afterEach(function () {
parentLog.close();
});
function makeLogger(parent, levels) {
parent = parent || parentLog;
var config = {
levels: Log.parseLevels(levels || 'trace')
};
return new TracerLogger(parent, config);
}
var stub = require('./auto_release_stub').make();
require('./generic_logger_tests')(makeLogger); require('./generic_logger_tests')(makeLogger);
describe('#write', function () { describe('#write', function () {
@ -30,12 +32,12 @@ describe('Tracer Logger', function () {
var logger = makeLogger(); var logger = makeLogger();
stub(logger.stream, 'write', function (string) { stub(logger.stream, 'write', function (string) {
string.replace(/(^#.*$|^curlcall$)/mg, '').trim().should.be.exactly(''); expect(string.replace(/(^#.*$|^curlcall$)/mg, '').trim()).to.be('');
}); });
logger.onTrace('message', 'curlcall'); logger.onTrace('message', 'curlcall');
logger.stream.write.callCount.should.eql(1); expect(logger.stream.write.callCount).to.eql(1);
}); });
}); });
}); });

View File

@ -4,7 +4,7 @@ var errors = require('../../src/lib/errors');
var when = require('when'); var when = require('when');
var sinon = require('sinon'); var sinon = require('sinon');
var should = require('should'); var expect = require('expect.js');
var _ = require('lodash'); var _ = require('lodash');
var nodeList = require('../fixtures/short_node_list.json'); var nodeList = require('../fixtures/short_node_list.json');
var stub = require('./auto_release_stub').make(); var stub = require('./auto_release_stub').make();
@ -33,7 +33,7 @@ describe('Transport Class', function () {
log: CustomLogClass log: CustomLogClass
}); });
trans.log.should.be.an.instanceOf(CustomLogClass); expect(trans.log).to.be.a(CustomLogClass);
}); });
it('Accepts a connection pool class and intanciates it at this.connectionPool', function () { it('Accepts a connection pool class and intanciates it at this.connectionPool', function () {
@ -42,7 +42,7 @@ describe('Transport Class', function () {
connectionPool: CustomConnectionPool connectionPool: CustomConnectionPool
}); });
trans.connectionPool.should.be.an.instanceOf(CustomConnectionPool); expect(trans.connectionPool).to.be.a(CustomConnectionPool);
}); });
it('Accepts the name of a connectionPool class that is defined on Transport.connectionPools', function () { it('Accepts the name of a connectionPool class that is defined on Transport.connectionPools', function () {
@ -52,16 +52,16 @@ describe('Transport Class', function () {
connectionPool: 'custom' connectionPool: 'custom'
}); });
trans.connectionPool.should.be.an.instanceOf(Transport.connectionPools.custom); expect(trans.connectionPool).to.be.a(Transport.connectionPools.custom);
delete Transport.connectionPools.custom; delete Transport.connectionPools.custom;
}); });
it('Throws an error when connectionPool config is set wrong', function () { it('Throws an error when connectionPool config is set wrong', function () {
(function () { expect(function () {
var trans = new Transport({ var trans = new Transport({
connectionPool: 'pasta' connectionPool: 'pasta'
}); });
}).should.throw(/invalid connectionpool/i); }).to.throwError(/invalid connectionpool/i);
}); });
it('calls sniff immediately if sniffOnStart is true', function () { it('calls sniff immediately if sniffOnStart is true', function () {
@ -70,7 +70,7 @@ describe('Transport Class', function () {
sniffOnStart: true sniffOnStart: true
}); });
trans.sniff.callCount.should.eql(1); expect(trans.sniff.callCount).to.eql(1);
}); });
it('schedules a sniff when sniffInterval is set', function () { it('schedules a sniff when sniffInterval is set', function () {
@ -81,34 +81,34 @@ describe('Transport Class', function () {
sniffInterval: 25000 sniffInterval: 25000
}); });
_.size(clock.timeouts).should.eql(1); expect(_.size(clock.timeouts)).to.eql(1);
var id = _.keys(clock.timeouts).pop(); var id = _.keys(clock.timeouts).pop();
clock.tick(25000); clock.tick(25000);
trans.sniff.callCount.should.eql(1); expect(trans.sniff.callCount).to.eql(1);
_.size(clock.timeouts).should.eql(1); expect(_.size(clock.timeouts)).to.eql(1);
_.keys(clock.timeouts).pop().should.not.eql(id); expect(clock.timeouts).to.not.have.key(id);
clock.restore(); clock.restore();
}); });
describe('host config', function () { describe('host config', function () {
it('rejects non-strings/objects', function () { it('rejects non-strings/objects', function () {
(function () { expect(function () {
var trans = new Transport({ var trans = new Transport({
host: [ host: [
'localhost', 'localhost',
9393 9393
] ]
}); });
}).should.throw(TypeError); }).to.throwError(TypeError);
(function () { expect(function () {
var trans = new Transport({ var trans = new Transport({
host: [ host: [
[9292] [9292]
] ]
}); });
}).should.throw(TypeError); }).to.throwError(TypeError);
}); });
it('accepts the config value on the host: key', function () { it('accepts the config value on the host: key', function () {
@ -117,8 +117,8 @@ describe('Transport Class', function () {
host: 'localhost' host: 'localhost'
}); });
trans.connectionPool.setHosts.callCount.should.eql(1); expect(trans.connectionPool.setHosts.callCount).to.eql(1);
trans.connectionPool.setHosts.lastCall.args[0].should.eql([ expect(trans.connectionPool.setHosts.lastCall.args[0]).to.eql([
new Host('localhost') new Host('localhost')
]); ]);
}); });
@ -129,8 +129,8 @@ describe('Transport Class', function () {
hosts: 'localhost' hosts: 'localhost'
}); });
trans.connectionPool.setHosts.callCount.should.eql(1); expect(trans.connectionPool.setHosts.callCount).to.eql(1);
trans.connectionPool.setHosts.lastCall.args[0].should.eql([ expect(trans.connectionPool.setHosts.lastCall.args[0]).to.eql([
new Host('localhost') new Host('localhost')
]); ]);
}); });
@ -142,8 +142,8 @@ describe('Transport Class', function () {
host: h host: h
}); });
trans.connectionPool.setHosts.callCount.should.eql(1); expect(trans.connectionPool.setHosts.callCount).to.eql(1);
trans.connectionPool.setHosts.lastCall.args[0][0].should.be.exactly(h); expect(trans.connectionPool.setHosts.lastCall.args[0][0]).to.be(h);
}); });
it('accepts strings as the config', function () { it('accepts strings as the config', function () {
@ -154,8 +154,8 @@ describe('Transport Class', function () {
] ]
}); });
trans.connectionPool.setHosts.callCount.should.eql(1); expect(trans.connectionPool.setHosts.callCount).to.eql(1);
trans.connectionPool.setHosts.lastCall.args[0].should.eql([ expect(trans.connectionPool.setHosts.lastCall.args[0]).to.eql([
new Host({ new Host({
host: 'localhost', host: 'localhost',
port: 8888 port: 8888
@ -179,8 +179,8 @@ describe('Transport Class', function () {
] ]
}); });
trans.connectionPool.setHosts.callCount.should.eql(1); expect(trans.connectionPool.setHosts.callCount).to.eql(1);
trans.connectionPool.setHosts.lastCall.args[0].should.eql([ expect(trans.connectionPool.setHosts.lastCall.args[0]).to.eql([
new Host('https://myescluster.com:777/bon/iver?access=all') new Host('https://myescluster.com:777/bon/iver?access=all')
]); ]);
}); });
@ -195,7 +195,7 @@ describe('Transport Class', function () {
hosts: 'localhost' hosts: 'localhost'
}); });
_.shuffle.callCount.should.eql(1); expect(_.shuffle.callCount).to.eql(1);
}); });
it('skips the call to _.shuffle when false', function () { it('skips the call to _.shuffle when false', function () {
var _ = require('../../src/lib/utils'); var _ = require('../../src/lib/utils');
@ -206,14 +206,14 @@ describe('Transport Class', function () {
randomizeHosts: false randomizeHosts: false
}); });
_.shuffle.callCount.should.eql(0); expect(_.shuffle.callCount).to.eql(0);
}); });
}); });
}); });
describe('#defer', function () { describe('#defer', function () {
it('returns a when.js promise by default', function () { it('returns a when.js promise by default', function () {
Transport.prototype.defer().constructor.should.be.exactly(when.defer().constructor); expect(Transport.prototype.defer().constructor).to.be(when.defer().constructor);
}); });
}); });
@ -239,13 +239,13 @@ describe('Transport Class', function () {
it('works without a callback', function (done) { it('works without a callback', function (done) {
trans.sniff(); trans.sniff();
setTimeout(function () { setTimeout(function () {
trans.request.callCount.should.eql(1); expect(trans.request.callCount).to.eql(1);
done(); done();
}, 5); }, 5);
}); });
it('calls the nodesToHostCallback with the list of nodes', function (done) { it('calls the nodesToHostCallback with the list of nodes', function (done) {
trans.nodesToHostCallback = function (nodes) { trans.nodesToHostCallback = function (nodes) {
nodes.should.eql(nodeList); expect(nodes).to.eql(nodeList);
done(); done();
return []; return [];
}; };
@ -254,18 +254,18 @@ describe('Transport Class', function () {
it('takes the host configs, converts them into Host objects, and passes them to connectionPool.setHosts', it('takes the host configs, converts them into Host objects, and passes them to connectionPool.setHosts',
function (done) { function (done) {
trans.sniff(function () { trans.sniff(function () {
trans.connectionPool.setHosts.callCount.should.eql(1); expect(trans.connectionPool.setHosts.callCount).to.eql(1);
var hosts = trans.connectionPool.setHosts.lastCall.args[0]; var hosts = trans.connectionPool.setHosts.lastCall.args[0];
hosts.should.have.length(2); expect(hosts).to.have.length(2);
hosts[0].should.be.an.instanceOf(Host); expect(hosts[0]).to.be.a(Host);
hosts[0].host.should.eql('10.10.10.100'); expect(hosts[0].host).to.eql('10.10.10.100');
hosts[0].port.should.eql(9205); expect(hosts[0].port).to.eql(9205);
hosts[0].should.be.an.instanceOf(Host); expect(hosts[0]).to.be.a(Host);
hosts[1].host.should.eql('10.10.10.101'); expect(hosts[1].host).to.eql('10.10.10.101');
hosts[1].port.should.eql(9205); expect(hosts[1].port).to.eql(9205);
done(); done();
}); });
}); });
@ -277,22 +277,20 @@ describe('Transport Class', function () {
}; };
trans.sniff(function (err) { trans.sniff(function (err) {
err.message.should.eql('something funked up'); expect(err.message).to.eql('something funked up');
done(); done();
}); });
}); });
it('passed back the full server response', function (done) { it('passed back the full server response', function (done) {
trans.sniff(function (err, resp, status) { trans.sniff(function (err, resp, status) {
resp.should.include({ expect(resp.ok).to.eql(true);
ok: true, expect(resp.cluster_name).to.eql('clustername');
cluster_name: 'clustername'
});
done(); done();
}); });
}); });
it('passed back the server response code', function (done) { it('passed back the server response code', function (done) {
trans.sniff(function (err, resp, status) { trans.sniff(function (err, resp, status) {
status.should.eql(200); expect(status).to.eql(200);
done(); done();
}); });
}); });
@ -308,7 +306,7 @@ describe('Transport Class', function () {
}); });
trans.request({}, function () { trans.request({}, function () {
trans.log.debug.callCount.should.eql(1); expect(trans.log.debug.callCount).to.eql(1);
done(); done();
}); });
}); });
@ -323,9 +321,8 @@ describe('Transport Class', function () {
body: 'JSON!!', body: 'JSON!!',
method: 'GET' method: 'GET'
}, function (err) { }, function (err) {
should.exist(err); expect(err).to.be.a(TypeError);
err.should.be.an.instanceOf(TypeError); expect(err.message).to.match(/body.*method.*get/i);
err.message.should.match(/body.*method.*get/i);
done(); done();
}); });
}); });
@ -342,7 +339,7 @@ describe('Transport Class', function () {
}; };
stub(conn, 'request', function (params) { stub(conn, 'request', function (params) {
JSON.parse(params.body).should.eql(body); expect(JSON.parse(params.body)).to.eql(body);
done(); done();
}); });
@ -361,7 +358,7 @@ describe('Transport Class', function () {
]; ];
stub(conn, 'request', function (params) { stub(conn, 'request', function (params) {
params.body.should.eql( expect(params.body).to.eql(
'{"_id":"simple body"}\n' + '{"_id":"simple body"}\n' +
'{"name":"ഢധയമബ"}\n' '{"name":"ഢധയമബ"}\n'
); );
@ -386,11 +383,11 @@ describe('Transport Class', function () {
}; };
body.body = body; body.body = body;
(function () { expect(function () {
trans.request({ trans.request({
body: body body: body
}); });
}).should.throw(TypeError); }).to.throwError(TypeError);
}); });
}); });
@ -399,10 +396,10 @@ describe('Transport Class', function () {
var trans = new Transport(); var trans = new Transport();
stub(trans.log, 'warning'); stub(trans.log, 'warning');
trans.request({}, function (err, body, status) { trans.request({}, function (err, body, status) {
trans.log.warning.callCount.should.eql(1); expect(trans.log.warning.callCount).to.eql(1);
err.should.be.an.instanceOf(errors.NoConnections); expect(err).to.be.a(errors.NoConnections);
should.not.exist(body); expect(body).to.be(undefined);
should.not.exist(status); expect(status).to.be(undefined);
done(); done();
}); });
}); });
@ -415,7 +412,7 @@ describe('Transport Class', function () {
}); });
trans.request({}, function (err, body, status) { trans.request({}, function (err, body, status) {
err.message.should.eql('I am broken'); expect(err.message).to.eql('I am broken');
}); });
}); });
it('quits if gets an error from an async selector', function () { it('quits if gets an error from an async selector', function () {
@ -429,7 +426,7 @@ describe('Transport Class', function () {
}); });
trans.request({}, function (err, body, status) { trans.request({}, function (err, body, status) {
err.message.should.eql('I am broken'); expect(err.message).to.eql('I am broken');
}); });
}); });
it('calls connection#request once it gets one', function (done) { it('calls connection#request once it gets one', function (done) {
@ -478,10 +475,10 @@ describe('Transport Class', function () {
}); });
trans.request({}, function (err, resp, body) { trans.request({}, function (err, resp, body) {
attempts.should.eql(retries + 1); expect(attempts).to.eql(retries + 1);
err.should.be.an.instanceOf(errors.ConnectionFault); expect(err).to.be.a(errors.ConnectionFault);
should.not.exist(resp); expect(resp).to.be(undefined);
should.not.exist(body); expect(body).to.be(undefined);
done(); done();
}); });
}; };
@ -497,15 +494,15 @@ describe('Transport Class', function () {
var tran = new Transport(); var tran = new Transport();
shortCircuitRequest(tran); shortCircuitRequest(tran);
var ret = tran.request({}, _.noop); var ret = tran.request({}, _.noop);
ret.should.have.type('object'); expect(ret).to.be.a('object');
ret.abort.should.have.type('function'); expect(ret.abort).to.be.a('function');
}); });
it('the object is a promise when a callback is not suplied', function () { it('the object is a promise when a callback is not suplied', function () {
var tran = new Transport(); var tran = new Transport();
shortCircuitRequest(tran); shortCircuitRequest(tran);
var ret = tran.request({}); var ret = tran.request({});
when.isPromise(ret).should.be.ok; expect(when.isPromise(ret)).to.be(true);
ret.abort.should.have.type('function'); expect(ret.abort).to.be.a('function');
}); });
it('promise is always pulled from the defer created by this.defer()', function () { it('promise is always pulled from the defer created by this.defer()', function () {
var fakePromise = {}; var fakePromise = {};
@ -521,8 +518,8 @@ describe('Transport Class', function () {
shortCircuitRequest(tran); shortCircuitRequest(tran);
var ret = tran.request({}); var ret = tran.request({});
Transport.prototype.defer = origDefer; Transport.prototype.defer = origDefer;
ret.should.be.exactly(fakePromise); expect(ret).to.be(fakePromise);
ret.abort.should.have.type('function'); expect(ret.abort).to.be.a('function');
}); });
}); });
@ -583,9 +580,9 @@ describe('Transport Class', function () {
tran.request({}); tran.request({});
_.size(clock.timeouts).should.eql(1); expect(_.size(clock.timeouts)).to.eql(1);
_.each(clock.timeouts, function (timer, id) { _.each(clock.timeouts, function (timer, id) {
timer.callAt.should.eql(30000); expect(timer.callAt).to.eql(30000);
clearTimeout(id); clearTimeout(id);
}); });
clock.restore(); clock.restore();
@ -599,9 +596,9 @@ describe('Transport Class', function () {
tran.request({}); tran.request({});
_.size(clock.timeouts).should.eql(1); expect(_.size(clock.timeouts)).to.eql(1);
_.each(clock.timeouts, function (timer, id) { _.each(clock.timeouts, function (timer, id) {
timer.callAt.should.eql(5000); expect(timer.callAt).to.eql(5000);
clearTimeout(id); clearTimeout(id);
}); });
clock.restore(); clock.restore();
@ -618,7 +615,7 @@ describe('Transport Class', function () {
requestTimeout: falsy requestTimeout: falsy
}, function (_err) {}); }, function (_err) {});
_.size(clock.timeouts).should.eql(0); expect(_.size(clock.timeouts)).to.eql(0);
clock.restore(); clock.restore();
}); });
}); });
@ -633,8 +630,8 @@ describe('Transport Class', function () {
tran.close(); tran.close();
tran.connectionPool.close.callCount.should.eql(1); expect(tran.connectionPool.close.callCount).to.eql(1);
tran.log.close.callCount.should.eql(1); expect(tran.log.close.callCount).to.eql(1);
}); });
}); });

View File

@ -2,10 +2,10 @@ var Transport = require('../../src/lib/transport');
var Host = require('../../src/lib/host'); var Host = require('../../src/lib/host');
var errors = require('../../src/lib/errors'); var errors = require('../../src/lib/errors');
var when = require('when'); var when = require('when');
var expect = require('expect.js');
var sinon = require('sinon'); var sinon = require('sinon');
var nock = require('../mocks/server.js'); var nock = require('../mocks/server.js');
var should = require('should');
var _ = require('lodash'); var _ = require('lodash');
var nodeList = require('../fixtures/short_node_list.json'); var nodeList = require('../fixtures/short_node_list.json');
var stub = require('./auto_release_stub').make(); var stub = require('./auto_release_stub').make();
@ -86,10 +86,10 @@ describe('Transport + Mock server', function () {
trans.request({ trans.request({
path: '/give-me-400' path: '/give-me-400'
}, function (err, body, status) { }, function (err, body, status) {
err.should.be.an.instanceOf(errors[400]); expect(err).to.be.a(errors[400]);
err.should.be.an.instanceOf(errors.BadRequest); expect(err).to.be.a(errors.BadRequest);
body.should.eql('sorry bub'); expect(body).to.eql('sorry bub');
status.should.eql(400); expect(status).to.eql(400);
done(); done();
}); });
}); });
@ -106,9 +106,9 @@ describe('Transport + Mock server', function () {
path: '/give-me-404', path: '/give-me-404',
castExists: true castExists: true
}, function (err, body, status) { }, function (err, body, status) {
should.not.exist(err); expect(err).to.be(undefined);
body.should.eql(false); expect(body).to.eql(false);
status.should.eql(404); expect(status).to.eql(404);
done(); done();
}); });
}); });
@ -122,10 +122,10 @@ describe('Transport + Mock server', function () {
trans.request({ trans.request({
path: '/give-me-404' path: '/give-me-404'
}, function (err, body, status) { }, function (err, body, status) {
err.should.be.an.instanceOf(errors[404]); expect(err).to.be.a(errors[404]);
err.should.be.an.instanceOf(errors.NotFound); expect(err).to.be.a(errors.NotFound);
body.should.eql('nothing here'); expect(body).to.eql('nothing here');
status.should.eql(404); expect(status).to.eql(404);
done(); done();
}); });
}); });
@ -141,10 +141,10 @@ describe('Transport + Mock server', function () {
trans.request({ trans.request({
path: '/give-me-500' path: '/give-me-500'
}, function (err, body, status) { }, function (err, body, status) {
err.should.be.an.instanceOf(errors[500]); expect(err).to.be.a(errors[500]);
err.should.be.an.instanceOf(errors.InternalServerError); expect(err).to.be.a(errors.InternalServerError);
body.should.eql('ah shit'); expect(body).to.eql('ah shit');
status.should.eql(500); expect(status).to.eql(500);
done(); done();
}); });
}); });
@ -159,9 +159,9 @@ describe('Transport + Mock server', function () {
trans.request({ trans.request({
path: '/huh?' path: '/huh?'
}, function (err, body, status) { }, function (err, body, status) {
err.should.be.an.instanceOf(errors.Generic); expect(err).to.be.a(errors.Generic);
body.should.eql('boo'); expect(body).to.eql('boo');
status.should.eql(530); expect(status).to.eql(530);
done(); done();
}); });
}); });
@ -178,9 +178,9 @@ describe('Transport + Mock server', function () {
path: '/exists?', path: '/exists?',
castExists: true castExists: true
}, function (err, body, status) { }, function (err, body, status) {
should.not.exist(err); expect(err).to.be(undefined);
body.should.eql(true); expect(body).to.eql(true);
status.should.eql(200); expect(status).to.eql(200);
done(); done();
}); });
}); });
@ -194,9 +194,9 @@ describe('Transport + Mock server', function () {
trans.request({ trans.request({
path: '/give-me-someth', path: '/give-me-someth',
}, function (err, body, status) { }, function (err, body, status) {
err.should.be.an.instanceOf(errors.Serialization); expect(err).to.be.a(errors.Serialization);
body.should.eql('{"not":"valid'); expect(body).to.eql('{"not":"valid');
status.should.eql(200); expect(status).to.eql(200);
done(); done();
}); });
}); });
@ -210,8 +210,8 @@ describe('Transport + Mock server', function () {
trans.request({ trans.request({
path: '/', path: '/',
}, function (err, body, status) { }, function (err, body, status) {
should.not.exist(err); expect(err).to.be(undefined);
body.should.eql({ expect(body).to.eql({
'the answer': 42 'the answer': 42
}); });
done(); done();
@ -229,8 +229,8 @@ describe('Transport + Mock server', function () {
trans.request({ trans.request({
path: '/hottie-threads', path: '/hottie-threads',
}, function (err, body, status) { }, function (err, body, status) {
should.not.exist(err); expect(err).to.be(undefined);
body.should.match(/s?he said/g); expect(body).to.match(/s?he said/g);
done(); done();
}); });
}); });
@ -250,7 +250,7 @@ describe('Transport + Mock server', function () {
}); });
tran.request({}).then(function (resp) { tran.request({}).then(function (resp) {
resp.should.eql({ expect(resp).to.eql({
good: 'day' good: 'day'
}); });
done(); done();
@ -272,10 +272,10 @@ describe('Transport + Mock server', function () {
}); });
tran.request({}, function (err, resp, status) { tran.request({}, function (err, resp, status) {
should.not.exist(err); expect(err).to.be(undefined);
resp.should.eql({ i: 'am here' }); expect(resp).to.eql({ i: 'am here' });
status.should.eql(200); expect(status).to.eql(200);
Object.keys(clock.timeouts).should.have.length(0); expect(_.keys(clock.timeouts)).to.have.length(0);
clock.restore(); clock.restore();
}); });
}); });
@ -296,8 +296,8 @@ describe('Transport + Mock server', function () {
tran.request({ tran.request({
requestTimeout: 25 requestTimeout: 25
}, function (err, resp, status) { }, function (err, resp, status) {
err.should.be.an.instanceOf(errors.RequestTimeout); expect(err).to.be.a(errors.RequestTimeout);
// Object.keys(clock.timeouts).should.have.length(0); // expect(_.keys(clock.timeouts)).to.have.length(0);
// clock.restore(); // clock.restore();
done(); done();
}); });

View File

@ -1,5 +1,5 @@
var _ = require('../../src/lib/utils'); var _ = require('../../src/lib/utils');
var should = require('should'); var expect = require('expect.js');
var stub = require('./auto_release_stub').make(); var stub = require('./auto_release_stub').make();
@ -34,61 +34,61 @@ describe('Utils', function () {
function (thing, name) { function (thing, name) {
describe('#isArrayOf' + name, function (test) { describe('#isArrayOf' + name, function (test) {
it('likes arrays of ' + name, function () { it('likes arrays of ' + name, function () {
should(_['isArrayOf' + name + 's'](thing.is)).be.ok; expect(_['isArrayOf' + name + 's'](thing.is)).to.be(true);
}); });
it('dislikes when there is even one non ' + name, function () { it('dislikes when there is even one non ' + name, function () {
// notice a string in the array // notice a string in the array
thing.is.push(thing.not || ' not '); thing.is.push(thing.not || ' not ');
should(_['isArrayOf' + name + 's'](thing.is)).not.be.ok; expect(_['isArrayOf' + name + 's'](thing.is)).to.be(false);
}); });
}); });
}); });
describe('#isNumeric', function () { describe('#isNumeric', function () {
it('likes integer literals', function () { it('likes integer literals', function () {
should(_.isNumeric('-10')).be.ok; expect(_.isNumeric('-10')).to.be(true);
should(_.isNumeric('0')).be.ok; expect(_.isNumeric('0')).to.be(true);
should(_.isNumeric('5')).be.ok; expect(_.isNumeric('5')).to.be(true);
should(_.isNumeric(-16)).be.ok; expect(_.isNumeric(-16)).to.be(true);
should(_.isNumeric(0)).be.ok; expect(_.isNumeric(0)).to.be(true);
should(_.isNumeric(32)).be.ok; expect(_.isNumeric(32)).to.be(true);
should(_.isNumeric('040')).be.ok; expect(_.isNumeric('040')).to.be(true);
should(_.isNumeric(0144)).be.ok; expect(_.isNumeric(0144)).to.be(true);
should(_.isNumeric('0xFF')).be.ok; expect(_.isNumeric('0xFF')).to.be(true);
should(_.isNumeric(0xFFF)).be.ok; expect(_.isNumeric(0xFFF)).to.be(true);
}); });
it('likes float literals', function () { it('likes float literals', function () {
should(_.isNumeric('-1.6')).be.ok; expect(_.isNumeric('-1.6')).to.be(true);
should(_.isNumeric('4.536')).be.ok; expect(_.isNumeric('4.536')).to.be(true);
should(_.isNumeric(-2.6)).be.ok; expect(_.isNumeric(-2.6)).to.be(true);
should(_.isNumeric(3.1415)).be.ok; expect(_.isNumeric(3.1415)).to.be(true);
should(_.isNumeric(8e5)).be.ok; expect(_.isNumeric(8e5)).to.be(true);
should(_.isNumeric('123e-2')).be.ok; expect(_.isNumeric('123e-2')).to.be(true);
}); });
it('dislikes non-numeric stuff', function () { it('dislikes non-numeric stuff', function () {
should(_.isNumeric('')).not.be.ok; expect(_.isNumeric('')).to.be(false);
should(_.isNumeric(' ')).not.be.ok; expect(_.isNumeric(' ')).to.be(false);
should(_.isNumeric('\t\t')).not.be.ok; expect(_.isNumeric('\t\t')).to.be(false);
should(_.isNumeric('abcdefghijklm1234567890')).not.be.ok; expect(_.isNumeric('abcdefghijklm1234567890')).to.be(false);
should(_.isNumeric('xabcdefx')).not.be.ok; expect(_.isNumeric('xabcdefx')).to.be(false);
should(_.isNumeric(true)).not.be.ok; expect(_.isNumeric(true)).to.be(false);
should(_.isNumeric(false)).not.be.ok; expect(_.isNumeric(false)).to.be(false);
should(_.isNumeric('bcfed5.2')).not.be.ok; expect(_.isNumeric('bcfed5.2')).to.be(false);
should(_.isNumeric('7.2acdgs')).not.be.ok; expect(_.isNumeric('7.2acdgs')).to.be(false);
should(_.isNumeric(undefined)).not.be.ok; expect(_.isNumeric(undefined)).to.be(false);
should(_.isNumeric(null)).not.be.ok; expect(_.isNumeric(null)).to.be(false);
should(_.isNumeric(NaN)).not.be.ok; expect(_.isNumeric(NaN)).to.be(false);
should(_.isNumeric(Infinity)).not.be.ok; expect(_.isNumeric(Infinity)).to.be(false);
should(_.isNumeric(Number.POSITIVE_INFINITY)).not.be.ok; expect(_.isNumeric(Number.POSITIVE_INFINITY)).to.be(false);
should(_.isNumeric(Number.NEGATIVE_INFINITY)).not.be.ok; expect(_.isNumeric(Number.NEGATIVE_INFINITY)).to.be(false);
should(_.isNumeric(new Date(2009, 1, 1))).not.be.ok; expect(_.isNumeric(new Date(2009, 1, 1))).to.be(false);
should(_.isNumeric([])).not.be.ok; expect(_.isNumeric([])).to.be(false);
should(_.isNumeric([1, 2, 3, 4])).not.be.ok; expect(_.isNumeric([1, 2, 3, 4])).to.be(false);
should(_.isNumeric({})).not.be.ok; expect(_.isNumeric({})).to.be(false);
should(_.isNumeric(function () {})).not.be.ok; expect(_.isNumeric(function () {})).to.be(false);
}); });
}); });
@ -105,20 +105,20 @@ describe('Utils', function () {
}, },
function (name, unit) { function (name, unit) {
it('likes ' + name, function () { it('likes ' + name, function () {
should(_.isInterval('1' + unit)).be.ok; expect(_.isInterval('1' + unit)).to.be(true);
}); });
it('likes decimal ' + name, function () { it('likes decimal ' + name, function () {
should(_.isInterval('1.5' + unit)).be.ok; expect(_.isInterval('1.5' + unit)).to.be(true);
}); });
}); });
it('dislikes more than one unit', function () { it('dislikes more than one unit', function () {
should(_.isInterval('1my')).not.be.ok; expect(_.isInterval('1my')).to.be(false);
}); });
it('dislikes spaces', function () { it('dislikes spaces', function () {
should(_.isInterval('1 m')).not.be.ok; expect(_.isInterval('1 m')).to.be(false);
}); });
}); });
}); });
@ -128,96 +128,96 @@ describe('Utils', function () {
describe('#camelCase', function () { describe('#camelCase', function () {
it('find spaces, underscores, and other natural word breaks', function () { it('find spaces, underscores, and other natural word breaks', function () {
_.camelCase('Neil Patrick.Harris-is_a.dog').should.eql('neilPatrickHarrisIsADog'); expect(_.camelCase('Neil Patrick.Harris-is_a.dog')).to.eql('neilPatrickHarrisIsADog');
}); });
it('ignores abreviations', function () { it('ignores abreviations', function () {
_.camelCase('Json_parser').should.eql('jsonParser'); expect(_.camelCase('Json_parser')).to.eql('jsonParser');
}); });
it('handles leading _', function () { it('handles leading _', function () {
_.camelCase('_thing_one_').should.eql('_thingOne'); expect(_.camelCase('_thing_one_')).to.eql('_thingOne');
}); });
}); });
describe('#studlyCase', function () { describe('#studlyCase', function () {
it('find spaces, underscores, and other natural word breaks', function () { it('find spaces, underscores, and other natural word breaks', function () {
_.studlyCase('Neil Patrick.Harris-is_a.dog').should.eql('NeilPatrickHarrisIsADog'); expect(_.studlyCase('Neil Patrick.Harris-is_a.dog')).to.eql('NeilPatrickHarrisIsADog');
}); });
it('ignores abreviations', function () { it('ignores abreviations', function () {
_.studlyCase('Json_parser').should.eql('JsonParser'); expect(_.studlyCase('Json_parser')).to.eql('JsonParser');
}); });
it('handles leading _', function () { it('handles leading _', function () {
_.studlyCase('_thing_one_').should.eql('_ThingOne'); expect(_.studlyCase('_thing_one_')).to.eql('_ThingOne');
}); });
}); });
describe('#snakeCase', function () { describe('#snakeCase', function () {
it('find spaces, underscores, and other natural word breaks', function () { it('find spaces, underscores, and other natural word breaks', function () {
_.snakeCase('Neil Patrick.Harris-is_a.dog').should.eql('neil_patrick_harris_is_a_dog'); expect(_.snakeCase('Neil Patrick.Harris-is_a.dog')).to.eql('neil_patrick_harris_is_a_dog');
}); });
it('ignores abreviations', function () { it('ignores abreviations', function () {
_.snakeCase('Json_parser').should.eql('json_parser'); expect(_.snakeCase('Json_parser')).to.eql('json_parser');
}); });
it('handles leading _', function () { it('handles leading _', function () {
_.snakeCase('_thing_one_').should.eql('_thing_one'); expect(_.snakeCase('_thing_one_')).to.eql('_thing_one');
}); });
}); });
describe('#toLowerString', function () { describe('#toLowerString', function () {
it('transforms normal strings', function () { it('transforms normal strings', function () {
_.toLowerString('PASTA').should.eql('pasta'); expect(_.toLowerString('PASTA')).to.eql('pasta');
}); });
it('ignores long form empty vals (null, false, undef)', function () { it('ignores long form empty vals (null, false, undef)', function () {
_.toLowerString(null).should.eql(''); expect(_.toLowerString(null)).to.eql('');
_.toLowerString(false).should.eql(''); expect(_.toLowerString(false)).to.eql('');
_.toLowerString(void 0).should.eql(''); expect(_.toLowerString(void 0)).to.eql('');
}); });
it('uses the objects own toString', function () { it('uses the objects own toString', function () {
_.toLowerString(['A', 'B']).should.eql('a,b'); expect(_.toLowerString(['A', 'B'])).to.eql('a,b');
}); });
it('sorta kinda works on objects', function () { it('sorta kinda works on objects', function () {
_.toLowerString({a: 'thing'}).should.eql('[object object]'); expect(_.toLowerString({a: 'thing'})).to.eql('[object object]');
}); });
}); });
describe('#toUpperString', function () { describe('#toUpperString', function () {
it('transforms normal strings', function () { it('transforms normal strings', function () {
_.toUpperString('PASTA').should.eql('PASTA'); expect(_.toUpperString('PASTA')).to.eql('PASTA');
}); });
it('ignores long form empty vals (null, false, undef)', function () { it('ignores long form empty vals (null, false, undef)', function () {
_.toUpperString(null).should.eql(''); expect(_.toUpperString(null)).to.eql('');
_.toUpperString(false).should.eql(''); expect(_.toUpperString(false)).to.eql('');
_.toUpperString(void 0).should.eql(''); expect(_.toUpperString(void 0)).to.eql('');
}); });
it('uses the objects own toString', function () { it('uses the objects own toString', function () {
_.toUpperString(['A', 'B']).should.eql('A,B'); expect(_.toUpperString(['A', 'B'])).to.eql('A,B');
}); });
it('sorta kinda works on objects', function () { it('sorta kinda works on objects', function () {
_.toUpperString({a: 'thing'}).should.eql('[OBJECT OBJECT]'); expect(_.toUpperString({a: 'thing'})).to.eql('[OBJECT OBJECT]');
}); });
}); });
describe('#repeat', function () { describe('#repeat', function () {
it('repeats strings', function () { it('repeats strings', function () {
_.repeat(' ', 5).should.eql(' '); expect(_.repeat(' ', 5)).to.eql(' ');
_.repeat('foobar', 2).should.eql('foobarfoobar'); expect(_.repeat('foobar', 2)).to.eql('foobarfoobar');
}); });
}); });
describe('#ucfirst', function () { describe('#ucfirst', function () {
it('only capitalized the first letter, lowercases everything else', function () { it('only capitalized the first letter, lowercases everything else', function () {
_.ucfirst('ALGER').should.eql('Alger'); expect(_.ucfirst('ALGER')).to.eql('Alger');
}); });
}); });
@ -230,7 +230,7 @@ describe('Utils', function () {
var obj = { var obj = {
foo: 'bar' foo: 'bar'
}; };
_.deepMerge(obj, { bar: 'baz' }).should.eql(obj); expect(_.deepMerge(obj, { bar: 'baz' })).to.eql(obj);
}); });
it('concats arrays', function () { it('concats arrays', function () {
@ -238,7 +238,7 @@ describe('Utils', function () {
foo: ['bax', 'boz'] foo: ['bax', 'boz']
}; };
_.deepMerge(obj, { foo: ['boop'] }); _.deepMerge(obj, { foo: ['boop'] });
obj.foo.should.have.a.lengthOf(3); expect(obj.foo).to.have.length(3);
}); });
it('wont merge values of different types', function () { it('wont merge values of different types', function () {
@ -246,7 +246,7 @@ describe('Utils', function () {
foo: ['stop', 'foo', 'stahp'] foo: ['stop', 'foo', 'stahp']
}; };
_.deepMerge(obj, { foo: 'string' }); _.deepMerge(obj, { foo: 'string' });
obj.foo.should.have.a.lengthOf(3); expect(obj.foo).to.have.length(3);
}); });
it('works recursively', function () { it('works recursively', function () {
@ -257,7 +257,7 @@ describe('Utils', function () {
} }
}; };
_.deepMerge(obj, { bax: { foo: ['poo'] }}); _.deepMerge(obj, { bax: { foo: ['poo'] }});
obj.bax.foo.should.have.a.lengthOf(3); expect(obj.bax.foo).to.have.length(3);
}); });
}); });
@ -266,30 +266,30 @@ describe('Utils', function () {
it('accepts an array of things and simply returns a copy of it', function () { it('accepts an array of things and simply returns a copy of it', function () {
var inp = [{ a: 1 }, 'pizza']; var inp = [{ a: 1 }, 'pizza'];
var out = _.createArray(inp); var out = _.createArray(inp);
out.should.eql(inp); expect(out).to.eql(inp);
out.should.not.be.exactly(inp); expect(out).to.not.be(inp);
}); });
it('accepts a primitive value and calls the the transform function', function (done) { it('accepts a primitive value and calls the the transform function', function (done) {
var out = _.createArray('str', function (val) { var out = _.createArray('str', function (val) {
val.should.be.exactly('str'); expect(val).to.be('str');
done(); done();
}); });
}); });
it('wraps any non-array in an array', function () { it('wraps any non-array in an array', function () {
_.createArray({}).should.eql([{}]); expect(_.createArray({})).to.eql([{}]);
_.createArray('').should.eql(['']); expect(_.createArray('')).to.eql(['']);
_.createArray(123).should.eql([123]); expect(_.createArray(123)).to.eql([123]);
_.createArray(/abc/).should.eql([/abc/]); expect(_.createArray(/abc/)).to.eql([/abc/]);
_.createArray(false).should.eql([false]); expect(_.createArray(false)).to.eql([false]);
}); });
it('returns false when the transform function returns undefined', function () { it('returns false when the transform function returns undefined', function () {
_.createArray(['str', 1], function (val) { expect(_.createArray(['str', 1], function (val) {
if (_.isString(val)) { if (_.isString(val)) {
return { return {
val: val val: val
}; };
} }
}).should.be.exactly(false); })).to.be(false);
}); });
}); });
@ -301,39 +301,39 @@ describe('Utils', function () {
var config = { var config = {
func: function () {} func: function () {}
}; };
_.funcEnum(config, 'func', {}, 'toString') expect(_.funcEnum(config, 'func', {}, 'toString'))
.should.be.exactly(config.func); .to.be(config.func);
}); });
it('tests if the value at key in object is undefined, returns the option at key default if so', function () { it('tests if the value at key in object is undefined, returns the option at key default if so', function () {
var config = { var config = {
func: undefined func: undefined
}; };
_.funcEnum(config, 'func', {}, 'toString') expect(_.funcEnum(config, 'func', {}, 'toString'))
.should.be.exactly(Object.prototype.toString); .to.be(Object.prototype.toString);
}); });
it('tests if the value at key in object is a string, returns the option at that key if so', function () { it('tests if the value at key in object is a string, returns the option at that key if so', function () {
var config = { var config = {
'config key name': 'toString' 'config key name': 'toString'
}; };
_.funcEnum(config, 'config key name', { toString: 'pizza' }, 'toJSON') expect(_.funcEnum(config, 'config key name', { toString: 'pizza' }, 'toJSON'))
.should.be.exactly('pizza'); .to.be('pizza');
}); });
it('throws an informative error if the selection if invalid', function () { it('throws an informative error if the selection if invalid', function () {
var config = { var config = {
'config': 'val' 'config': 'val'
}; };
(function () { expect(function () {
_.funcEnum(config, 'config', {}); _.funcEnum(config, 'config', {});
}).should.throw(/expected a function/i); }).to.throwError(/expected a function/i);
(function () { expect(function () {
_.funcEnum(config, 'config', { main: 'default' }, 'main'); _.funcEnum(config, 'config', { main: 'default' }, 'main');
}).should.throw(/expected a function or main/i); }).to.throwError(/expected a function or main/i);
(function () { expect(function () {
_.funcEnum(config, 'config', { main: 'default', other: 'default' }, 'main'); _.funcEnum(config, 'config', { main: 'default', other: 'default' }, 'main');
}).should.throw(/expected a function or one of main, other/i); }).to.throwError(/expected a function or one of main, other/i);
}); });
}); });
@ -350,11 +350,11 @@ describe('Utils', function () {
var args = _.map(new Array(i), function (val, i) { return i; }); var args = _.map(new Array(i), function (val, i) { return i; });
_.applyArgs(func, null, args); _.applyArgs(func, null, args);
func[method].callCount.should.eql(1); expect(func[method].callCount).to.eql(1);
if (method === 'apply') { if (method === 'apply') {
func.apply.lastCall.args[1].should.eql(args); expect(func.apply.lastCall.args[1]).to.eql(args);
} else { } else {
func.call.lastCall.args.splice(1).should.eql(args); expect(func.call.lastCall.args.splice(1)).to.eql(args);
} }
}); });
@ -367,11 +367,11 @@ describe('Utils', function () {
var expected = args.slice(slice); var expected = args.slice(slice);
_.applyArgs(func, null, args, slice); _.applyArgs(func, null, args, slice);
func[method].callCount.should.eql(1); expect(func[method].callCount).to.eql(1);
if (method === 'apply') { if (method === 'apply') {
func.apply.lastCall.args[1].should.eql(expected); expect(func.apply.lastCall.args[1]).to.eql(expected);
} else { } else {
func.call.lastCall.args.splice(1).should.eql(expected); expect(func.call.lastCall.args.splice(1)).to.eql(expected);
} }
}); });
}); });
@ -379,24 +379,24 @@ describe('Utils', function () {
describe('#getUnwrittenFromStream', function () { describe('#getUnwrittenFromStream', function () {
it('ignores things that do not have writableState', function () { it('ignores things that do not have writableState', function () {
should.not.exist(_.getUnwrittenFromStream()); expect(_.getUnwrittenFromStream()).to.be(undefined);
should.not.exist(_.getUnwrittenFromStream(false)); expect(_.getUnwrittenFromStream(false)).to.be(undefined);
should.not.exist(_.getUnwrittenFromStream([])); expect(_.getUnwrittenFromStream([])).to.be(undefined);
should.not.exist(_.getUnwrittenFromStream({})); expect(_.getUnwrittenFromStream({})).to.be(undefined);
}); });
if (require('stream').Writable) { if (require('stream').Writable) {
var MockWritableStream = require('../mocks/writable_stream'); var MockWritableStream = require('../mocks/writable_stream');
it('ignores empty stream', function () { it('ignores empty stream', function () {
var stream = new MockWritableStream(); var stream = new MockWritableStream();
_.getUnwrittenFromStream(stream).should.be.exactly(''); expect(_.getUnwrittenFromStream(stream)).to.be('');
}); });
it('returns only what is in the buffer', function () { it('returns only what is in the buffer', function () {
var stream = new MockWritableStream(); var stream = new MockWritableStream();
stream.write('hot'); stream.write('hot');
stream.write('dog'); stream.write('dog');
_.getUnwrittenFromStream(stream).should.be.exactly('dog'); expect(_.getUnwrittenFromStream(stream)).to.be('dog');
}); });
} }
}); });