Skip to content

Commit

Permalink
Added a helper for generating sequences.
Browse files Browse the repository at this point in the history
  • Loading branch information
wbyoung committed Jun 11, 2015
1 parent 402caad commit 12b9ff1
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 14 deletions.
44 changes: 30 additions & 14 deletions lib/adapter_responder.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,10 @@ module.exports = Mixin.create(/** @lends AdapterResponder# */ {
* @param {String|RegExp} regex
*/
fail: function(regex) {
/* jscs:disable jsDoc */

if (_.isString(regex)) { regex = new RegExp(regex, 'i'); }
var responder = function(/*client, sql, args*/) {
this.custom(regex, function(/*client, sql, args*/) {
throw new Error('FakeFail for ' + regex.toString());
};
responder.regex = regex;
this._responders.unshift(responder);

/* jscs:enable jsDoc */
});
},

/**
Expand All @@ -46,16 +40,38 @@ module.exports = Mixin.create(/** @lends AdapterResponder# */ {
* database (built from result if not provided).
*/
respond: function(regex, result) {
/* jscs:disable jsDoc */
var fields = arguments[2] || _(result)
.map(_.keys).flatten()
.uniq().value();

var fields = arguments[2] || _(result).map(_.keys).flatten().uniq().value();
var responder = function(/*client, sql, args*/) {
this.custom(regex, function(/*client, sql, args*/) {
return { rows: result, fields: fields };
};
});
},

/**
* Add a fake response that returns serial ids for a regex match.
*
* @param {RegExp} regex The SQL to match.
* @param {Number} n The starting number for the sequence.
*/
sequence: function(regex, n) {
this.custom(regex, function(/*client, sql, args*/) {
return { rows: [{ id: n++ }], fields: ['id'] };
});
},

/**
* Add a fake response that returns the result of a function.
*
* @param {RegExp} regex The SQL to match.
* @param {function(Object, String, Array): Object} fn The function to call
* to obtain the value.
*/
custom: function(regex, fn) {
var responder = _.partial(fn); // copy the function
responder.regex = regex;
this._responders.unshift(responder);

/* jscs:enable jsDoc */
},

/**
Expand Down
11 changes: 11 additions & 0 deletions test/adapter_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,17 @@ describe('fake adapter', __query(function() {
});
});

it('can generate sequences for queries', function() {
adapter.sequence(/.*/, 1);
return query.select('t1').then(function(result) {
result.should.eql({ fields: ['id'], rows: [{ id: 1 }] });
})
.then(function() { return query.select('t1'); })
.then(function(result) {
result.should.eql({ fields: ['id'], rows: [{ id: 2 }] });
});
});

it('can produce failures', function() {
adapter.fail(/.*/);
return query.select('t1').execute()
Expand Down

0 comments on commit 12b9ff1

Please sign in to comment.