Merge pull request #2047 from overleaf/spd-eslint-mocha-arrows

Enforce consistent callback style in mocha tests

GitOrigin-RevId: a64c293dae6926ef5831abe97eaf2044942a5c85
This commit is contained in:
Simon Detheridge 2019-08-07 15:04:04 +01:00 committed by sharelatex
parent 5c32523b53
commit 7588393580
112 changed files with 1461 additions and 1308 deletions

View file

@ -51,20 +51,33 @@
} }
], ],
// Add some mocha specific rules
"mocha/handle-done-callback": "error",
"mocha/no-exclusive-tests": "error",
"mocha/no-global-tests": "error",
"mocha/no-identical-title": "error",
"mocha/no-nested-tests": "error",
"mocha/no-pending-tests": "error",
"mocha/no-skipped-tests": "error",
// Add some chai specific rules
"chai-expect/missing-assertion": "error",
"chai-expect/terminating-properties": "error",
// Swap the no-unused-expressions rule with a more chai-friendly one // Swap the no-unused-expressions rule with a more chai-friendly one
"no-unused-expressions": 0, "no-unused-expressions": 0,
"chai-friendly/no-unused-expressions": "error" "chai-friendly/no-unused-expressions": "error"
} },
"overrides": [
{
"files": ["**/test/*/src/**/*.js"],
"rules": {
// mocha-specific rules
"mocha/handle-done-callback": "error",
"mocha/no-exclusive-tests": "error",
"mocha/no-global-tests": "error",
"mocha/no-identical-title": "error",
"mocha/no-nested-tests": "error",
"mocha/no-pending-tests": "error",
"mocha/no-skipped-tests": "error",
"mocha/no-mocha-arrows": "error",
// chai-specific rules
"chai-expect/missing-assertion": "error",
"chai-expect/terminating-properties": "error",
// prefer-arrow-callback applies to all callbacks, not just ones in mocha tests.
// we don't enforce this at the top-level - just in tests to manage `this` scope
// based on mocha's context mechanism
"mocha/prefer-arrow-callback": "error"
}
}
]
} }

View file

@ -50,14 +50,14 @@ describe('ApiClsiTests', function() {
return done() return done()
}) })
describe('valid request', () => describe('valid request', function() {
it('returns success and a list of output files', function(done) { it('returns success and a list of output files', function(done) {
return authed_request.post( return authed_request.post(
{ {
uri: '/api/clsi/compile/abcd', uri: '/api/clsi/compile/abcd',
json: this.compileSpec json: this.compileSpec
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
throw error throw error
} }
@ -82,16 +82,17 @@ describe('ApiClsiTests', function() {
return done() return done()
} }
) )
})) })
})
describe('unauthorized', () => describe('unauthorized', function() {
it('returns 401', function(done) { it('returns 401', function(done) {
return request.post( return request.post(
{ {
uri: '/api/clsi/compile/abcd', uri: '/api/clsi/compile/abcd',
json: this.compileSpec json: this.compileSpec
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
throw error throw error
} }
@ -100,15 +101,16 @@ describe('ApiClsiTests', function() {
return done() return done()
} }
) )
})) })
})
}) })
describe('get output', function() { describe('get output', function() {
describe('valid file', () => describe('valid file', function() {
it('returns the file', done => it('returns the file', function(done) {
authed_request.get( return authed_request.get(
'/api/clsi/compile/abcd/build/1234/output/project.pdf', '/api/clsi/compile/abcd/build/1234/output/project.pdf',
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
throw error throw error
} }
@ -116,13 +118,15 @@ describe('ApiClsiTests', function() {
expect(response.body).to.equal('mock-pdf') expect(response.body).to.equal('mock-pdf')
return done() return done()
} }
))) )
})
})
describe('invalid file', () => describe('invalid file', function() {
it('returns 404', done => it('returns 404', function(done) {
authed_request.get( return authed_request.get(
'/api/clsi/compile/abcd/build/1234/output/project.aux', '/api/clsi/compile/abcd/build/1234/output/project.aux',
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
throw error throw error
} }
@ -130,13 +134,15 @@ describe('ApiClsiTests', function() {
expect(response.body).to.not.equal('mock-pdf') expect(response.body).to.not.equal('mock-pdf')
return done() return done()
} }
))) )
})
})
describe('unauthorized', () => describe('unauthorized', function() {
it('returns 401', done => it('returns 401', function(done) {
request.get( return request.get(
'/api/clsi/compile/abcd/build/1234/output/project.pdf', '/api/clsi/compile/abcd/build/1234/output/project.pdf',
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
throw error throw error
} }
@ -144,6 +150,8 @@ describe('ApiClsiTests', function() {
expect(response.body).to.not.equal('mock-pdf') expect(response.body).to.not.equal('mock-pdf')
return done() return done()
} }
))) )
})
})
}) })
}) })

View file

@ -25,11 +25,7 @@ const try_read_access = (user, project_id, test, callback) =>
async.series( async.series(
[ [
cb => cb =>
user.request.get(`/project/${project_id}`, function( user.request.get(`/project/${project_id}`, (error, response, body) => {
error,
response,
body
) {
if (error != null) { if (error != null) {
return cb(error) return cb(error)
} }
@ -37,17 +33,16 @@ const try_read_access = (user, project_id, test, callback) =>
return cb() return cb()
}), }),
cb => cb =>
user.request.get(`/project/${project_id}/download/zip`, function( user.request.get(
error, `/project/${project_id}/download/zip`,
response, (error, response, body) => {
body if (error != null) {
) { return cb(error)
if (error != null) { }
return cb(error) test(response, body)
return cb()
} }
test(response, body) )
return cb()
})
], ],
callback callback
) )
@ -63,7 +58,7 @@ const try_settings_write_access = (user, project_id, test, callback) =>
compiler: 'latex' compiler: 'latex'
} }
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
return cb(error) return cb(error)
} }
@ -86,7 +81,7 @@ const try_admin_access = (user, project_id, test, callback) =>
newProjectName: 'new-name' newProjectName: 'new-name'
} }
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
return cb(error) return cb(error)
} }
@ -102,7 +97,7 @@ const try_admin_access = (user, project_id, test, callback) =>
publicAccessLevel: 'private' publicAccessLevel: 'private'
} }
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
return cb(error) return cb(error)
} }
@ -135,7 +130,7 @@ const try_content_access = function(user, project_id, test, callback) {
json: true, json: true,
jar: false jar: false
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
return callback(error) return callback(error)
} }
@ -204,7 +199,7 @@ const expect_no_read_access = (user, project_id, options, callback) =>
try_read_access( try_read_access(
user, user,
project_id, project_id,
function(response, body) { (response, body) => {
expect(response.statusCode).to.equal(302) expect(response.statusCode).to.equal(302)
return expect(response.headers.location).to.match( return expect(response.headers.location).to.match(
new RegExp(options.redirect_to) new RegExp(options.redirect_to)
@ -236,7 +231,7 @@ const expect_no_settings_write_access = (user, project_id, options, callback) =>
try_settings_write_access( try_settings_write_access(
user, user,
project_id, project_id,
function(response, body) { (response, body) => {
expect(response.statusCode).to.equal(302) expect(response.statusCode).to.equal(302)
return expect(response.headers.location).to.match( return expect(response.headers.location).to.match(
new RegExp(options.redirect_to) new RegExp(options.redirect_to)
@ -249,7 +244,7 @@ const expect_no_admin_access = (user, project_id, options, callback) =>
try_admin_access( try_admin_access(
user, user,
project_id, project_id,
function(response, body) { (response, body) => {
expect(response.statusCode).to.equal(302) expect(response.statusCode).to.equal(302)
return expect(response.headers.location).to.match( return expect(response.headers.location).to.match(
new RegExp(options.redirect_to) new RegExp(options.redirect_to)

View file

@ -15,22 +15,29 @@ const chai = require('chai')
const request = require('./helpers/request') const request = require('./helpers/request')
describe('siteIsOpen', function() { describe('siteIsOpen', function() {
describe('when siteIsOpen is default (true)', () => describe('when siteIsOpen is default (true)', function() {
it('should get page', done => it('should get page', function(done) {
request.get('/login', function(error, response, body) { return request.get('/login', (error, response, body) => {
response.statusCode.should.equal(200) response.statusCode.should.equal(200)
return done() return done()
}))) })
})
})
describe('when siteIsOpen is false', function() { describe('when siteIsOpen is false', function() {
beforeEach(() => (Settings.siteIsOpen = false)) beforeEach(function() {
return (Settings.siteIsOpen = false)
})
afterEach(() => (Settings.siteIsOpen = true)) afterEach(function() {
return (Settings.siteIsOpen = true)
})
it('should return maintenance page', done => it('should return maintenance page', function(done) {
request.get('/login', function(error, response) { return request.get('/login', (error, response) => {
response.statusCode.should.equal(503) response.statusCode.should.equal(503)
return done() return done()
})) })
})
}) })
}) })

View file

@ -10,8 +10,8 @@ const MockDocstoreApi = require('./helpers/MockDocstoreApi')
require('./helpers/MockTagsApi') require('./helpers/MockTagsApi')
require('./helpers/MockV1Api') require('./helpers/MockV1Api')
describe('Deleting a user', () => { describe('Deleting a user', function() {
beforeEach(done => { beforeEach(function(done) {
this.user = new User() this.user = new User()
async.series( async.series(
[ [
@ -23,7 +23,7 @@ describe('Deleting a user', () => {
) )
}) })
it('Should remove the user from active users', done => { it('Should remove the user from active users', function(done) {
this.user.get((error, user) => { this.user.get((error, user) => {
expect(error).not.to.exist expect(error).not.to.exist
expect(user).to.exist expect(user).to.exist
@ -38,7 +38,7 @@ describe('Deleting a user', () => {
}) })
}) })
it('Should create a soft-deleted user', done => { it('Should create a soft-deleted user', function(done) {
this.user.get((error, user) => { this.user.get((error, user) => {
expect(error).not.to.exist expect(error).not.to.exist
this.user.deleteUser(error => { this.user.deleteUser(error => {
@ -70,7 +70,7 @@ describe('Deleting a user', () => {
}) })
}) })
it('Should fail if the user has a subscription', done => { it('Should fail if the user has a subscription', function(done) {
Subscription.create( Subscription.create(
{ {
admin_id: this.user._id, admin_id: this.user._id,
@ -93,7 +93,7 @@ describe('Deleting a user', () => {
) )
}) })
it("Should delete the user's projects", done => { it("Should delete the user's projects", function(done) {
this.user.createProject('wombat', (error, projectId) => { this.user.createProject('wombat', (error, projectId) => {
expect(error).not.to.exist expect(error).not.to.exist
this.user.getProject(projectId, (error, project) => { this.user.getProject(projectId, (error, project) => {
@ -112,8 +112,8 @@ describe('Deleting a user', () => {
}) })
}) })
describe('when scrubbing the user', () => { describe('when scrubbing the user', function() {
beforeEach(done => { beforeEach(function(done) {
this.user.get((error, user) => { this.user.get((error, user) => {
if (error) { if (error) {
throw error throw error
@ -123,7 +123,7 @@ describe('Deleting a user', () => {
}) })
}) })
it('Should remove the user data from mongo', done => { it('Should remove the user data from mongo', function(done) {
db.deletedUsers.findOne( db.deletedUsers.findOne(
{ 'deleterData.deletedUserId': this.userId }, { 'deleterData.deletedUserId': this.userId },
(error, deletedUser) => { (error, deletedUser) => {
@ -163,8 +163,8 @@ describe('Deleting a user', () => {
}) })
}) })
describe('Deleting a project', () => { describe('Deleting a project', function() {
beforeEach(done => { beforeEach(function(done) {
this.user = new User() this.user = new User()
this.projectName = 'wombat' this.projectName = 'wombat'
this.user.ensureUserExists(() => { this.user.ensureUserExists(() => {
@ -177,7 +177,7 @@ describe('Deleting a project', () => {
}) })
}) })
it('Should remove the project from active projects', done => { it('Should remove the project from active projects', function(done) {
this.user.getProject(this.projectId, (error, project) => { this.user.getProject(this.projectId, (error, project) => {
expect(error).not.to.exist expect(error).not.to.exist
expect(project).to.exist expect(project).to.exist
@ -194,7 +194,7 @@ describe('Deleting a project', () => {
}) })
}) })
it('Should create a soft-deleted project', done => { it('Should create a soft-deleted project', function(done) {
this.user.getProject(this.projectId, (error, project) => { this.user.getProject(this.projectId, (error, project) => {
expect(error).not.to.exist expect(error).not.to.exist
@ -234,8 +234,8 @@ describe('Deleting a project', () => {
}) })
}) })
describe('When the project has docs', () => { describe('When the project has docs', function() {
beforeEach(done => { beforeEach(function(done) {
this.user.getProject(this.projectId, (error, project) => { this.user.getProject(this.projectId, (error, project) => {
if (error) { if (error) {
throw error throw error
@ -255,7 +255,7 @@ describe('Deleting a project', () => {
}) })
}) })
it('should mark the docs as deleted', done => { it('should mark the docs as deleted', function(done) {
let doc = let doc =
MockDocstoreApi.docs[this.projectId.toString()][this.docId.toString()] MockDocstoreApi.docs[this.projectId.toString()][this.docId.toString()]
expect(doc).to.exist expect(doc).to.exist
@ -270,8 +270,8 @@ describe('Deleting a project', () => {
}) })
}) })
describe('When the deleted project is expired', () => { describe('When the deleted project is expired', function() {
beforeEach(done => { beforeEach(function(done) {
this.user.deleteProject(this.projectId, error => { this.user.deleteProject(this.projectId, error => {
if (error) { if (error) {
throw error throw error
@ -280,7 +280,7 @@ describe('Deleting a project', () => {
}) })
}) })
it('Should destroy the docs', done => { it('Should destroy the docs', function(done) {
expect( expect(
MockDocstoreApi.docs[this.projectId.toString()][this.docId.toString()] MockDocstoreApi.docs[this.projectId.toString()][this.docId.toString()]
).to.exist ).to.exist
@ -304,7 +304,7 @@ describe('Deleting a project', () => {
) )
}) })
it('Should remove the project data from mongo', done => { it('Should remove the project data from mongo', function(done) {
db.deletedProjects.findOne( db.deletedProjects.findOne(
{ 'deleterData.deletedProjectId': ObjectId(this.projectId) }, { 'deleterData.deletedProjectId': ObjectId(this.projectId) },
(error, deletedProject) => { (error, deletedProject) => {

View file

@ -30,11 +30,11 @@ const syncUserAndGetFeatures = function(user, callback) {
if (callback == null) { if (callback == null) {
callback = function(error, features) {} callback = function(error, features) {}
} }
return FeaturesUpdater.refreshFeatures(user._id, function(error) { return FeaturesUpdater.refreshFeatures(user._id, error => {
if (error != null) { if (error != null) {
return callback(error) return callback(error)
} }
return User.findById(user._id, function(error, user) { return User.findById(user._id, (error, user) => {
if (error != null) { if (error != null) {
return callback(error) return callback(error)
} }
@ -48,7 +48,7 @@ const syncUserAndGetFeatures = function(user, callback) {
describe('FeatureUpdater.refreshFeatures', function() { describe('FeatureUpdater.refreshFeatures', function() {
beforeEach(function(done) { beforeEach(function(done) {
this.user = new UserClient() this.user = new UserClient()
return this.user.ensureUserExists(function(error) { return this.user.ensureUserExists(error => {
if (error != null) { if (error != null) {
throw error throw error
} }
@ -56,7 +56,7 @@ describe('FeatureUpdater.refreshFeatures', function() {
}) })
}) })
describe('when user has no subscriptions', () => describe('when user has no subscriptions', function() {
it('should set their features to the basic set', function(done) { it('should set their features to the basic set', function(done) {
return syncUserAndGetFeatures(this.user, (error, features) => { return syncUserAndGetFeatures(this.user, (error, features) => {
if (error != null) { if (error != null) {
@ -65,7 +65,8 @@ describe('FeatureUpdater.refreshFeatures', function() {
expect(features).to.deep.equal(settings.defaultFeatures) expect(features).to.deep.equal(settings.defaultFeatures)
return done() return done()
}) })
})) })
})
describe('when the user has an individual subscription', function() { describe('when the user has an individual subscription', function() {
beforeEach(function() { beforeEach(function() {

View file

@ -1,4 +1,6 @@
const App = require('../../../app.js') const App = require('../../../app.js')
require('logger-sharelatex').logger.level('error') require('logger-sharelatex').logger.level('error')
before(done => App.listen(3000, 'localhost', done)) before(function(done) {
return App.listen(3000, 'localhost', done)
})

View file

@ -40,7 +40,9 @@ describe('Labels', function() {
}) })
}) })
afterEach(() => MockProjectHistoryApi.reset()) afterEach(function() {
return MockProjectHistoryApi.reset()
})
it('getting labels', function(done) { it('getting labels', function(done) {
const label_id = new ObjectId().toString() const label_id = new ObjectId().toString()

View file

@ -367,7 +367,7 @@ describe('LinkedFiles', function() {
}) })
return this.owner.request.get( return this.owner.request.get(
`/project/${this.project_id}/file/${file._id}`, `/project/${this.project_id}/file/${file._id}`,
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
throw error throw error
} }
@ -429,7 +429,7 @@ describe('LinkedFiles', function() {
}) })
return this.owner.request.get( return this.owner.request.get(
`/project/${this.project_id}/file/${file._id}`, `/project/${this.project_id}/file/${file._id}`,
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
throw error throw error
} }
@ -556,7 +556,7 @@ describe('LinkedFiles', function() {
}) })
return this.owner.request.get( return this.owner.request.get(
`/project/${this.project_id}/file/${file._id}`, `/project/${this.project_id}/file/${file._id}`,
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
throw error throw error
} }

View file

@ -20,22 +20,24 @@ describe('Project CRUD', function() {
return this.user.login(done) return this.user.login(done)
}) })
describe("when project doesn't exist", () => describe("when project doesn't exist", function() {
it('should return 404', function(done) { it('should return 404', function(done) {
return this.user.request.get( return this.user.request.get(
'/project/aaaaaaaaaaaaaaaaaaaaaaaa', '/project/aaaaaaaaaaaaaaaaaaaaaaaa',
function(err, res, body) { (err, res, body) => {
expect(res.statusCode).to.equal(404) expect(res.statusCode).to.equal(404)
return done() return done()
} }
) )
})) })
})
describe('when project has malformed id', () => describe('when project has malformed id', function() {
it('should return 404', function(done) { it('should return 404', function(done) {
return this.user.request.get('/project/blah', function(err, res, body) { return this.user.request.get('/project/blah', (err, res, body) => {
expect(res.statusCode).to.equal(404) expect(res.statusCode).to.equal(404)
return done() return done()
}) })
})) })
})
}) })

View file

@ -63,17 +63,17 @@ describe('ProjectFeatures', function() {
}) })
it('should have premium features', function(done) { it('should have premium features', function(done) {
return joinProject(this.owner._id, this.project_id, function( return joinProject(
error, this.owner._id,
response, this.project_id,
body (error, response, body) => {
) { expect(body.project.features.compileGroup).to.equal('priority')
expect(body.project.features.compileGroup).to.equal('priority') expect(body.project.features.versioning).to.equal(true)
expect(body.project.features.versioning).to.equal(true) expect(body.project.features.templates).to.equal(true)
expect(body.project.features.templates).to.equal(true) expect(body.project.features.dropbox).to.equal(true)
expect(body.project.features.dropbox).to.equal(true) return done()
return done() }
}) )
}) })
}) })
@ -86,17 +86,17 @@ describe('ProjectFeatures', function() {
}) })
it('should have basic features', function(done) { it('should have basic features', function(done) {
return joinProject(this.owner._id, this.project_id, function( return joinProject(
error, this.owner._id,
response, this.project_id,
body (error, response, body) => {
) { expect(body.project.features.compileGroup).to.equal('standard')
expect(body.project.features.compileGroup).to.equal('standard') expect(body.project.features.versioning).to.equal(false)
expect(body.project.features.versioning).to.equal(false) expect(body.project.features.templates).to.equal(false)
expect(body.project.features.templates).to.equal(false) expect(body.project.features.dropbox).to.equal(false)
expect(body.project.features.dropbox).to.equal(false) return done()
return done() }
}) )
}) })
}) })
}) })

View file

@ -293,8 +293,8 @@ const expectInvitesInJoinProjectCount = (user, projectId, count, callback) => {
}) })
} }
describe('ProjectInviteTests', () => { describe('ProjectInviteTests', function() {
beforeEach(done => { beforeEach(function(done) {
this.sendingUser = new User() this.sendingUser = new User()
this.user = new User() this.user = new User()
this.site_admin = new User({ email: 'admin@example.com' }) this.site_admin = new User({ email: 'admin@example.com' })
@ -310,13 +310,13 @@ describe('ProjectInviteTests', () => {
) )
}) })
describe('creating invites', () => { describe('creating invites', function() {
beforeEach(() => { beforeEach(function() {
this.projectName = 'wat' this.projectName = 'wat'
}) })
describe('creating two invites', () => { describe('creating two invites', function() {
beforeEach(done => { beforeEach(function(done) {
createProject( createProject(
this.sendingUser, this.sendingUser,
this.projectName, this.projectName,
@ -329,7 +329,7 @@ describe('ProjectInviteTests', () => {
) )
}) })
it('should allow the project owner to create and remove invites', done => { it('should allow the project owner to create and remove invites', function(done) {
Async.series( Async.series(
[ [
cb => expectProjectAccess(this.sendingUser, this.projectId, cb), cb => expectProjectAccess(this.sendingUser, this.projectId, cb),
@ -408,7 +408,7 @@ describe('ProjectInviteTests', () => {
) )
}) })
it('should allow the project owner to create many invites at once', done => { it('should allow the project owner to create many invites at once', function(done) {
Async.series( Async.series(
[ [
cb => expectProjectAccess(this.sendingUser, this.projectId, cb), cb => expectProjectAccess(this.sendingUser, this.projectId, cb),
@ -482,8 +482,8 @@ describe('ProjectInviteTests', () => {
}) })
}) })
describe('clicking the invite link', () => { describe('clicking the invite link', function() {
beforeEach(done => { beforeEach(function(done) {
createProjectAndInvite( createProjectAndInvite(
this.sendingUser, this.sendingUser,
this.projectName, this.projectName,
@ -499,13 +499,13 @@ describe('ProjectInviteTests', () => {
) )
}) })
describe('user is logged in already', () => { describe('user is logged in already', function() {
beforeEach(done => { beforeEach(function(done) {
this.user.login(done) this.user.login(done)
}) })
describe('user is already a member of the project', () => { describe('user is already a member of the project', function() {
beforeEach(done => { beforeEach(function(done) {
Async.series( Async.series(
[ [
cb => expectInvitePage(this.user, this.link, cb), cb => expectInvitePage(this.user, this.link, cb),
@ -516,8 +516,8 @@ describe('ProjectInviteTests', () => {
) )
}) })
describe('when user clicks on the invite a second time', () => { describe('when user clicks on the invite a second time', function() {
it('should just redirect to the project page', done => { it('should just redirect to the project page', function(done) {
Async.series( Async.series(
[ [
cb => expectProjectAccess(this.user, this.invite.projectId, cb), cb => expectProjectAccess(this.user, this.invite.projectId, cb),
@ -534,8 +534,8 @@ describe('ProjectInviteTests', () => {
) )
}) })
describe('when the user recieves another invite to the same project', () => describe('when the user recieves another invite to the same project', function() {
it('should redirect to the project page', done => { it('should redirect to the project page', function(done) {
Async.series( Async.series(
[ [
cb => { cb => {
@ -575,12 +575,13 @@ describe('ProjectInviteTests', () => {
], ],
done done
) )
})) })
})
}) })
}) })
describe('user is not a member of the project', () => { describe('user is not a member of the project', function() {
it('should not grant access if the user does not accept the invite', done => { it('should not grant access if the user does not accept the invite', function(done) {
Async.series( Async.series(
[ [
cb => expectInvitePage(this.user, this.link, cb), cb => expectInvitePage(this.user, this.link, cb),
@ -590,7 +591,7 @@ describe('ProjectInviteTests', () => {
) )
}) })
it('should render the invalid-invite page if the token is invalid', done => { it('should render the invalid-invite page if the token is invalid', function(done) {
Async.series( Async.series(
[ [
cb => { cb => {
@ -607,7 +608,7 @@ describe('ProjectInviteTests', () => {
) )
}) })
it('should allow the user to accept the invite and access the project', done => { it('should allow the user to accept the invite and access the project', function(done) {
Async.series( Async.series(
[ [
cb => expectInvitePage(this.user, this.link, cb), cb => expectInvitePage(this.user, this.link, cb),
@ -620,13 +621,13 @@ describe('ProjectInviteTests', () => {
}) })
}) })
describe('user is not logged in initially', () => { describe('user is not logged in initially', function() {
describe('registration prompt workflow with valid token', () => { describe('registration prompt workflow with valid token', function() {
it('should redirect to the register page', done => { it('should redirect to the register page', function(done) {
expectInviteRedirectToRegister(this.user, this.link, done) expectInviteRedirectToRegister(this.user, this.link, done)
}) })
it('should allow user to accept the invite if the user registers a new account', done => { it('should allow user to accept the invite if the user registers a new account', function(done) {
Async.series( Async.series(
[ [
cb => expectInviteRedirectToRegister(this.user, this.link, cb), cb => expectInviteRedirectToRegister(this.user, this.link, cb),
@ -646,8 +647,8 @@ describe('ProjectInviteTests', () => {
}) })
}) })
describe('registration prompt workflow with non-valid token', () => { describe('registration prompt workflow with non-valid token', function() {
it('should redirect to the register page', done => { it('should redirect to the register page', function(done) {
Async.series( Async.series(
[ [
cb => expectInviteRedirectToRegister(this.user, this.link, cb), cb => expectInviteRedirectToRegister(this.user, this.link, cb),
@ -657,7 +658,7 @@ describe('ProjectInviteTests', () => {
) )
}) })
it('should display invalid-invite if the user registers a new account', done => { it('should display invalid-invite if the user registers a new account', function(done) {
const badLink = this.link.replace( const badLink = this.link.replace(
this.invite.token, this.invite.token,
'not_a_real_token' 'not_a_real_token'
@ -680,8 +681,8 @@ describe('ProjectInviteTests', () => {
}) })
}) })
describe('login workflow with valid token', () => { describe('login workflow with valid token', function() {
it('should redirect to the register page', done => { it('should redirect to the register page', function(done) {
Async.series( Async.series(
[ [
cb => expectInviteRedirectToRegister(this.user, this.link, cb), cb => expectInviteRedirectToRegister(this.user, this.link, cb),
@ -691,7 +692,7 @@ describe('ProjectInviteTests', () => {
) )
}) })
it('should allow the user to login to view the invite', done => { it('should allow the user to login to view the invite', function(done) {
Async.series( Async.series(
[ [
cb => expectInviteRedirectToRegister(this.user, this.link, cb), cb => expectInviteRedirectToRegister(this.user, this.link, cb),
@ -704,7 +705,7 @@ describe('ProjectInviteTests', () => {
) )
}) })
it('should allow user to accept the invite if the user logs in', done => { it('should allow user to accept the invite if the user logs in', function(done) {
Async.series( Async.series(
[ [
cb => expectInviteRedirectToRegister(this.user, this.link, cb), cb => expectInviteRedirectToRegister(this.user, this.link, cb),
@ -719,8 +720,8 @@ describe('ProjectInviteTests', () => {
}) })
}) })
describe('login workflow with non-valid token', () => { describe('login workflow with non-valid token', function() {
it('should redirect to the register page', done => { it('should redirect to the register page', function(done) {
Async.series( Async.series(
[ [
cb => expectInviteRedirectToRegister(this.user, this.link, cb), cb => expectInviteRedirectToRegister(this.user, this.link, cb),
@ -730,7 +731,7 @@ describe('ProjectInviteTests', () => {
) )
}) })
it('should show the invalid-invite page once the user has logged in', done => { it('should show the invalid-invite page once the user has logged in', function(done) {
const badLink = this.link.replace( const badLink = this.link.replace(
this.invite.token, this.invite.token,
'not_a_real_token' 'not_a_real_token'

View file

@ -30,7 +30,7 @@ const _ = require('lodash')
// It is tested that these methods DO work when the lock has not been taken in // It is tested that these methods DO work when the lock has not been taken in
// other acceptance tests. // other acceptance tests.
describe('ProjectStructureMongoLock', () => describe('ProjectStructureMongoLock', function() {
describe('whilst a project lock is taken', function() { describe('whilst a project lock is taken', function() {
beforeEach(function(done) { beforeEach(function(done) {
// We want to instantly fail if the lock is taken // We want to instantly fail if the lock is taken
@ -85,7 +85,7 @@ describe('ProjectStructureMongoLock', () =>
it(`cannot call ProjectEntityMongoUpdateHandler.${methodName}`, function(done) { it(`cannot call ProjectEntityMongoUpdateHandler.${methodName}`, function(done) {
const method = ProjectEntityMongoUpdateHandler[methodName] const method = ProjectEntityMongoUpdateHandler[methodName]
const args = _.times(method.length - 2, _.constant(null)) const args = _.times(method.length - 2, _.constant(null))
return method(this.locked_project._id, args, function(err) { return method(this.locked_project._id, args, err => {
expect(err).to.deep.equal(new Error('Timeout')) expect(err).to.deep.equal(new Error('Timeout'))
return done() return done()
}) })
@ -93,7 +93,7 @@ describe('ProjectStructureMongoLock', () =>
} }
it('cannot get the project without a projection', function(done) { it('cannot get the project without a projection', function(done) {
return ProjectGetter.getProject(this.locked_project._id, function(err) { return ProjectGetter.getProject(this.locked_project._id, err => {
expect(err).to.deep.equal(new Error('Timeout')) expect(err).to.deep.equal(new Error('Timeout'))
return done() return done()
}) })
@ -103,7 +103,7 @@ describe('ProjectStructureMongoLock', () =>
return ProjectGetter.getProject( return ProjectGetter.getProject(
this.locked_project._id, this.locked_project._id,
{ rootFolder: true }, { rootFolder: true },
function(err) { err => {
expect(err).to.deep.equal(new Error('Timeout')) expect(err).to.deep.equal(new Error('Timeout'))
return done() return done()
} }
@ -143,7 +143,7 @@ describe('ProjectStructureMongoLock', () =>
this.unlocked_project._id, this.unlocked_project._id,
this.unlocked_project.rootFolder[0]._id, this.unlocked_project.rootFolder[0]._id,
'new folder', 'new folder',
function(err, folder) { (err, folder) => {
expect(err).to.equal(null) expect(err).to.equal(null)
expect(folder).to.be.defined expect(folder).to.be.defined
return done() return done()
@ -162,4 +162,5 @@ describe('ProjectStructureMongoLock', () =>
) )
}) })
}) })
})) })
})

View file

@ -13,41 +13,41 @@ require('./helpers/MockFileStoreApi')
require('./helpers/MockProjectHistoryApi') require('./helpers/MockProjectHistoryApi')
const User = require('./helpers/User') const User = require('./helpers/User')
describe('ProjectStructureChanges', () => { describe('ProjectStructureChanges', function() {
beforeEach(done => { beforeEach(function(done) {
this.owner = new User() this.owner = new User()
this.owner.login(done) this.owner.login(done)
}) })
const createExampleProject = callback => { function createExampleProject(test, callback) {
this.owner.createProject( test.owner.createProject(
'example-project', 'example-project',
{ template: 'example' }, { template: 'example' },
(error, projectId) => { (error, projectId) => {
if (error) { if (error) {
throw error throw error
} }
this.exampleProjectId = projectId test.exampleProjectId = projectId
ProjectGetter.getProject(this.exampleProjectId, (error, project) => { ProjectGetter.getProject(test.exampleProjectId, (error, project) => {
if (error) { if (error) {
throw error throw error
} }
this.rootFolderId = project.rootFolder[0]._id.toString() test.rootFolderId = project.rootFolder[0]._id.toString()
callback() callback()
}) })
} }
) )
} }
const createExampleDoc = callback => { function createExampleDoc(test, callback) {
ProjectGetter.getProject(this.exampleProjectId, (error, project) => { ProjectGetter.getProject(test.exampleProjectId, (error, project) => {
if (error) { if (error) {
throw error throw error
} }
this.owner.request.post( test.owner.request.post(
{ {
uri: `project/${this.exampleProjectId}/doc`, uri: `project/${test.exampleProjectId}/doc`,
json: { json: {
name: 'new.tex', name: 'new.tex',
parent_folder_id: project.rootFolder[0]._id parent_folder_id: project.rootFolder[0]._id
@ -60,17 +60,17 @@ describe('ProjectStructureChanges', () => {
if (res.statusCode < 200 || res.statusCode >= 300) { if (res.statusCode < 200 || res.statusCode >= 300) {
throw new Error(`failed to add doc ${res.statusCode}`) throw new Error(`failed to add doc ${res.statusCode}`)
} }
this.exampleDocId = body._id test.exampleDocId = body._id
callback() callback()
} }
) )
}) })
} }
const createExampleFolder = callback => { function createExampleFolder(test, callback) {
this.owner.request.post( test.owner.request.post(
{ {
uri: `project/${this.exampleProjectId}/folder`, uri: `project/${test.exampleProjectId}/folder`,
json: { json: {
name: 'foo' name: 'foo'
} }
@ -82,22 +82,22 @@ describe('ProjectStructureChanges', () => {
if (res.statusCode < 200 || res.statusCode >= 300) { if (res.statusCode < 200 || res.statusCode >= 300) {
throw new Error(`failed to add doc ${res.statusCode}`) throw new Error(`failed to add doc ${res.statusCode}`)
} }
this.exampleFolderId = body._id test.exampleFolderId = body._id
callback() callback()
} }
) )
} }
const uploadFile = (file, name, contentType, callback) => { function uploadFile(test, file, name, contentType, callback) {
const imageFile = fs.createReadStream( const imageFile = fs.createReadStream(
Path.resolve(Path.join(__dirname, '..', 'files', file)) Path.resolve(Path.join(__dirname, '..', 'files', file))
) )
this.owner.request.post( test.owner.request.post(
{ {
uri: `project/${this.exampleProjectId}/upload`, uri: `project/${test.exampleProjectId}/upload`,
qs: { qs: {
folder_id: this.rootFolderId folder_id: test.rootFolderId
}, },
formData: { formData: {
qqfile: { qqfile: {
@ -117,17 +117,17 @@ describe('ProjectStructureChanges', () => {
throw new Error(`failed to upload file ${res.statusCode}`) throw new Error(`failed to upload file ${res.statusCode}`)
} }
this.exampleFileId = JSON.parse(body).entity_id test.exampleFileId = JSON.parse(body).entity_id
callback() callback()
} }
) )
} }
const uploadExampleFile = callback => { function uploadExampleFile(test, callback) {
uploadFile('1pixel.png', '1pixel.png', 'image/png', callback) uploadFile(test, '1pixel.png', '1pixel.png', 'image/png', callback)
} }
const uploadExampleProject = (zipFilename, options, callback) => { function uploadExampleProject(test, zipFilename, options, callback) {
if (typeof options === 'function') { if (typeof options === 'function') {
callback = options callback = options
options = {} options = {}
@ -137,7 +137,7 @@ describe('ProjectStructureChanges', () => {
Path.resolve(Path.join(__dirname, '..', 'files', zipFilename)) Path.resolve(Path.join(__dirname, '..', 'files', zipFilename))
) )
this.owner.request.post( test.owner.request.post(
{ {
uri: 'project/new/upload', uri: 'project/new/upload',
formData: { formData: {
@ -154,17 +154,17 @@ describe('ProjectStructureChanges', () => {
) { ) {
throw new Error(`failed to upload project ${res.statusCode}`) throw new Error(`failed to upload project ${res.statusCode}`)
} }
this.uploadedProjectId = JSON.parse(body).project_id test.uploadedProjectId = JSON.parse(body).project_id
this.res = res test.res = res
callback() callback()
} }
) )
} }
const moveItem = (type, itemId, folderId, callback) => { function moveItem(test, type, itemId, folderId, callback) {
this.owner.request.post( test.owner.request.post(
{ {
uri: `project/${this.exampleProjectId}/${type}/${itemId}/move`, uri: `project/${test.exampleProjectId}/${type}/${itemId}/move`,
json: { json: {
folder_id: folderId folder_id: folderId
} }
@ -182,10 +182,10 @@ describe('ProjectStructureChanges', () => {
) )
} }
const renameItem = (type, itemId, name, callback) => { function renameItem(test, type, itemId, name, callback) {
this.owner.request.post( test.owner.request.post(
{ {
uri: `project/${this.exampleProjectId}/${type}/${itemId}/rename`, uri: `project/${test.exampleProjectId}/${type}/${itemId}/rename`,
json: { json: {
name: name name: name
} }
@ -203,10 +203,10 @@ describe('ProjectStructureChanges', () => {
) )
} }
const deleteItem = (type, itemId, callback) => { function deleteItem(test, type, itemId, callback) {
this.owner.request.delete( test.owner.request.delete(
{ {
uri: `project/${this.exampleProjectId}/${type}/${itemId}` uri: `project/${test.exampleProjectId}/${type}/${itemId}`
}, },
(error, res) => { (error, res) => {
if (error) { if (error) {
@ -220,26 +220,26 @@ describe('ProjectStructureChanges', () => {
) )
} }
const verifyVersionIncremented = (updateVersion, increment, callback) => { function verifyVersionIncremented(test, updateVersion, increment, callback) {
expect(updateVersion).to.equal(this.project0.version + increment) expect(updateVersion).to.equal(test.project0.version + increment)
ProjectGetter.getProject(this.exampleProjectId, (error, newProject) => { ProjectGetter.getProject(test.exampleProjectId, (error, newProject) => {
if (error) { if (error) {
throw error throw error
} }
expect(newProject.version).to.equal(this.project0.version + increment) expect(newProject.version).to.equal(test.project0.version + increment)
callback() callback()
}) })
} }
describe('creating a project from the example template', () => { describe('creating a project from the example template', function() {
beforeEach(done => { beforeEach(function(done) {
MockDocUpdaterApi.clearProjectStructureUpdates() MockDocUpdaterApi.clearProjectStructureUpdates()
createExampleProject(done) createExampleProject(this, done)
}) })
it('should version creating a doc', () => { it('should version creating a doc', function() {
const { const {
docUpdates: updates, docUpdates: updates,
version version
@ -256,7 +256,7 @@ describe('ProjectStructureChanges', () => {
expect(version).to.equal(3) expect(version).to.equal(3)
}) })
it('should version creating a file', () => { it('should version creating a file', function() {
const { const {
fileUpdates: updates, fileUpdates: updates,
version version
@ -270,10 +270,10 @@ describe('ProjectStructureChanges', () => {
}) })
}) })
describe('duplicating a project', () => { describe('duplicating a project', function() {
beforeEach(done => { beforeEach(function(done) {
MockDocUpdaterApi.clearProjectStructureUpdates() MockDocUpdaterApi.clearProjectStructureUpdates()
createExampleProject(() => { createExampleProject(this, () => {
this.owner.request.post( this.owner.request.post(
{ {
uri: `/Project/${this.exampleProjectId}/clone`, uri: `/Project/${this.exampleProjectId}/clone`,
@ -295,7 +295,7 @@ describe('ProjectStructureChanges', () => {
}) })
}) })
it('should version the docs created', () => { it('should version the docs created', function() {
const { const {
docUpdates: updates, docUpdates: updates,
version version
@ -312,7 +312,7 @@ describe('ProjectStructureChanges', () => {
expect(version).to.equal(3) expect(version).to.equal(3)
}) })
it('should version the files created', () => { it('should version the files created', function() {
const { const {
fileUpdates: updates, fileUpdates: updates,
version version
@ -326,21 +326,21 @@ describe('ProjectStructureChanges', () => {
}) })
}) })
describe('adding a doc', () => { describe('adding a doc', function() {
beforeEach(done => { beforeEach(function(done) {
createExampleProject(() => { createExampleProject(this, () => {
MockDocUpdaterApi.clearProjectStructureUpdates() MockDocUpdaterApi.clearProjectStructureUpdates()
ProjectGetter.getProject(this.exampleProjectId, (error, project) => { ProjectGetter.getProject(this.exampleProjectId, (error, project) => {
if (error) { if (error) {
throw error throw error
} }
this.project0 = project this.project0 = project
createExampleDoc(done) createExampleDoc(this, done)
}) })
}) })
}) })
it('should version the doc added', done => { it('should version the doc added', function(done) {
const { const {
docUpdates: updates, docUpdates: updates,
version version
@ -351,16 +351,16 @@ describe('ProjectStructureChanges', () => {
expect(update.pathname).to.equal('/new.tex') expect(update.pathname).to.equal('/new.tex')
expect(update.docLines).to.be.a('string') expect(update.docLines).to.be.a('string')
verifyVersionIncremented(version, 1, done) verifyVersionIncremented(this, version, 1, done)
}) })
}) })
describe('uploading a project', () => { describe('uploading a project', function() {
beforeEach(done => { beforeEach(function(done) {
uploadExampleProject('test_project.zip', done) uploadExampleProject(this, 'test_project.zip', done)
}) })
it('should version the docs created', () => { it('should version the docs created', function() {
const { const {
docUpdates: updates, docUpdates: updates,
version version
@ -373,7 +373,7 @@ describe('ProjectStructureChanges', () => {
expect(version).to.equal(2) expect(version).to.equal(2)
}) })
it('should version the files created', () => { it('should version the files created', function() {
const { const {
fileUpdates: updates, fileUpdates: updates,
version version
@ -387,13 +387,13 @@ describe('ProjectStructureChanges', () => {
}) })
}) })
describe('uploading a project with a name', () => { describe('uploading a project with a name', function() {
beforeEach(done => { beforeEach(function(done) {
this.testProjectName = 'wombat' this.testProjectName = 'wombat'
uploadExampleProject('test_project_with_name.zip', done) uploadExampleProject(this, 'test_project_with_name.zip', done)
}) })
it('should set the project name from the zip contents', done => { it('should set the project name from the zip contents', function(done) {
ProjectGetter.getProject(this.uploadedProjectId, (error, project) => { ProjectGetter.getProject(this.uploadedProjectId, (error, project) => {
expect(error).not.to.exist expect(error).not.to.exist
expect(project.name).to.equal(this.testProjectName) expect(project.name).to.equal(this.testProjectName)
@ -402,13 +402,13 @@ describe('ProjectStructureChanges', () => {
}) })
}) })
describe('uploading a project with an invalid name', () => { describe('uploading a project with an invalid name', function() {
beforeEach(done => { beforeEach(function(done) {
this.testProjectMatch = /^bad[^\\]+name$/ this.testProjectMatch = /^bad[^\\]+name$/
uploadExampleProject('test_project_with_invalid_name.zip', done) uploadExampleProject(this, 'test_project_with_invalid_name.zip', done)
}) })
it('should set the project name from the zip contents', done => { it('should set the project name from the zip contents', function(done) {
ProjectGetter.getProject(this.uploadedProjectId, (error, project) => { ProjectGetter.getProject(this.uploadedProjectId, (error, project) => {
expect(error).not.to.exist expect(error).not.to.exist
expect(project.name).to.match(this.testProjectMatch) expect(project.name).to.match(this.testProjectMatch)
@ -417,43 +417,46 @@ describe('ProjectStructureChanges', () => {
}) })
}) })
describe('uploading an empty zipfile', () => { describe('uploading an empty zipfile', function() {
beforeEach(done => { beforeEach(function(done) {
uploadExampleProject( uploadExampleProject(
this,
'test_project_empty.zip', 'test_project_empty.zip',
{ allowBadStatus: true }, { allowBadStatus: true },
done done
) )
}) })
it('should fail with 422 error', () => { it('should fail with 422 error', function() {
expect(this.res.statusCode).to.equal(422) expect(this.res.statusCode).to.equal(422)
}) })
}) })
describe('uploading a zipfile containing only empty directories', () => { describe('uploading a zipfile containing only empty directories', function() {
beforeEach(done => { beforeEach(function(done) {
uploadExampleProject( uploadExampleProject(
this,
'test_project_with_empty_folder.zip', 'test_project_with_empty_folder.zip',
{ allowBadStatus: true }, { allowBadStatus: true },
done done
) )
}) })
it('should fail with 422 error', () => { it('should fail with 422 error', function() {
expect(this.res.statusCode).to.equal(422) expect(this.res.statusCode).to.equal(422)
}) })
}) })
describe('uploading a project with a shared top-level folder', () => { describe('uploading a project with a shared top-level folder', function() {
beforeEach(done => { beforeEach(function(done) {
uploadExampleProject( uploadExampleProject(
this,
'test_project_with_shared_top_level_folder.zip', 'test_project_with_shared_top_level_folder.zip',
done done
) )
}) })
it('should not create the top-level folder', done => { it('should not create the top-level folder', function(done) {
ProjectGetter.getProject(this.uploadedProjectId, (error, project) => { ProjectGetter.getProject(this.uploadedProjectId, (error, project) => {
expect(error).not.to.exist expect(error).not.to.exist
expect(project.rootFolder[0].folders.length).to.equal(0) expect(project.rootFolder[0].folders.length).to.equal(0)
@ -463,12 +466,16 @@ describe('ProjectStructureChanges', () => {
}) })
}) })
describe('uploading a project with backslashes in the path names', () => { describe('uploading a project with backslashes in the path names', function() {
beforeEach(done => { beforeEach(function(done) {
uploadExampleProject('test_project_with_backslash_in_filename.zip', done) uploadExampleProject(
this,
'test_project_with_backslash_in_filename.zip',
done
)
}) })
it('should treat the backslash as a directory separator', done => { it('should treat the backslash as a directory separator', function(done) {
ProjectGetter.getProject(this.uploadedProjectId, (error, project) => { ProjectGetter.getProject(this.uploadedProjectId, (error, project) => {
expect(error).not.to.exist expect(error).not.to.exist
expect(project.rootFolder[0].folders[0].name).to.equal('styles') expect(project.rootFolder[0].folders[0].name).to.equal('styles')
@ -478,12 +485,12 @@ describe('ProjectStructureChanges', () => {
}) })
}) })
describe('uploading a project with files in different encodings', () => { describe('uploading a project with files in different encodings', function() {
beforeEach(done => { beforeEach(function(done) {
uploadExampleProject('charsets/charsets.zip', done) uploadExampleProject(this, 'charsets/charsets.zip', done)
}) })
it('should correctly parse windows-1252', () => { it('should correctly parse windows-1252', function() {
const { const {
docUpdates: updates docUpdates: updates
} = MockDocUpdaterApi.getProjectStructureUpdates(this.uploadedProjectId) } = MockDocUpdaterApi.getProjectStructureUpdates(this.uploadedProjectId)
@ -496,7 +503,7 @@ describe('ProjectStructureChanges', () => {
) )
}) })
it('should correctly parse German utf8', () => { it('should correctly parse German utf8', function() {
const { const {
docUpdates: updates docUpdates: updates
} = MockDocUpdaterApi.getProjectStructureUpdates(this.uploadedProjectId) } = MockDocUpdaterApi.getProjectStructureUpdates(this.uploadedProjectId)
@ -509,7 +516,7 @@ describe('ProjectStructureChanges', () => {
) )
}) })
it('should correctly parse little-endian utf16', () => { it('should correctly parse little-endian utf16', function() {
const { const {
docUpdates: updates docUpdates: updates
} = MockDocUpdaterApi.getProjectStructureUpdates(this.uploadedProjectId) } = MockDocUpdaterApi.getProjectStructureUpdates(this.uploadedProjectId)
@ -522,7 +529,7 @@ describe('ProjectStructureChanges', () => {
) )
}) })
it('should correctly parse Greek utf8', () => { it('should correctly parse Greek utf8', function() {
const { const {
docUpdates: updates docUpdates: updates
} = MockDocUpdaterApi.getProjectStructureUpdates(this.uploadedProjectId) } = MockDocUpdaterApi.getProjectStructureUpdates(this.uploadedProjectId)
@ -536,21 +543,21 @@ describe('ProjectStructureChanges', () => {
}) })
}) })
describe('uploading a file', () => { describe('uploading a file', function() {
beforeEach(done => { beforeEach(function(done) {
createExampleProject(() => { createExampleProject(this, () => {
MockDocUpdaterApi.clearProjectStructureUpdates() MockDocUpdaterApi.clearProjectStructureUpdates()
ProjectGetter.getProject(this.exampleProjectId, (error, project) => { ProjectGetter.getProject(this.exampleProjectId, (error, project) => {
if (error) { if (error) {
throw error throw error
} }
this.project0 = project this.project0 = project
uploadExampleFile(done) uploadExampleFile(this, done)
}) })
}) })
}) })
it('should version a newly uploaded file', done => { it('should version a newly uploaded file', function(done) {
const { const {
fileUpdates: updates, fileUpdates: updates,
version version
@ -562,13 +569,13 @@ describe('ProjectStructureChanges', () => {
expect(update.url).to.be.a('string') expect(update.url).to.be.a('string')
// one file upload // one file upload
verifyVersionIncremented(version, 1, done) verifyVersionIncremented(this, version, 1, done)
}) })
it('should version a replacement file', done => { it('should version a replacement file', function(done) {
MockDocUpdaterApi.clearProjectStructureUpdates() MockDocUpdaterApi.clearProjectStructureUpdates()
uploadFile('2pixel.png', '1pixel.png', 'image/png', () => { uploadFile(this, '2pixel.png', '1pixel.png', 'image/png', () => {
const { const {
fileUpdates: updates, fileUpdates: updates,
version version
@ -583,17 +590,17 @@ describe('ProjectStructureChanges', () => {
expect(update.url).to.be.a('string') expect(update.url).to.be.a('string')
// two file uploads // two file uploads
verifyVersionIncremented(version, 2, done) verifyVersionIncremented(this, version, 2, done)
}) })
}) })
}) })
describe('moving entities', () => { describe('moving entities', function() {
beforeEach(done => { beforeEach(function(done) {
createExampleProject(() => { createExampleProject(this, () => {
createExampleDoc(() => { createExampleDoc(this, () => {
uploadExampleFile(() => { uploadExampleFile(this, () => {
createExampleFolder(() => { createExampleFolder(this, () => {
ProjectGetter.getProject( ProjectGetter.getProject(
this.exampleProjectId, this.exampleProjectId,
(error, project) => { (error, project) => {
@ -611,8 +618,8 @@ describe('ProjectStructureChanges', () => {
}) })
}) })
it('should version moving a doc', done => { it('should version moving a doc', function(done) {
moveItem('doc', this.exampleDocId, this.exampleFolderId, () => { moveItem(this, 'doc', this.exampleDocId, this.exampleFolderId, () => {
const { const {
docUpdates: updates, docUpdates: updates,
version version
@ -624,12 +631,12 @@ describe('ProjectStructureChanges', () => {
expect(update.newPathname).to.equal('/foo/new.tex') expect(update.newPathname).to.equal('/foo/new.tex')
// 2, because it's a delete and then add // 2, because it's a delete and then add
verifyVersionIncremented(version, 2, done) verifyVersionIncremented(this, version, 2, done)
}) })
}) })
it('should version moving a file', done => { it('should version moving a file', function(done) {
moveItem('file', this.exampleFileId, this.exampleFolderId, () => { moveItem(this, 'file', this.exampleFileId, this.exampleFolderId, () => {
const { const {
fileUpdates: updates, fileUpdates: updates,
version version
@ -641,12 +648,12 @@ describe('ProjectStructureChanges', () => {
expect(update.newPathname).to.equal('/foo/1pixel.png') expect(update.newPathname).to.equal('/foo/1pixel.png')
// 2, because it's a delete and then add // 2, because it's a delete and then add
verifyVersionIncremented(version, 2, done) verifyVersionIncremented(this, version, 2, done)
}) })
}) })
it('should version moving a folder', done => { it('should version moving a folder', function(done) {
moveItem('doc', this.exampleDocId, this.exampleFolderId, () => { moveItem(this, 'doc', this.exampleDocId, this.exampleFolderId, () => {
MockDocUpdaterApi.clearProjectStructureUpdates() MockDocUpdaterApi.clearProjectStructureUpdates()
this.owner.request.post( this.owner.request.post(
@ -662,7 +669,7 @@ describe('ProjectStructureChanges', () => {
} }
const newFolderId = body._id const newFolderId = body._id
moveItem('folder', this.exampleFolderId, newFolderId, () => { moveItem(this, 'folder', this.exampleFolderId, newFolderId, () => {
const { const {
docUpdates: updates, docUpdates: updates,
version version
@ -676,7 +683,7 @@ describe('ProjectStructureChanges', () => {
expect(update.newPathname).to.equal('/bar/foo/new.tex') expect(update.newPathname).to.equal('/bar/foo/new.tex')
// 5, because it's two file moves plus a folder // 5, because it's two file moves plus a folder
verifyVersionIncremented(version, 5, done) verifyVersionIncremented(this, version, 5, done)
}) })
} }
) )
@ -684,40 +691,47 @@ describe('ProjectStructureChanges', () => {
}) })
}) })
describe('renaming entities', () => { describe('renaming entities', function() {
beforeEach(done => { beforeEach(function(done) {
createExampleProject(() => { createExampleProject(this, () => {
createExampleDoc(() => { createExampleDoc(this, () => {
uploadExampleFile(() => { uploadExampleFile(this, () => {
createExampleFolder(() => { createExampleFolder(this, () => {
moveItem('doc', this.exampleDocId, this.exampleFolderId, () => { moveItem(
moveItem( this,
'file', 'doc',
this.exampleFileId, this.exampleDocId,
this.exampleFolderId, this.exampleFolderId,
() => { () => {
MockDocUpdaterApi.clearProjectStructureUpdates() moveItem(
ProjectGetter.getProject( this,
this.exampleProjectId, 'file',
(error, project) => { this.exampleFileId,
if (error) { this.exampleFolderId,
throw error () => {
MockDocUpdaterApi.clearProjectStructureUpdates()
ProjectGetter.getProject(
this.exampleProjectId,
(error, project) => {
if (error) {
throw error
}
this.project0 = project
done()
} }
this.project0 = project )
done() }
} )
) }
} )
)
})
}) })
}) })
}) })
}) })
}) })
it('should version renaming a doc', done => { it('should version renaming a doc', function(done) {
renameItem('Doc', this.exampleDocId, 'wombat.tex', () => { renameItem(this, 'Doc', this.exampleDocId, 'wombat.tex', () => {
const { const {
docUpdates: updates, docUpdates: updates,
version version
@ -728,12 +742,12 @@ describe('ProjectStructureChanges', () => {
expect(update.pathname).to.equal('/foo/new.tex') expect(update.pathname).to.equal('/foo/new.tex')
expect(update.newPathname).to.equal('/foo/wombat.tex') expect(update.newPathname).to.equal('/foo/wombat.tex')
verifyVersionIncremented(version, 1, done) verifyVersionIncremented(this, version, 1, done)
}) })
}) })
it('should version renaming a file', done => { it('should version renaming a file', function(done) {
renameItem('file', this.exampleFileId, 'potato.png', () => { renameItem(this, 'file', this.exampleFileId, 'potato.png', () => {
const { const {
fileUpdates: updates, fileUpdates: updates,
version version
@ -744,12 +758,12 @@ describe('ProjectStructureChanges', () => {
expect(update.pathname).to.equal('/foo/1pixel.png') expect(update.pathname).to.equal('/foo/1pixel.png')
expect(update.newPathname).to.equal('/foo/potato.png') expect(update.newPathname).to.equal('/foo/potato.png')
verifyVersionIncremented(version, 1, done) verifyVersionIncremented(this, version, 1, done)
}) })
}) })
it('should version renaming a folder', done => { it('should version renaming a folder', function(done) {
renameItem('folder', this.exampleFolderId, 'giraffe', () => { renameItem(this, 'folder', this.exampleFolderId, 'giraffe', () => {
const { const {
docUpdates, docUpdates,
fileUpdates, fileUpdates,
@ -767,45 +781,52 @@ describe('ProjectStructureChanges', () => {
expect(fileUpdate.pathname).to.equal('/foo/1pixel.png') expect(fileUpdate.pathname).to.equal('/foo/1pixel.png')
expect(fileUpdate.newPathname).to.equal('/giraffe/1pixel.png') expect(fileUpdate.newPathname).to.equal('/giraffe/1pixel.png')
verifyVersionIncremented(version, 1, done) verifyVersionIncremented(this, version, 1, done)
}) })
}) })
}) })
describe('deleting entities', () => { describe('deleting entities', function() {
beforeEach(done => { beforeEach(function(done) {
createExampleProject(() => { createExampleProject(this, () => {
createExampleFolder(() => { createExampleFolder(this, () => {
createExampleDoc(() => { createExampleDoc(this, () => {
uploadExampleFile(() => { uploadExampleFile(this, () => {
moveItem('doc', this.exampleDocId, this.exampleFolderId, () => { moveItem(
moveItem( this,
'file', 'doc',
this.exampleFileId, this.exampleDocId,
this.exampleFolderId, this.exampleFolderId,
() => { () => {
MockDocUpdaterApi.clearProjectStructureUpdates() moveItem(
ProjectGetter.getProject( this,
this.exampleProjectId, 'file',
(error, project) => { this.exampleFileId,
if (error) { this.exampleFolderId,
throw error () => {
MockDocUpdaterApi.clearProjectStructureUpdates()
ProjectGetter.getProject(
this.exampleProjectId,
(error, project) => {
if (error) {
throw error
}
this.project0 = project
done()
} }
this.project0 = project )
done() }
} )
) }
} )
)
})
}) })
}) })
}) })
}) })
}) })
it('should version deleting a folder', done => { it('should version deleting a folder', function(done) {
deleteItem('folder', this.exampleFolderId, () => { deleteItem(this, 'folder', this.exampleFolderId, () => {
const { const {
docUpdates, docUpdates,
fileUpdates, fileUpdates,
@ -823,13 +844,13 @@ describe('ProjectStructureChanges', () => {
expect(fileUpdate.pathname).to.equal('/foo/1pixel.png') expect(fileUpdate.pathname).to.equal('/foo/1pixel.png')
expect(fileUpdate.newPathname).to.equal('') expect(fileUpdate.newPathname).to.equal('')
verifyVersionIncremented(version, 1, done) verifyVersionIncremented(this, version, 1, done)
}) })
}) })
}) })
describe('tpds', () => { describe('tpds', function() {
beforeEach(done => { beforeEach(function(done) {
this.tpdsProjectName = `tpds-project-${new ObjectId().toString()}` this.tpdsProjectName = `tpds-project-${new ObjectId().toString()}`
this.owner.createProject(this.tpdsProjectName, (error, projectId) => { this.owner.createProject(this.tpdsProjectName, (error, projectId) => {
if (error) { if (error) {
@ -850,7 +871,7 @@ describe('ProjectStructureChanges', () => {
}) })
}) })
it('should version adding a doc', done => { it('should version adding a doc', function(done) {
const texFile = fs.createReadStream( const texFile = fs.createReadStream(
Path.resolve(Path.join(__dirname, '..', 'files', 'test.tex')) Path.resolve(Path.join(__dirname, '..', 'files', 'test.tex'))
) )
@ -887,13 +908,13 @@ describe('ProjectStructureChanges', () => {
expect(update.pathname).to.equal('/test.tex') expect(update.pathname).to.equal('/test.tex')
expect(update.docLines).to.equal('Test') expect(update.docLines).to.equal('Test')
verifyVersionIncremented(version, 1, done) verifyVersionIncremented(this, version, 1, done)
}) })
texFile.pipe(req) texFile.pipe(req)
}) })
it('should version adding a new file', done => { it('should version adding a new file', function(done) {
const imageFile = fs.createReadStream( const imageFile = fs.createReadStream(
Path.resolve(Path.join(__dirname, '..', 'files', '1pixel.png')) Path.resolve(Path.join(__dirname, '..', 'files', '1pixel.png'))
) )
@ -932,16 +953,16 @@ describe('ProjectStructureChanges', () => {
expect(update.pathname).to.equal('/1pixel.png') expect(update.pathname).to.equal('/1pixel.png')
expect(update.url).to.be.a('string') expect(update.url).to.be.a('string')
verifyVersionIncremented(version, 1, done) verifyVersionIncremented(this, version, 1, done)
}) })
imageFile.pipe(req) imageFile.pipe(req)
}) })
describe('when there are files in the project', () => { describe('when there are files in the project', function() {
beforeEach(done => { beforeEach(function(done) {
uploadExampleFile(() => { uploadExampleFile(this, () => {
createExampleDoc(() => { createExampleDoc(this, () => {
ProjectGetter.getProject( ProjectGetter.getProject(
this.exampleProjectId, this.exampleProjectId,
(error, project) => { (error, project) => {
@ -957,7 +978,7 @@ describe('ProjectStructureChanges', () => {
}) })
}) })
it('should version replacing a file', done => { it('should version replacing a file', function(done) {
const imageFile = fs.createReadStream( const imageFile = fs.createReadStream(
Path.resolve(Path.join(__dirname, '..', 'files', '2pixel.png')) Path.resolve(Path.join(__dirname, '..', 'files', '2pixel.png'))
) )
@ -1002,13 +1023,13 @@ describe('ProjectStructureChanges', () => {
expect(update.pathname).to.equal('/1pixel.png') expect(update.pathname).to.equal('/1pixel.png')
expect(update.url).to.be.a('string') expect(update.url).to.be.a('string')
verifyVersionIncremented(version, 1, done) verifyVersionIncremented(this, version, 1, done)
}) })
imageFile.pipe(req) imageFile.pipe(req)
}) })
it('should version deleting a doc', done => { it('should version deleting a doc', function(done) {
this.owner.request.delete( this.owner.request.delete(
{ {
uri: `/user/${this.owner._id}/update/${ uri: `/user/${this.owner._id}/update/${
@ -1040,24 +1061,25 @@ describe('ProjectStructureChanges', () => {
expect(update.pathname).to.equal('/new.tex') expect(update.pathname).to.equal('/new.tex')
expect(update.newPathname).to.equal('') expect(update.newPathname).to.equal('')
verifyVersionIncremented(version, 1, done) verifyVersionIncremented(this, version, 1, done)
} }
) )
}) })
}) })
}) })
describe('uploading a document', () => { describe('uploading a document', function() {
beforeEach(done => { beforeEach(function(done) {
createExampleProject(() => { createExampleProject(this, () => {
MockDocUpdaterApi.clearProjectStructureUpdates() MockDocUpdaterApi.clearProjectStructureUpdates()
done() done()
}) })
}) })
describe('with an unusual character set', () => { describe('with an unusual character set', function() {
it('should correctly handle utf16-le data', done => { it('should correctly handle utf16-le data', function(done) {
uploadFile( uploadFile(
this,
'charsets/test-greek-utf16-le-bom.tex', 'charsets/test-greek-utf16-le-bom.tex',
'test-greek-utf16-le-bom.tex', 'test-greek-utf16-le-bom.tex',
'text/x-tex', 'text/x-tex',
@ -1078,8 +1100,9 @@ describe('ProjectStructureChanges', () => {
) )
}) })
it('should correctly handle windows1252/iso-8859-1/latin1 data', done => { it('should correctly handle windows1252/iso-8859-1/latin1 data', function(done) {
uploadFile( uploadFile(
this,
'charsets/test-german-windows-1252.tex', 'charsets/test-german-windows-1252.tex',
'test-german-windows-1252.tex', 'test-german-windows-1252.tex',
'text/x-tex', 'text/x-tex',

View file

@ -16,7 +16,7 @@ const request = require('./helpers/request')
const MockV1Api = require('./helpers/MockV1Api') const MockV1Api = require('./helpers/MockV1Api')
const assertResponse = (path, expectedStatusCode, expectedBody, cb) => const assertResponse = (path, expectedStatusCode, expectedBody, cb) =>
request.get(path, function(error, response) { request.get(path, (error, response) => {
should.not.exist(error) should.not.exist(error)
response.statusCode.should.equal(expectedStatusCode) response.statusCode.should.equal(expectedStatusCode)
if (expectedBody) { if (expectedBody) {
@ -30,17 +30,18 @@ describe('ProxyUrls', function() {
return this.timeout(1000) return this.timeout(1000)
}) })
it('proxy static URLs', done => it('proxy static URLs', function(done) {
async.series( return async.series(
[ [
cb => assertResponse('/institutions/list', 200, [], cb), cb => assertResponse('/institutions/list', 200, [], cb),
cb => assertResponse('/institutions/domains', 200, [], cb) cb => assertResponse('/institutions/domains', 200, [], cb)
], ],
done done
)) )
})
it('proxy dynamic URLs', done => it('proxy dynamic URLs', function(done) {
async.series( return async.series(
[ [
cb => cb =>
assertResponse( assertResponse(
@ -58,17 +59,20 @@ describe('ProxyUrls', function() {
) )
], ],
done done
)) )
})
it('return 404 if proxy is not set', done => it('return 404 if proxy is not set', function(done) {
async.series( return async.series(
[cb => assertResponse('/institutions/foobar', 404, null, cb)], [cb => assertResponse('/institutions/foobar', 404, null, cb)],
done done
)) )
})
it('handle missing baseUrl', done => it('handle missing baseUrl', function(done) {
async.series( return async.series(
[cb => assertResponse('/proxy/missing/baseUrl', 500, null, cb)], [cb => assertResponse('/proxy/missing/baseUrl', 500, null, cb)],
done done
)) )
})
}) })

View file

@ -16,7 +16,7 @@ const request = require('./helpers/request')
const MockV1Api = require('./helpers/MockV1Api') const MockV1Api = require('./helpers/MockV1Api')
const assertRedirect = (method, path, expectedStatusCode, destination, cb) => const assertRedirect = (method, path, expectedStatusCode, destination, cb) =>
request[method](path, function(error, response) { request[method](path, (error, response) => {
should.not.exist(error) should.not.exist(error)
response.statusCode.should.equal(expectedStatusCode) response.statusCode.should.equal(expectedStatusCode)
response.headers.location.should.equal(destination) response.headers.location.should.equal(destination)
@ -28,61 +28,68 @@ describe('RedirectUrls', function() {
return this.timeout(1000) return this.timeout(1000)
}) })
it('proxy static URLs', done => it('proxy static URLs', function(done) {
assertRedirect('get', '/redirect/one', 302, '/destination/one', done)) return assertRedirect('get', '/redirect/one', 302, '/destination/one', done)
})
it('proxy dynamic URLs', done => it('proxy dynamic URLs', function(done) {
assertRedirect( return assertRedirect(
'get', 'get',
'/redirect/params/42', '/redirect/params/42',
302, 302,
'/destination/42/params', '/destination/42/params',
done done
)) )
})
it('proxy URLs with baseUrl', done => it('proxy URLs with baseUrl', function(done) {
assertRedirect( return assertRedirect(
'get', 'get',
'/redirect/base_url', '/redirect/base_url',
302, 302,
'https://example.com/destination/base_url', 'https://example.com/destination/base_url',
done done
)) )
})
it('proxy URLs with POST with a 307', done => it('proxy URLs with POST with a 307', function(done) {
assertRedirect( return assertRedirect(
'post', 'post',
'/redirect/get_and_post', '/redirect/get_and_post',
307, 307,
'/destination/get_and_post', '/destination/get_and_post',
done done
)) )
})
it('proxy URLs with multiple support methods', done => it('proxy URLs with multiple support methods', function(done) {
assertRedirect( return assertRedirect(
'get', 'get',
'/redirect/get_and_post', '/redirect/get_and_post',
302, 302,
'/destination/get_and_post', '/destination/get_and_post',
done done
)) )
})
it('redirects with query params', done => it('redirects with query params', function(done) {
assertRedirect( return assertRedirect(
'get', 'get',
'/redirect/qs?foo=bar&baz[]=qux1&baz[]=qux2', '/redirect/qs?foo=bar&baz[]=qux1&baz[]=qux2',
302, 302,
'/destination/qs?foo=bar&baz[]=qux1&baz[]=qux2', '/destination/qs?foo=bar&baz[]=qux1&baz[]=qux2',
done done
)) )
})
it("skips redirects if the 'skip-redirects' header is set", done => it("skips redirects if the 'skip-redirects' header is set", function(done) {
request.get( return request.get(
{ url: '/redirect/one', headers: { 'x-skip-redirects': 'true' } }, { url: '/redirect/one', headers: { 'x-skip-redirects': 'true' } },
function(error, response) { (error, response) => {
should.not.exist(error) should.not.exist(error)
response.statusCode.should.equal(404) response.statusCode.should.equal(404)
return done() return done()
} }
)) )
})
}) })

View file

@ -59,7 +59,7 @@ const tryLoginThroughRegistrationForm = function(
if (callback == null) { if (callback == null) {
callback = function(err, response, body) {} callback = function(err, response, body) {}
} }
return user.getCsrfToken(function(err) { return user.getCsrfToken(err => {
if (err != null) { if (err != null) {
return callback(err) return callback(err)
} }
@ -290,7 +290,7 @@ describe('LoginViaRegistration', function() {
return this.user1.addEmail(secondaryEmail, err => { return this.user1.addEmail(secondaryEmail, err => {
return this.user1.loginWith(secondaryEmail, err => { return this.user1.loginWith(secondaryEmail, err => {
expect(err != null).to.equal(false) expect(err != null).to.equal(false)
return this.user1.isLoggedIn(function(err, isLoggedIn) { return this.user1.isLoggedIn((err, isLoggedIn) => {
expect(isLoggedIn).to.equal(false) expect(isLoggedIn).to.equal(false)
return done() return done()
}) })
@ -299,7 +299,7 @@ describe('LoginViaRegistration', function() {
}) })
it('should have user1 login', function(done) { it('should have user1 login', function(done) {
return this.user1.login(function(err) { return this.user1.login(err => {
expect(err != null).to.equal(false) expect(err != null).to.equal(false)
return done() return done()
}) })

View file

@ -128,7 +128,7 @@ describe('RestoringFiles', function() {
version: 42 version: 42
} }
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
throw error throw error
} }
@ -175,7 +175,7 @@ describe('RestoringFiles', function() {
version: 42 version: 42
} }
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
throw error throw error
} }
@ -230,7 +230,7 @@ describe('RestoringFiles', function() {
version: 42 version: 42
} }
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
throw error throw error
} }
@ -276,7 +276,7 @@ describe('RestoringFiles', function() {
version: 42 version: 42
} }
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
throw error throw error
} }
@ -321,7 +321,7 @@ describe('RestoringFiles', function() {
version: 42 version: 42
} }
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
throw error throw error
} }

View file

@ -48,23 +48,26 @@ describe('SecurityHeaders', function() {
return (this.user = new User()) return (this.user = new User())
}) })
it('should not have x-powered-by header', done => it('should not have x-powered-by header', function(done) {
request.get('/', (err, res, body) => { return request.get('/', (err, res, body) => {
assert.isUndefined(res.headers['x-powered-by']) assert.isUndefined(res.headers['x-powered-by'])
return done() return done()
})) })
})
it('should have all common headers', done => it('should have all common headers', function(done) {
request.get('/', (err, res, body) => { return request.get('/', (err, res, body) => {
assert_has_common_headers(res) assert_has_common_headers(res)
return done() return done()
})) })
})
it('should not have cache headers on public pages', done => it('should not have cache headers on public pages', function(done) {
request.get('/', (err, res, body) => { return request.get('/', (err, res, body) => {
assert_has_no_cache_headers(res) assert_has_no_cache_headers(res)
return done() return done()
})) })
})
it('should have cache headers when user is logged in', function(done) { it('should have cache headers when user is logged in', function(done) {
return async.series( return async.series(

View file

@ -32,7 +32,7 @@ describe('Sessions', function() {
) )
}) })
describe('one session', () => describe('one session', function() {
it('should have one session in UserSessions set', function(done) { it('should have one session in UserSessions set', function(done) {
return async.series( return async.series(
[ [
@ -81,7 +81,8 @@ describe('Sessions', function() {
return done() return done()
} }
) )
})) })
})
describe('two sessions', function() { describe('two sessions', function() {
beforeEach(function() { beforeEach(function() {

View file

@ -42,7 +42,7 @@ describe('SettingsPage', function() {
}) })
it('load settings page', function(done) { it('load settings page', function(done) {
return this.user.getUserSettingsPage(function(err, statusCode) { return this.user.getUserSettingsPage((err, statusCode) => {
statusCode.should.equal(200) statusCode.should.equal(200)
return done() return done()
}) })
@ -52,7 +52,7 @@ describe('SettingsPage', function() {
const newEmail = 'foo@bar.com' const newEmail = 'foo@bar.com'
return this.user.updateSettings({ email: newEmail }, error => { return this.user.updateSettings({ email: newEmail }, error => {
should.not.exist(error) should.not.exist(error)
return this.user.get(function(error, user) { return this.user.get((error, user) => {
user.email.should.equal(newEmail) user.email.should.equal(newEmail)
user.emails.length.should.equal(1) user.emails.length.should.equal(1)
user.emails[0].email.should.equal(newEmail) user.emails[0].email.should.equal(newEmail)

View file

@ -145,7 +145,7 @@ describe('Subscriptions', function() {
// rebuild the view model with the redemptions // rebuild the view model with the redemptions
return SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel( return SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel(
this.user, this.user,
function(error, data) { (error, data) => {
expect(error).to.not.exist expect(error).to.not.exist
expect( expect(
data.personalSubscription.recurly.activeCoupons data.personalSubscription.recurly.activeCoupons

View file

@ -24,11 +24,7 @@ const try_read_access = (user, project_id, test, callback) =>
async.series( async.series(
[ [
cb => cb =>
user.request.get(`/project/${project_id}`, function( user.request.get(`/project/${project_id}`, (error, response, body) => {
error,
response,
body
) {
if (error != null) { if (error != null) {
return cb(error) return cb(error)
} }
@ -36,17 +32,16 @@ const try_read_access = (user, project_id, test, callback) =>
return cb() return cb()
}), }),
cb => cb =>
user.request.get(`/project/${project_id}/download/zip`, function( user.request.get(
error, `/project/${project_id}/download/zip`,
response, (error, response, body) => {
body if (error != null) {
) { return cb(error)
if (error != null) { }
return cb(error) test(response, body)
return cb()
} }
test(response, body) )
return cb()
})
], ],
callback callback
) )
@ -55,7 +50,7 @@ const try_read_only_token_access = (user, token, test, callback) =>
async.series( async.series(
[ [
cb => cb =>
user.request.get(`/read/${token}`, function(error, response, body) { user.request.get(`/read/${token}`, (error, response, body) => {
if (error != null) { if (error != null) {
return cb(error) return cb(error)
} }
@ -70,7 +65,7 @@ const try_read_and_write_token_access = (user, token, test, callback) =>
async.series( async.series(
[ [
cb => cb =>
user.request.get(`/${token}`, function(error, response, body) { user.request.get(`/${token}`, (error, response, body) => {
if (error != null) { if (error != null) {
return cb(error) return cb(error)
} }
@ -102,7 +97,7 @@ const try_content_access = function(user, project_id, test, callback) {
json: true, json: true,
jar: false jar: false
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
return callback(error) return callback(error)
} }
@ -142,7 +137,7 @@ const try_anon_content_access = function(
json: true, json: true,
jar: false jar: false
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
return callback(error) return callback(error)
} }
@ -851,9 +846,13 @@ describe('TokenAccess', function() {
}) })
describe('unimported v1 project', function() { describe('unimported v1 project', function() {
before(() => (settings.overleaf = { host: 'http://localhost:5000' })) before(function() {
return (settings.overleaf = { host: 'http://localhost:5000' })
})
after(() => delete settings.overleaf) after(function() {
return delete settings.overleaf
})
it('should show error page for read and write token', function(done) { it('should show error page for read and write token', function(done) {
const unimportedV1Token = '123abc' const unimportedV1Token = '123abc'
@ -955,7 +954,9 @@ describe('TokenAccess', function() {
}) })
describe('when importing check not configured', function() { describe('when importing check not configured', function() {
before(() => delete settings.projectImportingCheckMaxCreateDelta) before(function() {
return delete settings.projectImportingCheckMaxCreateDelta
})
it('should load editor', function(done) { it('should load editor', function(done) {
return try_read_and_write_token_access( return try_read_and_write_token_access(

View file

@ -49,7 +49,7 @@ describe('TpdsUpdateTests', function() {
sendImmediately: true sendImmediately: true
} }
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
throw error throw error
} }
@ -60,10 +60,7 @@ describe('TpdsUpdateTests', function() {
}) })
it('should have deleted the file', function(done) { it('should have deleted the file', function(done) {
return ProjectGetter.getProject(this.project_id, function( return ProjectGetter.getProject(this.project_id, (error, project) => {
error,
project
) {
if (error != null) { if (error != null) {
throw error throw error
} }

View file

@ -52,7 +52,7 @@ describe('UserEmails', function() {
cb => { cb => {
return this.user.request( return this.user.request(
{ url: '/user/emails', json: true }, { url: '/user/emails', json: true },
function(error, response, body) { (error, response, body) => {
expect(response.statusCode).to.equal(200) expect(response.statusCode).to.equal(200)
expect(body[0].confirmedAt).to.not.exist expect(body[0].confirmedAt).to.not.exist
expect(body[1].confirmedAt).to.not.exist expect(body[1].confirmedAt).to.not.exist
@ -100,7 +100,7 @@ describe('UserEmails', function() {
cb => { cb => {
return this.user.request( return this.user.request(
{ url: '/user/emails', json: true }, { url: '/user/emails', json: true },
function(error, response, body) { (error, response, body) => {
expect(response.statusCode).to.equal(200) expect(response.statusCode).to.equal(200)
expect(body[0].confirmedAt).to.not.exist expect(body[0].confirmedAt).to.not.exist
expect(body[1].confirmedAt).to.exist expect(body[1].confirmedAt).to.exist
@ -243,7 +243,7 @@ describe('UserEmails', function() {
cb => { cb => {
return this.user2.request( return this.user2.request(
{ url: '/user/emails', json: true }, { url: '/user/emails', json: true },
function(error, response, body) { (error, response, body) => {
expect(response.statusCode).to.equal(200) expect(response.statusCode).to.equal(200)
expect(body[0].confirmedAt).to.not.exist expect(body[0].confirmedAt).to.not.exist
expect(body[1].confirmedAt).to.exist expect(body[1].confirmedAt).to.exist
@ -257,7 +257,7 @@ describe('UserEmails', function() {
}) })
}) })
describe('with an expired token', () => describe('with an expired token', function() {
it('should not confirm the email', function(done) { it('should not confirm the email', function(done) {
let token = null let token = null
return async.series( return async.series(
@ -331,7 +331,8 @@ describe('UserEmails', function() {
], ],
done done
) )
})) })
})
describe('resending the confirmation', function() { describe('resending the confirmation', function() {
it('should generate a new token', function(done) { it('should generate a new token', function(done) {
@ -570,7 +571,7 @@ describe('UserEmails', function() {
cb => { cb => {
return this.user.request( return this.user.request(
{ url: '/user/emails', json: true }, { url: '/user/emails', json: true },
function(error, response, body) { (error, response, body) => {
expect(response.statusCode).to.equal(200) expect(response.statusCode).to.equal(200)
expect(body[0].confirmedAt).to.not.exist expect(body[0].confirmedAt).to.not.exist
expect(body[0].default).to.equal(false) expect(body[0].default).to.equal(false)
@ -641,7 +642,7 @@ describe('UserEmails', function() {
cb => { cb => {
return this.user.request( return this.user.request(
{ url: '/user/emails', json: true }, { url: '/user/emails', json: true },
function(error, response, body) { (error, response, body) => {
expect(body[0].default).to.equal(true) expect(body[0].default).to.equal(true)
expect(body[1].default).to.equal(false) expect(body[1].default).to.equal(false)
return cb() return cb()
@ -801,7 +802,7 @@ describe('UserEmails', function() {
cb => { cb => {
return this.user.request( return this.user.request(
{ url: '/user/emails', json: true }, { url: '/user/emails', json: true },
function(error, response, body) { (error, response, body) => {
expect(body[0].default).to.equal(false) expect(body[0].default).to.equal(false)
expect(body[1].default).to.equal(true) expect(body[1].default).to.equal(true)
return cb() return cb()

View file

@ -31,7 +31,7 @@ describe('User Must Reconfirm', function() {
it('should not allow sign in', function(done) { it('should not allow sign in', function(done) {
return this.user.login(err => { return this.user.login(err => {
expect(err != null).to.equal(false) expect(err != null).to.equal(false)
return this.user.isLoggedIn(function(err, isLoggedIn) { return this.user.isLoggedIn((err, isLoggedIn) => {
expect(isLoggedIn).to.equal(false) expect(isLoggedIn).to.equal(false)
return done() return done()
}) })

View file

@ -76,7 +76,7 @@ describe('ThirdPartyIdentityManager', function() {
}) })
}) })
describe('when third party identity does not exists', () => describe('when third party identity does not exists', function() {
it('should return error', function(done) { it('should return error', function(done) {
ThirdPartyIdentityManager.login( ThirdPartyIdentityManager.login(
this.provider, this.provider,
@ -87,23 +87,25 @@ describe('ThirdPartyIdentityManager', function() {
return done() return done()
} }
) )
})) })
})
}) })
describe('link', function() { describe('link', function() {
describe('when provider not already linked', () => describe('when provider not already linked', function() {
it('should link provider to user', function(done) { it('should link provider to user', function(done) {
ThirdPartyIdentityManager.link( ThirdPartyIdentityManager.link(
this.user.id, this.user.id,
this.provider, this.provider,
this.externalUserId, this.externalUserId,
this.externalData, this.externalData,
function(err, res) { (err, res) => {
expect(res.thirdPartyIdentifiers.length).to.equal(1) expect(res.thirdPartyIdentifiers.length).to.equal(1)
return done() return done()
} }
) )
})) })
})
describe('when provider is already linked', function() { describe('when provider is already linked', function() {
beforeEach(function(done) { beforeEach(function(done) {
@ -122,7 +124,7 @@ describe('ThirdPartyIdentityManager', function() {
this.provider, this.provider,
this.externalUserId, this.externalUserId,
this.externalData, this.externalData,
function(err, res) { (err, res) => {
expect(res).to.exist expect(res).to.exist
done() done()
} }
@ -135,7 +137,7 @@ describe('ThirdPartyIdentityManager', function() {
this.provider, this.provider,
this.externalUserId, this.externalUserId,
this.externalData, this.externalData,
function(err, user) { (err, user) => {
expect(user.thirdPartyIdentifiers.length).to.equal(1) expect(user.thirdPartyIdentifiers.length).to.equal(1)
return done() return done()
} }
@ -180,18 +182,19 @@ describe('ThirdPartyIdentityManager', function() {
}) })
describe('unlink', function() { describe('unlink', function() {
describe('when provider not already linked', () => describe('when provider not already linked', function() {
it('should succeed', function(done) { it('should succeed', function(done) {
return ThirdPartyIdentityManager.unlink( return ThirdPartyIdentityManager.unlink(
this.user.id, this.user.id,
this.provider, this.provider,
function(err, res) { (err, res) => {
expect(err).to.be.null expect(err).to.be.null
expect(res.thirdPartyIdentifiers.length).to.equal(0) expect(res.thirdPartyIdentifiers.length).to.equal(0)
return done() return done()
} }
) )
})) })
})
describe('when provider is already linked', function() { describe('when provider is already linked', function() {
beforeEach(function(done) { beforeEach(function(done) {

View file

@ -47,20 +47,19 @@ module.exports = MockClsiApi = {
app.post('/project/:project_id/compile', compile) app.post('/project/:project_id/compile', compile)
app.post('/project/:project_id/user/:user_id/compile', compile) app.post('/project/:project_id/user/:user_id/compile', compile)
app.get('/project/:project_id/build/:build_id/output/*', function( app.get(
req, '/project/:project_id/build/:build_id/output/*',
res, (req, res, next) => {
next const filename = req.params[0]
) { if (filename === 'project.pdf') {
const filename = req.params[0] return res.status(200).send('mock-pdf')
if (filename === 'project.pdf') { } else if (filename === 'project.log') {
return res.status(200).send('mock-pdf') return res.status(200).send('mock-log')
} else if (filename === 'project.log') { } else {
return res.status(200).send('mock-log') return res.sendStatus(404)
} else { }
return res.sendStatus(404)
} }
}) )
app.get( app.get(
'/project/:project_id/user/:user_id/build/:build_id/output/:output_path', '/project/:project_id/user/:user_id/build/:build_id/output/:output_path',
@ -74,12 +73,12 @@ module.exports = MockClsiApi = {
}) })
return app return app
.listen(3013, function(error) { .listen(3013, error => {
if (error != null) { if (error != null) {
throw error throw error
} }
}) })
.on('error', function(error) { .on('error', error => {
console.error('error starting MockClsiApi:', error.message) console.error('error starting MockClsiApi:', error.message)
return process.exit(1) return process.exit(1)
}) })

View file

@ -93,12 +93,12 @@ module.exports = MockDocUpdaterApi = {
}) })
return app return app
.listen(3003, function(error) { .listen(3003, error => {
if (error != null) { if (error != null) {
throw error throw error
} }
}) })
.on('error', function(error) { .on('error', error => {
console.error('error starting MockDocUpdaterApi:', error.message) console.error('error starting MockDocUpdaterApi:', error.message)
return process.exit(1) return process.exit(1)
}) })

View file

@ -83,12 +83,12 @@ module.exports = MockDocStoreApi = {
}) })
return app return app
.listen(3016, function(error) { .listen(3016, error => {
if (error != null) { if (error != null) {
throw error throw error
} }
}) })
.on('error', function(error) { .on('error', error => {
console.error('error starting MockDocStoreApi:', error.message) console.error('error starting MockDocStoreApi:', error.message)
return process.exit(1) return process.exit(1)
}) })

View file

@ -64,12 +64,12 @@ module.exports = MockFileStoreApi = {
) )
return app return app
.listen(3009, function(error) { .listen(3009, error => {
if (error != null) { if (error != null) {
throw error throw error
} }
}) })
.on('error', function(error) { .on('error', error => {
console.error('error starting MockFileStoreApi:', error.message) console.error('error starting MockFileStoreApi:', error.message)
return process.exit(1) return process.exit(1)
}) })

View file

@ -153,12 +153,12 @@ module.exports = MockProjectHistoryApi = {
}) })
return app return app
.listen(3054, function(error) { .listen(3054, error => {
if (error != null) { if (error != null) {
throw error throw error
} }
}) })
.on('error', function(error) { .on('error', error => {
console.error('error starting MockProjectHistoryApi:', error.message) console.error('error starting MockProjectHistoryApi:', error.message)
return process.exit(1) return process.exit(1)
}) })

View file

@ -100,7 +100,7 @@ module.exports = MockRecurlyApi = {
`) `)
}) })
return app.listen(6034, function(error) { return app.listen(6034, error => {
if (error != null) { if (error != null) {
throw error throw error
} }

View file

@ -16,12 +16,12 @@ const MockTagsApi = {
}) })
app app
.listen(3012, function(error) { .listen(3012, error => {
if (error) { if (error) {
throw error throw error
} }
}) })
.on('error', function(error) { .on('error', error => {
console.error('error starting MockTagsApi:', error.message) console.error('error starting MockTagsApi:', error.message)
process.exit(1) process.exit(1)
}) })

View file

@ -260,12 +260,12 @@ module.exports = MockV1Api = {
) )
return app return app
.listen(5000, function(error) { .listen(5000, error => {
if (error != null) { if (error != null) {
throw error throw error
} }
}) })
.on('error', function(error) { .on('error', error => {
console.error('error starting MockV1Api:', error.message) console.error('error starting MockV1Api:', error.message)
return process.exit(1) return process.exit(1)
}) })

View file

@ -61,12 +61,12 @@ module.exports = MockV1HistoryApi = {
) )
return app return app
.listen(3100, function(error) { .listen(3100, error => {
if (error != null) { if (error != null) {
throw error throw error
} }
}) })
.on('error', function(error) { .on('error', error => {
console.error('error starting MockV1HistoryApi:', error.message) console.error('error starting MockV1HistoryApi:', error.message)
return process.exit(1) return process.exit(1)
}) })

View file

@ -331,7 +331,7 @@ class User {
return db.projects.remove( return db.projects.remove(
{ owner_ref: ObjectId(user_id) }, { owner_ref: ObjectId(user_id) },
{ multi: true }, { multi: true },
function(err) { err => {
if (err != null) { if (err != null) {
callback(err) callback(err)
} }
@ -398,7 +398,7 @@ class User {
url: '/project/new', url: '/project/new',
json: Object.assign({ projectName: name }, options) json: Object.assign({ projectName: name }, options)
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
return callback(error) return callback(error)
} }
@ -425,7 +425,7 @@ class User {
{ {
url: `/project/${project_id}?forever=true` url: `/project/${project_id}?forever=true`
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
return callback(error) return callback(error)
} }
@ -453,7 +453,7 @@ class User {
{ {
url: `/project/${project_id}` url: `/project/${project_id}`
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
return callback(error) return callback(error)
} }
@ -517,7 +517,7 @@ class User {
publicAccessLevel: level publicAccessLevel: level
} }
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
return callback(error) return callback(error)
} }
@ -537,7 +537,7 @@ class User {
publicAccessLevel: 'private' publicAccessLevel: 'private'
} }
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
return callback(error) return callback(error)
} }
@ -557,7 +557,7 @@ class User {
publicAccessLevel: 'tokenBased' publicAccessLevel: 'tokenBased'
} }
}, },
function(error, response, body) { (error, response, body) => {
if (error != null) { if (error != null) {
return callback(error) return callback(error)
} }
@ -729,11 +729,7 @@ class User {
if (callback == null) { if (callback == null) {
callback = function(error, loggedIn) {} callback = function(error, loggedIn) {}
} }
return this.request.get('/user/personal_info', function( return this.request.get('/user/personal_info', (error, response, body) => {
error,
response,
body
) {
if (error != null) { if (error != null) {
return callback(error) return callback(error)
} }

View file

@ -36,7 +36,7 @@ module.exports = {
callback = function(err) {} callback = function(err) {}
} }
const sessionSetKey = UserSessionsRedis.sessionSetKey(user) const sessionSetKey = UserSessionsRedis.sessionSetKey(user)
return rclient.smembers(sessionSetKey, function(err, sessionKeys) { return rclient.smembers(sessionSetKey, (err, sessionKeys) => {
if (err) { if (err) {
return callback(err) return callback(err)
} }
@ -45,7 +45,7 @@ module.exports = {
} }
const actions = sessionKeys.map(k => cb => rclient.del(k, err => cb(err))) const actions = sessionKeys.map(k => cb => rclient.del(k, err => cb(err)))
return Async.series(actions, (err, results) => return Async.series(actions, (err, results) =>
rclient.srem(sessionSetKey, sessionKeys, function(err) { rclient.srem(sessionSetKey, sessionKeys, err => {
if (err) { if (err) {
return callback(err) return callback(err)
} }

View file

@ -36,7 +36,7 @@ const RateLimiter = require('../../../app/src/infrastructure/RateLimiter.js')
// Change cookie to be non secure so curl will send it // Change cookie to be non secure so curl will send it
const convertCookieFile = function(callback) { const convertCookieFile = function(callback) {
fs = require('fs') fs = require('fs')
return fs.readFile(cookeFilePath, 'utf8', function(err, data) { return fs.readFile(cookeFilePath, 'utf8', (err, data) => {
if (err) { if (err) {
return callback(err) return callback(err)
} }
@ -44,7 +44,7 @@ const convertCookieFile = function(callback) {
const secondTrue = data.indexOf('TRUE', firstTrue + 4) const secondTrue = data.indexOf('TRUE', firstTrue + 4)
const result = const result =
data.slice(0, secondTrue) + 'FALSE' + data.slice(secondTrue + 4) data.slice(0, secondTrue) + 'FALSE' + data.slice(secondTrue + 4)
return fs.writeFile(cookeFilePath, result, 'utf8', function(err) { return fs.writeFile(cookeFilePath, result, 'utf8', err => {
if (err) { if (err) {
return callback(err) return callback(err)
} }
@ -56,9 +56,7 @@ const convertCookieFile = function(callback) {
describe('Opening', function() { describe('Opening', function() {
before(function(done) { before(function(done) {
logger.log('smoke test: setup') logger.log('smoke test: setup')
LoginRateLimiter.recordSuccessfulLogin(Settings.smokeTest.user, function( LoginRateLimiter.recordSuccessfulLogin(Settings.smokeTest.user, err => {
err
) {
if (err != null) { if (err != null) {
logger.err({ err }, 'smoke test: error recoring successful login') logger.err({ err }, 'smoke test: error recoring successful login')
return done(err) return done(err)
@ -66,7 +64,7 @@ describe('Opening', function() {
return RateLimiter.clearRateLimit( return RateLimiter.clearRateLimit(
'open-project', 'open-project',
`${Settings.smokeTest.projectId}:${Settings.smokeTest.userId}`, `${Settings.smokeTest.projectId}:${Settings.smokeTest.userId}`,
function(err) { err => {
if (err != null) { if (err != null) {
logger.err( logger.err(
{ err }, { err },
@ -77,7 +75,7 @@ describe('Opening', function() {
return RateLimiter.clearRateLimit( return RateLimiter.clearRateLimit(
'overleaf-login', 'overleaf-login',
Settings.smokeTest.rateLimitSubject, Settings.smokeTest.rateLimitSubject,
function(err) { err => {
if (err != null) { if (err != null) {
logger.err( logger.err(
{ err }, { err },
@ -98,13 +96,13 @@ describe('Opening', function() {
let command = `\ let command = `\
curl -H "X-Forwarded-Proto: https" -c ${cookeFilePath} ${buildUrl('dev/csrf')}\ curl -H "X-Forwarded-Proto: https" -c ${cookeFilePath} ${buildUrl('dev/csrf')}\
` `
child.exec(command, function(err, stdout, stderr) { child.exec(command, (err, stdout, stderr) => {
if (err != null) { if (err != null) {
done(err) done(err)
} }
const csrf = stdout const csrf = stdout
logger.log('smoke test: converting cookie file 1') logger.log('smoke test: converting cookie file 1')
return convertCookieFile(function(err) { return convertCookieFile(err => {
if (err != null) { if (err != null) {
return done(err) return done(err)
} }
@ -114,7 +112,7 @@ curl -c ${cookeFilePath} -H "Content-Type: application/json" -H "X-Forwarded-Pro
Settings.smokeTest.user Settings.smokeTest.user
}", "password":"${Settings.smokeTest.password}"}' ${buildUrl('login')}\ }", "password":"${Settings.smokeTest.password}"}' ${buildUrl('login')}\
` `
return child.exec(command, function(err) { return child.exec(command, err => {
if (err != null) { if (err != null) {
return done(err) return done(err)
} }
@ -127,7 +125,7 @@ curl -c ${cookeFilePath} -H "Content-Type: application/json" -H "X-Forwarded-Pro
after(function(done) { after(function(done) {
logger.log('smoke test: converting cookie file 2') logger.log('smoke test: converting cookie file 2')
convertCookieFile(function(err) { convertCookieFile(err => {
if (err != null) { if (err != null) {
return done(err) return done(err)
} }
@ -135,13 +133,13 @@ curl -c ${cookeFilePath} -H "Content-Type: application/json" -H "X-Forwarded-Pro
let command = `\ let command = `\
curl -H "X-Forwarded-Proto: https" -c ${cookeFilePath} ${buildUrl('dev/csrf')}\ curl -H "X-Forwarded-Proto: https" -c ${cookeFilePath} ${buildUrl('dev/csrf')}\
` `
return child.exec(command, function(err, stdout, stderr) { return child.exec(command, (err, stdout, stderr) => {
if (err != null) { if (err != null) {
done(err) done(err)
} }
const csrf = stdout const csrf = stdout
logger.log('smoke test: converting cookie file 3') logger.log('smoke test: converting cookie file 3')
return convertCookieFile(function(err) { return convertCookieFile(err => {
if (err != null) { if (err != null) {
return done(err) return done(err)
} }
@ -150,7 +148,7 @@ curl -H "Content-Type: application/json" -H "X-Forwarded-Proto: https" -d '{"_cs
'logout' 'logout'
)}\ )}\
` `
return child.exec(command, function(err, stdout, stderr) { return child.exec(command, (err, stdout, stderr) => {
if (err != null) { if (err != null) {
return done(err) return done(err)
} }
@ -169,7 +167,7 @@ curl -H "X-Forwarded-Proto: https" -v ${buildUrl(
`project/${Settings.smokeTest.projectId}` `project/${Settings.smokeTest.projectId}`
)}\ )}\
` `
return child.exec(command, function(error, stdout, stderr) { return child.exec(command, (error, stdout, stderr) => {
expect(error, 'smoke test: error in getting project').to.not.exist expect(error, 'smoke test: error in getting project').to.not.exist
const statusCodeMatch = !!stderr.match('200 OK') const statusCodeMatch = !!stderr.match('200 OK')
@ -196,11 +194,9 @@ curl -H "X-Forwarded-Proto: https" -v ${buildUrl(
const command = `\ const command = `\
curl -H "X-Forwarded-Proto: https" -v ${buildUrl('project')}\ curl -H "X-Forwarded-Proto: https" -v ${buildUrl('project')}\
` `
return child.exec(command, function(error, stdout, stderr) { return child.exec(command, (error, stdout, stderr) => {
expect( expect(error, 'smoke test: error returned in getting project list').to.not
error, .exist
'smoke test: error returned in getting project list'
).to.not.exist
expect( expect(
!!stderr.match('200 OK'), !!stderr.match('200 OK'),
'smoke test: response code is not 200 getting project list' 'smoke test: response code is not 200 getting project list'

View file

@ -98,7 +98,9 @@ describe('AuthenticationController', function() {
this.next = sinon.stub() this.next = sinon.stub()
}) })
afterEach(() => tk.reset()) afterEach(function() {
return tk.reset()
})
describe('isUserLoggedIn', function() { describe('isUserLoggedIn', function() {
beforeEach(function() { beforeEach(function() {
@ -1007,7 +1009,7 @@ describe('AuthenticationController', function() {
}) })
}) })
describe('_getSafeRedirectPath', () => describe('_getSafeRedirectPath', function() {
it('sanitize redirect path to prevent open redirects', function() { it('sanitize redirect path to prevent open redirects', function() {
expect( expect(
this.AuthenticationController._getSafeRedirectPath('https://evil.com') this.AuthenticationController._getSafeRedirectPath('https://evil.com')
@ -1030,7 +1032,8 @@ describe('AuthenticationController', function() {
return expect( return expect(
this.AuthenticationController._getSafeRedirectPath('.evil.com') this.AuthenticationController._getSafeRedirectPath('.evil.com')
).to.equal('/.evil.com') ).to.equal('/.evil.com')
})) })
})
describe('_clearRedirectFromSession', function() { describe('_clearRedirectFromSession', function() {
beforeEach(function() { beforeEach(function() {

View file

@ -308,13 +308,14 @@ describe('AuthenticationManager', function() {
}) })
describe('validateEmail', function() { describe('validateEmail', function() {
describe('valid', () => describe('valid', function() {
it('should return null', function() { it('should return null', function() {
const result = this.AuthenticationManager.validateEmail( const result = this.AuthenticationManager.validateEmail(
'foo@example.com' 'foo@example.com'
) )
return expect(result).to.equal(null) return expect(result).to.equal(null)
})) })
})
describe('invalid', function() { describe('invalid', function() {
it('should return validation error object for no email', function() { it('should return validation error object for no email', function() {
@ -338,12 +339,13 @@ describe('AuthenticationManager', function() {
'0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef012345678') '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef012345678')
}) })
describe('with a null password', () => describe('with a null password', function() {
it('should return an error', function() { it('should return an error', function() {
return expect(this.AuthenticationManager.validatePassword()).to.eql({ return expect(this.AuthenticationManager.validatePassword()).to.eql({
message: 'password not set' message: 'password not set'
}) })
})) })
})
describe('password length', function() { describe('password length', function() {
describe('with the default password length options', function() { describe('with the default password length options', function() {
@ -519,7 +521,7 @@ describe('AuthenticationManager', function() {
return this.AuthenticationManager.setUserPassword( return this.AuthenticationManager.setUserPassword(
this.user_id, this.user_id,
this.password, this.password,
function(err) { err => {
expect(err).to.exist expect(err).to.exist
return done() return done()
} }
@ -554,7 +556,7 @@ describe('AuthenticationManager', function() {
return this.AuthenticationManager.setUserPassword( return this.AuthenticationManager.setUserPassword(
this.user_id, this.user_id,
this.password, this.password,
function(err) { err => {
expect(err).to.exist expect(err).to.exist
return done() return done()
} }

View file

@ -562,7 +562,7 @@ describe('AuthorizationManager', function() {
this.user_id, this.user_id,
this.project_id, this.project_id,
this.token, this.token,
function(error, canRead) { (error, canRead) => {
expect(canRead).to.equal(true) expect(canRead).to.equal(true)
return done() return done()
} }
@ -582,7 +582,7 @@ describe('AuthorizationManager', function() {
this.user_id, this.user_id,
this.project_id, this.project_id,
this.token, this.token,
function(error, canRead) { (error, canRead) => {
expect(canRead).to.equal(true) expect(canRead).to.equal(true)
return done() return done()
} }
@ -602,7 +602,7 @@ describe('AuthorizationManager', function() {
this.user_id, this.user_id,
this.project_id, this.project_id,
this.token, this.token,
function(error, canRead) { (error, canRead) => {
expect(canRead).to.equal(true) expect(canRead).to.equal(true)
return done() return done()
} }
@ -622,7 +622,7 @@ describe('AuthorizationManager', function() {
this.user_id, this.user_id,
this.project_id, this.project_id,
this.token, this.token,
function(error, canRead) { (error, canRead) => {
expect(canRead).to.equal(false) expect(canRead).to.equal(false)
return done() return done()
} }
@ -648,7 +648,7 @@ describe('AuthorizationManager', function() {
this.user_id, this.user_id,
this.project_id, this.project_id,
this.token, this.token,
function(error, canWrite) { (error, canWrite) => {
expect(canWrite).to.equal(true) expect(canWrite).to.equal(true)
return done() return done()
} }
@ -668,7 +668,7 @@ describe('AuthorizationManager', function() {
this.user_id, this.user_id,
this.project_id, this.project_id,
this.token, this.token,
function(error, canWrite) { (error, canWrite) => {
expect(canWrite).to.equal(true) expect(canWrite).to.equal(true)
return done() return done()
} }
@ -688,7 +688,7 @@ describe('AuthorizationManager', function() {
this.user_id, this.user_id,
this.project_id, this.project_id,
this.token, this.token,
function(error, canWrite) { (error, canWrite) => {
expect(canWrite).to.equal(false) expect(canWrite).to.equal(false)
return done() return done()
} }
@ -708,7 +708,7 @@ describe('AuthorizationManager', function() {
this.user_id, this.user_id,
this.project_id, this.project_id,
this.token, this.token,
function(error, canWrite) { (error, canWrite) => {
expect(canWrite).to.equal(false) expect(canWrite).to.equal(false)
return done() return done()
} }
@ -734,7 +734,7 @@ describe('AuthorizationManager', function() {
this.user_id, this.user_id,
this.project_id, this.project_id,
this.token, this.token,
function(error, canWrite) { (error, canWrite) => {
expect(canWrite).to.equal(true) expect(canWrite).to.equal(true)
return done() return done()
} }
@ -754,7 +754,7 @@ describe('AuthorizationManager', function() {
this.user_id, this.user_id,
this.project_id, this.project_id,
this.token, this.token,
function(error, canWrite) { (error, canWrite) => {
expect(canWrite).to.equal(true) expect(canWrite).to.equal(true)
return done() return done()
} }
@ -774,7 +774,7 @@ describe('AuthorizationManager', function() {
this.user_id, this.user_id,
this.project_id, this.project_id,
this.token, this.token,
function(error, canWrite) { (error, canWrite) => {
expect(canWrite).to.equal(false) expect(canWrite).to.equal(false)
return done() return done()
} }
@ -794,7 +794,7 @@ describe('AuthorizationManager', function() {
this.user_id, this.user_id,
this.project_id, this.project_id,
this.token, this.token,
function(error, canWrite) { (error, canWrite) => {
expect(canWrite).to.equal(false) expect(canWrite).to.equal(false)
return done() return done()
} }
@ -814,7 +814,7 @@ describe('AuthorizationManager', function() {
this.user_id, this.user_id,
this.project_id, this.project_id,
this.token, this.token,
function(error, canWrite) { (error, canWrite) => {
expect(canWrite).to.equal(false) expect(canWrite).to.equal(false)
return done() return done()
} }
@ -840,7 +840,7 @@ describe('AuthorizationManager', function() {
this.user_id, this.user_id,
this.project_id, this.project_id,
this.token, this.token,
function(error, canAdmin) { (error, canAdmin) => {
expect(canAdmin).to.equal(true) expect(canAdmin).to.equal(true)
return done() return done()
} }
@ -860,7 +860,7 @@ describe('AuthorizationManager', function() {
this.user_id, this.user_id,
this.project_id, this.project_id,
this.token, this.token,
function(error, canAdmin) { (error, canAdmin) => {
expect(canAdmin).to.equal(false) expect(canAdmin).to.equal(false)
return done() return done()
} }
@ -880,7 +880,7 @@ describe('AuthorizationManager', function() {
this.user_id, this.user_id,
this.project_id, this.project_id,
this.token, this.token,
function(error, canAdmin) { (error, canAdmin) => {
expect(canAdmin).to.equal(false) expect(canAdmin).to.equal(false)
return done() return done()
} }
@ -900,7 +900,7 @@ describe('AuthorizationManager', function() {
this.user_id, this.user_id,
this.project_id, this.project_id,
this.token, this.token,
function(error, canAdmin) { (error, canAdmin) => {
expect(canAdmin).to.equal(false) expect(canAdmin).to.equal(false)
return done() return done()
} }
@ -922,13 +922,13 @@ describe('AuthorizationManager', function() {
}) })
it('should return true', function(done) { it('should return true', function(done) {
return this.AuthorizationManager.isUserSiteAdmin(this.user_id, function( return this.AuthorizationManager.isUserSiteAdmin(
error, this.user_id,
isAdmin (error, isAdmin) => {
) { expect(isAdmin).to.equal(true)
expect(isAdmin).to.equal(true) return done()
return done() }
}) )
}) })
}) })
@ -940,13 +940,13 @@ describe('AuthorizationManager', function() {
}) })
it('should return false', function(done) { it('should return false', function(done) {
return this.AuthorizationManager.isUserSiteAdmin(this.user_id, function( return this.AuthorizationManager.isUserSiteAdmin(
error, this.user_id,
isAdmin (error, isAdmin) => {
) { expect(isAdmin).to.equal(false)
expect(isAdmin).to.equal(false) return done()
return done() }
}) )
}) })
}) })
@ -958,17 +958,17 @@ describe('AuthorizationManager', function() {
}) })
it('should return false', function(done) { it('should return false', function(done) {
return this.AuthorizationManager.isUserSiteAdmin(this.user_id, function( return this.AuthorizationManager.isUserSiteAdmin(
error, this.user_id,
isAdmin (error, isAdmin) => {
) { expect(isAdmin).to.equal(false)
expect(isAdmin).to.equal(false) return done()
return done() }
}) )
}) })
}) })
describe('when no user is passed', () => describe('when no user is passed', function() {
it('should return false', function(done) { it('should return false', function(done) {
return this.AuthorizationManager.isUserSiteAdmin( return this.AuthorizationManager.isUserSiteAdmin(
null, null,
@ -978,6 +978,7 @@ describe('AuthorizationManager', function() {
return done() return done()
} }
) )
})) })
})
}) })
}) })

View file

@ -231,7 +231,7 @@ describe('AuthorizationMiddleware', function() {
return this.AuthorizationMiddleware[middlewareMethod]( return this.AuthorizationMiddleware[middlewareMethod](
this.req, this.req,
this.res, this.res,
function(error) { error => {
error.should.be.instanceof(Errors.NotFoundError) error.should.be.instanceof(Errors.NotFoundError)
return done() return done()
} }
@ -392,7 +392,7 @@ describe('AuthorizationMiddleware', function() {
}) })
}) })
describe('with anonymous user', () => describe('with anonymous user', function() {
describe('when user has permission', function() { describe('when user has permission', function() {
describe('when user has permission to access all projects', function() { describe('when user has permission to access all projects', function() {
beforeEach(function() { beforeEach(function() {
@ -438,6 +438,7 @@ describe('AuthorizationMiddleware', function() {
.should.equal(true) .should.equal(true)
}) })
}) })
})) })
})
}) })
}) })

View file

@ -93,7 +93,7 @@ describe('BlogController', function() {
}) })
}) })
describe('getIndexPage', () => describe('getIndexPage', function() {
it('should change the url and send it to getPage', function(done) { it('should change the url and send it to getPage', function(done) {
this.req.url = '/blog' this.req.url = '/blog'
this.BlogController.getPage = function(req, res) { this.BlogController.getPage = function(req, res) {
@ -101,5 +101,6 @@ describe('BlogController', function() {
return done() return done()
} }
return this.BlogController.getIndexPage(this.req, this.res) return this.BlogController.getIndexPage(this.req, this.res)
})) })
})
}) })

View file

@ -178,7 +178,7 @@ describe('ChatController', function() {
] ]
} }
}, },
function(error, threads) { (error, threads) => {
expect(threads).to.deep.equal({ expect(threads).to.deep.equal({
thread1: { thread1: {
resolved: true, resolved: true,

View file

@ -123,7 +123,7 @@ describe('CollaboratorsHandler', function() {
it('should return a NotFoundError', function(done) { it('should return a NotFoundError', function(done) {
return this.CollaboratorHandler.getMemberIdsWithPrivilegeLevels( return this.CollaboratorHandler.getMemberIdsWithPrivilegeLevels(
this.project_id, this.project_id,
function(error) { error => {
error.should.be.instanceof(Errors.NotFoundError) error.should.be.instanceof(Errors.NotFoundError)
return done() return done()
} }
@ -383,7 +383,7 @@ describe('CollaboratorsHandler', function() {
return this.CollaboratorHandler.getMemberIdPrivilegeLevel( return this.CollaboratorHandler.getMemberIdPrivilegeLevel(
'member-id-2', 'member-id-2',
this.project_id, this.project_id,
function(error, level) { (error, level) => {
expect(level).to.equal('readOnly') expect(level).to.equal('readOnly')
return done() return done()
} }
@ -394,7 +394,7 @@ describe('CollaboratorsHandler', function() {
return this.CollaboratorHandler.getMemberIdPrivilegeLevel( return this.CollaboratorHandler.getMemberIdPrivilegeLevel(
'member-id-3', 'member-id-3',
this.project_id, this.project_id,
function(error, level) { (error, level) => {
expect(level).to.equal(false) expect(level).to.equal(false)
return done() return done()
} }

View file

@ -299,13 +299,13 @@ describe('ClsiCookieManager', function() {
}, },
requires: this.requires requires: this.requires
})() })()
return this.ClsiCookieManager.getCookieJar(this.project_id, function( return this.ClsiCookieManager.getCookieJar(
err, this.project_id,
jar (err, jar) => {
) { assert.deepEqual(jar, realRequst.jar())
assert.deepEqual(jar, realRequst.jar()) return done()
return done() }
}) )
}) })
}) })
}) })

View file

@ -154,7 +154,7 @@ describe('ClsiFormatChecker', function() {
return this.ClsiFormatChecker._checkForConflictingPaths( return this.ClsiFormatChecker._checkForConflictingPaths(
this.resources, this.resources,
function(err, conflictPathErrors) { (err, conflictPathErrors) => {
conflictPathErrors.length.should.equal(1) conflictPathErrors.length.should.equal(1)
conflictPathErrors[0].path.should.equal('stuff/image') conflictPathErrors[0].path.should.equal('stuff/image')
return done() return done()
@ -170,7 +170,7 @@ describe('ClsiFormatChecker', function() {
return this.ClsiFormatChecker._checkForConflictingPaths( return this.ClsiFormatChecker._checkForConflictingPaths(
this.resources, this.resources,
function(err, conflictPathErrors) { (err, conflictPathErrors) => {
conflictPathErrors.length.should.equal(1) conflictPathErrors.length.should.equal(1)
conflictPathErrors[0].path.should.equal('stuff') conflictPathErrors[0].path.should.equal('stuff')
return done() return done()
@ -186,7 +186,7 @@ describe('ClsiFormatChecker', function() {
return this.ClsiFormatChecker._checkForConflictingPaths( return this.ClsiFormatChecker._checkForConflictingPaths(
this.resources, this.resources,
function(err, conflictPathErrors) { (err, conflictPathErrors) => {
conflictPathErrors.length.should.equal(0) conflictPathErrors.length.should.equal(0)
return done() return done()
} }
@ -212,7 +212,7 @@ describe('ClsiFormatChecker', function() {
return this.ClsiFormatChecker._checkDocsAreUnderSizeLimit( return this.ClsiFormatChecker._checkDocsAreUnderSizeLimit(
this.resources, this.resources,
function(err, sizeError) { (err, sizeError) => {
sizeError.totalSize.should.equal(10000016) sizeError.totalSize.should.equal(10000016)
sizeError.resources.length.should.equal(10) sizeError.resources.length.should.equal(10)
sizeError.resources[0].path.should.equal('massive.tex') sizeError.resources[0].path.should.equal('massive.tex')
@ -239,7 +239,7 @@ describe('ClsiFormatChecker', function() {
return this.ClsiFormatChecker._checkDocsAreUnderSizeLimit( return this.ClsiFormatChecker._checkDocsAreUnderSizeLimit(
this.resources, this.resources,
function(err, sizeError) { (err, sizeError) => {
expect(sizeError).to.not.exist expect(sizeError).to.not.exist
return done() return done()
} }

View file

@ -784,7 +784,7 @@ describe('ClsiManager', function() {
}) })
}) })
describe('with the draft option', () => describe('with the draft option', function() {
it('should add the draft option into the request', function(done) { it('should add the draft option into the request', function(done) {
return this.ClsiManager._buildRequest( return this.ClsiManager._buildRequest(
this.project_id, this.project_id,
@ -794,7 +794,8 @@ describe('ClsiManager', function() {
return done() return done()
} }
) )
})) })
})
}) })
describe('_postToClsi', function() { describe('_postToClsi', function() {

View file

@ -478,7 +478,7 @@ describe('CompileController', function() {
}) })
}) })
describe('user with priority compile', () => describe('user with priority compile', function() {
beforeEach(function() { beforeEach(function() {
this.CompileManager.getProjectCompileLimits = sinon this.CompileManager.getProjectCompileLimits = sinon
.stub() .stub()
@ -490,7 +490,8 @@ describe('CompileController', function() {
this.res, this.res,
this.next this.next
) )
})) })
})
describe('user with standard priority via query string', function() { describe('user with standard priority via query string', function() {
beforeEach(function() { beforeEach(function() {

View file

@ -154,7 +154,7 @@ describe('CompileManager', function() {
}) })
}) })
describe('when the project has been recently compiled', () => describe('when the project has been recently compiled', function() {
it('should return', function(done) { it('should return', function(done) {
this.CompileManager._checkIfAutoCompileLimitHasBeenHit = ( this.CompileManager._checkIfAutoCompileLimitHasBeenHit = (
isAutoCompile, isAutoCompile,
@ -168,14 +168,15 @@ describe('CompileManager', function() {
this.project_id, this.project_id,
this.user_id, this.user_id,
{}, {},
function(err, status) { (err, status) => {
status.should.equal('too-recently-compiled') status.should.equal('too-recently-compiled')
return done() return done()
} }
) )
})) })
})
describe('should check the rate limit', () => describe('should check the rate limit', function() {
it('should return', function(done) { it('should return', function(done) {
this.CompileManager._checkIfAutoCompileLimitHasBeenHit = sinon this.CompileManager._checkIfAutoCompileLimitHasBeenHit = sinon
.stub() .stub()
@ -184,12 +185,13 @@ describe('CompileManager', function() {
this.project_id, this.project_id,
this.user_id, this.user_id,
{}, {},
function(err, status) { (err, status) => {
status.should.equal('autocompile-backoff') status.should.equal('autocompile-backoff')
return done() return done()
} }
) )
})) })
})
}) })
describe('getProjectCompileLimits', function() { describe('getProjectCompileLimits', function() {

View file

@ -35,12 +35,13 @@ describe('CooldownManager', function() {
})) }))
}) })
describe('_buildKey', () => describe('_buildKey', function() {
it('should build a properly formatted redis key', function() { it('should build a properly formatted redis key', function() {
return expect(this.CooldownManager._buildKey('ABC')).to.equal( return expect(this.CooldownManager._buildKey('ABC')).to.equal(
'Cooldown:{ABC}' 'Cooldown:{ABC}'
) )
})) })
})
describe('isProjectOnCooldown', function() { describe('isProjectOnCooldown', function() {
beforeEach(function() { beforeEach(function() {

View file

@ -812,7 +812,7 @@ describe('DocumentUpdaterHandler', function() {
return this.request.callsArgWith(1, null, { statusCode: 204 }, '') return this.request.callsArgWith(1, null, { statusCode: 204 }, '')
}) })
describe('when an entity has changed name', () => describe('when an entity has changed name', function() {
it('should send the structure update to the document updater', function(done) { it('should send the structure update to the document updater', function(done) {
this.docIdA = new ObjectId() this.docIdA = new ObjectId()
this.docIdB = new ObjectId() this.docIdB = new ObjectId()
@ -865,9 +865,10 @@ describe('DocumentUpdaterHandler', function() {
return done() return done()
} }
) )
})) })
})
describe('when a doc has been added', () => describe('when a doc has been added', function() {
it('should send the structure update to the document updater', function(done) { it('should send the structure update to the document updater', function(done) {
this.docId = new ObjectId() this.docId = new ObjectId()
this.changes = { this.changes = {
@ -909,9 +910,10 @@ describe('DocumentUpdaterHandler', function() {
return done() return done()
} }
) )
})) })
})
describe('when a file has been added', () => describe('when a file has been added', function() {
it('should send the structure update to the document updater', function(done) { it('should send the structure update to the document updater', function(done) {
this.fileId = new ObjectId() this.fileId = new ObjectId()
this.changes = { this.changes = {
@ -957,9 +959,10 @@ describe('DocumentUpdaterHandler', function() {
return done() return done()
} }
) )
})) })
})
describe('when an entity has been deleted', () => describe('when an entity has been deleted', function() {
it('should end the structure update to the document updater', function(done) { it('should end the structure update to the document updater', function(done) {
this.docId = new ObjectId() this.docId = new ObjectId()
this.changes = { this.changes = {
@ -999,9 +1002,10 @@ describe('DocumentUpdaterHandler', function() {
return done() return done()
} }
) )
})) })
})
describe('when the project version is missing', () => describe('when the project version is missing', function() {
it('should call the callback with an error', function() { it('should call the callback with an error', function() {
this.docId = new ObjectId() this.docId = new ObjectId()
this.changes = { this.changes = {
@ -1031,7 +1035,8 @@ describe('DocumentUpdaterHandler', function() {
return firstCallArgs[0].message.should.equal( return firstCallArgs[0].message.should.equal(
'did not receive project version in changes' 'did not receive project version in changes'
) )
})) })
})
}) })
}) })
}) })

View file

@ -49,7 +49,7 @@ describe('ProjectZipStreamManager', function() {
})) }))
}) })
describe('createZipStreamForMultipleProjects', () => describe('createZipStreamForMultipleProjects', function() {
describe('successfully', function() { describe('successfully', function() {
beforeEach(function(done) { beforeEach(function(done) {
this.project_ids = ['project-1', 'project-2'] this.project_ids = ['project-1', 'project-2']
@ -128,7 +128,8 @@ describe('ProjectZipStreamManager', function() {
.should.equal(true) .should.equal(true)
) )
}) })
})) })
})
describe('createZipStreamForProject', function() { describe('createZipStreamForProject', function() {
describe('successfully', function() { describe('successfully', function() {

View file

@ -637,7 +637,7 @@ describe('EditorController', function() {
}) })
}) })
describe('notifyUsersProjectHasBeenDeletedOrRenamed', () => describe('notifyUsersProjectHasBeenDeletedOrRenamed', function() {
it('should emmit a message to all users in a project', function(done) { it('should emmit a message to all users in a project', function(done) {
return this.EditorController.notifyUsersProjectHasBeenDeletedOrRenamed( return this.EditorController.notifyUsersProjectHasBeenDeletedOrRenamed(
this.project_id, this.project_id,
@ -651,7 +651,8 @@ describe('EditorController', function() {
return done() return done()
} }
) )
})) })
})
describe('updateProjectDescription', function() { describe('updateProjectDescription', function() {
beforeEach(function() { beforeEach(function() {

View file

@ -17,7 +17,7 @@ const modulePath = path.join(
const SpamSafe = require(modulePath) const SpamSafe = require(modulePath)
const { expect } = require('chai') const { expect } = require('chai')
describe('SpamSafe', () => describe('SpamSafe', function() {
it('should reject spammy names', function() { it('should reject spammy names', function() {
expect(SpamSafe.isSafeUserName('Charline Wałęsa')).to.equal(true) expect(SpamSafe.isSafeUserName('Charline Wałęsa')).to.equal(true)
expect( expect(
@ -83,4 +83,5 @@ describe('SpamSafe', () =>
return expect( return expect(
SpamSafe.safeEmail('sendME$$$@iAmAprince.com', 'A collaborator') SpamSafe.safeEmail('sendME$$$@iAmAprince.com', 'A collaborator')
).to.equal('A collaborator') ).to.equal('A collaborator')
})) })
})

View file

@ -7,8 +7,8 @@ const MockRequest = require('../helpers/MockRequest')
const Errors = require('../../../../app/src/Features/Errors/Errors') const Errors = require('../../../../app/src/Features/Errors/Errors')
const HttpErrors = require('@overleaf/o-error/http') const HttpErrors = require('@overleaf/o-error/http')
describe('HttpErrorController', () => { describe('HttpErrorController', function() {
beforeEach(() => { beforeEach(function() {
this.req = new MockRequest() this.req = new MockRequest()
this.res = new MockResponse() this.res = new MockResponse()
@ -33,10 +33,10 @@ describe('HttpErrorController', () => {
}) })
}) })
describe('handleError', () => { describe('handleError', function() {
beforeEach(() => {}) beforeEach(function() {})
it('logs and return status code', () => { it('logs and return status code', function() {
let error = new HttpErrors.UnprocessableEntityError() let error = new HttpErrors.UnprocessableEntityError()
this.ErrorController.handleError(error, this.req, this.res) this.ErrorController.handleError(error, this.req, this.res)
@ -49,7 +49,7 @@ describe('HttpErrorController', () => {
expect(url).to.not.be.defined expect(url).to.not.be.defined
}) })
it('logs url method and userId', () => { it('logs url method and userId', function() {
let error = new HttpErrors.UnprocessableEntityError() let error = new HttpErrors.UnprocessableEntityError()
this.AuthenticationController.getLoggedInUserId.returns('123abc') this.AuthenticationController.getLoggedInUserId.returns('123abc')
this.req.url = 'overleaf.url' this.req.url = 'overleaf.url'
@ -63,7 +63,7 @@ describe('HttpErrorController', () => {
expect(url).to.equal('overleaf.url') expect(url).to.equal('overleaf.url')
}) })
it('logs and return status code when wrapped', () => { it('logs and return status code when wrapped', function() {
let cause = new Errors.SubscriptionAdminDeletionError() let cause = new Errors.SubscriptionAdminDeletionError()
let error = new HttpErrors.UnprocessableEntityError({}).withCause(cause) let error = new HttpErrors.UnprocessableEntityError({}).withCause(cause)
@ -72,7 +72,7 @@ describe('HttpErrorController', () => {
sinon.assert.calledOnce(this.logger.warn) sinon.assert.calledOnce(this.logger.warn)
}) })
it('renders JSON with info', () => { it('renders JSON with info', function() {
let cause = new Errors.SubscriptionAdminDeletionError({ let cause = new Errors.SubscriptionAdminDeletionError({
info: { info: {
public: { some: 'data' } public: { some: 'data' }
@ -92,7 +92,7 @@ describe('HttpErrorController', () => {
) )
}) })
it('renders HTML with info', () => { it('renders HTML with info', function() {
let cause = new Errors.SubscriptionAdminDeletionError() let cause = new Errors.SubscriptionAdminDeletionError()
let error = new HttpErrors.UnprocessableEntityError({}).withCause(cause) let error = new HttpErrors.UnprocessableEntityError({}).withCause(cause)
this.req.accepts = () => 'html' this.req.accepts = () => 'html'

View file

@ -79,7 +79,7 @@ describe('ExportsController', function() {
})) }))
}) })
describe('without gallery fields', () => describe('without gallery fields', function() {
it('should ask the handler to perform the export', function(done) { it('should ask the handler to perform the export', function(done) {
this.handler.exportProject = sinon this.handler.exportProject = sinon
.stub() .stub()
@ -98,7 +98,8 @@ describe('ExportsController', function() {
return done() return done()
} }
}) })
})) })
})
describe('with gallery fields', function() { describe('with gallery fields', function() {
beforeEach(function() { beforeEach(function() {
@ -135,7 +136,7 @@ describe('ExportsController', function() {
}) })
}) })
describe('with an error return from v1 to forward to the publish modal', () => describe('with an error return from v1 to forward to the publish modal', function() {
it('should forward the response onward', function(done) { it('should forward the response onward', function(done) {
this.error_json = { status: 422, message: 'nope' } this.error_json = { status: 422, message: 'nope' }
this.handler.exportProject = sinon this.handler.exportProject = sinon
@ -145,7 +146,8 @@ describe('ExportsController', function() {
expect(this.res.json.args[0][0]).to.deep.equal(this.error_json) expect(this.res.json.args[0][0]).to.deep.equal(this.error_json)
expect(this.res.status.args[0][0]).to.equal(this.error_json.status) expect(this.res.status.args[0][0]).to.equal(this.error_json.status)
return done() return done()
})) })
})
it('should ask the handler to return the status of an export', function(done) { it('should ask the handler to return the status of an export', function(done) {
this.handler.fetchExport = sinon.stub().yields( this.handler.fetchExport = sinon.stub().yields(

View file

@ -327,7 +327,7 @@ describe('ExportsHandler', function() {
}) })
}) })
describe('when project has no root doc', () => describe('when project has no root doc', function() {
describe('when a root doc can be set automatically', function() { describe('when a root doc can be set automatically', function() {
beforeEach(function(done) { beforeEach(function(done) {
this.project.rootDoc_id = null this.project.rootDoc_id = null
@ -386,7 +386,8 @@ describe('ExportsHandler', function() {
.calledWith(null, expected_export_data) .calledWith(null, expected_export_data)
.should.equal(true) .should.equal(true)
}) })
})) })
})
describe('when project has an invalid root doc', function() { describe('when project has an invalid root doc', function() {
describe('when a new root doc can be set automatically', function() { describe('when a new root doc can be set automatically', function() {

View file

@ -49,7 +49,9 @@ describe('RestoreManager', function() {
return (this.callback = sinon.stub()) return (this.callback = sinon.stub())
}) })
afterEach(() => tk.reset()) afterEach(function() {
return tk.reset()
})
describe('restoreFileFromV2', function() { describe('restoreFileFromV2', function() {
beforeEach(function() { beforeEach(function() {

View file

@ -93,7 +93,7 @@ describe('InstitutionsAPI', function() {
}) })
}) })
describe('getInstitutionLicences', () => describe('getInstitutionLicences', function() {
it('get licences', function(done) { it('get licences', function(done) {
this.institutionId = 123 this.institutionId = 123
const responseBody = { const responseBody = {
@ -124,7 +124,8 @@ describe('InstitutionsAPI', function() {
return done() return done()
} }
) )
})) })
})
describe('getUserAffiliations', function() { describe('getUserAffiliations', function() {
it('get affiliations', function(done) { it('get affiliations', function(done) {

View file

@ -48,13 +48,13 @@ describe('InstitutionsFeatures', function() {
describe('hasLicence', function() { describe('hasLicence', function() {
it('should handle error', function(done) { it('should handle error', function(done) {
this.InstitutionsGetter.getConfirmedInstitutions.yields(new Error('Nope')) this.InstitutionsGetter.getConfirmedInstitutions.yields(new Error('Nope'))
return this.InstitutionsFeatures.hasLicence(this.userId, function( return this.InstitutionsFeatures.hasLicence(
error, this.userId,
hasLicence (error, hasLicence) => {
) { expect(error).to.exist
expect(error).to.exist return done()
return done() }
}) )
}) })
it('should return false if user has no confirmed affiliations', function(done) { it('should return false if user has no confirmed affiliations', function(done) {
@ -63,14 +63,14 @@ describe('InstitutionsFeatures', function() {
null, null,
institutions institutions
) )
return this.InstitutionsFeatures.hasLicence(this.userId, function( return this.InstitutionsFeatures.hasLicence(
error, this.userId,
hasLicence (error, hasLicence) => {
) { expect(error).to.not.exist
expect(error).to.not.exist expect(hasLicence).to.be.false
expect(hasLicence).to.be.false return done()
return done() }
}) )
}) })
it('should return false if user has no paid affiliations', function(done) { it('should return false if user has no paid affiliations', function(done) {
@ -79,14 +79,14 @@ describe('InstitutionsFeatures', function() {
null, null,
institutions institutions
) )
return this.InstitutionsFeatures.hasLicence(this.userId, function( return this.InstitutionsFeatures.hasLicence(
error, this.userId,
hasLicence (error, hasLicence) => {
) { expect(error).to.not.exist
expect(error).to.not.exist expect(hasLicence).to.be.false
expect(hasLicence).to.be.false return done()
return done() }
}) )
}) })
it('should return true if user has confirmed paid affiliation', function(done) { it('should return true if user has confirmed paid affiliation', function(done) {
@ -100,14 +100,14 @@ describe('InstitutionsFeatures', function() {
null, null,
institutions institutions
) )
return this.InstitutionsFeatures.hasLicence(this.userId, function( return this.InstitutionsFeatures.hasLicence(
error, this.userId,
hasLicence (error, hasLicence) => {
) { expect(error).to.not.exist
expect(error).to.not.exist expect(hasLicence).to.be.true
expect(hasLicence).to.be.true return done()
return done() }
}) )
}) })
}) })
@ -124,7 +124,7 @@ describe('InstitutionsFeatures', function() {
this.InstitutionsFeatures.getInstitutionsPlan.yields(new Error('Nope')) this.InstitutionsFeatures.getInstitutionsPlan.yields(new Error('Nope'))
return this.InstitutionsFeatures.getInstitutionsFeatures( return this.InstitutionsFeatures.getInstitutionsFeatures(
this.userId, this.userId,
function(error, features) { (error, features) => {
expect(error).to.exist expect(error).to.exist
return done() return done()
} }
@ -135,7 +135,7 @@ describe('InstitutionsFeatures', function() {
this.InstitutionsFeatures.getInstitutionsPlan.yields(null, null) this.InstitutionsFeatures.getInstitutionsPlan.yields(null, null)
return this.InstitutionsFeatures.getInstitutionsFeatures( return this.InstitutionsFeatures.getInstitutionsFeatures(
this.userId, this.userId,
function(error, features) { (error, features) => {
expect(error).to.not.exist expect(error).to.not.exist
expect(features).to.deep.equal({}) expect(features).to.deep.equal({})
return done() return done()
@ -168,7 +168,7 @@ describe('InstitutionsFeatures', function() {
this.InstitutionsFeatures.hasLicence.yields(new Error('Nope')) this.InstitutionsFeatures.hasLicence.yields(new Error('Nope'))
return this.InstitutionsFeatures.getInstitutionsPlan( return this.InstitutionsFeatures.getInstitutionsPlan(
this.userId, this.userId,
function(error) { error => {
expect(error).to.exist expect(error).to.exist
return done() return done()
} }
@ -179,7 +179,7 @@ describe('InstitutionsFeatures', function() {
this.InstitutionsFeatures.hasLicence.yields(null, false) this.InstitutionsFeatures.hasLicence.yields(null, false)
return this.InstitutionsFeatures.getInstitutionsPlan( return this.InstitutionsFeatures.getInstitutionsPlan(
this.userId, this.userId,
function(error, plan) { (error, plan) => {
expect(error).to.not.exist expect(error).to.not.exist
expect(plan).to.equal(null) expect(plan).to.equal(null)
return done() return done()

View file

@ -62,7 +62,7 @@ describe('InstitutionsGetter', function() {
this.UserGetter.getUserFullEmails.yields(null, this.userEmails) this.UserGetter.getUserFullEmails.yields(null, this.userEmails)
return this.InstitutionsGetter.getConfirmedInstitutions( return this.InstitutionsGetter.getConfirmedInstitutions(
this.userId, this.userId,
function(error, institutions) { (error, institutions) => {
expect(error).to.not.exist expect(error).to.not.exist
institutions.length.should.equal(1) institutions.length.should.equal(1)
institutions[0].id.should.equal(456) institutions[0].id.should.equal(456)
@ -75,7 +75,7 @@ describe('InstitutionsGetter', function() {
this.UserGetter.getUserFullEmails.yields(null, []) this.UserGetter.getUserFullEmails.yields(null, [])
return this.InstitutionsGetter.getConfirmedInstitutions( return this.InstitutionsGetter.getConfirmedInstitutions(
this.userId, this.userId,
function(error, institutions) { (error, institutions) => {
expect(error).to.not.exist expect(error).to.not.exist
institutions.length.should.equal(0) institutions.length.should.equal(0)
return done() return done()
@ -87,7 +87,7 @@ describe('InstitutionsGetter', function() {
this.UserGetter.getUserFullEmails.yields(new Error('Nope')) this.UserGetter.getUserFullEmails.yields(new Error('Nope'))
return this.InstitutionsGetter.getConfirmedInstitutions( return this.InstitutionsGetter.getConfirmedInstitutions(
this.userId, this.userId,
function(error, institutions) { (error, institutions) => {
expect(error).to.exist expect(error).to.exist
return done() return done()
} }

View file

@ -157,7 +157,7 @@ describe('InstitutionsManager', function() {
}) })
}) })
describe('checkInstitutionUsers', () => describe('checkInstitutionUsers', function() {
it('check all users Features', function(done) { it('check all users Features', function(done) {
const affiliations = [{ email: 'foo@bar.com' }, { email: 'baz@boo.edu' }] const affiliations = [{ email: 'foo@bar.com' }, { email: 'baz@boo.edu' }]
const stubbedUsers = [ const stubbedUsers = [
@ -190,9 +190,10 @@ describe('InstitutionsManager', function() {
return done() return done()
} }
) )
})) })
})
describe('getInstitutionUsersSubscriptions', () => describe('getInstitutionUsersSubscriptions', function() {
it('returns all institution users subscriptions', function(done) { it('returns all institution users subscriptions', function(done) {
const stubbedUsers = [ const stubbedUsers = [
{ user_id: '123abc123abc123abc123abc' }, { user_id: '123abc123abc123abc123abc' },
@ -208,5 +209,6 @@ describe('InstitutionsManager', function() {
return done() return done()
} }
) )
})) })
})
}) })

View file

@ -365,7 +365,7 @@ describe('PasswordResetController', function() {
}) })
}) })
describe('without a token in session', () => describe('without a token in session', function() {
it('should redirect to the reset request page', function(done) { it('should redirect to the reset request page', function(done) {
this.res.redirect = path => { this.res.redirect = path => {
path.should.equal('/user/password/reset') path.should.equal('/user/password/reset')
@ -376,7 +376,8 @@ describe('PasswordResetController', function() {
this.req, this.req,
this.res this.res
) )
})) })
})
}) })
}) })
}) })

View file

@ -264,7 +264,7 @@ describe('ProjectController', function() {
}) })
}) })
describe('updateProjectAdminSettings', () => describe('updateProjectAdminSettings', function() {
it('should update the public access level', function(done) { it('should update the public access level', function(done) {
this.EditorController.setPublicAccessLevel = sinon.stub().callsArg(2) this.EditorController.setPublicAccessLevel = sinon.stub().callsArg(2)
this.req.body = { this.req.body = {
@ -281,7 +281,8 @@ describe('ProjectController', function() {
this.req, this.req,
this.res this.res
) )
})) })
})
describe('deleteProject', function() { describe('deleteProject', function() {
it('should tell the project deleter to archive when forever=false', function(done) { it('should tell the project deleter to archive when forever=false', function(done) {
@ -311,7 +312,7 @@ describe('ProjectController', function() {
}) })
}) })
describe('restoreProject', () => describe('restoreProject', function() {
it('should tell the project deleter', function(done) { it('should tell the project deleter', function(done) {
this.res.sendStatus = code => { this.res.sendStatus = code => {
this.ProjectDeleter.restoreProject this.ProjectDeleter.restoreProject
@ -321,9 +322,10 @@ describe('ProjectController', function() {
return done() return done()
} }
return this.ProjectController.restoreProject(this.req, this.res) return this.ProjectController.restoreProject(this.req, this.res)
})) })
})
describe('cloneProject', () => describe('cloneProject', function() {
it('should call the project duplicator', function(done) { it('should call the project duplicator', function(done) {
this.res.send = json => { this.res.send = json => {
this.ProjectDuplicator.duplicate this.ProjectDuplicator.duplicate
@ -333,7 +335,8 @@ describe('ProjectController', function() {
return done() return done()
} }
return this.ProjectController.cloneProject(this.req, this.res) return this.ProjectController.cloneProject(this.req, this.res)
})) })
})
describe('newProject', function() { describe('newProject', function() {
it('should call the projectCreationHandler with createExampleProject', function(done) { it('should call the projectCreationHandler with createExampleProject', function(done) {
@ -580,7 +583,7 @@ describe('ProjectController', function() {
this.tokenReadOnly.length + this.tokenReadOnly.length +
this.V1Response.projects.length this.V1Response.projects.length
) )
opts.projects.forEach(function(p) { opts.projects.forEach(p => {
// Check properties correctly mapped from V1 // Check properties correctly mapped from V1
expect(p).to.have.property('id') expect(p).to.have.property('id')
expect(p).to.have.property('name') expect(p).to.have.property('name')
@ -598,7 +601,7 @@ describe('ProjectController', function() {
opts.tags.length.should.equal( opts.tags.length.should.equal(
this.tags.length + this.V1Response.tags.length this.tags.length + this.V1Response.tags.length
) )
opts.tags.forEach(function(t) { opts.tags.forEach(t => {
expect(t).to.have.property('name') expect(t).to.have.property('name')
return expect(t).to.have.property('project_ids') return expect(t).to.have.property('project_ids')
}) })

View file

@ -130,14 +130,15 @@ describe('ProjectCreationHandler', function() {
}) })
it('should return the project in the callback', function(done) { it('should return the project in the callback', function(done) {
return this.handler.createBlankProject(ownerId, projectName, function( return this.handler.createBlankProject(
err, ownerId,
project projectName,
) { (err, project) => {
project.name.should.equal(projectName) project.name.should.equal(projectName)
;(project.owner_ref + '').should.equal(ownerId) ;(project.owner_ref + '').should.equal(ownerId)
return done() return done()
}) }
)
}) })
it('should initialize the project overleaf if history id not provided', function(done) { it('should initialize the project overleaf if history id not provided', function(done) {
@ -171,7 +172,7 @@ describe('ProjectCreationHandler', function() {
ownerId, ownerId,
projectName, projectName,
attributes, attributes,
function(err, project) { (err, project) => {
project.overleaf.history.id.should.equal(overleaf_id) project.overleaf.history.id.should.equal(overleaf_id)
return done() return done()
} }
@ -179,13 +180,14 @@ describe('ProjectCreationHandler', function() {
}) })
it('should set the language from the user', function(done) { it('should set the language from the user', function(done) {
return this.handler.createBlankProject(ownerId, projectName, function( return this.handler.createBlankProject(
err, ownerId,
project projectName,
) { (err, project) => {
project.spellCheckLanguage.should.equal('de') project.spellCheckLanguage.should.equal('de')
return done() return done()
}) }
)
}) })
it('should set the imageName to currentImageName if set and no imageName attribute', function(done) { it('should set the imageName to currentImageName if set and no imageName attribute', function(done) {

View file

@ -9,8 +9,8 @@ const { Project } = require('../helpers/models/Project')
const { DeletedProject } = require('../helpers/models/DeletedProject') const { DeletedProject } = require('../helpers/models/DeletedProject')
const { ObjectId } = require('mongoose').Types const { ObjectId } = require('mongoose').Types
describe('ProjectDeleter', () => { describe('ProjectDeleter', function() {
beforeEach(() => { beforeEach(function() {
tk.freeze(Date.now()) tk.freeze(Date.now())
this.project_id = ObjectId('588fffffffffffffffffffff') this.project_id = ObjectId('588fffffffffffffffffffff')
this.ip = '192.170.18.1' this.ip = '192.170.18.1'
@ -143,14 +143,14 @@ describe('ProjectDeleter', () => {
}) })
}) })
afterEach(() => { afterEach(function() {
tk.reset() tk.reset()
this.DeletedProjectMock.restore() this.DeletedProjectMock.restore()
this.ProjectMock.restore() this.ProjectMock.restore()
}) })
describe('mark as deleted by external source', () => { describe('mark as deleted by external source', function() {
beforeEach(() => { beforeEach(function() {
this.ProjectMock.expects('update') this.ProjectMock.expects('update')
.withArgs( .withArgs(
{ _id: this.project_id }, { _id: this.project_id },
@ -159,14 +159,14 @@ describe('ProjectDeleter', () => {
.yields() .yields()
}) })
it('should update the project with the flag set to true', done => { it('should update the project with the flag set to true', function(done) {
this.ProjectDeleter.markAsDeletedByExternalSource(this.project_id, () => { this.ProjectDeleter.markAsDeletedByExternalSource(this.project_id, () => {
this.ProjectMock.verify() this.ProjectMock.verify()
done() done()
}) })
}) })
it('should tell the editor controler so users are notified', done => { it('should tell the editor controler so users are notified', function(done) {
this.ProjectDeleter.markAsDeletedByExternalSource(this.project_id, () => { this.ProjectDeleter.markAsDeletedByExternalSource(this.project_id, () => {
this.editorController.notifyUsersProjectHasBeenDeletedOrRenamed this.editorController.notifyUsersProjectHasBeenDeletedOrRenamed
.calledWith(this.project_id) .calledWith(this.project_id)
@ -176,8 +176,8 @@ describe('ProjectDeleter', () => {
}) })
}) })
describe('unmarkAsDeletedByExternalSource', done => { describe('unmarkAsDeletedByExternalSource', function(done) {
beforeEach(() => { beforeEach(function() {
this.ProjectMock.expects('update') this.ProjectMock.expects('update')
.withArgs( .withArgs(
{ _id: this.project_id }, { _id: this.project_id },
@ -187,13 +187,13 @@ describe('ProjectDeleter', () => {
this.ProjectDeleter.unmarkAsDeletedByExternalSource(this.project_id, done) this.ProjectDeleter.unmarkAsDeletedByExternalSource(this.project_id, done)
}) })
it('should remove the flag from the project', () => { it('should remove the flag from the project', function() {
this.ProjectMock.verify() this.ProjectMock.verify()
}) })
}) })
describe('deleteUsersProjects', () => { describe('deleteUsersProjects', function() {
beforeEach(() => { beforeEach(function() {
this.ProjectMock.expects('find') this.ProjectMock.expects('find')
.withArgs({ owner_ref: this.user._id }) .withArgs({ owner_ref: this.user._id })
.yields(null, [{ _id: 'wombat' }, { _id: 'potato' }]) .yields(null, [{ _id: 'wombat' }, { _id: 'potato' }])
@ -201,14 +201,14 @@ describe('ProjectDeleter', () => {
this.ProjectDeleter.deleteProject = sinon.stub().yields() this.ProjectDeleter.deleteProject = sinon.stub().yields()
}) })
it('should find all the projects owned by the user_id', done => { it('should find all the projects owned by the user_id', function(done) {
this.ProjectDeleter.deleteUsersProjects(this.user._id, () => { this.ProjectDeleter.deleteUsersProjects(this.user._id, () => {
this.ProjectMock.verify() this.ProjectMock.verify()
done() done()
}) })
}) })
it('should call deleteProject once for each project', done => { it('should call deleteProject once for each project', function(done) {
this.ProjectDeleter.deleteUsersProjects(this.user._id, () => { this.ProjectDeleter.deleteUsersProjects(this.user._id, () => {
sinon.assert.calledTwice(this.ProjectDeleter.deleteProject) sinon.assert.calledTwice(this.ProjectDeleter.deleteProject)
sinon.assert.calledWith(this.ProjectDeleter.deleteProject, 'wombat') sinon.assert.calledWith(this.ProjectDeleter.deleteProject, 'wombat')
@ -217,7 +217,7 @@ describe('ProjectDeleter', () => {
}) })
}) })
it('should remove all the projects the user is a collaborator of', done => { it('should remove all the projects the user is a collaborator of', function(done) {
this.ProjectDeleter.deleteUsersProjects(this.user._id, () => { this.ProjectDeleter.deleteUsersProjects(this.user._id, () => {
sinon.assert.calledWith( sinon.assert.calledWith(
this.CollaboratorsHandler.removeUserFromAllProjets, this.CollaboratorsHandler.removeUserFromAllProjets,
@ -231,8 +231,8 @@ describe('ProjectDeleter', () => {
}) })
}) })
describe('deleteProject', () => { describe('deleteProject', function() {
beforeEach(() => { beforeEach(function() {
this.deleterData = { this.deleterData = {
deletedAt: new Date(), deletedAt: new Date(),
deletedProjectId: this.project._id, deletedProjectId: this.project._id,
@ -256,7 +256,7 @@ describe('ProjectDeleter', () => {
.resolves(this.project) .resolves(this.project)
}) })
it('should save a DeletedProject with additional deleterData', done => { it('should save a DeletedProject with additional deleterData', function(done) {
this.deleterData.deleterIpAddress = this.ip this.deleterData.deleterIpAddress = this.ip
this.deleterData.deleterId = this.user._id this.deleterData.deleterId = this.user._id
@ -281,7 +281,7 @@ describe('ProjectDeleter', () => {
) )
}) })
it('should flushProjectToMongoAndDelete in doc updater', done => { it('should flushProjectToMongoAndDelete in doc updater', function(done) {
this.ProjectMock.expects('remove') this.ProjectMock.expects('remove')
.chain('exec') .chain('exec')
.resolves() .resolves()
@ -299,7 +299,7 @@ describe('ProjectDeleter', () => {
) )
}) })
it('should removeProjectFromAllTags', done => { it('should removeProjectFromAllTags', function(done) {
this.ProjectMock.expects('remove') this.ProjectMock.expects('remove')
.chain('exec') .chain('exec')
.resolves() .resolves()
@ -320,7 +320,7 @@ describe('ProjectDeleter', () => {
}) })
}) })
it('should remove the project from Mongo', done => { it('should remove the project from Mongo', function(done) {
this.ProjectMock.expects('remove') this.ProjectMock.expects('remove')
.withArgs({ _id: this.project_id }) .withArgs({ _id: this.project_id })
.chain('exec') .chain('exec')
@ -334,8 +334,8 @@ describe('ProjectDeleter', () => {
}) })
}) })
describe('expireDeletedProjectsAfterDuration', () => { describe('expireDeletedProjectsAfterDuration', function() {
beforeEach(done => { beforeEach(function(done) {
this.ProjectDeleter.expireDeletedProject = sinon this.ProjectDeleter.expireDeletedProject = sinon
.stub() .stub()
.callsArgWith(1, null) .callsArgWith(1, null)
@ -354,11 +354,11 @@ describe('ProjectDeleter', () => {
this.ProjectDeleter.expireDeletedProjectsAfterDuration(done) this.ProjectDeleter.expireDeletedProjectsAfterDuration(done)
}) })
it('should call find with a date 90 days earlier than today', () => { it('should call find with a date 90 days earlier than today', function() {
this.DeletedProjectMock.verify() this.DeletedProjectMock.verify()
}) })
it('should call expireDeletedProject', done => { it('should call expireDeletedProject', function(done) {
expect(this.ProjectDeleter.expireDeletedProject).to.have.been.calledWith( expect(this.ProjectDeleter.expireDeletedProject).to.have.been.calledWith(
this.deletedProjects[0].deleterData.deletedProjectId this.deletedProjects[0].deleterData.deletedProjectId
) )
@ -366,8 +366,8 @@ describe('ProjectDeleter', () => {
}) })
}) })
describe('expireDeletedProject', () => { describe('expireDeletedProject', function() {
beforeEach(done => { beforeEach(function(done) {
this.DeletedProjectMock.expects('update') this.DeletedProjectMock.expects('update')
.withArgs( .withArgs(
{ {
@ -396,19 +396,19 @@ describe('ProjectDeleter', () => {
) )
}) })
it('should find the specified deletedProject and remove its project and ip address', () => { it('should find the specified deletedProject and remove its project and ip address', function() {
this.DeletedProjectMock.verify() this.DeletedProjectMock.verify()
}) })
it('should destroy the docs in docstore', () => { it('should destroy the docs in docstore', function() {
expect(this.DocstoreManager.destroyProject).to.have.been.calledWith( expect(this.DocstoreManager.destroyProject).to.have.been.calledWith(
this.deletedProjects[0].project._id this.deletedProjects[0].project._id
) )
}) })
}) })
describe('archiveProject', () => { describe('archiveProject', function() {
beforeEach(() => { beforeEach(function() {
this.ProjectMock.expects('update') this.ProjectMock.expects('update')
.withArgs( .withArgs(
{ {
@ -421,7 +421,7 @@ describe('ProjectDeleter', () => {
.yields() .yields()
}) })
it('should update the project', done => { it('should update the project', function(done) {
this.ProjectDeleter.archiveProject(this.project_id, () => { this.ProjectDeleter.archiveProject(this.project_id, () => {
this.ProjectMock.verify() this.ProjectMock.verify()
done() done()
@ -429,8 +429,8 @@ describe('ProjectDeleter', () => {
}) })
}) })
describe('restoreProject', () => { describe('restoreProject', function() {
beforeEach(() => { beforeEach(function() {
this.ProjectMock.expects('update') this.ProjectMock.expects('update')
.withArgs( .withArgs(
{ {
@ -443,7 +443,7 @@ describe('ProjectDeleter', () => {
.yields() .yields()
}) })
it('should unset the archive attribute', done => { it('should unset the archive attribute', function(done) {
this.ProjectDeleter.restoreProject(this.project_id, () => { this.ProjectDeleter.restoreProject(this.project_id, () => {
this.ProjectMock.verify() this.ProjectMock.verify()
done() done()
@ -451,8 +451,8 @@ describe('ProjectDeleter', () => {
}) })
}) })
describe('undeleteProject', () => { describe('undeleteProject', function() {
beforeEach(() => { beforeEach(function() {
this.deletedProject = { this.deletedProject = {
_id: 'deleted', _id: 'deleted',
project: this.project, project: this.project,
@ -486,7 +486,7 @@ describe('ProjectDeleter', () => {
.resolves() .resolves()
}) })
it('should return not found if the project does not exist', done => { it('should return not found if the project does not exist', function(done) {
this.ProjectDeleter.undeleteProject('wombat', err => { this.ProjectDeleter.undeleteProject('wombat', err => {
expect(err).to.exist expect(err).to.exist
expect(err.name).to.equal('NotFoundError') expect(err.name).to.equal('NotFoundError')
@ -495,7 +495,7 @@ describe('ProjectDeleter', () => {
}) })
}) })
it('should return not found if the project has been expired', done => { it('should return not found if the project has been expired', function(done) {
this.ProjectDeleter.undeleteProject('purgedProject', err => { this.ProjectDeleter.undeleteProject('purgedProject', err => {
expect(err.name).to.equal('NotFoundError') expect(err.name).to.equal('NotFoundError')
expect(err.message).to.equal('project_too_old_to_restore') expect(err.message).to.equal('project_too_old_to_restore')
@ -503,7 +503,7 @@ describe('ProjectDeleter', () => {
}) })
}) })
it('should insert the project into the collection', done => { it('should insert the project into the collection', function(done) {
this.ProjectDeleter.undeleteProject(this.project._id, err => { this.ProjectDeleter.undeleteProject(this.project._id, err => {
expect(err).not.to.exist expect(err).not.to.exist
sinon.assert.calledWith( sinon.assert.calledWith(
@ -517,7 +517,42 @@ describe('ProjectDeleter', () => {
}) })
}) })
it('should remove the DeletedProject', done => { it('should clear the archive bit', function(done) {
this.project.archived = true
this.ProjectDeleter.undeleteProject(this.project._id, err => {
expect(err).not.to.exist
sinon.assert.calledWith(
this.db.projects.insert,
sinon.match({ archived: undefined })
)
done()
})
})
it('should generate a unique name for the project', function(done) {
this.ProjectDeleter.undeleteProject(this.project._id, err => {
expect(err).not.to.exist
sinon.assert.calledWith(
this.ProjectDetailsHandler.generateUniqueName,
this.project.owner_ref
)
done()
})
})
it('should add a suffix to the project name', function(done) {
this.ProjectDeleter.undeleteProject(this.project._id, err => {
expect(err).not.to.exist
sinon.assert.calledWith(
this.ProjectDetailsHandler.generateUniqueName,
this.project.owner_ref,
this.project.name + ' (Restored)'
)
done()
})
})
it('should remove the DeletedProject', function(done) {
// need to change the mock just to include the methods we want // need to change the mock just to include the methods we want
this.DeletedProjectMock.restore() this.DeletedProjectMock.restore()
this.DeletedProjectMock = sinon.mock(DeletedProject) this.DeletedProjectMock = sinon.mock(DeletedProject)
@ -536,40 +571,5 @@ describe('ProjectDeleter', () => {
done() done()
}) })
}) })
it('should clear the archive bit', done => {
this.project.archived = true
this.ProjectDeleter.undeleteProject(this.project._id, err => {
expect(err).not.to.exist
sinon.assert.calledWith(
this.db.projects.insert,
sinon.match({ archived: undefined })
)
done()
})
})
it('should generate a unique name for the project', done => {
this.ProjectDeleter.undeleteProject(this.project._id, err => {
expect(err).not.to.exist
sinon.assert.calledWith(
this.ProjectDetailsHandler.generateUniqueName,
this.project.owner_ref
)
done()
})
})
it('should add a suffix to the project name', done => {
this.ProjectDeleter.undeleteProject(this.project._id, err => {
expect(err).not.to.exist
sinon.assert.calledWith(
this.ProjectDetailsHandler.generateUniqueName,
this.project.owner_ref,
this.project.name + ' (Restored)'
)
done()
})
})
}) })
}) })

View file

@ -138,7 +138,7 @@ describe('ProjectDetailsHandler', function() {
it("should return a not found error if the project can't be found", function(done) { it("should return a not found error if the project can't be found", function(done) {
this.ProjectGetter.getProject.callsArgWith(2) this.ProjectGetter.getProject.callsArgWith(2)
return this.handler.transferOwnership('abc', '123', function(err) { return this.handler.transferOwnership('abc', '123', err => {
err.should.exist err.should.exist
err.name.should.equal('NotFoundError') err.name.should.equal('NotFoundError')
return done() return done()
@ -147,7 +147,7 @@ describe('ProjectDetailsHandler', function() {
it("should return a not found error if the user can't be found", function(done) { it("should return a not found error if the user can't be found", function(done) {
this.ProjectGetter.getProject.callsArgWith(2) this.ProjectGetter.getProject.callsArgWith(2)
return this.handler.transferOwnership('abc', '123', function(err) { return this.handler.transferOwnership('abc', '123', err => {
err.should.exist err.should.exist
err.name.should.equal('NotFoundError') err.name.should.equal('NotFoundError')
return done() return done()
@ -160,7 +160,7 @@ describe('ProjectDetailsHandler', function() {
2, 2,
errorMessage errorMessage
) )
return this.handler.transferOwnership('abc', '123', function(err) { return this.handler.transferOwnership('abc', '123', err => {
err.should.exist err.should.exist
err.should.equal(errorMessage) err.should.equal(errorMessage)
return done() return done()
@ -318,28 +318,28 @@ describe('ProjectDetailsHandler', function() {
describe('validateProjectName', function() { describe('validateProjectName', function() {
it('should reject undefined names', function(done) { it('should reject undefined names', function(done) {
return this.handler.validateProjectName(undefined, function(error) { return this.handler.validateProjectName(undefined, error => {
expect(error).to.exist expect(error).to.exist
return done() return done()
}) })
}) })
it('should reject empty names', function(done) { it('should reject empty names', function(done) {
return this.handler.validateProjectName('', function(error) { return this.handler.validateProjectName('', error => {
expect(error).to.exist expect(error).to.exist
return done() return done()
}) })
}) })
it('should reject names with /s', function(done) { it('should reject names with /s', function(done) {
return this.handler.validateProjectName('foo/bar', function(error) { return this.handler.validateProjectName('foo/bar', error => {
expect(error).to.exist expect(error).to.exist
return done() return done()
}) })
}) })
it('should reject names with \\s', function(done) { it('should reject names with \\s', function(done) {
return this.handler.validateProjectName('foo\\bar', function(error) { return this.handler.validateProjectName('foo\\bar', error => {
expect(error).to.exist expect(error).to.exist
return done() return done()
}) })
@ -348,7 +348,7 @@ describe('ProjectDetailsHandler', function() {
it('should reject long names', function(done) { it('should reject long names', function(done) {
return this.handler.validateProjectName( return this.handler.validateProjectName(
new Array(1000).join('a'), new Array(1000).join('a'),
function(error) { error => {
expect(error).to.exist expect(error).to.exist
return done() return done()
} }
@ -356,7 +356,7 @@ describe('ProjectDetailsHandler', function() {
}) })
it('should accept normal names', function(done) { it('should accept normal names', function(done) {
return this.handler.validateProjectName('foobar', function(error) { return this.handler.validateProjectName('foobar', error => {
expect(error).to.not.exist expect(error).to.not.exist
return done() return done()
}) })
@ -420,7 +420,7 @@ describe('ProjectDetailsHandler', function() {
this.user_id, this.user_id,
'unique-name', 'unique-name',
['-test-suffix'], ['-test-suffix'],
function(error, name, changed) { (error, name, changed) => {
expect(name).to.equal('unique-name') expect(name).to.equal('unique-name')
expect(changed).to.equal(false) expect(changed).to.equal(false)
return done() return done()
@ -433,7 +433,7 @@ describe('ProjectDetailsHandler', function() {
this.user_id, this.user_id,
'name1', 'name1',
['-test-suffix'], ['-test-suffix'],
function(error, name, changed) { (error, name, changed) => {
expect(name).to.equal('name1-test-suffix') expect(name).to.equal('name1-test-suffix')
expect(changed).to.equal(true) expect(changed).to.equal(true)
return done() return done()
@ -446,7 +446,7 @@ describe('ProjectDetailsHandler', function() {
this.user_id, this.user_id,
'name1', 'name1',
['1', '-test-suffix'], ['1', '-test-suffix'],
function(error, name, changed) { (error, name, changed) => {
expect(name).to.equal('name1-test-suffix') expect(name).to.equal('name1-test-suffix')
expect(changed).to.equal(true) expect(changed).to.equal(true)
return done() return done()
@ -460,7 +460,7 @@ describe('ProjectDetailsHandler', function() {
this.user_id, this.user_id,
'x'.repeat(15), 'x'.repeat(15),
['-test-suffix'], ['-test-suffix'],
function(error, name, changed) { (error, name, changed) => {
expect(name).to.equal('x'.repeat(8) + '-test-suffix') expect(name).to.equal('x'.repeat(8) + '-test-suffix')
expect(changed).to.equal(true) expect(changed).to.equal(true)
return done() return done()
@ -473,7 +473,7 @@ describe('ProjectDetailsHandler', function() {
this.user_id, this.user_id,
'name1', 'name1',
[], [],
function(error, name, changed) { (error, name, changed) => {
expect(name).to.equal('name1 (1)') expect(name).to.equal('name1 (1)')
expect(changed).to.equal(true) expect(changed).to.equal(true)
return done() return done()
@ -486,7 +486,7 @@ describe('ProjectDetailsHandler', function() {
this.user_id, this.user_id,
'name', 'name',
['1', '11'], ['1', '11'],
function(error, name, changed) { (error, name, changed) => {
expect(name).to.equal('name (1)') expect(name).to.equal('name (1)')
expect(changed).to.equal(true) expect(changed).to.equal(true)
return done() return done()
@ -499,7 +499,7 @@ describe('ProjectDetailsHandler', function() {
this.user_id, this.user_id,
'numeric', 'numeric',
[], [],
function(error, name, changed) { (error, name, changed) => {
expect(name).to.equal('numeric (21)') expect(name).to.equal('numeric (21)')
expect(changed).to.equal(true) expect(changed).to.equal(true)
return done() return done()
@ -512,7 +512,7 @@ describe('ProjectDetailsHandler', function() {
this.user_id, this.user_id,
'numeric (5)', 'numeric (5)',
[], [],
function(error, name, changed) { (error, name, changed) => {
expect(name).to.equal('numeric (21)') expect(name).to.equal('numeric (21)')
expect(changed).to.equal(true) expect(changed).to.equal(true)
return done() return done()
@ -525,7 +525,7 @@ describe('ProjectDetailsHandler', function() {
this.user_id, this.user_id,
'numeric (31)', 'numeric (31)',
[], [],
function(error, name, changed) { (error, name, changed) => {
expect(name).to.equal('numeric (41)') expect(name).to.equal('numeric (41)')
expect(changed).to.equal(true) expect(changed).to.equal(true)
return done() return done()

View file

@ -82,7 +82,9 @@ describe('ProjectEntityMongoUpdateHandler', function() {
})) }))
}) })
afterEach(() => tk.reset()) afterEach(function() {
return tk.reset()
})
describe('addDoc', function() { describe('addDoc', function() {
beforeEach(function() { beforeEach(function() {

View file

@ -492,7 +492,7 @@ describe('ProjectEntityUpdateHandler', function() {
}) })
}) })
describe('setRootDoc', () => describe('setRootDoc', function() {
it('should call Project.update', function() { it('should call Project.update', function() {
const rootDoc_id = 'root-doc-id-123123' const rootDoc_id = 'root-doc-id-123123'
this.ProjectModel.update = sinon.stub() this.ProjectModel.update = sinon.stub()
@ -500,16 +500,18 @@ describe('ProjectEntityUpdateHandler', function() {
return this.ProjectModel.update return this.ProjectModel.update
.calledWith({ _id: project_id }, { rootDoc_id }) .calledWith({ _id: project_id }, { rootDoc_id })
.should.equal(true) .should.equal(true)
})) })
})
describe('unsetRootDoc', () => describe('unsetRootDoc', function() {
it('should call Project.update', function() { it('should call Project.update', function() {
this.ProjectModel.update = sinon.stub() this.ProjectModel.update = sinon.stub()
this.ProjectEntityUpdateHandler.unsetRootDoc(project_id) this.ProjectEntityUpdateHandler.unsetRootDoc(project_id)
return this.ProjectModel.update return this.ProjectModel.update
.calledWith({ _id: project_id }, { $unset: { rootDoc_id: true } }) .calledWith({ _id: project_id }, { $unset: { rootDoc_id: true } })
.should.equal(true) .should.equal(true)
})) })
})
describe('addDoc', function() { describe('addDoc', function() {
describe('adding a doc', function() { describe('adding a doc', function() {

View file

@ -86,7 +86,7 @@ describe('ProjectLocator', function() {
it('finds one at the root level', function(done) { it('finds one at the root level', function(done) {
return this.locator.findElement( return this.locator.findElement(
{ project_id: project._id, element_id: doc2._id, type: 'docs' }, { project_id: project._id, element_id: doc2._id, type: 'docs' },
function(err, foundElement, path, parentFolder) { (err, foundElement, path, parentFolder) => {
assert(err == null) assert(err == null)
foundElement._id.should.equal(doc2._id) foundElement._id.should.equal(doc2._id)
path.fileSystem.should.equal(`/${doc2.name}`) path.fileSystem.should.equal(`/${doc2.name}`)
@ -100,7 +100,7 @@ describe('ProjectLocator', function() {
it('when it is nested', function(done) { it('when it is nested', function(done) {
return this.locator.findElement( return this.locator.findElement(
{ project_id: project._id, element_id: subSubDoc._id, type: 'doc' }, { project_id: project._id, element_id: subSubDoc._id, type: 'doc' },
function(err, foundElement, path, parentFolder) { (err, foundElement, path, parentFolder) => {
assert(err == null) assert(err == null)
should.equal(foundElement._id, subSubDoc._id) should.equal(foundElement._id, subSubDoc._id)
path.fileSystem.should.equal( path.fileSystem.should.equal(
@ -116,7 +116,7 @@ describe('ProjectLocator', function() {
it('should give error if element could not be found', function(done) { it('should give error if element could not be found', function(done) {
return this.locator.findElement( return this.locator.findElement(
{ project_id: project._id, element_id: 'ddsd432nj42', type: 'docs' }, { project_id: project._id, element_id: 'ddsd432nj42', type: 'docs' },
function(err, foundElement, path, parentFolder) { (err, foundElement, path, parentFolder) => {
err.should.deep.equal(new Errors.NotFoundError('entity not found')) err.should.deep.equal(new Errors.NotFoundError('entity not found'))
return done() return done()
} }
@ -128,7 +128,7 @@ describe('ProjectLocator', function() {
it('should return root folder when looking for root folder', function(done) { it('should return root folder when looking for root folder', function(done) {
return this.locator.findElement( return this.locator.findElement(
{ project_id: project._id, element_id: rootFolder._id, type: 'folder' }, { project_id: project._id, element_id: rootFolder._id, type: 'folder' },
function(err, foundElement, path, parentFolder) { (err, foundElement, path, parentFolder) => {
assert(!err) assert(!err)
foundElement._id.should.equal(rootFolder._id) foundElement._id.should.equal(rootFolder._id)
return done() return done()
@ -139,7 +139,7 @@ describe('ProjectLocator', function() {
it('when at root', function(done) { it('when at root', function(done) {
return this.locator.findElement( return this.locator.findElement(
{ project_id: project._id, element_id: subFolder._id, type: 'folder' }, { project_id: project._id, element_id: subFolder._id, type: 'folder' },
function(err, foundElement, path, parentFolder) { (err, foundElement, path, parentFolder) => {
assert(!err) assert(!err)
foundElement._id.should.equal(subFolder._id) foundElement._id.should.equal(subFolder._id)
path.fileSystem.should.equal(`/${subFolder.name}`) path.fileSystem.should.equal(`/${subFolder.name}`)
@ -157,7 +157,7 @@ describe('ProjectLocator', function() {
element_id: secondSubFolder._id, element_id: secondSubFolder._id,
type: 'folder' type: 'folder'
}, },
function(err, foundElement, path, parentFolder) { (err, foundElement, path, parentFolder) => {
assert(!err) assert(!err)
foundElement._id.should.equal(secondSubFolder._id) foundElement._id.should.equal(secondSubFolder._id)
path.fileSystem.should.equal( path.fileSystem.should.equal(
@ -175,7 +175,7 @@ describe('ProjectLocator', function() {
it('when at root', function(done) { it('when at root', function(done) {
return this.locator.findElement( return this.locator.findElement(
{ project_id: project._id, element_id: file1._id, type: 'fileRefs' }, { project_id: project._id, element_id: file1._id, type: 'fileRefs' },
function(err, foundElement, path, parentFolder) { (err, foundElement, path, parentFolder) => {
assert(!err) assert(!err)
foundElement._id.should.equal(file1._id) foundElement._id.should.equal(file1._id)
path.fileSystem.should.equal(`/${file1.name}`) path.fileSystem.should.equal(`/${file1.name}`)
@ -193,7 +193,7 @@ describe('ProjectLocator', function() {
element_id: subSubFile._id, element_id: subSubFile._id,
type: 'fileRefs' type: 'fileRefs'
}, },
function(err, foundElement, path, parentFolder) { (err, foundElement, path, parentFolder) => {
assert(!err) assert(!err)
foundElement._id.should.equal(subSubFile._id) foundElement._id.should.equal(subSubFile._id)
path.fileSystem.should.equal( path.fileSystem.should.equal(
@ -211,7 +211,7 @@ describe('ProjectLocator', function() {
it('should add an s onto the element type', function(done) { it('should add an s onto the element type', function(done) {
return this.locator.findElement( return this.locator.findElement(
{ project_id: project._id, element_id: subSubDoc._id, type: 'doc' }, { project_id: project._id, element_id: subSubDoc._id, type: 'doc' },
function(err, foundElement, path, parentFolder) { (err, foundElement, path, parentFolder) => {
assert(!err) assert(!err)
foundElement._id.should.equal(subSubDoc._id) foundElement._id.should.equal(subSubDoc._id)
return done() return done()
@ -222,7 +222,7 @@ describe('ProjectLocator', function() {
it('should convert file to fileRefs', function(done) { it('should convert file to fileRefs', function(done) {
return this.locator.findElement( return this.locator.findElement(
{ project_id: project._id, element_id: file1._id, type: 'fileRefs' }, { project_id: project._id, element_id: file1._id, type: 'fileRefs' },
function(err, foundElement, path, parentFolder) { (err, foundElement, path, parentFolder) => {
assert(!err) assert(!err)
foundElement._id.should.equal(file1._id) foundElement._id.should.equal(file1._id)
return done() return done()
@ -247,7 +247,7 @@ describe('ProjectLocator', function() {
it('should find doc in project', function(done) { it('should find doc in project', function(done) {
return this.locator.findElement( return this.locator.findElement(
{ project: project2, element_id: doc3._id, type: 'docs' }, { project: project2, element_id: doc3._id, type: 'docs' },
function(err, foundElement, path, parentFolder) { (err, foundElement, path, parentFolder) => {
assert(err == null) assert(err == null)
foundElement._id.should.equal(doc3._id) foundElement._id.should.equal(doc3._id)
path.fileSystem.should.equal(`/${doc3.name}`) path.fileSystem.should.equal(`/${doc3.name}`)
@ -261,7 +261,7 @@ describe('ProjectLocator', function() {
describe('finding root doc', function() { describe('finding root doc', function() {
it('should return root doc when passed project', function(done) { it('should return root doc when passed project', function(done) {
return this.locator.findRootDoc(project, function(err, doc) { return this.locator.findRootDoc(project, (err, doc) => {
assert(err == null) assert(err == null)
doc._id.should.equal(rootDoc._id) doc._id.should.equal(rootDoc._id)
return done() return done()
@ -269,7 +269,7 @@ describe('ProjectLocator', function() {
}) })
it('should return root doc when passed project_id', function(done) { it('should return root doc when passed project_id', function(done) {
return this.locator.findRootDoc(project._id, function(err, doc) { return this.locator.findRootDoc(project._id, (err, doc) => {
assert(err == null) assert(err == null)
doc._id.should.equal(rootDoc._id) doc._id.should.equal(rootDoc._id)
return done() return done()
@ -278,7 +278,7 @@ describe('ProjectLocator', function() {
it('should return null when the project has no rootDoc', function(done) { it('should return null when the project has no rootDoc', function(done) {
project.rootDoc_id = null project.rootDoc_id = null
return this.locator.findRootDoc(project, function(err, doc) { return this.locator.findRootDoc(project, (err, doc) => {
assert(err == null) assert(err == null)
expect(doc).to.equal(null) expect(doc).to.equal(null)
return done() return done()
@ -287,7 +287,7 @@ describe('ProjectLocator', function() {
it('should return null when the rootDoc_id no longer exists', function(done) { it('should return null when the rootDoc_id no longer exists', function(done) {
project.rootDoc_id = 'doesntexist' project.rootDoc_id = 'doesntexist'
return this.locator.findRootDoc(project, function(err, doc) { return this.locator.findRootDoc(project, (err, doc) => {
assert(err == null) assert(err == null)
expect(doc).to.equal(null) expect(doc).to.equal(null)
return done() return done()
@ -298,136 +298,126 @@ describe('ProjectLocator', function() {
describe('findElementByPath', function() { describe('findElementByPath', function() {
it('should take a doc path and return the element for a root level document', function(done) { it('should take a doc path and return the element for a root level document', function(done) {
const path = `${doc1.name}` const path = `${doc1.name}`
return this.locator.findElementByPath({ project, path }, function( return this.locator.findElementByPath(
err, { project, path },
element, (err, element, type) => {
type element.should.deep.equal(doc1)
) { expect(type).to.equal('doc')
element.should.deep.equal(doc1) return done()
expect(type).to.equal('doc') }
return done() )
})
}) })
it('should take a doc path and return the element for a root level document with a starting slash', function(done) { it('should take a doc path and return the element for a root level document with a starting slash', function(done) {
const path = `/${doc1.name}` const path = `/${doc1.name}`
return this.locator.findElementByPath({ project, path }, function( return this.locator.findElementByPath(
err, { project, path },
element, (err, element, type) => {
type element.should.deep.equal(doc1)
) { expect(type).to.equal('doc')
element.should.deep.equal(doc1) return done()
expect(type).to.equal('doc') }
return done() )
})
}) })
it('should take a doc path and return the element for a nested document', function(done) { it('should take a doc path and return the element for a nested document', function(done) {
const path = `${subFolder.name}/${secondSubFolder.name}/${subSubDoc.name}` const path = `${subFolder.name}/${secondSubFolder.name}/${subSubDoc.name}`
return this.locator.findElementByPath({ project, path }, function( return this.locator.findElementByPath(
err, { project, path },
element, (err, element, type) => {
type element.should.deep.equal(subSubDoc)
) { expect(type).to.equal('doc')
element.should.deep.equal(subSubDoc) return done()
expect(type).to.equal('doc') }
return done() )
})
}) })
it('should take a file path and return the element for a root level document', function(done) { it('should take a file path and return the element for a root level document', function(done) {
const path = `${file1.name}` const path = `${file1.name}`
return this.locator.findElementByPath({ project, path }, function( return this.locator.findElementByPath(
err, { project, path },
element, (err, element, type) => {
type element.should.deep.equal(file1)
) { expect(type).to.equal('file')
element.should.deep.equal(file1) return done()
expect(type).to.equal('file') }
return done() )
})
}) })
it('should take a file path and return the element for a nested document', function(done) { it('should take a file path and return the element for a nested document', function(done) {
const path = `${subFolder.name}/${secondSubFolder.name}/${ const path = `${subFolder.name}/${secondSubFolder.name}/${
subSubFile.name subSubFile.name
}` }`
return this.locator.findElementByPath({ project, path }, function( return this.locator.findElementByPath(
err, { project, path },
element, (err, element, type) => {
type element.should.deep.equal(subSubFile)
) { expect(type).to.equal('file')
element.should.deep.equal(subSubFile) return done()
expect(type).to.equal('file') }
return done() )
})
}) })
it('should take a file path and return the element for a nested document case insenstive', function(done) { it('should take a file path and return the element for a nested document case insenstive', function(done) {
const path = `${subFolder.name.toUpperCase()}/${secondSubFolder.name.toUpperCase()}/${subSubFile.name.toUpperCase()}` const path = `${subFolder.name.toUpperCase()}/${secondSubFolder.name.toUpperCase()}/${subSubFile.name.toUpperCase()}`
return this.locator.findElementByPath({ project, path }, function( return this.locator.findElementByPath(
err, { project, path },
element, (err, element, type) => {
type element.should.deep.equal(subSubFile)
) { expect(type).to.equal('file')
element.should.deep.equal(subSubFile) return done()
expect(type).to.equal('file') }
return done() )
})
}) })
it('should take a file path and return the element for a nested folder', function(done) { it('should take a file path and return the element for a nested folder', function(done) {
const path = `${subFolder.name}/${secondSubFolder.name}` const path = `${subFolder.name}/${secondSubFolder.name}`
return this.locator.findElementByPath({ project, path }, function( return this.locator.findElementByPath(
err, { project, path },
element, (err, element, type) => {
type element.should.deep.equal(secondSubFolder)
) { expect(type).to.equal('folder')
element.should.deep.equal(secondSubFolder) return done()
expect(type).to.equal('folder') }
return done() )
})
}) })
it('should take a file path and return the root folder', function(done) { it('should take a file path and return the root folder', function(done) {
const path = '/' const path = '/'
return this.locator.findElementByPath({ project, path }, function( return this.locator.findElementByPath(
err, { project, path },
element, (err, element, type) => {
type element.should.deep.equal(rootFolder)
) { expect(type).to.equal('folder')
element.should.deep.equal(rootFolder) return done()
expect(type).to.equal('folder') }
return done() )
})
}) })
it('should return an error if the file can not be found inside know folder', function(done) { it('should return an error if the file can not be found inside know folder', function(done) {
const path = `${subFolder.name}/${secondSubFolder.name}/exist.txt` const path = `${subFolder.name}/${secondSubFolder.name}/exist.txt`
return this.locator.findElementByPath({ project, path }, function( return this.locator.findElementByPath(
err, { project, path },
element, (err, element, type) => {
type err.should.not.equal(undefined)
) { assert.equal(element, undefined)
err.should.not.equal(undefined) expect(type).to.be.undefined
assert.equal(element, undefined) return done()
expect(type).to.be.undefined }
return done() )
})
}) })
it('should return an error if the file can not be found inside unknown folder', function(done) { it('should return an error if the file can not be found inside unknown folder', function(done) {
const path = 'this/does/not/exist.txt' const path = 'this/does/not/exist.txt'
return this.locator.findElementByPath({ project, path }, function( return this.locator.findElementByPath(
err, { project, path },
element, (err, element, type) => {
type err.should.not.equal(undefined)
) { assert.equal(element, undefined)
err.should.not.equal(undefined) expect(type).to.be.undefined
assert.equal(element, undefined) return done()
expect(type).to.be.undefined }
return done() )
})
}) })
describe('where duplicate folder exists', function() { describe('where duplicate folder exists', function() {
@ -491,7 +481,7 @@ describe('ProjectLocator', function() {
const path = '/other.tex' const path = '/other.tex'
return this.locator.findElementByPath( return this.locator.findElementByPath(
{ project: this.project, path }, { project: this.project, path },
function(err, element) { (err, element) => {
element.name.should.equal('other.tex') element.name.should.equal('other.tex')
return done() return done()
} }
@ -508,7 +498,7 @@ describe('ProjectLocator', function() {
const path = '/other.tex' const path = '/other.tex'
return this.locator.findElementByPath( return this.locator.findElementByPath(
{ project_id: project._id, path }, { project_id: project._id, path },
function(err, element) { (err, element) => {
expect(err).to.exist expect(err).to.exist
return done() return done()
} }
@ -516,7 +506,7 @@ describe('ProjectLocator', function() {
}) })
}) })
describe('with a project_id', () => describe('with a project_id', function() {
it('should take a doc path and return the element for a root level document', function(done) { it('should take a doc path and return the element for a root level document', function(done) {
const path = `${doc1.name}` const path = `${doc1.name}`
return this.locator.findElementByPath( return this.locator.findElementByPath(
@ -530,7 +520,8 @@ describe('ProjectLocator', function() {
return done() return done()
} }
) )
})) })
})
}) })
describe('findUsersProjectByName finding a project by user_id and project name', function() { describe('findUsersProjectByName finding a project by user_id and project name', function() {
@ -551,7 +542,7 @@ describe('ProjectLocator', function() {
return this.locator.findUsersProjectByName( return this.locator.findUsersProjectByName(
user_id, user_id,
stubbedProject.name.toLowerCase(), stubbedProject.name.toLowerCase(),
function(err, project) { (err, project) => {
project.should.equal(stubbedProject) project.should.equal(stubbedProject)
return done() return done()
} }
@ -577,7 +568,7 @@ describe('ProjectLocator', function() {
return this.locator.findUsersProjectByName( return this.locator.findUsersProjectByName(
user_id, user_id,
stubbedProject.name.toLowerCase(), stubbedProject.name.toLowerCase(),
function(err, project) { (err, project) => {
project._id.should.equal(stubbedProject._id) project._id.should.equal(stubbedProject._id)
return done() return done()
} }
@ -597,7 +588,7 @@ describe('ProjectLocator', function() {
return this.locator.findUsersProjectByName( return this.locator.findUsersProjectByName(
user_id, user_id,
stubbedProject.name.toLowerCase(), stubbedProject.name.toLowerCase(),
function(err, project) { (err, project) => {
project.should.equal(stubbedProject) project.should.equal(stubbedProject)
return done() return done()
} }

View file

@ -151,7 +151,7 @@ describe('ProjectOptionsHandler', function() {
}) })
}) })
describe('unsetting the brandVariationId', () => describe('unsetting the brandVariationId', function() {
it('should perform and update on mongo', function(done) { it('should perform and update on mongo', function(done) {
this.handler.unsetBrandVariationId(project_id, err => { this.handler.unsetBrandVariationId(project_id, err => {
const args = this.projectModel.update.args[0] const args = this.projectModel.update.args[0]
@ -160,5 +160,6 @@ describe('ProjectOptionsHandler', function() {
return done() return done()
}) })
return this.projectModel.update.args[0][3]() return this.projectModel.update.args[0][3]()
})) })
})
}) })

View file

@ -90,7 +90,7 @@ describe('ProjectUpdateHandler', function() {
}) })
}) })
describe('markAsOpened', () => describe('markAsOpened', function() {
it('should send an update to mongo', function(done) { it('should send an update to mongo', function(done) {
const project_id = 'project_id' const project_id = 'project_id'
return this.handler.markAsOpened(project_id, err => { return this.handler.markAsOpened(project_id, err => {
@ -101,9 +101,10 @@ describe('ProjectUpdateHandler', function() {
date.substring(0, 5).should.equal(now.substring(0, 5)) date.substring(0, 5).should.equal(now.substring(0, 5))
return done() return done()
}) })
})) })
})
describe('markAsInactive', () => describe('markAsInactive', function() {
it('should send an update to mongo', function(done) { it('should send an update to mongo', function(done) {
const project_id = 'project_id' const project_id = 'project_id'
return this.handler.markAsInactive(project_id, err => { return this.handler.markAsInactive(project_id, err => {
@ -112,9 +113,10 @@ describe('ProjectUpdateHandler', function() {
args[1].active.should.equal(false) args[1].active.should.equal(false)
return done() return done()
}) })
})) })
})
describe('markAsActive', () => describe('markAsActive', function() {
it('should send an update to mongo', function(done) { it('should send an update to mongo', function(done) {
const project_id = 'project_id' const project_id = 'project_id'
return this.handler.markAsActive(project_id, err => { return this.handler.markAsActive(project_id, err => {
@ -123,5 +125,6 @@ describe('ProjectUpdateHandler', function() {
args[1].active.should.equal(true) args[1].active.should.equal(true)
return done() return done()
}) })
})) })
})
}) })

View file

@ -60,14 +60,15 @@ describe('PublishersGetter', function() {
return (this.userId = '12345abcde') return (this.userId = '12345abcde')
}) })
describe('getManagedPublishers', () => describe('getManagedPublishers', function() {
it('fetches v1 data before returning publisher list', function(done) { it('fetches v1 data before returning publisher list', function(done) {
return this.PublishersGetter.getManagedPublishers(this.userId, function( return this.PublishersGetter.getManagedPublishers(
error, this.userId,
publishers (error, publishers) => {
) { publishers.length.should.equal(1)
publishers.length.should.equal(1) return done()
return done() }
}) )
})) })
})
}) })

View file

@ -39,7 +39,7 @@ describe('Referal connect middle wear', function() {
query: { referal: '12345' }, query: { referal: '12345' },
session: {} session: {}
} }
return this.connect.use(req, {}, function() { return this.connect.use(req, {}, () => {
req.session.referal_id.should.equal(req.query.referal) req.session.referal_id.should.equal(req.query.referal)
return done() return done()
}) })
@ -50,7 +50,7 @@ describe('Referal connect middle wear', function() {
query: {}, query: {},
session: { referal_id: 'same' } session: { referal_id: 'same' }
} }
return this.connect.use(req, {}, function() { return this.connect.use(req, {}, () => {
req.session.referal_id.should.equal('same') req.session.referal_id.should.equal('same')
return done() return done()
}) })
@ -61,7 +61,7 @@ describe('Referal connect middle wear', function() {
query: { fb_ref: '12345' }, query: { fb_ref: '12345' },
session: {} session: {}
} }
return this.connect.use(req, {}, function() { return this.connect.use(req, {}, () => {
req.session.referal_id.should.equal(req.query.fb_ref) req.session.referal_id.should.equal(req.query.fb_ref)
return done() return done()
}) })
@ -72,7 +72,7 @@ describe('Referal connect middle wear', function() {
query: { rm: 'fb' }, query: { rm: 'fb' },
session: {} session: {}
} }
return this.connect.use(req, {}, function() { return this.connect.use(req, {}, () => {
req.session.referal_medium.should.equal('facebook') req.session.referal_medium.should.equal('facebook')
return done() return done()
}) })
@ -83,7 +83,7 @@ describe('Referal connect middle wear', function() {
query: { rm: 't' }, query: { rm: 't' },
session: {} session: {}
} }
return this.connect.use(req, {}, function() { return this.connect.use(req, {}, () => {
req.session.referal_medium.should.equal('twitter') req.session.referal_medium.should.equal('twitter')
return done() return done()
}) })
@ -94,7 +94,7 @@ describe('Referal connect middle wear', function() {
query: { rm: 'gp' }, query: { rm: 'gp' },
session: {} session: {}
} }
return this.connect.use(req, {}, function() { return this.connect.use(req, {}, () => {
req.session.referal_medium.should.equal('google_plus') req.session.referal_medium.should.equal('google_plus')
return done() return done()
}) })
@ -105,7 +105,7 @@ describe('Referal connect middle wear', function() {
query: { rm: 'e' }, query: { rm: 'e' },
session: {} session: {}
} }
return this.connect.use(req, {}, function() { return this.connect.use(req, {}, () => {
req.session.referal_medium.should.equal('email') req.session.referal_medium.should.equal('email')
return done() return done()
}) })
@ -116,7 +116,7 @@ describe('Referal connect middle wear', function() {
query: { rm: 'd' }, query: { rm: 'd' },
session: {} session: {}
} }
return this.connect.use(req, {}, function() { return this.connect.use(req, {}, () => {
req.session.referal_medium.should.equal('direct') req.session.referal_medium.should.equal('direct')
return done() return done()
}) })
@ -127,7 +127,7 @@ describe('Referal connect middle wear', function() {
query: { rs: 'b' }, query: { rs: 'b' },
session: {} session: {}
} }
return this.connect.use(req, {}, function() { return this.connect.use(req, {}, () => {
req.session.referal_source.should.equal('bonus') req.session.referal_source.should.equal('bonus')
return done() return done()
}) })
@ -138,7 +138,7 @@ describe('Referal connect middle wear', function() {
query: { rs: 'ps' }, query: { rs: 'ps' },
session: {} session: {}
} }
return this.connect.use(req, {}, function() { return this.connect.use(req, {}, () => {
req.session.referal_source.should.equal('public_share') req.session.referal_source.should.equal('public_share')
return done() return done()
}) })
@ -149,7 +149,7 @@ describe('Referal connect middle wear', function() {
query: { rs: 'ci' }, query: { rs: 'ci' },
session: {} session: {}
} }
return this.connect.use(req, {}, function() { return this.connect.use(req, {}, () => {
req.session.referal_source.should.equal('collaborator_invite') req.session.referal_source.should.equal('collaborator_invite')
return done() return done()
}) })

View file

@ -19,7 +19,7 @@ const modulePath = require('path').join(
'../../../../app/src/Features/Referal/ReferalController.js' '../../../../app/src/Features/Referal/ReferalController.js'
) )
describe('Referal controller', () => describe('Referal controller', function() {
beforeEach(function() { beforeEach(function() {
return (this.controller = SandboxedModule.require(modulePath, { return (this.controller = SandboxedModule.require(modulePath, {
globals: { globals: {
@ -32,4 +32,5 @@ describe('Referal controller', () =>
} }
} }
})) }))
})) })
})

View file

@ -48,57 +48,53 @@ describe('Referal handler', function() {
} }
this.User.findById.callsArgWith(1, null, user) this.User.findById.callsArgWith(1, null, user)
return this.handler.getReferedUsers(this.user_id, function( return this.handler.getReferedUsers(
err, this.user_id,
passedReferedUserIds, (err, passedReferedUserIds, passedReferedUserCount) => {
passedReferedUserCount passedReferedUserIds.should.deep.equal(user.refered_users)
) { passedReferedUserCount.should.equal(3)
passedReferedUserIds.should.deep.equal(user.refered_users) return done()
passedReferedUserCount.should.equal(3) }
return done() )
})
}) })
it('should return an empty array if it is not set', function(done) { it('should return an empty array if it is not set', function(done) {
const user = {} const user = {}
this.User.findById.callsArgWith(1, null, user) this.User.findById.callsArgWith(1, null, user)
return this.handler.getReferedUsers(this.user_id, function( return this.handler.getReferedUsers(
err, this.user_id,
passedReferedUserIds, (err, passedReferedUserIds, passedReferedUserCount) => {
passedReferedUserCount passedReferedUserIds.length.should.equal(0)
) { return done()
passedReferedUserIds.length.should.equal(0) }
return done() )
})
}) })
it('should return a zero count if netither it or the array are set', function(done) { it('should return a zero count if netither it or the array are set', function(done) {
const user = {} const user = {}
this.User.findById.callsArgWith(1, null, user) this.User.findById.callsArgWith(1, null, user)
return this.handler.getReferedUsers(this.user_id, function( return this.handler.getReferedUsers(
err, this.user_id,
passedReferedUserIds, (err, passedReferedUserIds, passedReferedUserCount) => {
passedReferedUserCount passedReferedUserCount.should.equal(0)
) { return done()
passedReferedUserCount.should.equal(0) }
return done() )
})
}) })
it('should return the array length if count is not set', function(done) { it('should return the array length if count is not set', function(done) {
const user = { refered_users: ['1234', '312312', '3213129'] } const user = { refered_users: ['1234', '312312', '3213129'] }
this.User.findById.callsArgWith(1, null, user) this.User.findById.callsArgWith(1, null, user)
return this.handler.getReferedUsers(this.user_id, function( return this.handler.getReferedUsers(
err, this.user_id,
passedReferedUserIds, (err, passedReferedUserIds, passedReferedUserCount) => {
passedReferedUserCount passedReferedUserCount.should.equal(3)
) { return done()
passedReferedUserCount.should.equal(3) }
return done() )
})
}) })
it('should return the count if it differs from the array length', function(done) { it('should return the count if it differs from the array length', function(done) {
@ -108,14 +104,13 @@ describe('Referal handler', function() {
} }
this.User.findById.callsArgWith(1, null, user) this.User.findById.callsArgWith(1, null, user)
return this.handler.getReferedUsers(this.user_id, function( return this.handler.getReferedUsers(
err, this.user_id,
passedReferedUserIds, (err, passedReferedUserIds, passedReferedUserCount) => {
passedReferedUserCount passedReferedUserCount.should.equal(5)
) { return done()
passedReferedUserCount.should.equal(5) }
return done() )
})
}) })
}) })
}) })

View file

@ -48,7 +48,9 @@ describe('OneTimeTokenHandler', function() {
})) }))
}) })
afterEach(() => tk.reset()) afterEach(function() {
return tk.reset()
})
describe('getNewToken', function() { describe('getNewToken', function() {
beforeEach(function() { beforeEach(function() {

View file

@ -386,36 +386,36 @@ describe('LimitationsManager', function() {
this.SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, { this.SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, {
recurlySubscription_id: '1234' recurlySubscription_id: '1234'
}) })
return this.LimitationsManager.userHasV2Subscription(this.user, function( return this.LimitationsManager.userHasV2Subscription(
err, this.user,
hasSubscription (err, hasSubscription) => {
) { hasSubscription.should.equal(true)
hasSubscription.should.equal(true) return done()
return done() }
}) )
}) })
it('should return false if the recurly token is not set', function(done) { it('should return false if the recurly token is not set', function(done) {
this.SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, {}) this.SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, {})
this.subscription = {} this.subscription = {}
return this.LimitationsManager.userHasV2Subscription(this.user, function( return this.LimitationsManager.userHasV2Subscription(
err, this.user,
hasSubscription (err, hasSubscription) => {
) { hasSubscription.should.equal(false)
hasSubscription.should.equal(false) return done()
return done() }
}) )
}) })
it('should return false if the subscription is undefined', function(done) { it('should return false if the subscription is undefined', function(done) {
this.SubscriptionLocator.getUsersSubscription.callsArgWith(1) this.SubscriptionLocator.getUsersSubscription.callsArgWith(1)
return this.LimitationsManager.userHasV2Subscription(this.user, function( return this.LimitationsManager.userHasV2Subscription(
err, this.user,
hasSubscription (err, hasSubscription) => {
) { hasSubscription.should.equal(false)
hasSubscription.should.equal(false) return done()
return done() }
}) )
}) })
it('should return the subscription', function(done) { it('should return the subscription', function(done) {
@ -425,14 +425,13 @@ describe('LimitationsManager', function() {
null, null,
stubbedSubscription stubbedSubscription
) )
return this.LimitationsManager.userHasV2Subscription(this.user, function( return this.LimitationsManager.userHasV2Subscription(
err, this.user,
hasSubOrIsGroupMember, (err, hasSubOrIsGroupMember, subscription) => {
subscription subscription.should.deep.equal(stubbedSubscription)
) { return done()
subscription.should.deep.equal(stubbedSubscription) }
return done() )
})
}) })
describe('when user has a custom account', function() { describe('when user has a custom account', function() {
@ -448,7 +447,7 @@ describe('LimitationsManager', function() {
it('should return true', function(done) { it('should return true', function(done) {
return this.LimitationsManager.userHasV2Subscription( return this.LimitationsManager.userHasV2Subscription(
this.user, this.user,
function(err, hasSubscription, subscription) { (err, hasSubscription, subscription) => {
hasSubscription.should.equal(true) hasSubscription.should.equal(true)
return done() return done()
} }
@ -476,7 +475,7 @@ describe('LimitationsManager', function() {
this.SubscriptionLocator.getMemberSubscriptions.callsArgWith(1, null, []) this.SubscriptionLocator.getMemberSubscriptions.callsArgWith(1, null, [])
return this.LimitationsManager.userIsMemberOfGroupSubscription( return this.LimitationsManager.userIsMemberOfGroupSubscription(
this.user, this.user,
function(err, isMember) { (err, isMember) => {
isMember.should.equal(false) isMember.should.equal(false)
return done() return done()
} }
@ -492,7 +491,7 @@ describe('LimitationsManager', function() {
) )
return this.LimitationsManager.userIsMemberOfGroupSubscription( return this.LimitationsManager.userIsMemberOfGroupSubscription(
this.user, this.user,
function(err, isMember, retSubscriptions) { (err, isMember, retSubscriptions) => {
isMember.should.equal(true) isMember.should.equal(true)
retSubscriptions.should.equal(subscriptions) retSubscriptions.should.equal(subscriptions)
return done() return done()
@ -518,55 +517,55 @@ describe('LimitationsManager', function() {
this.LimitationsManager.userIsMemberOfGroupSubscription = sinon this.LimitationsManager.userIsMemberOfGroupSubscription = sinon
.stub() .stub()
.yields(null, true) .yields(null, true)
return this.LimitationsManager.hasPaidSubscription(this.user, function( return this.LimitationsManager.hasPaidSubscription(
err, this.user,
hasSubOrIsGroupMember (err, hasSubOrIsGroupMember) => {
) { hasSubOrIsGroupMember.should.equal(true)
hasSubOrIsGroupMember.should.equal(true) return done()
return done() }
}) )
}) })
it('should return true if userHasV2Subscription', function(done) { it('should return true if userHasV2Subscription', function(done) {
this.LimitationsManager.userHasV2Subscription = sinon this.LimitationsManager.userHasV2Subscription = sinon
.stub() .stub()
.yields(null, true) .yields(null, true)
return this.LimitationsManager.hasPaidSubscription(this.user, function( return this.LimitationsManager.hasPaidSubscription(
err, this.user,
hasSubOrIsGroupMember (err, hasSubOrIsGroupMember) => {
) { hasSubOrIsGroupMember.should.equal(true)
hasSubOrIsGroupMember.should.equal(true) return done()
return done() }
}) )
}) })
it('should return true if userHasV1Subscription', function(done) { it('should return true if userHasV1Subscription', function(done) {
this.LimitationsManager.userHasV1Subscription = sinon this.LimitationsManager.userHasV1Subscription = sinon
.stub() .stub()
.yields(null, true) .yields(null, true)
return this.LimitationsManager.hasPaidSubscription(this.user, function( return this.LimitationsManager.hasPaidSubscription(
err, this.user,
hasSubOrIsGroupMember (err, hasSubOrIsGroupMember) => {
) { hasSubOrIsGroupMember.should.equal(true)
hasSubOrIsGroupMember.should.equal(true) return done()
return done() }
}) )
}) })
it('should return false if none are true', function(done) { it('should return false if none are true', function(done) {
return this.LimitationsManager.hasPaidSubscription(this.user, function( return this.LimitationsManager.hasPaidSubscription(
err, this.user,
hasSubOrIsGroupMember (err, hasSubOrIsGroupMember) => {
) { hasSubOrIsGroupMember.should.equal(false)
hasSubOrIsGroupMember.should.equal(false) return done()
return done() }
}) )
}) })
it('should have userHasSubscriptionOrIsGroupMember alias', function(done) { it('should have userHasSubscriptionOrIsGroupMember alias', function(done) {
return this.LimitationsManager.userHasSubscriptionOrIsGroupMember( return this.LimitationsManager.userHasSubscriptionOrIsGroupMember(
this.user, this.user,
function(err, hasSubOrIsGroupMember) { (err, hasSubOrIsGroupMember) => {
hasSubOrIsGroupMember.should.equal(false) hasSubOrIsGroupMember.should.equal(false)
return done() return done()
} }
@ -590,7 +589,7 @@ describe('LimitationsManager', function() {
.yields(null, true) .yields(null, true)
return this.LimitationsManager.userHasV1OrV2Subscription( return this.LimitationsManager.userHasV1OrV2Subscription(
this.user, this.user,
function(err, hasSub) { (err, hasSub) => {
hasSub.should.equal(true) hasSub.should.equal(true)
return done() return done()
} }
@ -603,7 +602,7 @@ describe('LimitationsManager', function() {
.yields(null, true) .yields(null, true)
return this.LimitationsManager.userHasV1OrV2Subscription( return this.LimitationsManager.userHasV1OrV2Subscription(
this.user, this.user,
function(err, hasSub) { (err, hasSub) => {
hasSub.should.equal(true) hasSub.should.equal(true)
return done() return done()
} }
@ -613,7 +612,7 @@ describe('LimitationsManager', function() {
it('should return false if none are true', function(done) { it('should return false if none are true', function(done) {
return this.LimitationsManager.userHasV1OrV2Subscription( return this.LimitationsManager.userHasV1OrV2Subscription(
this.user, this.user,
function(err, hasSub) { (err, hasSub) => {
hasSub.should.equal(false) hasSub.should.equal(false)
return done() return done()
} }
@ -641,7 +640,7 @@ describe('LimitationsManager', function() {
) )
return this.LimitationsManager.hasGroupMembersLimitReached( return this.LimitationsManager.hasGroupMembersLimitReached(
this.subscriptionId, this.subscriptionId,
function(err, limitReached) { (err, limitReached) => {
limitReached.should.equal(true) limitReached.should.equal(true)
return done() return done()
} }
@ -657,7 +656,7 @@ describe('LimitationsManager', function() {
) )
return this.LimitationsManager.hasGroupMembersLimitReached( return this.LimitationsManager.hasGroupMembersLimitReached(
this.subscriptionId, this.subscriptionId,
function(err, limitReached) { (err, limitReached) => {
limitReached.should.equal(false) limitReached.should.equal(false)
return done() return done()
} }
@ -673,7 +672,7 @@ describe('LimitationsManager', function() {
) )
return this.LimitationsManager.hasGroupMembersLimitReached( return this.LimitationsManager.hasGroupMembersLimitReached(
this.subscriptionId, this.subscriptionId,
function(err, limitReached) { (err, limitReached) => {
limitReached.should.equal(true) limitReached.should.equal(true)
return done() return done()
} }

View file

@ -162,7 +162,9 @@ describe('RecurlyWrapper', function() {
)) ))
}) })
after(() => tk.reset()) after(function() {
return tk.reset()
})
describe('getSubscription', function() { describe('getSubscription', function() {
describe('with proper subscription id', function() { describe('with proper subscription id', function() {

View file

@ -200,17 +200,18 @@ describe('SubscriptionController', function() {
return this.PlansLocator.findLocalPlanInSettings.returns({}) return this.PlansLocator.findLocalPlanInSettings.returns({})
}) })
describe('with a valid plan code', () => describe('with a valid plan code', function() {
it('should render the new subscription page', function(done) { it('should render the new subscription page', function(done) {
this.res.render = (page, opts) => { this.res.render = (page, opts) => {
page.should.equal('subscriptions/new') page.should.equal('subscriptions/new')
return done() return done()
} }
return this.SubscriptionController.paymentPage(this.req, this.res) return this.SubscriptionController.paymentPage(this.req, this.res)
})) })
})
}) })
describe('with a user with subscription', () => describe('with a user with subscription', function() {
it('should redirect to the subscription dashboard', function(done) { it('should redirect to the subscription dashboard', function(done) {
this.LimitationsManager.userHasV1OrV2Subscription.callsArgWith( this.LimitationsManager.userHasV1OrV2Subscription.callsArgWith(
1, 1,
@ -222,9 +223,10 @@ describe('SubscriptionController', function() {
return done() return done()
} }
return this.SubscriptionController.paymentPage(this.req, this.res) return this.SubscriptionController.paymentPage(this.req, this.res)
})) })
})
describe('with an invalid plan code', () => describe('with an invalid plan code', function() {
it('should redirect to the subscription dashboard', function(done) { it('should redirect to the subscription dashboard', function(done) {
this.LimitationsManager.userHasV1OrV2Subscription.callsArgWith( this.LimitationsManager.userHasV1OrV2Subscription.callsArgWith(
1, 1,
@ -237,7 +239,8 @@ describe('SubscriptionController', function() {
return done() return done()
} }
return this.SubscriptionController.paymentPage(this.req, this.res) return this.SubscriptionController.paymentPage(this.req, this.res)
})) })
})
describe('which currency to use', function() { describe('which currency to use', function() {
beforeEach(function() { beforeEach(function() {
@ -278,7 +281,7 @@ describe('SubscriptionController', function() {
}) })
}) })
describe('with a recurly subscription already', () => describe('with a recurly subscription already', function() {
it('should redirect to the subscription dashboard', function(done) { it('should redirect to the subscription dashboard', function(done) {
this.LimitationsManager.userHasV1OrV2Subscription.callsArgWith( this.LimitationsManager.userHasV1OrV2Subscription.callsArgWith(
1, 1,
@ -293,10 +296,11 @@ describe('SubscriptionController', function() {
return done() return done()
} }
return this.SubscriptionController.paymentPage(this.req, this.res) return this.SubscriptionController.paymentPage(this.req, this.res)
})) })
})
}) })
describe('successful_subscription', () => describe('successful_subscription', function() {
beforeEach(function(done) { beforeEach(function(done) {
this.SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel.callsArgWith( this.SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel.callsArgWith(
1, 1,
@ -308,7 +312,8 @@ describe('SubscriptionController', function() {
this.req, this.req,
this.res this.res
) )
})) })
})
describe('userSubscriptionPage', function() { describe('userSubscriptionPage', function() {
beforeEach(function(done) { beforeEach(function(done) {

View file

@ -74,7 +74,7 @@ describe('SubscriptionGroupController', function() {
})) }))
}) })
describe('removeUserFromGroup', () => describe('removeUserFromGroup', function() {
it('should use the subscription id for the logged in user and take the user id from the params', function(done) { it('should use the subscription id for the logged in user and take the user id from the params', function(done) {
const userIdToRemove = '31231' const userIdToRemove = '31231'
this.req.params = { user_id: userIdToRemove } this.req.params = { user_id: userIdToRemove }
@ -89,5 +89,6 @@ describe('SubscriptionGroupController', function() {
} }
} }
return this.Controller.removeUserFromGroup(this.req, res) return this.Controller.removeUserFromGroup(this.req, res)
})) })
})
}) })

View file

@ -116,7 +116,7 @@ describe('SubscriptionGroupHandler', function() {
})) }))
}) })
describe('removeUserFromGroup', () => describe('removeUserFromGroup', function() {
it('should call the subscription updater to remove the user', function(done) { it('should call the subscription updater to remove the user', function(done) {
return this.Handler.removeUserFromGroup( return this.Handler.removeUserFromGroup(
this.adminUser_id, this.adminUser_id,
@ -128,7 +128,8 @@ describe('SubscriptionGroupHandler', function() {
return done() return done()
} }
) )
})) })
})
describe('replaceUserReferencesInGroups', function() { describe('replaceUserReferencesInGroups', function() {
beforeEach(function(done) { beforeEach(function(done) {
@ -196,7 +197,7 @@ describe('SubscriptionGroupHandler', function() {
return this.Handler.isUserPartOfGroup( return this.Handler.isUserPartOfGroup(
this.user_id, this.user_id,
this.subscription_id, this.subscription_id,
function(err, partOfGroup) { (err, partOfGroup) => {
partOfGroup.should.equal(true) partOfGroup.should.equal(true)
return done() return done()
} }
@ -211,7 +212,7 @@ describe('SubscriptionGroupHandler', function() {
return this.Handler.isUserPartOfGroup( return this.Handler.isUserPartOfGroup(
this.user_id, this.user_id,
this.subscription_id, this.subscription_id,
function(err, partOfGroup) { (err, partOfGroup) => {
partOfGroup.should.equal(false) partOfGroup.should.equal(false)
return done() return done()
} }
@ -237,7 +238,7 @@ describe('SubscriptionGroupHandler', function() {
) )
}) })
}) })
describe('for nonexistent subscriptions', () => describe('for nonexistent subscriptions', function() {
it('should return undefined', function(done) { it('should return undefined', function(done) {
return this.Handler.getTotalConfirmedUsersInGroup( return this.Handler.getTotalConfirmedUsersInGroup(
'fake-id', 'fake-id',
@ -246,6 +247,7 @@ describe('SubscriptionGroupHandler', function() {
return done() return done()
} }
) )
})) })
})
}) })
}) })

View file

@ -177,7 +177,7 @@ describe('SubscriptionHandler', function() {
}) })
describe('updateSubscription', function() { describe('updateSubscription', function() {
describe('with a user with a subscription', () => describe('with a user with a subscription', function() {
describe('with a valid plan code', function() { describe('with a valid plan code', function() {
beforeEach(function(done) { beforeEach(function(done) {
this.plan_code = 'collaborator' this.plan_code = 'collaborator'
@ -221,7 +221,8 @@ describe('SubscriptionHandler', function() {
this.user._id this.user._id
) )
}) })
})) })
})
describe('with a user without a subscription', function() { describe('with a user without a subscription', function() {
beforeEach(function(done) { beforeEach(function(done) {
@ -383,7 +384,7 @@ describe('SubscriptionHandler', function() {
}) })
}) })
describe('recurlyCallback', () => describe('recurlyCallback', function() {
describe('with an actionable request', function() { describe('with an actionable request', function() {
beforeEach(function(done) { beforeEach(function(done) {
this.user.id = this.activeRecurlySubscription.account.account_code this.user.id = this.activeRecurlySubscription.account.account_code
@ -418,7 +419,8 @@ describe('SubscriptionHandler', function() {
this.user._id this.user._id
) )
}) })
})) })
})
describe('validateNoSubscriptionInRecurly', function() { describe('validateNoSubscriptionInRecurly', function() {
beforeEach(function() { beforeEach(function() {

View file

@ -82,7 +82,7 @@ describe('Subscription Locator Tests', function() {
) )
}) })
describe('finding managed subscription', () => describe('finding managed subscription', function() {
it('should query the database', function(done) { it('should query the database', function(done) {
this.Subscription.findOne.callsArgWith(1, null, this.subscription) this.Subscription.findOne.callsArgWith(1, null, this.subscription)
return this.SubscriptionLocator.findManagedSubscription( return this.SubscriptionLocator.findManagedSubscription(
@ -95,6 +95,7 @@ describe('Subscription Locator Tests', function() {
return done() return done()
} }
) )
})) })
})
}) })
}) })

View file

@ -309,7 +309,7 @@ describe('SubscriptionUpdater', function() {
}) })
}) })
describe('_createNewSubscription', () => describe('_createNewSubscription', function() {
it('should create a new subscription then update the subscription', function(done) { it('should create a new subscription then update the subscription', function(done) {
this.SubscriptionUpdater._createNewSubscription( this.SubscriptionUpdater._createNewSubscription(
this.adminUser._id, this.adminUser._id,
@ -320,7 +320,8 @@ describe('SubscriptionUpdater', function() {
done() done()
} }
) )
})) })
})
describe('addUserToGroup', function() { describe('addUserToGroup', function() {
beforeEach(function() { beforeEach(function() {

View file

@ -118,14 +118,13 @@ describe('TeamInvitesHandler', function() {
it("returns teamNotFound if there's none", function(done) { it("returns teamNotFound if there's none", function(done) {
this.Subscription.findOne = sinon.stub().yields(null, null) this.Subscription.findOne = sinon.stub().yields(null, null)
this.TeamInvitesHandler.getInvite(this.token, function( this.TeamInvitesHandler.getInvite(
err, this.token,
invite, (err, invite, subscription) => {
subscription expect(err).to.be.instanceof(Errors.NotFoundError)
) { done()
expect(err).to.be.instanceof(Errors.NotFoundError) }
done() )
})
}) })
}) })
@ -304,7 +303,7 @@ describe('TeamInvitesHandler', function() {
}) })
}) })
describe('revokeInvite', () => describe('revokeInvite', function() {
it('removes the team invite from the subscription', function(done) { it('removes the team invite from the subscription', function(done) {
this.TeamInvitesHandler.revokeInvite( this.TeamInvitesHandler.revokeInvite(
this.manager._id, this.manager._id,
@ -327,7 +326,8 @@ describe('TeamInvitesHandler', function() {
done() done()
} }
) )
})) })
})
describe('createTeamInvitesForLegacyInvitedEmail', function(done) { describe('createTeamInvitesForLegacyInvitedEmail', function(done) {
beforeEach(function() { beforeEach(function() {

View file

@ -37,7 +37,7 @@ describe('UserFeaturesUpdater', function() {
})) }))
}) })
describe('updateFeatures', () => describe('updateFeatures', function() {
it('should send the users features', function(done) { it('should send the users features', function(done) {
const user_id = '5208dd34438842e2db000005' const user_id = '5208dd34438842e2db000005'
this.features = { versioning: true, collaborators: 10 } this.features = { versioning: true, collaborators: 10 }
@ -56,5 +56,6 @@ describe('UserFeaturesUpdater', function() {
return done() return done()
} }
) )
})) })
})
}) })

View file

@ -120,15 +120,16 @@ describe('V1SubscriptionManager', function() {
}) })
describe('getGrandfatheredFeaturesForV1User', function() { describe('getGrandfatheredFeaturesForV1User', function() {
describe('when the user ID is greater than the cutoff', () => describe('when the user ID is greater than the cutoff', function() {
it('should return an empty feature set', function(done) { it('should return an empty feature set', function(done) {
expect( expect(
this.V1SubscriptionManager.getGrandfatheredFeaturesForV1User(100) this.V1SubscriptionManager.getGrandfatheredFeaturesForV1User(100)
).to.eql({}) ).to.eql({})
return done() return done()
})) })
})
describe('when the user ID is less than the cutoff', () => describe('when the user ID is less than the cutoff', function() {
it('should return a feature set with grandfathered properties for github and mendeley', function(done) { it('should return a feature set with grandfathered properties for github and mendeley', function(done) {
expect( expect(
this.V1SubscriptionManager.getGrandfatheredFeaturesForV1User(1) this.V1SubscriptionManager.getGrandfatheredFeaturesForV1User(1)
@ -137,7 +138,8 @@ describe('V1SubscriptionManager', function() {
mendeley: true mendeley: true
}) })
return done() return done()
})) })
})
}) })
describe('_v1Request', function() { describe('_v1Request', function() {

View file

@ -49,12 +49,13 @@ describe('SudoModeHandler', function() {
})) }))
}) })
describe('_buildKey', () => describe('_buildKey', function() {
it('should build a properly formed key', function() { it('should build a properly formed key', function() {
return expect(this.SudoModeHandler._buildKey('123')).to.equal( return expect(this.SudoModeHandler._buildKey('123')).to.equal(
'SudoMode:{123}' 'SudoMode:{123}'
) )
})) })
})
describe('activateSudoMode', function() { describe('activateSudoMode', function() {
beforeEach(function() { beforeEach(function() {

View file

@ -69,7 +69,7 @@ describe('TagsController', function() {
return (this.res.json = sinon.stub()) return (this.res.json = sinon.stub())
}) })
describe('getAllTags', () => describe('getAllTags', function() {
it('should ask the handler for all tags', function(done) { it('should ask the handler for all tags', function(done) {
const allTags = [{ name: 'tag', projects: ['123423', '423423'] }] const allTags = [{ name: 'tag', projects: ['123423', '423423'] }]
this.handler.getAllTags = sinon.stub().callsArgWith(1, null, allTags) this.handler.getAllTags = sinon.stub().callsArgWith(1, null, allTags)
@ -80,7 +80,8 @@ describe('TagsController', function() {
return done() return done()
} }
}) })
})) })
})
describe('createTag', function() { describe('createTag', function() {
beforeEach(function() { beforeEach(function() {

View file

@ -53,7 +53,7 @@ describe('TagsHandler', function() {
})) }))
}) })
describe('removeProjectFromAllTags', () => describe('removeProjectFromAllTags', function() {
it('should tell the tags api to remove the project_id from all the users tags', function(done) { it('should tell the tags api to remove the project_id from all the users tags', function(done) {
return this.handler.removeProjectFromAllTags(user_id, project_id, () => { return this.handler.removeProjectFromAllTags(user_id, project_id, () => {
this.request.del this.request.del
@ -64,7 +64,8 @@ describe('TagsHandler', function() {
.should.equal(true) .should.equal(true)
return done() return done()
}) })
})) })
})
describe('_requestTags', function() { describe('_requestTags', function() {
it('should return an err and empty array on error', function(done) { it('should return an err and empty array on error', function(done) {

View file

@ -42,7 +42,7 @@ describe('TpdsController', function() {
this.user_id = 'dsad29jlkjas' this.user_id = 'dsad29jlkjas'
}) })
describe('getting an update', () => { describe('getting an update', function() {
it('should process the update with the update receiver', function(done) { it('should process the update with the update receiver', function(done) {
const path = '/projectName/here.txt' const path = '/projectName/here.txt'
const req = { const req = {
@ -118,7 +118,7 @@ describe('TpdsController', function() {
}) })
}) })
describe('getting a delete update', () => describe('getting a delete update', function() {
it('should process the delete with the update reciver', function(done) { it('should process the delete with the update reciver', function(done) {
const path = '/projectName/here.txt' const path = '/projectName/here.txt'
const req = { const req = {
@ -140,7 +140,8 @@ describe('TpdsController', function() {
} }
} }
this.TpdsController.deleteUpdate(req, res) this.TpdsController.deleteUpdate(req, res)
})) })
})
describe('parseParams', function() { describe('parseParams', function() {
it('should take the project name off the start and replace with slash', function() { it('should take the project name off the start and replace with slash', function() {
@ -152,7 +153,7 @@ describe('TpdsController', function() {
result.projectName.should.equal(path) result.projectName.should.equal(path)
}) })
it('should take the project name off the start and return it with no slashes in', function() { it('should take the project name off the start and it with no slashes in', function() {
const path = '/project/file.tex' const path = '/project/file.tex'
const req = { params: { 0: path, user_id: this.user_id } } const req = { params: { 0: path, user_id: this.user_id } }
const result = this.TpdsController.parseParams(req) const result = this.TpdsController.parseParams(req)

View file

@ -125,7 +125,7 @@ describe('TpdsUpdateSender', function() {
} }
return this.updateSender.addFile( return this.updateSender.addFile(
{ project_id, file_id, path, project_name }, { project_id, file_id, path, project_name },
function() {} () => {}
) )
}) })

View file

@ -86,7 +86,7 @@ describe('TokenAccessHandler', function() {
it('should return projectExists flag as true', function(done) { it('should return projectExists flag as true', function(done) {
return this.TokenAccessHandler.findProjectWithReadOnlyToken( return this.TokenAccessHandler.findProjectWithReadOnlyToken(
this.token, this.token,
function(err, project, projectExists) { (err, project, projectExists) => {
expect(projectExists).to.equal(true) expect(projectExists).to.equal(true)
return done() return done()
} }
@ -124,7 +124,7 @@ describe('TokenAccessHandler', function() {
it('should not return a project', function(done) { it('should not return a project', function(done) {
return this.TokenAccessHandler.findProjectWithReadOnlyToken( return this.TokenAccessHandler.findProjectWithReadOnlyToken(
this.token, this.token,
function(err, project) { (err, project) => {
expect(err).to.not.exist expect(err).to.not.exist
expect(project).to.not.exist expect(project).to.not.exist
return done() return done()
@ -135,7 +135,7 @@ describe('TokenAccessHandler', function() {
it('should return projectExists flag as true', function(done) { it('should return projectExists flag as true', function(done) {
return this.TokenAccessHandler.findProjectWithReadOnlyToken( return this.TokenAccessHandler.findProjectWithReadOnlyToken(
this.token, this.token,
function(err, project, projectExists) { (err, project, projectExists) => {
expect(projectExists).to.equal(true) expect(projectExists).to.equal(true)
return done() return done()
} }
@ -151,7 +151,7 @@ describe('TokenAccessHandler', function() {
it('should not return a project', function(done) { it('should not return a project', function(done) {
return this.TokenAccessHandler.findProjectWithReadOnlyToken( return this.TokenAccessHandler.findProjectWithReadOnlyToken(
this.token, this.token,
function(err, project) { (err, project) => {
expect(err).to.not.exist expect(err).to.not.exist
expect(project).to.not.exist expect(project).to.not.exist
return done() return done()
@ -162,7 +162,7 @@ describe('TokenAccessHandler', function() {
it('should return projectExists flag as false', function(done) { it('should return projectExists flag as false', function(done) {
return this.TokenAccessHandler.findProjectWithReadOnlyToken( return this.TokenAccessHandler.findProjectWithReadOnlyToken(
this.token, this.token,
function(err, project, projectExists) { (err, project, projectExists) => {
expect(projectExists).to.equal(false) expect(projectExists).to.equal(false)
return done() return done()
} }
@ -215,7 +215,7 @@ describe('TokenAccessHandler', function() {
it('should return projectExists flag as true', function(done) { it('should return projectExists flag as true', function(done) {
return this.TokenAccessHandler.findProjectWithReadAndWriteToken( return this.TokenAccessHandler.findProjectWithReadAndWriteToken(
this.token, this.token,
function(err, project, projectExists) { (err, project, projectExists) => {
expect(projectExists).to.equal(true) expect(projectExists).to.equal(true)
return done() return done()
} }
@ -253,7 +253,7 @@ describe('TokenAccessHandler', function() {
it('should not return a project', function(done) { it('should not return a project', function(done) {
return this.TokenAccessHandler.findProjectWithReadAndWriteToken( return this.TokenAccessHandler.findProjectWithReadAndWriteToken(
this.token, this.token,
function(err, project) { (err, project) => {
expect(err).to.not.exist expect(err).to.not.exist
expect(project).to.not.exist expect(project).to.not.exist
return done() return done()
@ -264,7 +264,7 @@ describe('TokenAccessHandler', function() {
it('should return projectExists flag as true', function(done) { it('should return projectExists flag as true', function(done) {
return this.TokenAccessHandler.findProjectWithReadAndWriteToken( return this.TokenAccessHandler.findProjectWithReadAndWriteToken(
this.token, this.token,
function(err, project, projectExists) { (err, project, projectExists) => {
expect(projectExists).to.equal(true) expect(projectExists).to.equal(true)
return done() return done()
} }
@ -287,7 +287,7 @@ describe('TokenAccessHandler', function() {
it('should not return a project', function(done) { it('should not return a project', function(done) {
return this.TokenAccessHandler.findProjectWithReadAndWriteToken( return this.TokenAccessHandler.findProjectWithReadAndWriteToken(
this.token, this.token,
function(err, project) { (err, project) => {
expect(err).to.not.exist expect(err).to.not.exist
expect(project).to.not.exist expect(project).to.not.exist
return done() return done()

View file

@ -386,7 +386,7 @@ describe('ProjectUploadManager', function() {
}) })
}) })
describe('_getDestinationDirectory', () => describe('_getDestinationDirectory', function() {
it('should return the path with the time appended', function() { it('should return the path with the time appended', function() {
const date = Date.now() const date = Date.now()
sinon.stub(Date, 'now', () => date) sinon.stub(Date, 'now', () => date)
@ -394,5 +394,6 @@ describe('ProjectUploadManager', function() {
'/path/to/zip/file.zip' '/path/to/zip/file.zip'
).should.equal(`/path/to/zip/file-${date}`) ).should.equal(`/path/to/zip/file-${date}`)
Date.now.restore() Date.now.restore()
})) })
})
}) })

View file

@ -269,7 +269,7 @@ describe('UserController', function() {
}) })
}) })
describe('unsubscribe', () => describe('unsubscribe', function() {
it('should send the user to unsubscribe', function(done) { it('should send the user to unsubscribe', function(done) {
this.res.send = code => { this.res.send = code => {
this.NewsLetterManager.unsubscribe this.NewsLetterManager.unsubscribe
@ -278,7 +278,8 @@ describe('UserController', function() {
return done() return done()
} }
return this.UserController.unsubscribe(this.req, this.res) return this.UserController.unsubscribe(this.req, this.res)
})) })
})
describe('updateUserSettings', function() { describe('updateUserSettings', function() {
beforeEach(function() { beforeEach(function() {
@ -501,7 +502,7 @@ describe('UserController', function() {
return this.UserController.clearSessions(this.req, this.res) return this.UserController.clearSessions(this.req, this.res)
}) })
describe('when revokeAllUserSessions produces an error', () => describe('when revokeAllUserSessions produces an error', function() {
it('should call next with an error', function(done) { it('should call next with an error', function(done) {
this.UserSessionsManager.revokeAllUserSessions.callsArgWith( this.UserSessionsManager.revokeAllUserSessions.callsArgWith(
2, 2,
@ -513,7 +514,8 @@ describe('UserController', function() {
return done() return done()
} }
return this.UserController.clearSessions(this.req, this.res, next) return this.UserController.clearSessions(this.req, this.res, next)
})) })
})
}) })
describe('changePassword', function() { describe('changePassword', function() {

View file

@ -12,8 +12,8 @@ const expect = chai.expect
const modulePath = '../../../../app/src/Features/User/UserDeleter.js' const modulePath = '../../../../app/src/Features/User/UserDeleter.js'
describe('UserDeleter', () => { describe('UserDeleter', function() {
beforeEach(() => { beforeEach(function() {
tk.freeze(Date.now()) tk.freeze(Date.now())
this.userId = ObjectId() this.userId = ObjectId()
@ -90,14 +90,14 @@ describe('UserDeleter', () => {
}) })
}) })
afterEach(() => { afterEach(function() {
this.DeletedUserMock.restore() this.DeletedUserMock.restore()
this.UserMock.restore() this.UserMock.restore()
this.mockedUser.restore() this.mockedUser.restore()
}) })
describe('deleteUser', () => { describe('deleteUser', function() {
beforeEach(() => { beforeEach(function() {
this.UserDeleter.promises.ensureCanDeleteUser = sinon.stub().resolves() this.UserDeleter.promises.ensureCanDeleteUser = sinon.stub().resolves()
this.UserMock.expects('findById') this.UserMock.expects('findById')
@ -106,8 +106,8 @@ describe('UserDeleter', () => {
.resolves(this.user) .resolves(this.user)
}) })
describe('when the user can be deleted', () => { describe('when the user can be deleted', function() {
beforeEach(() => { beforeEach(function() {
this.deletedUser = { this.deletedUser = {
user: this.user, user: this.user,
deleterData: { deleterData: {
@ -131,81 +131,81 @@ describe('UserDeleter', () => {
.resolves() .resolves()
}) })
describe('when no options are passed', () => { describe('when no options are passed', function() {
beforeEach(() => { beforeEach(function() {
this.DeletedUserMock.expects('create') this.DeletedUserMock.expects('create')
.withArgs(this.deletedUser) .withArgs(this.deletedUser)
.chain('exec') .chain('exec')
.resolves() .resolves()
}) })
it('should find and the user in mongo by its id', async () => { it('should find and the user in mongo by its id', async function() {
await this.UserDeleter.promises.deleteUser(this.userId) await this.UserDeleter.promises.deleteUser(this.userId)
this.UserMock.verify() this.UserMock.verify()
}) })
it('should unsubscribe the user from the news letter', async () => { it('should unsubscribe the user from the news letter', async function() {
await this.UserDeleter.promises.deleteUser(this.userId) await this.UserDeleter.promises.deleteUser(this.userId)
expect(this.NewsletterManager.unsubscribe).to.have.been.calledWith( expect(this.NewsletterManager.unsubscribe).to.have.been.calledWith(
this.user this.user
) )
}) })
it('should delete all the projects of a user', async () => { it('should delete all the projects of a user', async function() {
await this.UserDeleter.promises.deleteUser(this.userId) await this.UserDeleter.promises.deleteUser(this.userId)
expect( expect(
this.ProjectDeleter.promises.deleteUsersProjects this.ProjectDeleter.promises.deleteUsersProjects
).to.have.been.calledWith(this.userId) ).to.have.been.calledWith(this.userId)
}) })
it("should cancel the user's subscription", async () => { it("should cancel the user's subscription", async function() {
await this.UserDeleter.promises.deleteUser(this.userId) await this.UserDeleter.promises.deleteUser(this.userId)
expect( expect(
this.SubscriptionHandler.cancelSubscription this.SubscriptionHandler.cancelSubscription
).to.have.been.calledWith(this.user) ).to.have.been.calledWith(this.user)
}) })
it('should delete user affiliations', async () => { it('should delete user affiliations', async function() {
await this.UserDeleter.promises.deleteUser(this.userId) await this.UserDeleter.promises.deleteUser(this.userId)
expect( expect(
this.InstitutionsApi.deleteAffiliations this.InstitutionsApi.deleteAffiliations
).to.have.been.calledWith(this.userId) ).to.have.been.calledWith(this.userId)
}) })
it('should remove user from group subscriptions', async () => { it('should remove user from group subscriptions', async function() {
await this.UserDeleter.promises.deleteUser(this.userId) await this.UserDeleter.promises.deleteUser(this.userId)
expect( expect(
this.SubscriptionUpdater.removeUserFromAllGroups this.SubscriptionUpdater.removeUserFromAllGroups
).to.have.been.calledWith(this.userId) ).to.have.been.calledWith(this.userId)
}) })
it('should remove user memberships', async () => { it('should remove user memberships', async function() {
await this.UserDeleter.promises.deleteUser(this.userId) await this.UserDeleter.promises.deleteUser(this.userId)
expect( expect(
this.UserMembershipsHandler.removeUserFromAllEntities this.UserMembershipsHandler.removeUserFromAllEntities
).to.have.been.calledWith(this.userId) ).to.have.been.calledWith(this.userId)
}) })
it('ensures user can be deleted', async () => { it('ensures user can be deleted', async function() {
await this.UserDeleter.promises.deleteUser(this.userId) await this.UserDeleter.promises.deleteUser(this.userId)
expect( expect(
this.UserDeleter.promises.ensureCanDeleteUser this.UserDeleter.promises.ensureCanDeleteUser
).to.have.been.calledWith(this.user) ).to.have.been.calledWith(this.user)
}) })
it('should create a deletedUser', async () => { it('should create a deletedUser', async function() {
await this.UserDeleter.promises.deleteUser(this.userId) await this.UserDeleter.promises.deleteUser(this.userId)
this.DeletedUserMock.verify() this.DeletedUserMock.verify()
}) })
describe('when unsubscribing from mailchimp fails', () => { describe('when unsubscribing from mailchimp fails', function() {
beforeEach(() => { beforeEach(function() {
this.NewsletterManager.unsubscribe = sinon this.NewsletterManager.unsubscribe = sinon
.stub() .stub()
.yields(new Error('something went wrong')) .yields(new Error('something went wrong'))
}) })
it('should not return an error', async () => { it('should not return an error', async function() {
try { try {
await this.UserDeleter.promises.deleteUser(this.userId) await this.UserDeleter.promises.deleteUser(this.userId)
} catch (error) { } catch (error) {
@ -218,19 +218,19 @@ describe('UserDeleter', () => {
) )
}) })
it('should delete the user', async () => { it('should delete the user', async function() {
await this.UserDeleter.promises.deleteUser(this.userId) await this.UserDeleter.promises.deleteUser(this.userId)
this.UserMock.verify() this.UserMock.verify()
}) })
it('should log an error', async () => { it('should log an error', async function() {
await this.UserDeleter.promises.deleteUser(this.userId) await this.UserDeleter.promises.deleteUser(this.userId)
sinon.assert.called(this.logger.err) sinon.assert.called(this.logger.err)
}) })
}) })
describe('when called as a callback', () => { describe('when called as a callback', function() {
it('should delete the user', done => { it('should delete the user', function(done) {
this.UserDeleter.deleteUser(this.userId, err => { this.UserDeleter.deleteUser(this.userId, err => {
expect(err).not.to.exist expect(err).not.to.exist
this.UserMock.verify() this.UserMock.verify()
@ -241,8 +241,8 @@ describe('UserDeleter', () => {
}) })
}) })
describe('when a user and IP address are specified', () => { describe('when a user and IP address are specified', function() {
beforeEach(() => { beforeEach(function() {
this.ipAddress = '1.2.3.4' this.ipAddress = '1.2.3.4'
this.deleterId = ObjectId() this.deleterId = ObjectId()
@ -255,7 +255,7 @@ describe('UserDeleter', () => {
.resolves() .resolves()
}) })
it('should add the deleted user id and ip address to the deletedUser', async () => { it('should add the deleted user id and ip address to the deletedUser', async function() {
await this.UserDeleter.promises.deleteUser(this.userId, { await this.UserDeleter.promises.deleteUser(this.userId, {
deleterUser: { _id: this.deleterId }, deleterUser: { _id: this.deleterId },
ipAddress: this.ipAddress ipAddress: this.ipAddress
@ -263,8 +263,8 @@ describe('UserDeleter', () => {
this.DeletedUserMock.verify() this.DeletedUserMock.verify()
}) })
describe('when called as a callback', () => { describe('when called as a callback', function() {
it('should delete the user', done => { it('should delete the user', function(done) {
this.UserDeleter.deleteUser( this.UserDeleter.deleteUser(
this.userId, this.userId,
{ {
@ -283,14 +283,14 @@ describe('UserDeleter', () => {
}) })
}) })
describe('when the user cannot be deleted because they are a subscription admin', () => { describe('when the user cannot be deleted because they are a subscription admin', function() {
beforeEach(() => { beforeEach(function() {
this.UserDeleter.promises.ensureCanDeleteUser.rejects( this.UserDeleter.promises.ensureCanDeleteUser.rejects(
new Errors.SubscriptionAdminDeletionError() new Errors.SubscriptionAdminDeletionError()
) )
}) })
it('fails with a SubscriptionAdminDeletionError', async () => { it('fails with a SubscriptionAdminDeletionError', async function() {
let error let error
try { try {
await this.UserDeleter.promises.deleteUser(this.userId) await this.UserDeleter.promises.deleteUser(this.userId)
@ -301,7 +301,7 @@ describe('UserDeleter', () => {
} }
}) })
it('should not create a deletedUser', async () => { it('should not create a deletedUser', async function() {
try { try {
await this.UserDeleter.promises.deleteUser(this.userId) await this.UserDeleter.promises.deleteUser(this.userId)
} catch (e) { } catch (e) {
@ -310,7 +310,7 @@ describe('UserDeleter', () => {
} }
}) })
it('should not remove the user from mongo', async () => { it('should not remove the user from mongo', async function() {
try { try {
await this.UserDeleter.promises.deleteUser(this.userId) await this.UserDeleter.promises.deleteUser(this.userId)
} catch (e) { } catch (e) {
@ -321,8 +321,8 @@ describe('UserDeleter', () => {
}) })
}) })
describe('ensureCanDeleteUser', () => { describe('ensureCanDeleteUser', function() {
it('should not return error when user can be deleted', async () => { it('should not return error when user can be deleted', async function() {
this.SubscriptionLocator.getUsersSubscription.yields(null, null) this.SubscriptionLocator.getUsersSubscription.yields(null, null)
let error let error
try { try {
@ -334,7 +334,7 @@ describe('UserDeleter', () => {
} }
}) })
it('should return custom error when user is group admin', async () => { it('should return custom error when user is group admin', async function() {
this.SubscriptionLocator.getUsersSubscription.yields(null, { this.SubscriptionLocator.getUsersSubscription.yields(null, {
_id: '123abc' _id: '123abc'
}) })
@ -348,7 +348,7 @@ describe('UserDeleter', () => {
} }
}) })
it('propagates errors', async () => { it('propagates errors', async function() {
this.SubscriptionLocator.getUsersSubscription.yields( this.SubscriptionLocator.getUsersSubscription.yields(
new Error('Some error') new Error('Some error')
) )
@ -363,8 +363,8 @@ describe('UserDeleter', () => {
}) })
}) })
describe('expireDeletedUsersAfterDuration', () => { describe('expireDeletedUsersAfterDuration', function() {
beforeEach(() => { beforeEach(function() {
this.UserDeleter.promises.expireDeletedUser = sinon.stub().resolves() this.UserDeleter.promises.expireDeletedUser = sinon.stub().resolves()
this.deletedUsers = [ this.deletedUsers = [
{ {
@ -390,7 +390,7 @@ describe('UserDeleter', () => {
.resolves(this.deletedUsers) .resolves(this.deletedUsers)
}) })
it('calls expireDeletedUser for each user', async () => { it('calls expireDeletedUser for each user', async function() {
await this.UserDeleter.promises.expireDeletedUsersAfterDuration() await this.UserDeleter.promises.expireDeletedUsersAfterDuration()
expect( expect(
this.UserDeleter.promises.expireDeletedUser this.UserDeleter.promises.expireDeletedUser
@ -401,8 +401,8 @@ describe('UserDeleter', () => {
}) })
}) })
describe('expireDeletedUser', () => { describe('expireDeletedUser', function() {
beforeEach(() => { beforeEach(function() {
this.mockedDeletedUser = sinon.mock( this.mockedDeletedUser = sinon.mock(
new DeletedUser({ new DeletedUser({
user: this.user, user: this.user,
@ -422,37 +422,37 @@ describe('UserDeleter', () => {
.resolves(this.deletedUser) .resolves(this.deletedUser)
}) })
afterEach(() => { afterEach(function() {
this.mockedDeletedUser.restore() this.mockedDeletedUser.restore()
}) })
it('should find the user by user ID', async () => { it('should find the user by user ID', async function() {
await this.UserDeleter.promises.expireDeletedUser('giraffe') await this.UserDeleter.promises.expireDeletedUser('giraffe')
this.DeletedUserMock.verify() this.DeletedUserMock.verify()
}) })
it('should remove the user data from mongo', async () => { it('should remove the user data from mongo', async function() {
await this.UserDeleter.promises.expireDeletedUser('giraffe') await this.UserDeleter.promises.expireDeletedUser('giraffe')
expect(this.deletedUser.user).not.to.exist expect(this.deletedUser.user).not.to.exist
}) })
it('should remove the IP address from mongo', async () => { it('should remove the IP address from mongo', async function() {
await this.UserDeleter.promises.expireDeletedUser('giraffe') await this.UserDeleter.promises.expireDeletedUser('giraffe')
expect(this.deletedUser.deleterData.ipAddress).not.to.exist expect(this.deletedUser.deleterData.ipAddress).not.to.exist
}) })
it('should not delete other deleterData fields', async () => { it('should not delete other deleterData fields', async function() {
await this.UserDeleter.promises.expireDeletedUser('giraffe') await this.UserDeleter.promises.expireDeletedUser('giraffe')
expect(this.deletedUser.deleterData.deletedUserId).to.equal(this.userId) expect(this.deletedUser.deleterData.deletedUserId).to.equal(this.userId)
}) })
it('should save the record to mongo', async () => { it('should save the record to mongo', async function() {
await this.UserDeleter.promises.expireDeletedUser('giraffe') await this.UserDeleter.promises.expireDeletedUser('giraffe')
this.mockedDeletedUser.verify() this.mockedDeletedUser.verify()
}) })
describe('when called as a callback', () => { describe('when called as a callback', function() {
it('should expire the user', done => { it('should expire the user', function(done) {
this.UserDeleter.expireDeletedUser('giraffe', err => { this.UserDeleter.expireDeletedUser('giraffe', err => {
expect(err).not.to.exists expect(err).not.to.exists
this.DeletedUserMock.verify() this.DeletedUserMock.verify()

View file

@ -272,7 +272,7 @@ describe('UserGetter', function() {
}) })
}) })
describe('getUsersByHostname', () => describe('getUsersByHostname', function() {
it('should find user by hostname', function(done) { it('should find user by hostname', function(done) {
const hostname = 'bar.foo' const hostname = 'bar.foo'
const expectedQuery = { const expectedQuery = {
@ -292,9 +292,10 @@ describe('UserGetter', function() {
return done() return done()
} }
) )
})) })
})
describe('getUsersByV1Id', () => describe('getUsersByV1Id', function() {
it('should find users by list of v1 ids', function(done) { it('should find users by list of v1 ids', function(done) {
const v1Ids = [501] const v1Ids = [501]
const expectedQuery = { const expectedQuery = {
@ -310,7 +311,8 @@ describe('UserGetter', function() {
return done() return done()
} }
) )
})) })
})
describe('ensureUniqueEmailAddress', function() { describe('ensureUniqueEmailAddress', function() {
beforeEach(function() { beforeEach(function() {

Some files were not shown because too many files have changed in this diff Show more