Skip to content

Instantly share code, notes, and snippets.

@munro
Created June 20, 2012 18:37
Show Gist options
  • Save munro/2961471 to your computer and use it in GitHub Desktop.
Save munro/2961471 to your computer and use it in GitHub Desktop.
Parallelize Vow Contexts
/*jslint node: true, nomen: true, sloppy: true, newcap: true */
var vows = require('vows'),
utils = require('./util');
vows.describe('array stuffs').addBatch(util.parallelize({
'when I have an array': {
topic: function () {
return [1, 2, 3];
},
'and I push': {
topic: function (data) {
data.push(4);
return data;
},
'it adds 4 to the list': function (data) {
assert.equal(data.toString(), '1,2,3,4');
}
},
'and I pop': {
topic: function (data) {
data.pop();
return data;
},
'it has 2 items': function (data) {
assert.equal(data.length, 2);
}
}
}
})).exportTo(module);
/*jslint node: true, nomen: true, sloppy: true, newcap: true */
var _ = require('underscore');
/**
* Crawl a batch
* @param {Object} ctx A vows context
* @param {String} ctx_name The name of this context
*/
function crawl(ctx, ctx_name) {
/* We're dealing with a sub-batch here! */
if (_.isObject(ctx) && ctx.topic) {
/* Splay each test into it's own test, with a copy of the topic */
return _.reduce(ctx, function (sub_ctx, sub_value, sub_ctx_name) {
if (sub_ctx_name === 'topic') {
return sub_ctx;
}
/* Crawl sub-context, duplicated this test for each one */
_.each(crawl(sub_value, sub_ctx_name), function (sub_sub_vow) {
var obj = {topic: ctx.topic};
obj[sub_ctx_name] = sub_sub_vow;
sub_ctx.push(obj);
});
return sub_ctx;
}, []);
}
/**
* Return the function wrapped in an array to make the return value
* similar to as if it were an object that was crawled.
*/
if (_.isFunction(ctx)) {
var obj = {};
obj[ctx_name] = ctx;
return [obj];
}
throw new Error('Not sure how to parallelize this type');
}
/**
* Topics are shared in vows' batches, so instead use topics as a separate setup
* function for every new test.
*
* @param {Object} batch A vows batch object
* @return {Object} Parallelize version of the batch
*/
exports.parallelize = function (batch) {
/**
* Top level contexts in a batch are already parallelized, so let's crawl
* sub-contexts to parallelize them.
*/
return _.reduce(batch, function (parallel_batch, ctx, ctx_name) {
_.each(crawl(ctx), function (vow, index) {
/**
* Can't have duplicate context names at the top level, so prepend them
* with a number.
*/
parallel_batch['#' + (index + 1) + ' ' + ctx_name] = vow;
});
return parallel_batch;
}, {});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment