diff --git a/server/commons/logging.coffee b/server/commons/logging.coffee index 537e045e0..d0b7f6972 100644 --- a/server/commons/logging.coffee +++ b/server/commons/logging.coffee @@ -2,7 +2,8 @@ winston = require 'winston' module.exports.setup = -> winston.remove(winston.transports.Console) - winston.add(winston.transports.Console, - colorize: true, - timestamp: true - ) + if not global.testing + winston.add(winston.transports.Console, + colorize: true, + timestamp: true + ) diff --git a/server/handlers/earned_achievement_handler.coffee b/server/handlers/earned_achievement_handler.coffee index 53c3d8979..4a609d5a9 100644 --- a/server/handlers/earned_achievement_handler.coffee +++ b/server/handlers/earned_achievement_handler.coffee @@ -158,7 +158,7 @@ class EarnedAchievementHandler extends Handler onFinished = -> t1 = new Date().getTime() runningTime = ((t1-t0)/1000/60/60).toFixed(2) - console.log "we finished in #{runningTime} hours" + log.info "we finished in #{runningTime} hours" callback arguments... filter = {} @@ -278,7 +278,7 @@ class EarnedAchievementHandler extends Handler #log.debug "Incrementing score for these achievements with #{newTotalPoints - previousPoints}" pointDelta = newTotalPoints - previousPoints pctDone = (100 * usersFinished / total).toFixed(2) - console.log "Updated points to #{newTotalPoints} (#{if pointDelta < 0 then '' else '+'}#{pointDelta}) for #{user.get('name') or '???'} (#{user.get('_id')}) (#{pctDone}%)" + log.info "Updated points to #{newTotalPoints} (#{if pointDelta < 0 then '' else '+'}#{pointDelta}) for #{user.get('name') or '???'} (#{user.get('_id')}) (#{pctDone}%)" if recalculatingAll update = {$set: {points: newTotalPoints, 'earned.gems': 0, 'earned.heroes': [], 'earned.items': [], 'earned.levels': []}} else diff --git a/server/handlers/payment_handler.coffee b/server/handlers/payment_handler.coffee index c43cb77d8..0487d0a8e 100644 --- a/server/handlers/payment_handler.coffee +++ b/server/handlers/payment_handler.coffee @@ -34,7 +34,7 @@ PaymentHandler = class PaymentHandler extends Handler super arguments... logPaymentError: (req, msg) -> - console.warn "Payment Error: #{req.user.get('slug')} (#{req.user._id}): '#{msg}'" + log.warn "Payment Error: #{req.user.get('slug')} (#{req.user._id}): '#{msg}'" makeNewInstance: (req) -> payment = super(req) diff --git a/server/handlers/subscription_handler.coffee b/server/handlers/subscription_handler.coffee index a01421404..cf1fe8134 100644 --- a/server/handlers/subscription_handler.coffee +++ b/server/handlers/subscription_handler.coffee @@ -21,7 +21,7 @@ recipientCouponID = 'free' class SubscriptionHandler extends Handler logSubscriptionError: (user, msg) -> - console.warn "Subscription Error: #{user.get('slug')} (#{user._id}): '#{msg}'" + log.warn "Subscription Error: #{user.get('slug')} (#{user._id}): '#{msg}'" getByRelationship: (req, res, args...) -> return @getStripeEvents(req, res) if args[1] is 'stripe_events' diff --git a/server/handlers/user_handler.coffee b/server/handlers/user_handler.coffee index 455aa90bb..73be9b4ad 100644 --- a/server/handlers/user_handler.coffee +++ b/server/handlers/user_handler.coffee @@ -119,7 +119,7 @@ UserHandler = class UserHandler extends Handler log.error "Database error setting user name: #{err}" if err return callback(res: 'Database error.', code: 500) if err r = {message: 'is already used by another account', property: 'name'} - console.log 'Another user exists' if otherUser + log.info 'Another user exists' if otherUser return callback({res: r, code: 409}) if otherUser user.set('name', req.body.name) callback(null, req, user) @@ -775,7 +775,7 @@ UserHandler = class UserHandler extends Handler else update = $unset: {} update.$unset[statKey] = '' - console.log "... updating #{userStringID} patches #{statKey} to #{count}, #{usersTotal} players found so far." if count + log.info "... updating #{userStringID} patches #{statKey} to #{count}, #{usersTotal} players found so far." if count User.findByIdAndUpdate user.get('_id'), update, (err) -> log.error err if err? doneWithUser() @@ -801,7 +801,7 @@ UserHandler = class UserHandler extends Handler update = {} update[method] = {} update[method][statName] = count or '' - console.log "... updating #{user.get('_id')} patches #{JSON.stringify(query)} #{statName} to #{count}, #{usersTotal} players found so far." if count + log.info "... updating #{user.get('_id')} patches #{JSON.stringify(query)} #{statName} to #{count}, #{usersTotal} players found so far." if count User.findByIdAndUpdate user.get('_id'), update, doneUpdatingUser userStream = User.find({anonymous: false}).sort('_id').stream() @@ -865,7 +865,7 @@ UserHandler = class UserHandler extends Handler update = {} update[method] = {} update[method][statName] = count or '' - console.log "... updating #{userStringID} patches #{query} to #{count}, #{usersTotal} players found so far." if count + log.info "... updating #{userStringID} patches #{query} to #{count}, #{usersTotal} players found so far." if count User.findByIdAndUpdate user.get('_id'), update, doneWithUser statRecalculators: @@ -883,7 +883,7 @@ UserHandler = class UserHandler extends Handler --numberRunning userStream.resume() if streamFinished and usersFinished is usersTotal - console.log "----------- Finished recalculating statistics for gamesCompleted for #{usersFinished} players. -----------" + log.info "----------- Finished recalculating statistics for gamesCompleted for #{usersFinished} players. -----------" done?() userStream.on 'error', (err) -> log.error err userStream.on 'close', -> streamFinished = true @@ -895,7 +895,7 @@ UserHandler = class UserHandler extends Handler LevelSession.count {creator: userID, 'state.complete': true}, (err, count) -> update = if count then {$set: 'stats.gamesCompleted': count} else {$unset: 'stats.gamesCompleted': ''} - console.log "... updating #{userID} gamesCompleted to #{count}, #{usersTotal} players found so far." if Math.random() < 0.001 + log.info "... updating #{userID} gamesCompleted to #{count}, #{usersTotal} players found so far." if Math.random() < 0.001 User.findByIdAndUpdate user.get('_id'), update, doneWithUser articleEdits: (done) -> diff --git a/server/middleware/courses.coffee b/server/middleware/courses.coffee index 678b9f601..85b0a1240 100644 --- a/server/middleware/courses.coffee +++ b/server/middleware/courses.coffee @@ -39,7 +39,7 @@ module.exports = throw new errors.NotFound('Level original ObjectId not found in that course') if not nextLevelOriginal - res.status(200).send({}) + return res.status(200).send({}) dbq = Level.findOne({original: mongoose.Types.ObjectId(nextLevelOriginal)}) diff --git a/server/models/User.coffee b/server/models/User.coffee index fa43f8c32..56cae0eb6 100644 --- a/server/models/User.coffee +++ b/server/models/User.coffee @@ -350,7 +350,6 @@ UserSchema.pre('save', (next) -> Classroom = require './Classroom' if @isTeacher() and not @wasTeacher Classroom.update({members: @_id}, {$pull: {members: @_id}}, {multi: true}).exec (err, res) -> - console.log 'removed self from all classrooms as a member', err, res if email = @get('email') @set('emailLower', email.toLowerCase()) if name = @get('name') diff --git a/server_setup.coffee b/server_setup.coffee index c1adc9b79..4bf4fe632 100644 --- a/server_setup.coffee +++ b/server_setup.coffee @@ -84,7 +84,7 @@ setupExpressMiddleware = (app) -> app.use express.compress filter: (req, res) -> return false if req.headers.host is 'codecombat.com' # CloudFlare will gzip it for us on codecombat.com compressible res.getHeader('Content-Type') - else + else if not global.testing express.logger.format('dev', developmentLogging) app.use(express.logger('dev')) app.use(express.static(path.join(__dirname, 'public'), maxAge: 0)) # CloudFlare overrides maxAge, and we don't want local development caching. diff --git a/spec/helpers/helper.js b/spec/helpers/helper.js index 09be41fa3..095663f95 100644 --- a/spec/helpers/helper.js +++ b/spec/helpers/helper.js @@ -39,11 +39,22 @@ if (database.generateMongoConnectionString() !== dbString) { jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 10; // for long Stripe tests require('../server/common'); // Make sure global testing functions are set up +// Ignore Stripe/Nocking erroring +console.error = function() { + try { + if(arguments[1].stack.indexOf('An error occurred with our connection to Stripe') > -1) + return; + } + catch (e) { } + console.log.apply(console, arguments); +}; + var initialized = false; beforeEach(function(done) { if (initialized) { return done(); } + console.log('/spec/helpers/helper.js - Initializing spec environment...'); var async = require('async'); async.series([ @@ -103,6 +114,7 @@ beforeEach(function(done) { process.exit(1); } initialized = true; + console.log('/spec/helpers/helper.js - Done'); done(); }); }); diff --git a/spec/server/common.coffee b/spec/server/common.coffee index ae6fa307c..29c47d0c3 100644 --- a/spec/server/common.coffee +++ b/spec/server/common.coffee @@ -1,7 +1,7 @@ # import this at the top of every file so we're not juggling connections # and common libraries are available -console.log 'IT BEGINS' +console.log '/spec/server/common.coffee - Setting up spec globals...' if process.env.COCO_MONGO_HOST throw Error('Tests may not run with production environment') @@ -60,7 +60,7 @@ unittest.getUser = (name, email, password, done, force) -> return done(unittest.users[email]) if unittest.users[email] and not force request.post getURL('/auth/logout'), -> request.get getURL('/auth/whoami'), -> - req = request.post(getURL('/db/user'), (err, response, body) -> + req = request.post({url: getURL('/db/user'), json: {email, password}}, (err, response, body) -> throw err if err User.findOne({email: email}).exec((err, user) -> throw err if err @@ -70,9 +70,6 @@ unittest.getUser = (name, email, password, done, force) -> wrapUpGetUser(email, user, done) ) ) - form = req.form() - form.append('email', email) - form.append('password', password) wrapUpGetUser = (email, user, done) -> unittest.users[email] = user @@ -139,58 +136,48 @@ GLOBAL.loginNewUser = (done) -> email = "#{name}@me.com" request.post getURL('/auth/logout'), -> unittest.getUser name, email, password, (user) -> - req = request.post(getURL('/auth/login'), (error, response) -> + json = {username: email, password} + req = request.post({url: getURL('/auth/login'), json}, (error, response) -> expect(response.statusCode).toBe(200) done(user) ) - form = req.form() - form.append('username', email) - form.append('password', password) , true GLOBAL.loginJoe = (done) -> request.post getURL('/auth/logout'), -> unittest.getNormalJoe (user) -> - req = request.post(getURL('/auth/login'), (error, response) -> + json = {username: 'normal@jo.com', password: 'food'} + req = request.post({url: getURL('/auth/login'), json}, (error, response) -> expect(response.statusCode).toBe(200) done(user) ) - form = req.form() - form.append('username', 'normal@jo.com') - form.append('password', 'food') GLOBAL.loginSam = (done) -> request.post getURL('/auth/logout'), -> unittest.getOtherSam (user) -> - req = request.post(getURL('/auth/login'), (error, response) -> + json = { username: 'other@sam.com', password: 'beer'} + req = request.post({url: getURL('/auth/login'), json}, (error, response) -> expect(response.statusCode).toBe(200) done(user) ) - form = req.form() - form.append('username', 'other@sam.com') - form.append('password', 'beer') GLOBAL.loginAdmin = (done) -> request.post getURL('/auth/logout'), -> unittest.getAdmin (user) -> - req = request.post(getURL('/auth/login'), (error, response) -> + json = { username: 'admin@afc.com', password: '80yqxpb38j' } + req = request.post({url: getURL('/auth/login'), json}, (error, response) -> expect(response.statusCode).toBe(200) done(user) ) - form = req.form() - form.append('username', 'admin@afc.com') - form.append('password', '80yqxpb38j') # find some other way to make the admin object an admin... maybe directly? GLOBAL.loginUser = (user, done) -> request.post getURL('/auth/logout'), -> - req = request.post(getURL('/auth/login'), (error, response) -> + json = { username: user.get('email'), password: user.get('name') } + req = request.post({ url: getURL('/auth/login'), json}, (error, response) -> expect(response.statusCode).toBe(200) done(user) ) - form = req.form() - form.append('username', user.get('email')) - form.append('password', user.get('name')) GLOBAL.logoutUser = (done) -> request.post getURL('/auth/logout'), -> @@ -213,3 +200,4 @@ _drop = (done) -> GLOBAL.resetUserIDCounter = (number=0) -> User.idCounter = number +console.log '/spec/server/common.coffee - Done' diff --git a/spec/server/functional/contact.spec.coffee b/spec/server/functional/contact.spec.coffee index 0c18a201e..906b3baba 100644 --- a/spec/server/functional/contact.spec.coffee +++ b/spec/server/functional/contact.spec.coffee @@ -4,23 +4,23 @@ request = require '../request' User = require '../../../server/models/User' # TODO: need to update this test since /contact calls external Close.io API now -xdescribe 'POST /contact', -> - - beforeEach utils.wrap (done) -> - spyOn(sendwithus.api, 'send') - @teacher = yield utils.initUser({role: 'teacher'}) - yield utils.loginUser(@teacher) - done() - - describe 'when recipientID is "schools@codecombat.com"', -> - it 'sends to that email', utils.wrap (done) -> - [res, body] = yield request.postAsync({url: getURL('/contact'), json: { - sender: 'some@email.com' - message: 'A message' - recipientID: 'schools@codecombat.com' - }}) - expect(sendwithus.api.send).toHaveBeenCalled() - user = yield User.findById(@teacher.id) - yield new Promise((resolve) -> setTimeout(resolve, 10)) - expect(user.get('enrollmentRequestSent')).toBe(true) - done() +#xdescribe 'POST /contact', -> +# +# beforeEach utils.wrap (done) -> +# spyOn(sendwithus.api, 'send') +# @teacher = yield utils.initUser({role: 'teacher'}) +# yield utils.loginUser(@teacher) +# done() +# +# describe 'when recipientID is "schools@codecombat.com"', -> +# it 'sends to that email', utils.wrap (done) -> +# [res, body] = yield request.postAsync({url: getURL('/contact'), json: { +# sender: 'some@email.com' +# message: 'A message' +# recipientID: 'schools@codecombat.com' +# }}) +# expect(sendwithus.api.send).toHaveBeenCalled() +# user = yield User.findById(@teacher.id) +# yield new Promise((resolve) -> setTimeout(resolve, 10)) +# expect(user.get('enrollmentRequestSent')).toBe(true) +# done() diff --git a/spec/server/functional/file.spec.coffee b/spec/server/functional/file.spec.coffee index 26699bd0c..2282dbf4d 100644 --- a/spec/server/functional/file.spec.coffee +++ b/spec/server/functional/file.spec.coffee @@ -1,178 +1,178 @@ -require '../common' - -# Doesn't work on Travis. Need to figure out why, probably by having the -# url not depend on some external resource. -mongoose = require 'mongoose' -request = require '../request' - -xdescribe '/file', -> - url = getURL('/file') - files = [] - options = { - uri: url - json: { - # url: 'http://scotterickson.info/images/where-are-you.jpg' - url: 'http://fc07.deviantart.net/fs37/f/2008/283/5/1/Chu_Chu_Pikachu_by_angelishi.gif' - filename: 'where-are-you.jpg' - mimetype: 'image/jpeg' - description: 'None!' - } - } - filepath = 'tmp/file' # TODO Warning hard coded path !!! - - jsonOptions= { - path: 'my_path' - postName: 'my_buffer' - filename: 'ittybitty.data' - mimetype: 'application/octet-stream' - description: 'rando-info' - # my_buffer_url: 'http://scotterickson.info/images/where-are-you.jpg' - my_buffer_url: 'http://fc07.deviantart.net/fs37/f/2008/283/5/1/Chu_Chu_Pikachu_by_angelishi.gif' - } - - allowHeader = 'GET, POST' - - it 'preparing test : deletes all the files first', (done) -> - dropGridFS -> - done() - - it 'can\'t be created if invalid (property path is required)', (done) -> - func = (err, res, body) -> - expect(res.statusCode).toBe(422) - done() - - loginAdmin -> - request.post(options, func) - - it 'can be created by an admin', (done) -> - func = (err, res, body) -> - expect(res.statusCode).toBe(200) - expect(body._id).toBeDefined() - expect(body.filename).toBe(options.json.filename) - expect(body.contentType).toBe(options.json.mimetype) - expect(body.length).toBeDefined() - expect(body.uploadDate).toBeDefined() - expect(body.metadata).toBeDefined() - expect(body.metadata.name).toBeDefined() - expect(body.metadata.path).toBe(options.json.path) - expect(body.metadata.creator).toBeDefined() - expect(body.metadata.description).toBe(options.json.description) - expect(body.md5).toBeDefined() - files.push(body) - done() - - options.json.path = filepath - request.post(options, func) - - it 'can be read by an admin.', (done) -> - request.get {uri: url+'/'+files[0]._id}, (err, res) -> - expect(res.statusCode).toBe(200) - expect(res.headers['content-type']).toBe(files[0].contentType) - done() - - it 'returns 404 for missing files', (done) -> - id = '000000000000000000000000' - request.get {uri: url+'/'+id}, (err, res) -> - expect(res.statusCode).toBe(404) - done() - - it 'returns 404 for invalid ids', (done) -> - request.get {uri: url+'/thiswillnotwork'}, (err, res) -> - expect(res.statusCode).toBe(404) - done() - - it 'can be created directly with form parameters', (done) -> - options2 = { - uri: url - } - - func = (err, res, body) -> - expect(res.statusCode).toBe(200) - body = JSON.parse(body) - expect(body._id).toBeDefined() - expect(body.filename).toBe(jsonOptions.filename) - expect(body.contentType).toBe(jsonOptions.mimetype) - expect(body.length).toBeDefined() - expect(body.uploadDate).toBeDefined() - expect(body.metadata).toBeDefined() - expect(body.metadata.name).toBeDefined() - expect(body.metadata.path).toBe(jsonOptions.path) - expect(body.metadata.creator).toBeDefined() - expect(body.metadata.description).toBe(jsonOptions.description) - expect(body.md5).toBeDefined() - files.push(body) - done() - - # the only way I could figure out how to get request to do what I wanted... - r = request.post(options2, func) - form = r.form() - form.append('path', jsonOptions.path) - form.append('postName', jsonOptions.postName) - form.append('filename', jsonOptions.filename) - form.append('mimetype', jsonOptions.mimetype) - form.append('description', jsonOptions.description) - form.append('my_buffer', request(jsonOptions.my_buffer_url)) - - it 'created directly, can be read', (done) -> - request.get {uri: url+'/'+files[1]._id}, (err, res) -> - expect(res.statusCode).toBe(200) - expect(res.headers['content-type']).toBe(files[1].contentType) - done() - - it 'does not overwrite existing files', (done) -> - options.json.description = 'Face' - - func = (err, res, body) -> - expect(res.statusCode).toBe(409) - collection = mongoose.connection.db.collection('media.files') - collection.find({}).toArray (err, results) -> - # ittybitty.data, and just one Where are you.jpg - expect(results.length).toBe(2) - for f in results - expect(f.metadata.description).not.toBe('Face') - done() - - request.post(options, func) - - it 'does overwrite existing files if force is true', (done) -> - options.json.force = 'true' # TODO ask why it's a string and not a boolean ? - - func = (err, res, body) -> - expect(res.statusCode).toBe(200) - collection = mongoose.connection.db.collection('media.files') - collection.find({}).toArray (err, results) -> - # ittybitty.data, and just one Where are you.jpg - expect(results.length).toBe(2) - hit = false - for f in results - hit = true if f.metadata.description is 'Face' - expect(hit).toBe(true) - done() - - request.post(options, func) - - it ' can\'t be requested with HTTP PATCH method', (done) -> - request {method: 'patch', uri: url}, (err, res) -> - expect(res.statusCode).toBe(405) - expect(res.headers.allow).toBe(allowHeader) - done() - - it ' can\'t be requested with HTTP PUT method', (done) -> - request.put {uri: url}, (err, res) -> - expect(res.statusCode).toBe(405) - expect(res.headers.allow).toBe(allowHeader) - done() - - it ' can\'t be requested with HTTP HEAD method', (done) -> - request.head {uri: url}, (err, res) -> - expect(res.statusCode).toBe(405) - expect(res.headers.allow).toBe(allowHeader) - done() - - it ' can\'t be requested with HTTP DEL method', (done) -> - request.del {uri: url}, (err, res) -> - expect(res.statusCode).toBe(405) - expect(res.headers.allow).toBe(allowHeader) - done() - -# TODO: test server errors, see what they do +#require '../common' +# +## Doesn't work on Travis. Need to figure out why, probably by having the +## url not depend on some external resource. +#mongoose = require 'mongoose' +#request = require '../request' +# +#xdescribe '/file', -> +# url = getURL('/file') +# files = [] +# options = { +# uri: url +# json: { +# # url: 'http://scotterickson.info/images/where-are-you.jpg' +# url: 'http://fc07.deviantart.net/fs37/f/2008/283/5/1/Chu_Chu_Pikachu_by_angelishi.gif' +# filename: 'where-are-you.jpg' +# mimetype: 'image/jpeg' +# description: 'None!' +# } +# } +# filepath = 'tmp/file' # TODO Warning hard coded path !!! +# +# jsonOptions= { +# path: 'my_path' +# postName: 'my_buffer' +# filename: 'ittybitty.data' +# mimetype: 'application/octet-stream' +# description: 'rando-info' +# # my_buffer_url: 'http://scotterickson.info/images/where-are-you.jpg' +# my_buffer_url: 'http://fc07.deviantart.net/fs37/f/2008/283/5/1/Chu_Chu_Pikachu_by_angelishi.gif' +# } +# +# allowHeader = 'GET, POST' +# +# it 'preparing test : deletes all the files first', (done) -> +# dropGridFS -> +# done() +# +# it 'can\'t be created if invalid (property path is required)', (done) -> +# func = (err, res, body) -> +# expect(res.statusCode).toBe(422) +# done() +# +# loginAdmin -> +# request.post(options, func) +# +# it 'can be created by an admin', (done) -> +# func = (err, res, body) -> +# expect(res.statusCode).toBe(200) +# expect(body._id).toBeDefined() +# expect(body.filename).toBe(options.json.filename) +# expect(body.contentType).toBe(options.json.mimetype) +# expect(body.length).toBeDefined() +# expect(body.uploadDate).toBeDefined() +# expect(body.metadata).toBeDefined() +# expect(body.metadata.name).toBeDefined() +# expect(body.metadata.path).toBe(options.json.path) +# expect(body.metadata.creator).toBeDefined() +# expect(body.metadata.description).toBe(options.json.description) +# expect(body.md5).toBeDefined() +# files.push(body) +# done() +# +# options.json.path = filepath +# request.post(options, func) +# +# it 'can be read by an admin.', (done) -> +# request.get {uri: url+'/'+files[0]._id}, (err, res) -> +# expect(res.statusCode).toBe(200) +# expect(res.headers['content-type']).toBe(files[0].contentType) +# done() +# +# it 'returns 404 for missing files', (done) -> +# id = '000000000000000000000000' +# request.get {uri: url+'/'+id}, (err, res) -> +# expect(res.statusCode).toBe(404) +# done() +# +# it 'returns 404 for invalid ids', (done) -> +# request.get {uri: url+'/thiswillnotwork'}, (err, res) -> +# expect(res.statusCode).toBe(404) +# done() +# +# it 'can be created directly with form parameters', (done) -> +# options2 = { +# uri: url +# } +# +# func = (err, res, body) -> +# expect(res.statusCode).toBe(200) +# body = JSON.parse(body) +# expect(body._id).toBeDefined() +# expect(body.filename).toBe(jsonOptions.filename) +# expect(body.contentType).toBe(jsonOptions.mimetype) +# expect(body.length).toBeDefined() +# expect(body.uploadDate).toBeDefined() +# expect(body.metadata).toBeDefined() +# expect(body.metadata.name).toBeDefined() +# expect(body.metadata.path).toBe(jsonOptions.path) +# expect(body.metadata.creator).toBeDefined() +# expect(body.metadata.description).toBe(jsonOptions.description) +# expect(body.md5).toBeDefined() +# files.push(body) +# done() +# +# # the only way I could figure out how to get request to do what I wanted... +# r = request.post(options2, func) +# form = r.form() +# form.append('path', jsonOptions.path) +# form.append('postName', jsonOptions.postName) +# form.append('filename', jsonOptions.filename) +# form.append('mimetype', jsonOptions.mimetype) +# form.append('description', jsonOptions.description) +# form.append('my_buffer', request(jsonOptions.my_buffer_url)) +# +# it 'created directly, can be read', (done) -> +# request.get {uri: url+'/'+files[1]._id}, (err, res) -> +# expect(res.statusCode).toBe(200) +# expect(res.headers['content-type']).toBe(files[1].contentType) +# done() +# +# it 'does not overwrite existing files', (done) -> +# options.json.description = 'Face' +# +# func = (err, res, body) -> +# expect(res.statusCode).toBe(409) +# collection = mongoose.connection.db.collection('media.files') +# collection.find({}).toArray (err, results) -> +# # ittybitty.data, and just one Where are you.jpg +# expect(results.length).toBe(2) +# for f in results +# expect(f.metadata.description).not.toBe('Face') +# done() +# +# request.post(options, func) +# +# it 'does overwrite existing files if force is true', (done) -> +# options.json.force = 'true' # TODO ask why it's a string and not a boolean ? +# +# func = (err, res, body) -> +# expect(res.statusCode).toBe(200) +# collection = mongoose.connection.db.collection('media.files') +# collection.find({}).toArray (err, results) -> +# # ittybitty.data, and just one Where are you.jpg +# expect(results.length).toBe(2) +# hit = false +# for f in results +# hit = true if f.metadata.description is 'Face' +# expect(hit).toBe(true) +# done() +# +# request.post(options, func) +# +# it ' can\'t be requested with HTTP PATCH method', (done) -> +# request {method: 'patch', uri: url}, (err, res) -> +# expect(res.statusCode).toBe(405) +# expect(res.headers.allow).toBe(allowHeader) +# done() +# +# it ' can\'t be requested with HTTP PUT method', (done) -> +# request.put {uri: url}, (err, res) -> +# expect(res.statusCode).toBe(405) +# expect(res.headers.allow).toBe(allowHeader) +# done() +# +# it ' can\'t be requested with HTTP HEAD method', (done) -> +# request.head {uri: url}, (err, res) -> +# expect(res.statusCode).toBe(405) +# expect(res.headers.allow).toBe(allowHeader) +# done() +# +# it ' can\'t be requested with HTTP DEL method', (done) -> +# request.del {uri: url}, (err, res) -> +# expect(res.statusCode).toBe(405) +# expect(res.headers.allow).toBe(allowHeader) +# done() +# +## TODO: test server errors, see what they do diff --git a/spec/server/functional/level_session.spec.coffee b/spec/server/functional/level_session.spec.coffee index 02b48b220..5b445b029 100644 --- a/spec/server/functional/level_session.spec.coffee +++ b/spec/server/functional/level_session.spec.coffee @@ -23,14 +23,14 @@ describe '/db/level.session', -> # TODO Tried to mimic what happens on the site. Why is this even so hard to do. # Right now it's even possible to create ownerless sessions through POST - xit 'allows users to create level sessions through PATCH', (done) -> - loginJoe (joe) -> - request {method: 'patch', uri: url + mongoose.Types.ObjectId(), json: session}, (err, res, body) -> - expect(err).toBeNull() - expect(res.statusCode).toBe 200 - console.log body - expect(body.creator).toEqual joe.get('_id').toHexString() - done() +# xit 'allows users to create level sessions through PATCH', (done) -> +# loginJoe (joe) -> +# request {method: 'patch', uri: url + mongoose.Types.ObjectId(), json: session}, (err, res, body) -> +# expect(err).toBeNull() +# expect(res.statusCode).toBe 200 +# console.log body +# expect(body.creator).toEqual joe.get('_id').toHexString() +# done() # Should remove this as soon as the PATCH test case above works it 'create a level session', (done) -> diff --git a/spec/server/functional/nocked.spec.coffee b/spec/server/functional/nocked.spec.coffee deleted file mode 100644 index 3c02c0b9f..000000000 --- a/spec/server/functional/nocked.spec.coffee +++ /dev/null @@ -1,29 +0,0 @@ -require '../common' -config = require '../../../server_config' -nockUtils = require('../nock-utils') -request = require '../request' - -xdescribe 'nock-utils', -> - afterEach nockUtils.teardownNock - - describe 'a test using setupNock', -> - it 'records and plays back third-party requests, but not localhost requests', (done) -> - nockUtils.setupNock 'nock-test.json', (err, nockDone) -> - request.get { uri: getURL('/db/level') }, (err) -> - expect(err).toBeNull() - t0 = new Date().getTime() - request.get { uri: 'http://zombo.com/' }, (err) -> - console.log 'cached speed', new Date().getTime() - t0 - expect(err).toBeNull() - nockDone() - done() - - describe 'another, sibling test that does not use setupNock', -> - it 'is proceeds normally', (done) -> - request.get { uri: getURL('/db/level') }, (err) -> - expect(err).toBeNull() - t0 = new Date().getTime() - request.get { uri: 'http://zombo.com/' }, (err) -> - console.log 'uncached speed', new Date().getTime() - t0 - expect(err).toBeNull() - done() diff --git a/spec/server/functional/queue.spec.coffee b/spec/server/functional/queue.spec.coffee index 4f622d310..91cd90f35 100644 --- a/spec/server/functional/queue.spec.coffee +++ b/spec/server/functional/queue.spec.coffee @@ -1,24 +1,24 @@ -require '../common' -request = require '../request' - -describe 'queue', -> - someURL = getURL('/queue/') - allowHeader = 'GET, POST, PUT' - - xit 'can\'t be requested with HTTP PATCH method', (done) -> - request {method: 'patch', uri: someURL}, (err, res, body) -> - expect(res.statusCode).toBe(405) - expect(res.headers.allow).toBe(allowHeader) - done() - - xit 'can\'t be requested with HTTP HEAD method', (done) -> - request.head {uri: someURL}, (err, res, body) -> - expect(res.statusCode).toBe(405) - expect(res.headers.allow).toBe(allowHeader) - done() - - xit 'can\'t be requested with HTTP DELETE method', (done) -> - request.del {uri: someURL}, (err, res, body) -> - expect(res.statusCode).toBe(405) - expect(res.headers.allow).toBe(allowHeader) - done() +#require '../common' +#request = require '../request' +# +#describe 'queue', -> +# someURL = getURL('/queue/') +# allowHeader = 'GET, POST, PUT' +# +# xit 'can\'t be requested with HTTP PATCH method', (done) -> +# request {method: 'patch', uri: someURL}, (err, res, body) -> +# expect(res.statusCode).toBe(405) +# expect(res.headers.allow).toBe(allowHeader) +# done() +# +# xit 'can\'t be requested with HTTP HEAD method', (done) -> +# request.head {uri: someURL}, (err, res, body) -> +# expect(res.statusCode).toBe(405) +# expect(res.headers.allow).toBe(allowHeader) +# done() +# +# xit 'can\'t be requested with HTTP DELETE method', (done) -> +# request.del {uri: someURL}, (err, res, body) -> +# expect(res.statusCode).toBe(405) +# expect(res.headers.allow).toBe(allowHeader) +# done() diff --git a/spec/server/functional/subscription.spec.coffee b/spec/server/functional/subscription.spec.coffee index 08425668e..57c2b2c26 100644 --- a/spec/server/functional/subscription.spec.coffee +++ b/spec/server/functional/subscription.spec.coffee @@ -1441,62 +1441,62 @@ describe 'Subscriptions', -> nockDone() done() - xit 'Unsubscribed user1 subscribes 13 users, unsubcribes 2', (done) -> - nockUtils.setupNock 'sub-test-34.json', (err, nockDone) -> - # TODO: Hits the Stripe error 'Request rate limit exceeded'. - # TODO: Need a better test for 12+ bulk discounts. Or, we could update the bulk disount logic. - # TODO: verify interim invoices? - recipientCount = 13 - recipientsToVerify = [0, 1, 10, 11, 12] - recipients = new SubbedRecipients recipientCount, recipientsToVerify - - # Create recipients - recipients.createRecipients -> - expect(recipients.length()).toEqual(recipientCount) - - stripe.tokens.create { - card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' } - }, (err, token) -> - - # Create sponsor user - loginNewUser (user1) -> - - # Subscribe recipients - recipients.subRecipients user1, token, -> - User.findById user1.id, (err, user1) -> - - # Unsubscribe first recipient - unsubscribeRecipient user1, recipients.get(0), -> - User.findById user1.id, (err, user1) -> - - stripeInfo = user1.get('stripe') - expect(stripeInfo.recipients.length).toEqual(recipientCount - 1) - verifyNotSponsoring user1.id, recipients.get(0).id, -> - verifyNotRecipient recipients.get(0).id, -> - stripe.customers.retrieveSubscription stripeInfo.customerID, stripeInfo.sponsorSubscriptionID, (err, subscription) -> - expect(err).toBeNull() - expect(subscription).not.toBeNull() - expect(subscription.quantity).toEqual(getUnsubscribedQuantity(recipientCount - 1)) - - # Unsubscribe last recipient - unsubscribeRecipient user1, recipients.get(recipientCount - 1), -> - User.findById user1.id, (err, user1) -> - stripeInfo = user1.get('stripe') - expect(stripeInfo.recipients.length).toEqual(recipientCount - 2) - verifyNotSponsoring user1.id, recipients.get(recipientCount - 1).id, -> - verifyNotRecipient recipients.get(recipientCount - 1).id, -> - stripe.customers.retrieveSubscription stripeInfo.customerID, stripeInfo.sponsorSubscriptionID, (err, subscription) -> - expect(err).toBeNull() - expect(subscription).not.toBeNull() - numSponsored = recipientCount - 2 - if numSponsored <= 1 - expect(subscription.quantity).toEqual(subPrice) - else if numSponsored <= 11 - expect(subscription.quantity).toEqual(subPrice + (numSponsored - 1) * subPrice * 0.8) - else - expect(subscription.quantity).toEqual(subPrice + 10 * subPrice * 0.8 + (numSponsored - 11) * subPrice * 0.6) - nockDone() - done() +# xit 'Unsubscribed user1 subscribes 13 users, unsubcribes 2', (done) -> +# nockUtils.setupNock 'sub-test-34.json', (err, nockDone) -> +# # TODO: Hits the Stripe error 'Request rate limit exceeded'. +# # TODO: Need a better test for 12+ bulk discounts. Or, we could update the bulk disount logic. +# # TODO: verify interim invoices? +# recipientCount = 13 +# recipientsToVerify = [0, 1, 10, 11, 12] +# recipients = new SubbedRecipients recipientCount, recipientsToVerify +# +# # Create recipients +# recipients.createRecipients -> +# expect(recipients.length()).toEqual(recipientCount) +# +# stripe.tokens.create { +# card: { number: '4242424242424242', exp_month: 12, exp_year: 2020, cvc: '123' } +# }, (err, token) -> +# +# # Create sponsor user +# loginNewUser (user1) -> +# +# # Subscribe recipients +# recipients.subRecipients user1, token, -> +# User.findById user1.id, (err, user1) -> +# +# # Unsubscribe first recipient +# unsubscribeRecipient user1, recipients.get(0), -> +# User.findById user1.id, (err, user1) -> +# +# stripeInfo = user1.get('stripe') +# expect(stripeInfo.recipients.length).toEqual(recipientCount - 1) +# verifyNotSponsoring user1.id, recipients.get(0).id, -> +# verifyNotRecipient recipients.get(0).id, -> +# stripe.customers.retrieveSubscription stripeInfo.customerID, stripeInfo.sponsorSubscriptionID, (err, subscription) -> +# expect(err).toBeNull() +# expect(subscription).not.toBeNull() +# expect(subscription.quantity).toEqual(getUnsubscribedQuantity(recipientCount - 1)) +# +# # Unsubscribe last recipient +# unsubscribeRecipient user1, recipients.get(recipientCount - 1), -> +# User.findById user1.id, (err, user1) -> +# stripeInfo = user1.get('stripe') +# expect(stripeInfo.recipients.length).toEqual(recipientCount - 2) +# verifyNotSponsoring user1.id, recipients.get(recipientCount - 1).id, -> +# verifyNotRecipient recipients.get(recipientCount - 1).id, -> +# stripe.customers.retrieveSubscription stripeInfo.customerID, stripeInfo.sponsorSubscriptionID, (err, subscription) -> +# expect(err).toBeNull() +# expect(subscription).not.toBeNull() +# numSponsored = recipientCount - 2 +# if numSponsored <= 1 +# expect(subscription.quantity).toEqual(subPrice) +# else if numSponsored <= 11 +# expect(subscription.quantity).toEqual(subPrice + (numSponsored - 1) * subPrice * 0.8) +# else +# expect(subscription.quantity).toEqual(subPrice + 10 * subPrice * 0.8 + (numSponsored - 11) * subPrice * 0.6) +# nockDone() +# done() describe 'APIs', -> subscriptionURL = getURL('/db/subscription') @@ -1694,7 +1694,6 @@ describe 'Subscriptions', -> token: token.id timestamp: new Date() request.put {uri: "#{subscriptionURL}/-/year_sale", json: requestBody, headers: headers }, (err, res) -> - console.log err expect(err).toBeNull() nockDone() done() diff --git a/spec/server/functional/user.spec.coffee b/spec/server/functional/user.spec.coffee index 69e22e1c8..a735088d6 100644 --- a/spec/server/functional/user.spec.coffee +++ b/spec/server/functional/user.spec.coffee @@ -11,16 +11,13 @@ describe 'POST /db/user', -> createAnonNameUser = (name, done)-> request.post getURL('/auth/logout'), -> request.get getURL('/auth/whoami'), -> - req = request.post(getURL('/db/user'), (err, response) -> + req = request.post({ url: getURL('/db/user'), json: {name}}, (err, response) -> expect(response.statusCode).toBe(200) - request.get getURL('/auth/whoami'), (request, response, body) -> - res = JSON.parse(response.body) - expect(res.anonymous).toBeTruthy() - expect(res.name).toEqual(name) + request.get { url: getURL('/auth/whoami'), json: true }, (request, response, body) -> + expect(body.anonymous).toBeTruthy() + expect(body.name).toEqual(name) done() ) - form = req.form() - form.append('name', name) it 'preparing test : clears the db first', (done) -> clearModels [User], (err) -> @@ -77,16 +74,13 @@ describe 'POST /db/user', -> createAnonNameUser('Jim', done) it 'should allow setting existing user name to anonymous user', (done) -> - req = request.post(getURL('/db/user'), (err, response, body) -> + req = request.post({url: getURL('/db/user'), json: {email: 'new@user.com', password: 'new'}}, (err, response, body) -> expect(response.statusCode).toBe(200) request.get getURL('/auth/whoami'), (request, response, body) -> res = JSON.parse(response.body) expect(res.anonymous).toBeFalsy() createAnonNameUser 'Jim', done ) - form = req.form() - form.append('email', 'new@user.com') - form.append('password', 'new') describe 'PUT /db/user', -> @@ -103,23 +97,22 @@ describe 'PUT /db/user', -> it 'denies requests to edit someone who is not joe', (done) -> unittest.getAdmin (admin) -> - req = request.put getURL(urlUser), - (err, res) -> + request.put {url: getURL(urlUser), json: {_id: admin.id}}, (err, res) -> expect(res.statusCode).toBe(403) done() - req.form().append('_id', admin.id) it 'denies invalid data', (done) -> unittest.getNormalJoe (joe) -> - req = request.put getURL(urlUser), - (err, res) -> + json = { + _id: joe.id + email: 'farghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlar +ghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghl' + } + request.put { url: getURL(urlUser), json }, (err, res) -> expect(res.statusCode).toBe(422) - expect(res.body.indexOf('too long')).toBeGreaterThan(-1) + expect(res.body[0].message.indexOf('too long')).toBeGreaterThan(-1) done() - form = req.form() - form.append('_id', joe.id) - form.append('email', 'farghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlar -ghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghl') + it 'does not allow normals to edit their permissions', utils.wrap (done) -> user = yield utils.initUser() @@ -132,47 +125,45 @@ ghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghl loginAdmin -> done() it 'denies non-existent ids', (done) -> - req = request.put getURL(urlUser), - (err, res) -> + json = { + _id: '513108d4cb8b610000000004', + email: 'perfectly@good.com' + } + request.put {url: getURL(urlUser), json}, (err, res) -> expect(res.statusCode).toBe(404) done() - form = req.form() - form.append('_id', '513108d4cb8b610000000004') - form.append('email', 'perfectly@good.com') it 'denies if the email being changed is already taken', (done) -> unittest.getNormalJoe (joe) -> unittest.getAdmin (admin) -> - req = request.put getURL(urlUser), (err, res) -> + json = { _id: admin.id, email: joe.get('email').toUpperCase() } + request.put { url: getURL(urlUser), json }, (err, res) -> expect(res.statusCode).toBe(409) - expect(res.body.indexOf('already used')).toBeGreaterThan(-1) + expect(res.body.message.indexOf('already used')).toBeGreaterThan(-1) done() - form = req.form() - form.append('_id', String(admin._id)) - form.append('email', joe.get('email').toUpperCase()) it 'does not care if you include your existing name', (done) -> unittest.getNormalJoe (joe) -> - req = request.put getURL(urlUser+'/'+joe._id), (err, res) -> + json = { _id: joe._id, name: 'Joe' } + request.put { url: getURL(urlUser+'/'+joe._id), json }, (err, res) -> expect(res.statusCode).toBe(200) done() - form = req.form() - form.append('_id', String(joe._id)) - form.append('name', 'Joe') it 'accepts name and email changes', (done) -> unittest.getNormalJoe (joe) -> - req = request.put getURL(urlUser), (err, res) -> + json = { + _id: joe.id + email: 'New@email.com' + name: 'Wilhelm' + } + request.put { url: getURL(urlUser), json }, (err, res) -> expect(res.statusCode).toBe(200) unittest.getUser('Wilhelm', 'New@email.com', 'null', (joe) -> expect(joe.get('name')).toBe('Wilhelm') expect(joe.get('emailLower')).toBe('new@email.com') expect(joe.get('email')).toBe('New@email.com') done()) - form = req.form() - form.append('_id', String(joe._id)) - form.append('email', 'New@email.com') - form.append('name', 'Wilhelm') + it 'should not allow two users with the same name slug', (done) -> loginSam (sam) -> @@ -189,7 +180,8 @@ ghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghl it 'should silently rename an anonymous user if their name conflicts upon signup', (done) -> request.post getURL('/auth/logout'), -> request.get getURL('/auth/whoami'), -> - req = request.post getURL('/db/user'), (err, response) -> + json = { name: 'admin' } + request.post { url: getURL('/db/user'), json }, (err, response) -> expect(response.statusCode).toBe(200) request.get getURL('/auth/whoami'), (err, response) -> expect(err).toBeNull() @@ -205,8 +197,6 @@ ghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghlfarghlarghl expect(finalGuy.name).not.toEqual guy.name expect(finalGuy.name.length).toBe guy.name.length + 1 done() - form = req.form() - form.append('name', 'admin') it 'should be able to unset a slug by setting an empty name', (done) -> loginSam (sam) -> @@ -467,13 +457,13 @@ describe 'PUT /db/user/-/remain-teacher', -> describe 'GET /db/user', -> it 'logs in as admin', (done) -> - req = request.post(getURL('/auth/login'), (error, response) -> + json = { + username: 'admin@afc.com' + password: '80yqxpb38j' + } + request.post { url: getURL('/auth/login'), json }, (error, response) -> expect(response.statusCode).toBe(200) done() - ) - form = req.form() - form.append('username', 'admin@afc.com') - form.append('password', '80yqxpb38j') it 'get schema', (done) -> request.get {uri: getURL(urlUser+'/schema')}, (err, res, body) -> @@ -523,7 +513,7 @@ describe 'GET /db/user', -> # TODO Ruben should be able to fetch other users but probably with restricted data access # Add to the test case above an extra data check - xit 'can fetch another user with restricted fields' +# xit 'can fetch another user with restricted fields' describe 'GET /db/user/:handle', -> diff --git a/spec/server/nock-utils.coffee b/spec/server/nock-utils.coffee index 308e373da..d18d63d1c 100644 --- a/spec/server/nock-utils.coffee +++ b/spec/server/nock-utils.coffee @@ -77,4 +77,4 @@ module.exports.teardownNock = -> before = (scope) -> scope.body = (body) -> true -Promise.promisifyAll(module.exports) \ No newline at end of file +Promise.promisifyAll(module.exports) diff --git a/spec/server/unit/analytics.spec.coffee b/spec/server/unit/analytics.spec.coffee index c6dbc2605..22f1bc66a 100644 --- a/spec/server/unit/analytics.spec.coffee +++ b/spec/server/unit/analytics.spec.coffee @@ -1,77 +1,77 @@ -GLOBAL._ = require 'lodash' - -require '../common' -AnalyticsUsersActive = require '../../../server/models/AnalyticsUsersActive' -LevelSession = require '../../../server/models/LevelSession' -User = require '../../../server/models/User' -mongoose = require 'mongoose' - -# TODO: these tests have some rerun/cleanup issues -# TODO: add tests for purchase, payment, subscribe, unsubscribe, and earned achievements - -# TODO: AnalyticsUsersActive collection isn't currently used. -# TODO: Will remove these tests if we end up ripping out the disabled saveActiveUser calls. - -describe 'Analytics', -> - - xit 'registered user', (done) -> - clearModels [AnalyticsUsersActive], (err) -> - expect(err).toBeNull() - user = new User - permissions: [] - name: "Fred" + Math.floor(Math.random() * 10000) - user.save (err) -> - expect(err).toBeNull() - userID = mongoose.Types.ObjectId(user.get('_id')) - AnalyticsUsersActive.find {creator : userID}, (err, activeUsers) -> - expect(activeUsers.length).toEqual(0) - user.register -> - AnalyticsUsersActive.find {creator : userID}, (err, activeUsers) -> - expect(err).toBeNull() - expect(activeUsers.length).toEqual(1) - expect(activeUsers[0]?.get('event')).toEqual('register') - done() - - xit 'level completed', (done) -> - clearModels [AnalyticsUsersActive], (err) -> - expect(err).toBeNull() - unittest.getNormalJoe (joe) -> - userID = mongoose.Types.ObjectId(joe.get('_id')) - session = new LevelSession - name: 'Beat Gandalf' - levelID: 'lotr' - permissions: simplePermissions - state: complete: false - creator: userID - session.save (err) -> - expect(err).toBeNull() - AnalyticsUsersActive.find {creator : userID}, (err, activeUsers) -> - expect(activeUsers.length).toEqual(0) - session.set 'state', complete: true - session.save (err) -> - expect(err).toBeNull() - AnalyticsUsersActive.find {creator : userID}, (err, activeUsers) -> - expect(err).toBeNull() - expect(activeUsers.length).toEqual(1) - expect(activeUsers[0]?.get('event')).toEqual('level-completed/lotr') - done() - - xit 'level playtime', (done) -> - clearModels [AnalyticsUsersActive], (err) -> - expect(err).toBeNull() - unittest.getNormalJoe (joe) -> - userID = mongoose.Types.ObjectId(joe.get('_id')) - session = new LevelSession - name: 'Beat Gandalf' - levelID: 'lotr' - permissions: simplePermissions - playtime: 60 - creator: userID - session.save (err) -> - expect(err).toBeNull() - AnalyticsUsersActive.find {creator : userID}, (err, activeUsers) -> - expect(err).toBeNull() - expect(activeUsers.length).toEqual(1) - expect(activeUsers[0]?.get('event')).toEqual('level-playtime/lotr') - done() - +#GLOBAL._ = require 'lodash' +# +#require '../common' +#AnalyticsUsersActive = require '../../../server/models/AnalyticsUsersActive' +#LevelSession = require '../../../server/models/LevelSession' +#User = require '../../../server/models/User' +#mongoose = require 'mongoose' +# +## TODO: these tests have some rerun/cleanup issues +## TODO: add tests for purchase, payment, subscribe, unsubscribe, and earned achievements +# +## TODO: AnalyticsUsersActive collection isn't currently used. +## TODO: Will remove these tests if we end up ripping out the disabled saveActiveUser calls. +# +#describe 'Analytics', -> +# +# xit 'registered user', (done) -> +# clearModels [AnalyticsUsersActive], (err) -> +# expect(err).toBeNull() +# user = new User +# permissions: [] +# name: "Fred" + Math.floor(Math.random() * 10000) +# user.save (err) -> +# expect(err).toBeNull() +# userID = mongoose.Types.ObjectId(user.get('_id')) +# AnalyticsUsersActive.find {creator : userID}, (err, activeUsers) -> +# expect(activeUsers.length).toEqual(0) +# user.register -> +# AnalyticsUsersActive.find {creator : userID}, (err, activeUsers) -> +# expect(err).toBeNull() +# expect(activeUsers.length).toEqual(1) +# expect(activeUsers[0]?.get('event')).toEqual('register') +# done() +# +# xit 'level completed', (done) -> +# clearModels [AnalyticsUsersActive], (err) -> +# expect(err).toBeNull() +# unittest.getNormalJoe (joe) -> +# userID = mongoose.Types.ObjectId(joe.get('_id')) +# session = new LevelSession +# name: 'Beat Gandalf' +# levelID: 'lotr' +# permissions: simplePermissions +# state: complete: false +# creator: userID +# session.save (err) -> +# expect(err).toBeNull() +# AnalyticsUsersActive.find {creator : userID}, (err, activeUsers) -> +# expect(activeUsers.length).toEqual(0) +# session.set 'state', complete: true +# session.save (err) -> +# expect(err).toBeNull() +# AnalyticsUsersActive.find {creator : userID}, (err, activeUsers) -> +# expect(err).toBeNull() +# expect(activeUsers.length).toEqual(1) +# expect(activeUsers[0]?.get('event')).toEqual('level-completed/lotr') +# done() +# +# xit 'level playtime', (done) -> +# clearModels [AnalyticsUsersActive], (err) -> +# expect(err).toBeNull() +# unittest.getNormalJoe (joe) -> +# userID = mongoose.Types.ObjectId(joe.get('_id')) +# session = new LevelSession +# name: 'Beat Gandalf' +# levelID: 'lotr' +# permissions: simplePermissions +# playtime: 60 +# creator: userID +# session.save (err) -> +# expect(err).toBeNull() +# AnalyticsUsersActive.find {creator : userID}, (err, activeUsers) -> +# expect(err).toBeNull() +# expect(activeUsers.length).toEqual(1) +# expect(activeUsers[0]?.get('event')).toEqual('level-playtime/lotr') +# done() +#