Skip to content

Instantly share code, notes, and snippets.

@mrkurt
Created August 20, 2011 06:04
Show Gist options
  • Save mrkurt/1158736 to your computer and use it in GitHub Desktop.
Save mrkurt/1158736 to your computer and use it in GitHub Desktop.
Testing Mongo map/reduce functions in isolation
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
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
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