Created
August 20, 2011 06:04
-
-
Save mrkurt/1158736 to your computer and use it in GitHub Desktop.
Testing Mongo map/reduce functions in isolation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
map = ()-> | |
return unless @a? #skip things with no actions array | |
return unless @i? | |
time = @_id.getTimestamp().getTime() | |
hour = time / 1000 / 3600 | |
cst = hour - 6 | |
key = parseInt(cst / 24).toString() + "-" + hex_md5(@i.join('-')) | |
val = {actions : {}, ids : @i, time : time} | |
for a in @a | |
val.actions[a] = 1 | |
emit key, val |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mongodb = require('mongodb') | |
crypto = require('crypto') | |
vm = require('vm') | |
MongoContext = ()-> | |
return | |
MongoContext::hex_md5 = (raw)-> | |
h = crypto.createHash('md5') | |
h.update(raw) | |
h.digest('hex') | |
MongoContext::ObjectId = ObjectId = (raw)-> | |
id = mongodb.pure().ObjectID(raw) | |
id.getTimestamp = ()-> | |
new Date(id.generationTime) | |
id | |
exports.runLikeMongo = (fn, scope, args...)-> | |
scope ||= {} | |
args ||= [] | |
context = new MongoContext() | |
context.emits = emits = [] | |
context.emit = (key,value)-> | |
emits.push [key, value] | |
context.scope = scope | |
context.args = args | |
context.log = (msg)-> console.log(msg) | |
context.result = null | |
script = "result = (#{fn.toString()}).apply(scope, args);" | |
vm.runInNewContext(script, context, "op.js") | |
context |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
test = require 'nodeunit' | |
mongo = require '../src/mongo' | |
job = mongo.jobs.dailyActions | |
helper = require '../test_helper' | |
module.exports = | |
"#map should ignore things without actions or ids" : (test)-> | |
data = [{ ids : ["1","2"] }, { actions : ["a", "b"] }] | |
for d in data | |
context = helper.runLikeMongo(job.map, d) | |
test.ok context.emits.length is 0 | |
test.done() | |
"#map should emit keys for good docs" : (test)-> | |
for d in helper.eventData | |
context = helper.runLikeMongo(job.map, d) | |
test.ok context.emits.length is 1 | |
test.done() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment