fix jscs errors

This commit is contained in:
Rob Halff 2014-11-21 03:35:36 +01:00
parent 38757c1c88
commit 36e1f6840c
26 changed files with 722 additions and 732 deletions

View File

@ -47,8 +47,8 @@ module.exports = function(grunt) {
gruntfile: 'Gruntfile.js', gruntfile: 'Gruntfile.js',
lib: ['lib/**/*.js'], lib: ['lib/**/*.js'],
common: ['common/**/*.js'], common: ['common/**/*.js'],
server: ['server/**/*.js'] server: ['server/**/*.js'],
// TODO(bajtos) - test/**/*.js test: ['test/**/*.js']
}, },
watch: { watch: {
gruntfile: { gruntfile: {

View File

@ -10,17 +10,17 @@ var USER = {email: 'test@test.test', password: 'test'};
var CURRENT_USER = {email: 'current@test.test', password: 'test'}; var CURRENT_USER = {email: 'current@test.test', password: 'test'};
var debug = require('debug')('loopback:test:access-control.integration'); var debug = require('debug')('loopback:test:access-control.integration');
describe('access control - integration', function () { describe('access control - integration', function() {
lt.beforeEach.withApp(app); lt.beforeEach.withApp(app);
/* /*
describe('accessToken', function() { describe('accessToken', function() {
// it('should be a sublcass of AccessToken', function () { // it('should be a sublcass of AccessToken', function() {
// assert(app.models.accessToken.prototype instanceof loopback.AccessToken); // assert(app.models.accessToken.prototype instanceof loopback.AccessToken);
// }); // });
it('should have a validate method', function () { it('should have a validate method', function() {
var token = new app.models.accessToken; var token = new app.models.accessToken;
assert.equal(typeof token.validate, 'function'); assert.equal(typeof token.validate, 'function');
}); });
@ -60,7 +60,7 @@ describe('access control - integration', function () {
}); });
*/ */
describe('/users', function () { describe('/users', function() {
lt.beforeEach.givenModel('user', USER, 'randomUser'); lt.beforeEach.givenModel('user', USER, 'randomUser');
@ -70,7 +70,7 @@ describe('access control - integration', function () {
lt.it.shouldBeDeniedWhenCalledAnonymously('GET', urlForUser); lt.it.shouldBeDeniedWhenCalledAnonymously('GET', urlForUser);
lt.it.shouldBeDeniedWhenCalledUnauthenticated('GET', urlForUser); lt.it.shouldBeDeniedWhenCalledUnauthenticated('GET', urlForUser);
lt.it.shouldBeDeniedWhenCalledByUser(CURRENT_USER,'GET', urlForUser); lt.it.shouldBeDeniedWhenCalledByUser(CURRENT_USER, 'GET', urlForUser);
lt.it.shouldBeAllowedWhenCalledAnonymously( lt.it.shouldBeAllowedWhenCalledAnonymously(
'POST', '/api/users', newUserData()); 'POST', '/api/users', newUserData());
@ -133,7 +133,7 @@ describe('access control - integration', function () {
} }
}); });
describe('/banks', function () { describe('/banks', function() {
lt.beforeEach.givenModel('bank'); lt.beforeEach.givenModel('bank');
lt.it.shouldBeAllowedWhenCalledAnonymously('GET', '/api/banks'); lt.it.shouldBeAllowedWhenCalledAnonymously('GET', '/api/banks');
@ -161,13 +161,13 @@ describe('access control - integration', function () {
} }
}); });
describe('/accounts', function () { describe('/accounts', function() {
var count = 0; var count = 0;
before(function() { before(function() {
var roleModel = loopback.getModelByType(loopback.Role); var roleModel = loopback.getModelByType(loopback.Role);
roleModel.registerResolver('$dummy', function (role, context, callback) { roleModel.registerResolver('$dummy', function(role, context, callback) {
process.nextTick(function () { process.nextTick(function() {
if(context.remotingContext) { if (context.remotingContext) {
count++; count++;
} }
callback && callback(null, false); // Always true callback && callback(null, false); // Always true

View File

@ -6,14 +6,14 @@ var ACL = loopback.ACL;
describe('loopback.token(options)', function() { describe('loopback.token(options)', function() {
beforeEach(createTestingToken); beforeEach(createTestingToken);
it('should populate req.token from the query string', function (done) { it('should populate req.token from the query string', function(done) {
createTestAppAndRequest(this.token, done) createTestAppAndRequest(this.token, done)
.get('/?access_token=' + this.token.id) .get('/?access_token=' + this.token.id)
.expect(200) .expect(200)
.end(done); .end(done);
}); });
it('should populate req.token from an authorization header', function (done) { it('should populate req.token from an authorization header', function(done) {
createTestAppAndRequest(this.token, done) createTestAppAndRequest(this.token, done)
.get('/') .get('/')
.set('authorization', this.token.id) .set('authorization', this.token.id)
@ -21,7 +21,7 @@ describe('loopback.token(options)', function() {
.end(done); .end(done);
}); });
it('should populate req.token from an X-Access-Token header', function (done) { it('should populate req.token from an X-Access-Token header', function(done) {
createTestAppAndRequest(this.token, done) createTestAppAndRequest(this.token, done)
.get('/') .get('/')
.set('X-Access-Token', this.token.id) .set('X-Access-Token', this.token.id)
@ -29,9 +29,9 @@ describe('loopback.token(options)', function() {
.end(done); .end(done);
}); });
it('should populate req.token from an authorization header with bearer token', function (done) { it('should populate req.token from an authorization header with bearer token', function(done) {
var token = this.token.id; var token = this.token.id;
token = 'Bearer '+ new Buffer(token).toString('base64'); token = 'Bearer ' + new Buffer(token).toString('base64');
createTestAppAndRequest(this.token, done) createTestAppAndRequest(this.token, done)
.get('/') .get('/')
.set('authorization', this.token.id) .set('authorization', this.token.id)
@ -39,7 +39,7 @@ describe('loopback.token(options)', function() {
.end(done); .end(done);
}); });
it('should populate req.token from a secure cookie', function (done) { it('should populate req.token from a secure cookie', function(done) {
var app = createTestApp(this.token, done); var app = createTestApp(this.token, done);
request(app) request(app)
@ -52,7 +52,7 @@ describe('loopback.token(options)', function() {
}); });
}); });
it('should populate req.token from a header or a secure cookie', function (done) { it('should populate req.token from a header or a secure cookie', function(done) {
var app = createTestApp(this.token, done); var app = createTestApp(this.token, done);
var id = this.token.id; var id = this.token.id;
request(app) request(app)
@ -88,20 +88,20 @@ describe('loopback.token(options)', function() {
}); });
}); });
describe('AccessToken', function () { describe('AccessToken', function() {
beforeEach(createTestingToken); beforeEach(createTestingToken);
it('should auto-generate id', function () { it('should auto-generate id', function() {
assert(this.token.id); assert(this.token.id);
assert.equal(this.token.id.length, 64); assert.equal(this.token.id.length, 64);
}); });
it('should auto-generate created date', function () { it('should auto-generate created date', function() {
assert(this.token.created); assert(this.token.created);
assert(Object.prototype.toString.call(this.token.created), '[object Date]'); assert(Object.prototype.toString.call(this.token.created), '[object Date]');
}); });
it('should be validateable', function (done) { it('should be validateable', function(done) {
this.token.validate(function(err, isValid) { this.token.validate(function(err, isValid) {
assert(isValid); assert(isValid);
done(); done();
@ -144,7 +144,7 @@ describe('AccessToken', function () {
describe('app.enableAuth()', function() { describe('app.enableAuth()', function() {
beforeEach(createTestingToken); beforeEach(createTestingToken);
it('prevents remote call with 401 status on denied ACL', function (done) { it('prevents remote call with 401 status on denied ACL', function(done) {
createTestAppAndRequest(this.token, done) createTestAppAndRequest(this.token, done)
.del('/tests/123') .del('/tests/123')
.expect(401) .expect(401)
@ -152,7 +152,7 @@ describe('app.enableAuth()', function() {
.end(done); .end(done);
}); });
it('prevent remote call with app setting status on denied ACL', function (done) { it('prevent remote call with app setting status on denied ACL', function(done) {
createTestAppAndRequest(this.token, {app:{aclErrorStatus:403}}, done) createTestAppAndRequest(this.token, {app:{aclErrorStatus:403}}, done)
.del('/tests/123') .del('/tests/123')
.expect(403) .expect(403)
@ -160,7 +160,7 @@ describe('app.enableAuth()', function() {
.end(done); .end(done);
}); });
it('prevent remote call with app setting status on denied ACL', function (done) { it('prevent remote call with app setting status on denied ACL', function(done) {
createTestAppAndRequest(this.token, {model:{aclErrorStatus:404}}, done) createTestAppAndRequest(this.token, {model:{aclErrorStatus:404}}, done)
.del('/tests/123') .del('/tests/123')
.expect(404) .expect(404)
@ -168,7 +168,7 @@ describe('app.enableAuth()', function() {
.end(done); .end(done);
}); });
it('prevent remote call if the accessToken is missing and required', function (done) { it('prevent remote call if the accessToken is missing and required', function(done) {
createTestAppAndRequest(null, done) createTestAppAndRequest(null, done)
.del('/tests/123') .del('/tests/123')
.expect(401) .expect(401)
@ -210,8 +210,8 @@ describe('app.enableAuth()', function() {
function createTestingToken(done) { function createTestingToken(done) {
var test = this; var test = this;
Token.create({}, function (err, token) { Token.create({}, function(err, token) {
if(err) return done(err); if (err) return done(err);
test.token = token; test.token = token;
done(); done();
}); });
@ -223,8 +223,8 @@ function createTestAppAndRequest(testToken, settings, done) {
} }
function createTestApp(testToken, settings, done) { function createTestApp(testToken, settings, done) {
done = arguments[arguments.length-1]; done = arguments[arguments.length - 1];
if(settings == done) settings = {}; if (settings == done) settings = {};
settings = settings || {}; settings = settings || {};
var appSettings = settings.app || {}; var appSettings = settings.app || {};
@ -238,11 +238,11 @@ function createTestApp(testToken, settings, done) {
res.cookie('authorization', testToken.id, {signed: true}); res.cookie('authorization', testToken.id, {signed: true});
res.end(); res.end();
}); });
app.get('/', function (req, res) { app.get('/', function(req, res) {
try { try {
assert(req.accessToken, 'req should have accessToken'); assert(req.accessToken, 'req should have accessToken');
assert(req.accessToken.id === testToken.id); assert(req.accessToken.id === testToken.id);
} catch(e) { } catch (e) {
return done(e); return done(e);
} }
res.send('ok'); res.send('ok');
@ -250,7 +250,7 @@ function createTestApp(testToken, settings, done) {
app.use(loopback.rest()); app.use(loopback.rest());
app.enableAuth(); app.enableAuth();
Object.keys(appSettings).forEach(function(key){ Object.keys(appSettings).forEach(function(key) {
app.set(key, appSettings[key]); app.set(key, appSettings[key]);
}); });
@ -266,7 +266,7 @@ function createTestApp(testToken, settings, done) {
] ]
}; };
Object.keys(modelSettings).forEach(function(key){ Object.keys(modelSettings).forEach(function(key) {
modelOptions[key] = modelSettings[key]; modelOptions[key] = modelSettings[key];
}); });

View File

@ -17,7 +17,7 @@ before(function() {
ds = loopback.createDataSource({connector: loopback.Memory}); ds = loopback.createDataSource({connector: loopback.Memory});
}); });
describe('security scopes', function () { describe('security scopes', function() {
beforeEach(function() { beforeEach(function() {
var ds = this.ds = loopback.createDataSource({connector: loopback.Memory}); var ds = this.ds = loopback.createDataSource({connector: loopback.Memory});
testModel = loopback.PersistedModel.extend('testModel'); testModel = loopback.PersistedModel.extend('testModel');
@ -29,11 +29,11 @@ describe('security scopes', function () {
testModel.attachTo(ds); testModel.attachTo(ds);
}); });
it('should allow access to models for the given scope by wildcard', function () { it('should allow access to models for the given scope by wildcard', function() {
Scope.create({name: 'userScope', description: 'access user information'}, function (err, scope) { Scope.create({name: 'userScope', description: 'access user information'}, function(err, scope) {
ACL.create({principalType: ACL.SCOPE, principalId: scope.id, model: 'User', property: ACL.ALL, ACL.create({principalType: ACL.SCOPE, principalId: scope.id, model: 'User', property: ACL.ALL,
accessType: ACL.ALL, permission: ACL.ALLOW}, accessType: ACL.ALL, permission: ACL.ALLOW},
function (err, resource) { function(err, resource) {
Scope.checkPermission('userScope', 'User', ACL.ALL, ACL.ALL, checkResult); Scope.checkPermission('userScope', 'User', ACL.ALL, ACL.ALL, checkResult);
Scope.checkPermission('userScope', 'User', 'name', ACL.ALL, checkResult); Scope.checkPermission('userScope', 'User', 'name', ACL.ALL, checkResult);
Scope.checkPermission('userScope', 'User', 'name', ACL.READ, checkResult); Scope.checkPermission('userScope', 'User', 'name', ACL.READ, checkResult);
@ -42,25 +42,25 @@ describe('security scopes', function () {
}); });
it('should allow access to models for the given scope', function () { it('should allow access to models for the given scope', function() {
Scope.create({name: 'testModelScope', description: 'access testModel information'}, function (err, scope) { Scope.create({name: 'testModelScope', description: 'access testModel information'}, function(err, scope) {
ACL.create({principalType: ACL.SCOPE, principalId: scope.id, ACL.create({principalType: ACL.SCOPE, principalId: scope.id,
model: 'testModel', property: 'name', accessType: ACL.READ, permission: ACL.ALLOW}, model: 'testModel', property: 'name', accessType: ACL.READ, permission: ACL.ALLOW},
function (err, resource) { function(err, resource) {
ACL.create({principalType: ACL.SCOPE, principalId: scope.id, ACL.create({principalType: ACL.SCOPE, principalId: scope.id,
model: 'testModel', property: 'name', accessType: ACL.WRITE, permission: ACL.DENY}, model: 'testModel', property: 'name', accessType: ACL.WRITE, permission: ACL.DENY},
function (err, resource) { function(err, resource) {
// console.log(resource); // console.log(resource);
Scope.checkPermission('testModelScope', 'testModel', ACL.ALL, ACL.ALL, function (err, perm) { Scope.checkPermission('testModelScope', 'testModel', ACL.ALL, ACL.ALL, function(err, perm) {
assert(perm.permission === ACL.DENY); // because name.WRITE == DENY assert(perm.permission === ACL.DENY); // because name.WRITE == DENY
}); });
Scope.checkPermission('testModelScope', 'testModel', 'name', ACL.ALL, function (err, perm) { Scope.checkPermission('testModelScope', 'testModel', 'name', ACL.ALL, function(err, perm) {
assert(perm.permission === ACL.DENY); // because name.WRITE == DENY assert(perm.permission === ACL.DENY); // because name.WRITE == DENY
}); });
Scope.checkPermission('testModelScope', 'testModel', 'name', ACL.READ, function (err, perm) { Scope.checkPermission('testModelScope', 'testModel', 'name', ACL.READ, function(err, perm) {
assert(perm.permission === ACL.ALLOW); assert(perm.permission === ACL.ALLOW);
}); });
Scope.checkPermission('testModelScope', 'testModel', 'name', ACL.WRITE, function (err, perm) { Scope.checkPermission('testModelScope', 'testModel', 'name', ACL.WRITE, function(err, perm) {
assert(perm.permission === ACL.DENY); assert(perm.permission === ACL.DENY);
}); });
}); });
@ -71,7 +71,7 @@ describe('security scopes', function () {
}); });
describe('security ACLs', function () { describe('security ACLs', function() {
it('should order ACL entries based on the matching score', function() { it('should order ACL entries based on the matching score', function() {
var acls = [ var acls = [
{ {
@ -111,18 +111,18 @@ describe('security ACLs', function () {
methodNames: []}); methodNames: []});
}); });
it('should allow access to models for the given principal by wildcard', function () { it('should allow access to models for the given principal by wildcard', function() {
ACL.create({principalType: ACL.USER, principalId: 'u001', model: 'User', property: ACL.ALL, ACL.create({principalType: ACL.USER, principalId: 'u001', model: 'User', property: ACL.ALL,
accessType: ACL.ALL, permission: ACL.ALLOW}, function (err, acl) { accessType: ACL.ALL, permission: ACL.ALLOW}, function(err, acl) {
ACL.create({principalType: ACL.USER, principalId: 'u001', model: 'User', property: ACL.ALL, ACL.create({principalType: ACL.USER, principalId: 'u001', model: 'User', property: ACL.ALL,
accessType: ACL.READ, permission: ACL.DENY}, function (err, acl) { accessType: ACL.READ, permission: ACL.DENY}, function(err, acl) {
ACL.checkPermission(ACL.USER, 'u001', 'User', 'name', ACL.READ, function (err, perm) { ACL.checkPermission(ACL.USER, 'u001', 'User', 'name', ACL.READ, function(err, perm) {
assert(perm.permission === ACL.DENY); assert(perm.permission === ACL.DENY);
}); });
ACL.checkPermission(ACL.USER, 'u001', 'User', 'name', ACL.ALL, function (err, perm) { ACL.checkPermission(ACL.USER, 'u001', 'User', 'name', ACL.ALL, function(err, perm) {
assert(perm.permission === ACL.DENY); assert(perm.permission === ACL.DENY);
}); });
@ -132,26 +132,26 @@ describe('security ACLs', function () {
}); });
it('should allow access to models by exception', function () { it('should allow access to models by exception', function() {
ACL.create({principalType: ACL.USER, principalId: 'u001', model: 'testModel', property: ACL.ALL, ACL.create({principalType: ACL.USER, principalId: 'u001', model: 'testModel', property: ACL.ALL,
accessType: ACL.ALL, permission: ACL.DENY}, function (err, acl) { accessType: ACL.ALL, permission: ACL.DENY}, function(err, acl) {
ACL.create({principalType: ACL.USER, principalId: 'u001', model: 'testModel', property: ACL.ALL, ACL.create({principalType: ACL.USER, principalId: 'u001', model: 'testModel', property: ACL.ALL,
accessType: ACL.READ, permission: ACL.ALLOW}, function (err, acl) { accessType: ACL.READ, permission: ACL.ALLOW}, function(err, acl) {
ACL.checkPermission(ACL.USER, 'u001', 'testModel', 'name', ACL.READ, function (err, perm) { ACL.checkPermission(ACL.USER, 'u001', 'testModel', 'name', ACL.READ, function(err, perm) {
assert(perm.permission === ACL.ALLOW); assert(perm.permission === ACL.ALLOW);
}); });
ACL.checkPermission(ACL.USER, 'u001', 'testModel', ACL.ALL, ACL.READ, function (err, perm) { ACL.checkPermission(ACL.USER, 'u001', 'testModel', ACL.ALL, ACL.READ, function(err, perm) {
assert(perm.permission === ACL.ALLOW); assert(perm.permission === ACL.ALLOW);
}); });
ACL.checkPermission(ACL.USER, 'u001', 'testModel', 'name', ACL.WRITE, function (err, perm) { ACL.checkPermission(ACL.USER, 'u001', 'testModel', 'name', ACL.WRITE, function(err, perm) {
assert(perm.permission === ACL.DENY); assert(perm.permission === ACL.DENY);
}); });
ACL.checkPermission(ACL.USER, 'u001', 'testModel', 'name', ACL.ALL, function (err, perm) { ACL.checkPermission(ACL.USER, 'u001', 'testModel', 'name', ACL.ALL, function(err, perm) {
assert(perm.permission === ACL.DENY); assert(perm.permission === ACL.DENY);
}); });
@ -161,7 +161,7 @@ describe('security ACLs', function () {
}); });
it('should honor defaultPermission from the model', function () { it('should honor defaultPermission from the model', function() {
var Customer = ds.createModel('Customer', { var Customer = ds.createModel('Customer', {
name: { name: {
type: String, type: String,
@ -178,21 +178,21 @@ describe('security ACLs', function () {
Customer.settings.defaultPermission = ACL.DENY; Customer.settings.defaultPermission = ACL.DENY;
ACL.checkPermission(ACL.USER, 'u001', 'Customer', 'name', ACL.WRITE, function (err, perm) { ACL.checkPermission(ACL.USER, 'u001', 'Customer', 'name', ACL.WRITE, function(err, perm) {
assert(perm.permission === ACL.DENY); assert(perm.permission === ACL.DENY);
}); });
ACL.checkPermission(ACL.USER, 'u001', 'Customer', 'name', ACL.READ, function (err, perm) { ACL.checkPermission(ACL.USER, 'u001', 'Customer', 'name', ACL.READ, function(err, perm) {
assert(perm.permission === ACL.ALLOW); assert(perm.permission === ACL.ALLOW);
}); });
ACL.checkPermission(ACL.USER, 'u002', 'Customer', 'name', ACL.WRITE, function (err, perm) { ACL.checkPermission(ACL.USER, 'u002', 'Customer', 'name', ACL.WRITE, function(err, perm) {
assert(perm.permission === ACL.DENY); assert(perm.permission === ACL.DENY);
}); });
}); });
it('should honor static ACLs from the model', function () { it('should honor static ACLs from the model', function() {
var Customer = ds.createModel('Customer', { var Customer = ds.createModel('Customer', {
name: { name: {
type: String, type: String,
@ -213,15 +213,15 @@ describe('security ACLs', function () {
]; ];
*/ */
ACL.checkPermission(ACL.USER, 'u001', 'Customer', 'name', ACL.WRITE, function (err, perm) { ACL.checkPermission(ACL.USER, 'u001', 'Customer', 'name', ACL.WRITE, function(err, perm) {
assert(perm.permission === ACL.DENY); assert(perm.permission === ACL.DENY);
}); });
ACL.checkPermission(ACL.USER, 'u001', 'Customer', 'name', ACL.READ, function (err, perm) { ACL.checkPermission(ACL.USER, 'u001', 'Customer', 'name', ACL.READ, function(err, perm) {
assert(perm.permission === ACL.ALLOW); assert(perm.permission === ACL.ALLOW);
}); });
ACL.checkPermission(ACL.USER, 'u001', 'Customer', 'name', ACL.ALL, function (err, perm) { ACL.checkPermission(ACL.USER, 'u001', 'Customer', 'name', ACL.ALL, function(err, perm) {
assert(perm.permission === ACL.ALLOW); assert(perm.permission === ACL.ALLOW);
}); });
@ -254,12 +254,12 @@ describe('security ACLs', function () {
assert(staticACLs.length === 1); assert(staticACLs.length === 1);
}); });
it('should check access against LDL, ACL, and Role', function () { it('should check access against LDL, ACL, and Role', function() {
// var log = console.log; // var log = console.log;
var log = function() {}; var log = function() {};
// Create // Create
User.create({name: 'Raymond', email: 'x@y.com', password: 'foobar'}, function (err, user) { User.create({name: 'Raymond', email: 'x@y.com', password: 'foobar'}, function(err, user) {
log('User: ', user.toObject()); log('User: ', user.toObject());
@ -282,19 +282,19 @@ describe('security ACLs', function () {
}); });
ACL.create({principalType: ACL.USER, principalId: userId, model: 'Customer', property: ACL.ALL, ACL.create({principalType: ACL.USER, principalId: userId, model: 'Customer', property: ACL.ALL,
accessType: ACL.ALL, permission: ACL.ALLOW}, function (err, acl) { accessType: ACL.ALL, permission: ACL.ALLOW}, function(err, acl) {
log('ACL 1: ', acl.toObject()); log('ACL 1: ', acl.toObject());
Role.create({name: 'MyRole'}, function (err, myRole) { Role.create({name: 'MyRole'}, function(err, myRole) {
log('Role: ', myRole.toObject()); log('Role: ', myRole.toObject());
myRole.principals.create({principalType: RoleMapping.USER, principalId: userId}, function (err, p) { myRole.principals.create({principalType: RoleMapping.USER, principalId: userId}, function(err, p) {
log('Principal added to role: ', p.toObject()); log('Principal added to role: ', p.toObject());
ACL.create({principalType: ACL.ROLE, principalId: 'MyRole', model: 'Customer', property: ACL.ALL, ACL.create({principalType: ACL.ROLE, principalId: 'MyRole', model: 'Customer', property: ACL.ALL,
accessType: ACL.READ, permission: ACL.DENY}, function (err, acl) { accessType: ACL.READ, permission: ACL.DENY}, function(err, acl) {
log('ACL 2: ', acl.toObject()); log('ACL 2: ', acl.toObject());

View File

@ -307,7 +307,8 @@ describe('app', function() {
}); });
describe('app.model(Model)', function() { describe('app.model(Model)', function() {
var app, db; var app;
var db;
beforeEach(function() { beforeEach(function() {
app = loopback(); app = loopback();
db = loopback.createDataSource({connector: loopback.Memory}); db = loopback.createDataSource({connector: loopback.Memory});
@ -378,7 +379,7 @@ describe('app', function() {
}); });
describe('app.model(name, config)', function () { describe('app.model(name, config)', function() {
var app; var app;
beforeEach(function() { beforeEach(function() {
@ -388,7 +389,7 @@ describe('app', function() {
}); });
}); });
it('Sugar for defining a fully built model', function () { it('Sugar for defining a fully built model', function() {
app.model('foo', { app.model('foo', {
dataSource: 'db' dataSource: 'db'
}); });
@ -561,15 +562,15 @@ describe('app', function() {
}); });
}); });
describe.onServer('app.get('/', loopback.status())', function () { describe.onServer('app.get(\'/\', loopback.status())', function() {
it('should return the status of the application', function (done) { it('should return the status of the application', function(done) {
var app = loopback(); var app = loopback();
app.get('/', loopback.status()); app.get('/', loopback.status());
request(app) request(app)
.get('/') .get('/')
.expect(200) .expect(200)
.end(function(err, res) { .end(function(err, res) {
if(err) return done(err); if (err) return done(err);
assert.equal(typeof res.body, 'object'); assert.equal(typeof res.body, 'object');
assert(res.body.started); assert(res.body.started);
@ -651,7 +652,8 @@ describe('app', function() {
}); });
describe('normalizeHttpPath option', function() { describe('normalizeHttpPath option', function() {
var app, db; var app;
var db;
beforeEach(function() { beforeEach(function() {
app = loopback(); app = loopback();
db = loopback.createDataSource({ connector: loopback.Memory }); db = loopback.createDataSource({ connector: loopback.Memory });

View File

@ -1,7 +1,7 @@
var Change; var Change;
var TestModel; var TestModel;
describe('Change', function(){ describe('Change', function() {
beforeEach(function() { beforeEach(function() {
var memory = loopback.createDataSource({ var memory = loopback.createDataSource({
connector: loopback.Memory connector: loopback.Memory
@ -20,7 +20,7 @@ describe('Change', function(){
foo: 'bar' foo: 'bar'
}; };
TestModel.create(test.data, function(err, model) { TestModel.create(test.data, function(err, model) {
if(err) return done(err); if (err) return done(err);
test.model = model; test.model = model;
test.modelId = model.id; test.modelId = model.id;
test.revisionForModel = Change.revisionForInst(model); test.revisionForModel = Change.revisionForInst(model);
@ -28,8 +28,8 @@ describe('Change', function(){
}); });
}); });
describe('change.id', function () { describe('change.id', function() {
it('should be a hash of the modelName and modelId', function () { it('should be a hash of the modelName and modelId', function() {
var change = new Change({ var change = new Change({
rev: 'abc', rev: 'abc',
modelName: 'foo', modelName: 'foo',
@ -42,17 +42,17 @@ describe('Change', function(){
}); });
}); });
describe('Change.rectifyModelChanges(modelName, modelIds, callback)', function () { describe('Change.rectifyModelChanges(modelName, modelIds, callback)', function() {
describe('using an existing untracked model', function () { describe('using an existing untracked model', function() {
beforeEach(function(done) { beforeEach(function(done) {
var test = this; var test = this;
Change.rectifyModelChanges(this.modelName, [this.modelId], function(err, trackedChanges) { Change.rectifyModelChanges(this.modelName, [this.modelId], function(err, trackedChanges) {
if(err) return done(err); if (err) return done(err);
done(); done();
}); });
}); });
it('should create an entry', function (done) { it('should create an entry', function(done) {
var test = this; var test = this;
Change.find(function(err, trackedChanges) { Change.find(function(err, trackedChanges) {
assert.equal(trackedChanges[0].modelId, test.modelId.toString()); assert.equal(trackedChanges[0].modelId, test.modelId.toString());
@ -60,7 +60,7 @@ describe('Change', function(){
}); });
}); });
it('should only create one change', function (done) { it('should only create one change', function(done) {
Change.count(function(err, count) { Change.count(function(err, count) {
assert.equal(count, 1); assert.equal(count, 1);
done(); done();
@ -69,19 +69,19 @@ describe('Change', function(){
}); });
}); });
describe('Change.findOrCreateChange(modelName, modelId, callback)', function () { describe('Change.findOrCreateChange(modelName, modelId, callback)', function() {
describe('when a change doesnt exist', function () { describe('when a change doesnt exist', function() {
beforeEach(function(done) { beforeEach(function(done) {
var test = this; var test = this;
Change.findOrCreateChange(this.modelName, this.modelId, function(err, result) { Change.findOrCreateChange(this.modelName, this.modelId, function(err, result) {
if(err) return done(err); if (err) return done(err);
test.result = result; test.result = result;
done(); done();
}); });
}); });
it('should create an entry', function (done) { it('should create an entry', function(done) {
var test = this; var test = this;
Change.findById(this.result.id, function(err, change) { Change.findById(this.result.id, function(err, change) {
if (err) return done(err); if (err) return done(err);
@ -91,7 +91,7 @@ describe('Change', function(){
}); });
}); });
describe('when a change does exist', function () { describe('when a change does exist', function() {
beforeEach(function(done) { beforeEach(function(done) {
var test = this; var test = this;
Change.create({ Change.create({
@ -106,13 +106,13 @@ describe('Change', function(){
beforeEach(function(done) { beforeEach(function(done) {
var test = this; var test = this;
Change.findOrCreateChange(this.modelName, this.modelId, function(err, result) { Change.findOrCreateChange(this.modelName, this.modelId, function(err, result) {
if(err) return done(err); if (err) return done(err);
test.result = result; test.result = result;
done(); done();
}); });
}); });
it('should find the entry', function (done) { it('should find the entry', function(done) {
var test = this; var test = this;
assert.equal(test.existingChange.id, test.result.id); assert.equal(test.existingChange.id, test.result.id);
done(); done();
@ -120,8 +120,8 @@ describe('Change', function(){
}); });
}); });
describe('change.rectify(callback)', function () { describe('change.rectify(callback)', function() {
it('should create a new change with the correct revision', function (done) { it('should create a new change with the correct revision', function(done) {
var test = this; var test = this;
var change = new Change({ var change = new Change({
modelName: this.modelName, modelName: this.modelName,
@ -135,8 +135,8 @@ describe('Change', function(){
}); });
}); });
describe('change.currentRevision(callback)', function () { describe('change.currentRevision(callback)', function() {
it('should get the correct revision', function (done) { it('should get the correct revision', function(done) {
var test = this; var test = this;
var change = new Change({ var change = new Change({
modelName: this.modelName, modelName: this.modelName,
@ -150,9 +150,9 @@ describe('Change', function(){
}); });
}); });
describe('Change.hash(str)', function () { describe('Change.hash(str)', function() {
// todo(ritch) test other hashing algorithms // todo(ritch) test other hashing algorithms
it('should hash the given string', function () { it('should hash the given string', function() {
var str = 'foo'; var str = 'foo';
var hash = Change.hash(str); var hash = Change.hash(str);
assert(hash !== str); assert(hash !== str);
@ -160,8 +160,8 @@ describe('Change', function(){
}); });
}); });
describe('Change.revisionForInst(inst)', function () { describe('Change.revisionForInst(inst)', function() {
it('should return the same revision for the same data', function () { it('should return the same revision for the same data', function() {
var a = { var a = {
b: { b: {
b: ['c', 'd'], b: ['c', 'd'],
@ -181,34 +181,34 @@ describe('Change', function(){
}); });
}); });
describe('change.type()', function () { describe('change.type()', function() {
it('CREATE', function () { it('CREATE', function() {
var change = new Change({ var change = new Change({
rev: this.revisionForModel rev: this.revisionForModel
}); });
assert.equal(Change.CREATE, change.type()); assert.equal(Change.CREATE, change.type());
}); });
it('UPDATE', function () { it('UPDATE', function() {
var change = new Change({ var change = new Change({
rev: this.revisionForModel, rev: this.revisionForModel,
prev: this.revisionForModel prev: this.revisionForModel
}); });
assert.equal(Change.UPDATE, change.type()); assert.equal(Change.UPDATE, change.type());
}); });
it('DELETE', function () { it('DELETE', function() {
var change = new Change({ var change = new Change({
prev: this.revisionForModel prev: this.revisionForModel
}); });
assert.equal(Change.DELETE, change.type()); assert.equal(Change.DELETE, change.type());
}); });
it('UNKNOWN', function () { it('UNKNOWN', function() {
var change = new Change(); var change = new Change();
assert.equal(Change.UNKNOWN, change.type()); assert.equal(Change.UNKNOWN, change.type());
}); });
}); });
describe('change.getModelCtor()', function () { describe('change.getModelCtor()', function() {
it('should get the correct model class', function () { it('should get the correct model class', function() {
var change = new Change({ var change = new Change({
modelName: this.modelName modelName: this.modelName
}); });
@ -217,8 +217,8 @@ describe('Change', function(){
}); });
}); });
describe('change.equals(otherChange)', function () { describe('change.equals(otherChange)', function() {
it('should return true when the change is equal', function () { it('should return true when the change is equal', function() {
var change = new Change({ var change = new Change({
rev: this.revisionForModel rev: this.revisionForModel
}); });
@ -230,7 +230,7 @@ describe('Change', function(){
assert.equal(change.equals(otherChange), true); assert.equal(change.equals(otherChange), true);
}); });
it('should return true when both changes are deletes', function () { it('should return true when both changes are deletes', function() {
var REV = 'foo'; var REV = 'foo';
var change = new Change({ var change = new Change({
rev: null, rev: null,
@ -249,8 +249,8 @@ describe('Change', function(){
}); });
}); });
describe('change.isBasedOn(otherChange)', function () { describe('change.isBasedOn(otherChange)', function() {
it('should return true when the change is based on the other', function () { it('should return true when the change is based on the other', function() {
var change = new Change({ var change = new Change({
prev: this.revisionForModel prev: this.revisionForModel
}); });
@ -263,7 +263,7 @@ describe('Change', function(){
}); });
}); });
describe('Change.diff(modelName, since, remoteChanges, callback)', function () { describe('Change.diff(modelName, since, remoteChanges, callback)', function() {
beforeEach(function(done) { beforeEach(function(done) {
Change.create([ Change.create([
{rev: 'foo', modelName: this.modelName, modelId: 9, checkpoint: 1}, {rev: 'foo', modelName: this.modelName, modelId: 9, checkpoint: 1},
@ -272,7 +272,7 @@ describe('Change', function(){
], done); ], done);
}); });
it('should return delta and conflict lists', function (done) { it('should return delta and conflict lists', function(done) {
var remoteChanges = [ var remoteChanges = [
// an update => should result in a delta // an update => should result in a delta
{rev: 'foo2', prev: 'foo', modelName: this.modelName, modelId: 9, checkpoint: 1}, {rev: 'foo2', prev: 'foo', modelName: this.modelName, modelId: 9, checkpoint: 1},

View File

@ -1,7 +1,7 @@
describe('DataSource', function() { describe('DataSource', function() {
var memory; var memory;
beforeEach(function(){ beforeEach(function() {
memory = loopback.createDataSource({ memory = loopback.createDataSource({
connector: loopback.Memory connector: loopback.Memory
}); });

View File

@ -14,22 +14,22 @@ describe('RemoteConnector', function() {
TestModel.attachTo(ds); TestModel.attachTo(ds);
}); });
it('should be able to call create', function (done) { it('should be able to call create', function(done) {
TestModel.create({ TestModel.create({
foo: 'bar' foo: 'bar'
}, function(err, inst) { }, function(err, inst) {
if(err) return done(err); if (err) return done(err);
assert(inst.id); assert(inst.id);
done(); done();
}); });
}); });
it('should be able to call save', function (done) { it('should be able to call save', function(done) {
var m = new TestModel({ var m = new TestModel({
foo: 'bar' foo: 'bar'
}); });
m.save(function(err, data) { m.save(function(err, data) {
if(err) return done(err); if (err) return done(err);
assert(data.foo === 'bar'); assert(data.foo === 'bar');
done(); done();
}); });

View File

@ -19,14 +19,14 @@ describe('Replication', function() {
LocalTestModel.attachTo(memory); LocalTestModel.attachTo(memory);
}); });
it('should replicate local data to the remote', function (done) { it('should replicate local data to the remote', function(done) {
var RANDOM = Math.random(); var RANDOM = Math.random();
LocalTestModel.create({ LocalTestModel.create({
n: RANDOM n: RANDOM
}, function(err, created) { }, function(err, created) {
LocalTestModel.replicate(0, TestModel, function() { LocalTestModel.replicate(0, TestModel, function() {
if(err) return done(err); if (err) return done(err);
TestModel.findOne({n: RANDOM}, function(err, found) { TestModel.findOne({n: RANDOM}, function(err, found) {
assert.equal(created.id, found.id); assert.equal(created.id, found.id);
done(); done();

View File

@ -3,30 +3,29 @@ var MyEmail;
var assert = require('assert'); var assert = require('assert');
var MailConnector = require('../lib/connectors/mail'); var MailConnector = require('../lib/connectors/mail');
describe('Email connector', function () { describe('Email connector', function() {
it('should set up SMTP', function () { it('should set up SMTP', function() {
var connector = new MailConnector({transports: [ var connector = new MailConnector({transports: [
{type: 'smtp', service: 'gmail'} {type: 'smtp', service: 'gmail'}
]}); ]});
assert(connector.transportForName('smtp')); assert(connector.transportForName('smtp'));
}); });
it('should set up DIRECT', function () { it('should set up DIRECT', function() {
var connector = new MailConnector({transports: [ var connector = new MailConnector({transports: [
{type: 'direct', name: 'localhost'} {type: 'direct', name: 'localhost'}
]}); ]});
assert(connector.transportForName('direct')); assert(connector.transportForName('direct'));
}); });
it('should set up STUB', function () { it('should set up STUB', function() {
var connector = new MailConnector({transports: [ var connector = new MailConnector({transports: [
{type: 'stub', service: 'gmail'} {type: 'stub', service: 'gmail'}
]}); ]});
assert(connector.transportForName('stub')); assert(connector.transportForName('stub'));
}); });
it('should set up a single transport for SMTP' , function() {
it('should set up a single transport for SMTP' , function () {
var connector = new MailConnector({transport: var connector = new MailConnector({transport:
{type: 'smtp', service: 'gmail'} {type: 'smtp', service: 'gmail'}
}); });
@ -34,22 +33,21 @@ describe('Email connector', function () {
assert(connector.transportForName('smtp')); assert(connector.transportForName('smtp'));
}); });
}); });
describe('Email and SMTP', function () { describe('Email and SMTP', function() {
beforeEach(function() { beforeEach(function() {
MyEmail = loopback.Email.extend('my-email'); MyEmail = loopback.Email.extend('my-email');
loopback.autoAttach(); loopback.autoAttach();
}); });
it('should have a send method', function () { it('should have a send method', function() {
assert(typeof MyEmail.send === 'function'); assert(typeof MyEmail.send === 'function');
assert(typeof MyEmail.prototype.send === 'function'); assert(typeof MyEmail.prototype.send === 'function');
}); });
describe('MyEmail', function () { describe('MyEmail', function() {
it('MyEmail.send(options, callback)', function (done) { it('MyEmail.send(options, callback)', function(done) {
var options = { var options = {
to: 'to@to.com', to: 'to@to.com',
from: 'from@from.com', from: 'from@from.com',
@ -67,7 +65,7 @@ describe('Email and SMTP', function () {
}); });
}); });
it('myEmail.send(callback)', function (done) { it('myEmail.send(callback)', function(done) {
var message = new MyEmail({ var message = new MyEmail({
to: 'to@to.com', to: 'to@to.com',
from: 'from@from.com', from: 'from@from.com',
@ -76,7 +74,7 @@ describe('Email and SMTP', function () {
html: '<h1>html</h1>' html: '<h1>html</h1>'
}); });
message.send(function (err, mail) { message.send(function(err, mail) {
assert(mail.response); assert(mail.response);
assert(mail.envelope); assert(mail.envelope);
assert(mail.messageId); assert(mail.messageId);
@ -85,5 +83,3 @@ describe('Email and SMTP', function () {
}); });
}); });
}); });

View File

@ -19,7 +19,7 @@ describe('GeoPoint', function() {
}); });
}); });
describe('GeoPoint()', function(){ describe('GeoPoint()', function() {
it('Create from string', function() { it('Create from string', function() {
var point = new GeoPoint('1.234,5.678'); var point = new GeoPoint('1.234,5.678');
assert.equal(point.lng, 1.234); assert.equal(point.lng, 1.234);

View File

@ -1,7 +1,7 @@
var loopback = require('../'); var loopback = require('../');
describe('hidden properties', function () { describe('hidden properties', function() {
beforeEach(function (done) { beforeEach(function(done) {
var app = this.app = loopback(); var app = this.app = loopback();
var Product = this.Product = loopback.PersistedModel.extend('product', var Product = this.Product = loopback.PersistedModel.extend('product',
{}, {},
@ -34,27 +34,27 @@ describe('hidden properties', function () {
}); });
}); });
it('should hide a property remotely', function (done) { it('should hide a property remotely', function(done) {
request(this.app) request(this.app)
.get('/products') .get('/products')
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200) .expect(200)
.end(function(err, res){ .end(function(err, res) {
if(err) return done(err); if (err) return done(err);
var product = res.body[0]; var product = res.body[0];
assert.equal(product.secret, undefined); assert.equal(product.secret, undefined);
done(); done();
}); });
}); });
it('should hide a property of nested models', function (done) { it('should hide a property of nested models', function(done) {
var app = this.app; var app = this.app;
request(app) request(app)
.get('/categories?filter[include]=products') .get('/categories?filter[include]=products')
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200) .expect(200)
.end(function(err, res){ .end(function(err, res) {
if(err) return done(err); if (err) return done(err);
var category = res.body[0]; var category = res.body[0];
var product = category.products[0]; var product = category.products[0];
assert.equal(product.secret, undefined); assert.equal(product.secret, undefined);

View File

@ -36,7 +36,7 @@ describe('loopback', function() {
}); });
describe('data source created by loopback', function() { describe('data source created by loopback', function() {
it('should create model extending Model by default', function () { it('should create model extending Model by default', function() {
var dataSource = loopback.createDataSource({ var dataSource = loopback.createDataSource({
connector: loopback.Memory connector: loopback.Memory
}); });
@ -52,8 +52,8 @@ describe('loopback', function() {
}); });
}); });
describe('loopback.autoAttach', function () { describe('loopback.autoAttach', function() {
it('doesn\'t overwrite model with datasource configured', function () { it('doesn\'t overwrite model with datasource configured', function() {
var ds1 = loopback.createDataSource('db1', { var ds1 = loopback.createDataSource('db1', {
connector: loopback.Memory connector: loopback.Memory
}); });
@ -102,9 +102,9 @@ describe('loopback', function() {
}); });
}); });
describe('loopback.createModel(name, properties, options)', function () { describe('loopback.createModel(name, properties, options)', function() {
describe('options.base', function () { describe('options.base', function() {
it('should extend from options.base', function () { it('should extend from options.base', function() {
var MyModel = loopback.createModel('MyModel', {}, { var MyModel = loopback.createModel('MyModel', {}, {
foo: { foo: {
bar: 'bat' bar: 'bat'
@ -122,8 +122,8 @@ describe('loopback', function() {
}); });
}); });
describe('loopback.getModel and getModelByType', function () { describe('loopback.getModel and getModelByType', function() {
it('should be able to get model by name', function () { it('should be able to get model by name', function() {
var MyModel = loopback.createModel('MyModel', {}, { var MyModel = loopback.createModel('MyModel', {}, {
foo: { foo: {
bar: 'bat' bar: 'bat'
@ -139,7 +139,7 @@ describe('loopback', function() {
assert(loopback.getModel('MyCustomModel') === MyCustomModel); assert(loopback.getModel('MyCustomModel') === MyCustomModel);
assert(loopback.findModel('Invalid') === undefined); assert(loopback.findModel('Invalid') === undefined);
}); });
it('should be able to get model by type', function () { it('should be able to get model by type', function() {
var MyModel = loopback.createModel('MyModel', {}, { var MyModel = loopback.createModel('MyModel', {}, {
foo: { foo: {
bar: 'bat' bar: 'bat'

View File

@ -1,4 +1,4 @@
describe('Memory Connector', function(){ describe('Memory Connector', function() {
it('Create a model using the memory connector', function(done) { it('Create a model using the memory connector', function(done) {
// use the built in memory function // use the built in memory function
// to create a memory data source // to create a memory data source
@ -26,7 +26,7 @@ describe('Memory Connector', function(){
], count); ], count);
function count() { function count() {
Product.count(function (err, count) { Product.count(function(err, count) {
assert.equal(count, 3); assert.equal(count, 3);
done(); done();
}); });

View File

@ -2,13 +2,13 @@ var loopback = require(('../'));
var assert = require('assert'); var assert = require('assert');
var Application = loopback.Application; var Application = loopback.Application;
describe('Application', function () { describe('Application', function() {
var registeredApp = null; var registeredApp = null;
it('Create a new application', function (done) { it('Create a new application', function(done) {
Application.create({owner: 'rfeng', Application.create({owner: 'rfeng',
name: 'MyApp1', name: 'MyApp1',
description: 'My first mobile application'}, function (err, result) { description: 'My first mobile application'}, function(err, result) {
var app = result; var app = result;
assert.equal(app.owner, 'rfeng'); assert.equal(app.owner, 'rfeng');
assert.equal(app.name, 'MyApp1'); assert.equal(app.name, 'MyApp1');
@ -25,7 +25,7 @@ describe('Application', function () {
}); });
}); });
it('Create a new application with push settings', function (done) { it('Create a new application with push settings', function(done) {
Application.create({owner: 'rfeng', Application.create({owner: 'rfeng',
name: 'MyAppWithPush', name: 'MyAppWithPush',
description: 'My push mobile application', description: 'My push mobile application',
@ -49,7 +49,7 @@ describe('Application', function () {
serverApiKey: 'serverKey' serverApiKey: 'serverKey'
} }
}}, }},
function (err, result) { function(err, result) {
var app = result; var app = result;
assert.deepEqual(app.pushSettings.toObject(), { assert.deepEqual(app.pushSettings.toObject(), {
apns: { apns: {
@ -75,9 +75,9 @@ describe('Application', function () {
}); });
}); });
beforeEach(function (done) { beforeEach(function(done) {
Application.register('rfeng', 'MyApp2', Application.register('rfeng', 'MyApp2',
{description: 'My second mobile application'}, function (err, result) { {description: 'My second mobile application'}, function(err, result) {
var app = result; var app = result;
assert.equal(app.owner, 'rfeng'); assert.equal(app.owner, 'rfeng');
assert.equal(app.name, 'MyApp2'); assert.equal(app.name, 'MyApp2');
@ -94,8 +94,8 @@ describe('Application', function () {
}); });
}); });
it('Reset keys', function (done) { it('Reset keys', function(done) {
Application.resetKeys(registeredApp.id, function (err, result) { Application.resetKeys(registeredApp.id, function(err, result) {
var app = result; var app = result;
assert.equal(app.owner, 'rfeng'); assert.equal(app.owner, 'rfeng');
assert.equal(app.name, 'MyApp2'); assert.equal(app.name, 'MyApp2');
@ -119,67 +119,67 @@ describe('Application', function () {
}); });
}); });
it('Authenticate with application id & clientKey', function (done) { it('Authenticate with application id & clientKey', function(done) {
Application.authenticate(registeredApp.id, registeredApp.clientKey, Application.authenticate(registeredApp.id, registeredApp.clientKey,
function (err, result) { function(err, result) {
assert.equal(result.application.id, registeredApp.id); assert.equal(result.application.id, registeredApp.id);
assert.equal(result.keyType, 'clientKey'); assert.equal(result.keyType, 'clientKey');
done(err, result); done(err, result);
}); });
}); });
it('Authenticate with application id & javaScriptKey', function (done) { it('Authenticate with application id & javaScriptKey', function(done) {
Application.authenticate(registeredApp.id, registeredApp.javaScriptKey, Application.authenticate(registeredApp.id, registeredApp.javaScriptKey,
function (err, result) { function(err, result) {
assert.equal(result.application.id, registeredApp.id); assert.equal(result.application.id, registeredApp.id);
assert.equal(result.keyType, 'javaScriptKey'); assert.equal(result.keyType, 'javaScriptKey');
done(err, result); done(err, result);
}); });
}); });
it('Authenticate with application id & restApiKey', function (done) { it('Authenticate with application id & restApiKey', function(done) {
Application.authenticate(registeredApp.id, registeredApp.restApiKey, Application.authenticate(registeredApp.id, registeredApp.restApiKey,
function (err, result) { function(err, result) {
assert.equal(result.application.id, registeredApp.id); assert.equal(result.application.id, registeredApp.id);
assert.equal(result.keyType, 'restApiKey'); assert.equal(result.keyType, 'restApiKey');
done(err, result); done(err, result);
}); });
}); });
it('Authenticate with application id & masterKey', function (done) { it('Authenticate with application id & masterKey', function(done) {
Application.authenticate(registeredApp.id, registeredApp.masterKey, Application.authenticate(registeredApp.id, registeredApp.masterKey,
function (err, result) { function(err, result) {
assert.equal(result.application.id, registeredApp.id); assert.equal(result.application.id, registeredApp.id);
assert.equal(result.keyType, 'masterKey'); assert.equal(result.keyType, 'masterKey');
done(err, result); done(err, result);
}); });
}); });
it('Authenticate with application id & windowsKey', function (done) { it('Authenticate with application id & windowsKey', function(done) {
Application.authenticate(registeredApp.id, registeredApp.windowsKey, Application.authenticate(registeredApp.id, registeredApp.windowsKey,
function (err, result) { function(err, result) {
assert.equal(result.application.id, registeredApp.id); assert.equal(result.application.id, registeredApp.id);
assert.equal(result.keyType, 'windowsKey'); assert.equal(result.keyType, 'windowsKey');
done(err, result); done(err, result);
}); });
}); });
it('Fail to authenticate with application id & invalid key', function (done) { it('Fail to authenticate with application id & invalid key', function(done) {
Application.authenticate(registeredApp.id, 'invalid-key', Application.authenticate(registeredApp.id, 'invalid-key',
function (err, result) { function(err, result) {
assert(!result); assert(!result);
done(err, result); done(err, result);
}); });
}); });
}); });
describe('Application subclass', function () { describe('Application subclass', function() {
it('should use subclass model name', function (done) { it('should use subclass model name', function(done) {
var MyApp = Application.extend('MyApp'); var MyApp = Application.extend('MyApp');
var ds = loopback.createDataSource({connector: loopback.Memory}); var ds = loopback.createDataSource({connector: loopback.Memory});
MyApp.attachTo(ds); MyApp.attachTo(ds);
MyApp.register('rfeng', 'MyApp123', MyApp.register('rfeng', 'MyApp123',
{description: 'My 123 mobile application'}, function (err, result) { {description: 'My 123 mobile application'}, function(err, result) {
var app = result; var app = result;
assert.equal(app.owner, 'rfeng'); assert.equal(app.owner, 'rfeng');
assert.equal(app.name, 'MyApp123'); assert.equal(app.name, 'MyApp123');
@ -192,12 +192,12 @@ describe('Application subclass', function () {
assert(app.created); assert(app.created);
assert(app.modified); assert(app.modified);
// Remove all instances from Application model to avoid left-over data // Remove all instances from Application model to avoid left-over data
Application.destroyAll(function () { Application.destroyAll(function() {
MyApp.findById(app.id, function (err, myApp) { MyApp.findById(app.id, function(err, myApp) {
assert(!err); assert(!err);
assert(myApp); assert(myApp);
Application.findById(app.id, function (err, myApp) { Application.findById(app.id, function(err, myApp) {
assert(!err); assert(!err);
assert(myApp === null); assert(myApp === null);
done(err, myApp); done(err, myApp);
@ -207,4 +207,3 @@ describe('Application subclass', function () {
}); });
}); });
}); });

View File

@ -37,8 +37,8 @@ describe('Model / PersistedModel', function() {
var joe = new User({email: 'joe@joe.com'}); var joe = new User({email: 'joe@joe.com'});
var joe2 = new User({email: 'joe@joe.com'}); var joe2 = new User({email: 'joe@joe.com'});
joe.save(function () { joe.save(function() {
joe2.save(function (err) { joe2.save(function(err) {
assert(err, 'should get a validation error'); assert(err, 'should get a validation error');
assert(joe2.errors.email, 'model should have email error'); assert(joe2.errors.email, 'model should have email error');
@ -64,13 +64,13 @@ describe('Model / PersistedModel', function() {
}); });
}); });
describe.onServer('Remote Methods', function(){ describe.onServer('Remote Methods', function() {
var User; var User;
var dataSource; var dataSource;
var app; var app;
beforeEach(function () { beforeEach(function() {
User = PersistedModel.extend('user', { User = PersistedModel.extend('user', {
'first': String, 'first': String,
'last': String, 'last': String,
@ -89,8 +89,8 @@ describe.onServer('Remote Methods', function(){
User.attachTo(dataSource); User.attachTo(dataSource);
User.login = function (username, password, fn) { User.login = function(username, password, fn) {
if(username === 'foo' && password === 'bar') { if (username === 'foo' && password === 'bar') {
fn(null, 123); fn(null, 123);
} else { } else {
throw new Error('bad username and password!'); throw new Error('bad username and password!');
@ -122,10 +122,10 @@ describe.onServer('Remote Methods', function(){
.task(User, 'create', {first: 'jan'}) .task(User, 'create', {first: 'jan'})
.task(User, 'create', {first: 'sam'}) .task(User, 'create', {first: 'sam'})
.task(User, 'create', {first: 'suzy'}) .task(User, 'create', {first: 'suzy'})
.on('done', function () { .on('done', function() {
User.count(function (err, count) { User.count(function(err, count) {
User.destroyAll(function () { User.destroyAll(function() {
User.count(function (err, count) { User.count(function(err, count) {
assert.equal(count, 0); assert.equal(count, 0);
done(); done();
}); });
@ -135,14 +135,14 @@ describe.onServer('Remote Methods', function(){
}); });
}); });
describe('Example Remote Method', function () { describe('Example Remote Method', function() {
it('Call the method using HTTP / REST', function(done) { it('Call the method using HTTP / REST', function(done) {
request(app) request(app)
.get('/users/sign-in?username=foo&password=bar') .get('/users/sign-in?username=foo&password=bar')
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200) .expect(200)
.end(function(err, res){ .end(function(err, res) {
if(err) return done(err); if (err) return done(err);
assert.equal(res.body, 123); assert.equal(res.body, 123);
done(); done();
}); });
@ -156,7 +156,7 @@ describe.onServer('Remote Methods', function(){
}); });
}); });
describe('Model.beforeRemote(name, fn)', function(){ describe('Model.beforeRemote(name, fn)', function() {
it('Run a function before a remote method is called by a client', function(done) { it('Run a function before a remote method is called by a client', function(done) {
var hookCalled = false; var hookCalled = false;
@ -172,14 +172,14 @@ describe.onServer('Remote Methods', function(){
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200) .expect(200)
.end(function(err, res) { .end(function(err, res) {
if(err) return done(err); if (err) return done(err);
assert(hookCalled, 'hook wasnt called'); assert(hookCalled, 'hook wasnt called');
done(); done();
}); });
}); });
}); });
describe('Model.afterRemote(name, fn)', function(){ describe('Model.afterRemote(name, fn)', function() {
it('Run a function after a remote method is called by a client', function(done) { it('Run a function after a remote method is called by a client', function(done) {
var beforeCalled = false; var beforeCalled = false;
var afterCalled = false; var afterCalled = false;
@ -202,7 +202,7 @@ describe.onServer('Remote Methods', function(){
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200) .expect(200)
.end(function(err, res) { .end(function(err, res) {
if(err) return done(err); if (err) return done(err);
assert(beforeCalled, 'before hook was not called'); assert(beforeCalled, 'before hook was not called');
assert(afterCalled, 'after hook was not called'); assert(afterCalled, 'after hook was not called');
done(); done();
@ -210,7 +210,7 @@ describe.onServer('Remote Methods', function(){
}); });
}); });
describe('Remote Method invoking context', function () { describe('Remote Method invoking context', function() {
describe('ctx.req', function() { describe('ctx.req', function() {
it('The express ServerRequest object', function(done) { it('The express ServerRequest object', function(done) {
var hookCalled = false; var hookCalled = false;
@ -233,7 +233,7 @@ describe.onServer('Remote Methods', function(){
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200) .expect(200)
.end(function(err, res) { .end(function(err, res) {
if(err) return done(err); if (err) return done(err);
assert(hookCalled); assert(hookCalled);
done(); done();
}); });
@ -262,7 +262,7 @@ describe.onServer('Remote Methods', function(){
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200) .expect(200)
.end(function(err, res) { .end(function(err, res) {
if(err) return done(err); if (err) return done(err);
assert(hookCalled); assert(hookCalled);
done(); done();
}); });
@ -281,9 +281,9 @@ describe.onServer('Remote Methods', function(){
Book.create({title: 'Into the Wild', author: 'Jon Krakauer'}, function(err, book) { Book.create({title: 'Into the Wild', author: 'Jon Krakauer'}, function(err, book) {
// using 'chapters' scope for build: // using 'chapters' scope for build:
var c = book.chapters.build({title: 'Chapter 1'}); var c = book.chapters.build({title: 'Chapter 1'});
book.chapters.create({title: 'Chapter 2'}, function () { book.chapters.create({title: 'Chapter 2'}, function() {
c.save(function () { c.save(function() {
Chapter.count({bookId: book.id}, function (err, count) { Chapter.count({bookId: book.id}, function(err, count) {
assert.equal(count, 2); assert.equal(count, 2);
book.chapters({where: {title: 'Chapter 1'}}, function(err, chapters) { book.chapters({where: {title: 'Chapter 1'}}, function(err, chapters) {
assert.equal(chapters.length, 1); assert.equal(chapters.length, 1);
@ -297,7 +297,7 @@ describe.onServer('Remote Methods', function(){
}); });
}); });
describe('Model.properties', function(){ describe('Model.properties', function() {
it('Normalized properties passed in originally by loopback.createModel()', function() { it('Normalized properties passed in originally by loopback.createModel()', function() {
var props = { var props = {
s: String, s: String,
@ -309,19 +309,18 @@ describe.onServer('Remote Methods', function(){
var MyModel = loopback.createModel('foo', props); var MyModel = loopback.createModel('foo', props);
Object.keys(MyModel.definition.properties).forEach(function (key) { Object.keys(MyModel.definition.properties).forEach(function(key) {
var p = MyModel.definition.properties[key]; var p = MyModel.definition.properties[key];
var o = MyModel.definition.properties[key]; var o = MyModel.definition.properties[key];
assert(p); assert(p);
assert(o); assert(o);
assert(typeof p.type === 'function'); assert(typeof p.type === 'function');
if(typeof o === 'function') { if (typeof o === 'function') {
// the normalized property // the normalized property
// should match the given property // should match the given property
assert( assert(
p.type.name === o.name p.type.name === o.name ||
||
p.type.name === o p.type.name === o
); );
} }
@ -329,17 +328,17 @@ describe.onServer('Remote Methods', function(){
}); });
}); });
describe('Model.extend()', function(){ describe('Model.extend()', function() {
it('Create a new model by extending an existing model', function() { it('Create a new model by extending an existing model', function() {
var User = loopback.PersistedModel.extend('test-user', { var User = loopback.PersistedModel.extend('test-user', {
email: String email: String
}); });
User.foo = function () { User.foo = function() {
return 'bar'; return 'bar';
}; };
User.prototype.bar = function () { User.prototype.bar = function() {
return 'foo'; return 'foo';
}; };
@ -379,7 +378,6 @@ describe.onServer('Remote Methods', function(){
user1Triggered = true; user1Triggered = true;
}); });
var user2Triggered = false; var user2Triggered = false;
User2.once('x', function(event) { User2.once('x', function(event) {
user2Triggered = true; user2Triggered = true;
@ -396,7 +394,7 @@ describe.onServer('Remote Methods', function(){
}); });
describe('Model.checkAccessTypeForMethod(remoteMethod)', function () { describe('Model.checkAccessTypeForMethod(remoteMethod)', function() {
shouldReturn('create', ACL.WRITE); shouldReturn('create', ACL.WRITE);
shouldReturn('updateOrCreate', ACL.WRITE); shouldReturn('updateOrCreate', ACL.WRITE);
shouldReturn('upsert', ACL.WRITE); shouldReturn('upsert', ACL.WRITE);
@ -411,7 +409,7 @@ describe.onServer('Remote Methods', function(){
shouldReturn('unkown-model-method', ACL.EXECUTE); shouldReturn('unkown-model-method', ACL.EXECUTE);
function shouldReturn(methodName, expectedAccessType) { function shouldReturn(methodName, expectedAccessType) {
describe(methodName, function () { describe(methodName, function() {
it('should return ' + expectedAccessType, function() { it('should return ' + expectedAccessType, function() {
var remoteMethod = {name: methodName}; var remoteMethod = {name: methodName};
assert.equal( assert.equal(
@ -424,7 +422,7 @@ describe.onServer('Remote Methods', function(){
}); });
describe('Model.getChangeModel()', function() { describe('Model.getChangeModel()', function() {
it('Get the Change Model', function () { it('Get the Change Model', function() {
var UserChange = User.getChangeModel(); var UserChange = User.getChangeModel();
var change = new UserChange(); var change = new UserChange();
assert(change instanceof Change); assert(change instanceof Change);
@ -432,7 +430,7 @@ describe.onServer('Remote Methods', function(){
}); });
describe('Model.getSourceId(callback)', function() { describe('Model.getSourceId(callback)', function() {
it('Get the Source Id', function (done) { it('Get the Source Id', function(done) {
User.getSourceId(function(err, id) { User.getSourceId(function(err, id) {
assert.equal('memory-user', id); assert.equal('memory-user', id);
done(); done();
@ -441,7 +439,7 @@ describe.onServer('Remote Methods', function(){
}); });
describe('Model.checkpoint(callback)', function() { describe('Model.checkpoint(callback)', function() {
it('Create a checkpoint', function (done) { it('Create a checkpoint', function(done) {
var Checkpoint = User.getChangeModel().getCheckpointModel(); var Checkpoint = User.getChangeModel().getCheckpointModel();
var tasks = [ var tasks = [
getCurrentCheckpoint, getCurrentCheckpoint,
@ -451,7 +449,7 @@ describe.onServer('Remote Methods', function(){
var current; var current;
async.series(tasks, function(err) { async.series(tasks, function(err) {
if(err) return done(err); if (err) return done(err);
assert.equal(result, current + 1); assert.equal(result, current + 1);
done(); done();

View File

@ -10,7 +10,7 @@ var expect = require('chai').expect;
var debug = require('debug')('loopback:test:relations.integration'); var debug = require('debug')('loopback:test:relations.integration');
var async = require('async'); var async = require('async');
describe('relations - integration', function () { describe('relations - integration', function() {
lt.beforeEach.withApp(app); lt.beforeEach.withApp(app);
@ -37,7 +37,7 @@ describe('relations - integration', function () {
}); });
}); });
describe('/store/:id/widgets', function () { describe('/store/:id/widgets', function() {
beforeEach(function() { beforeEach(function() {
this.url = '/api/stores/' + this.store.id + '/widgets'; this.url = '/api/stores/' + this.store.id + '/widgets';
}); });
@ -81,7 +81,7 @@ describe('relations - integration', function () {
this.http = this.post(this.url, this.newWidget); this.http = this.post(this.url, this.newWidget);
this.http.send(this.newWidget); this.http.send(this.newWidget);
this.http.end(function(err) { this.http.end(function(err) {
if(err) return done(err); if (err) return done(err);
this.req = this.http.req; this.req = this.http.req;
this.res = this.http.res; this.res = this.http.res;
done(); done();
@ -104,11 +104,11 @@ describe('relations - integration', function () {
assert.equal(this.widget.name, this.newWidgetName); assert.equal(this.widget.name, this.newWidgetName);
}); });
}); });
it('should have a single widget with storeId', function (done) { it('should have a single widget with storeId', function(done) {
this.app.models.widget.count({ this.app.models.widget.count({
storeId: this.store.id storeId: this.store.id
}, function(err, count) { }, function(err, count) {
if(err) return done(err); if (err) return done(err);
assert.equal(count, 2); assert.equal(count, 2);
done(); done();
}); });
@ -116,8 +116,8 @@ describe('relations - integration', function () {
}); });
}); });
describe('/stores/:id/widgets/:fk - 200', function () { describe('/stores/:id/widgets/:fk - 200', function() {
beforeEach(function (done) { beforeEach(function(done) {
var self = this; var self = this;
this.store.widgets.create({ this.store.widgets.create({
name: this.widgetName name: this.widgetName
@ -127,27 +127,27 @@ describe('relations - integration', function () {
done(); done();
}); });
}); });
lt.describe.whenCalledRemotely('GET', '/stores/:id/widgets/:fk', function () { lt.describe.whenCalledRemotely('GET', '/stores/:id/widgets/:fk', function() {
it('should succeed with statusCode 200', function () { it('should succeed with statusCode 200', function() {
assert.equal(this.res.statusCode, 200); assert.equal(this.res.statusCode, 200);
assert.equal(this.res.body.id, this.widget.id); assert.equal(this.res.body.id, this.widget.id);
}); });
}); });
}); });
describe('/stores/:id/widgets/:fk - 404', function () { describe('/stores/:id/widgets/:fk - 404', function() {
beforeEach(function () { beforeEach(function() {
this.url = '/api/stores/' + this.store.id + '/widgets/123456'; this.url = '/api/stores/' + this.store.id + '/widgets/123456';
}); });
lt.describe.whenCalledRemotely('GET', '/stores/:id/widgets/:fk', function () { lt.describe.whenCalledRemotely('GET', '/stores/:id/widgets/:fk', function() {
it('should fail with statusCode 404', function () { it('should fail with statusCode 404', function() {
assert.equal(this.res.statusCode, 404); assert.equal(this.res.statusCode, 404);
assert.equal(this.res.body.error.status, 404); assert.equal(this.res.body.error.status, 404);
}); });
}); });
}); });
describe('/store/:id/widgets/count', function () { describe('/store/:id/widgets/count', function() {
beforeEach(function() { beforeEach(function() {
this.url = '/api/stores/' + this.store.id + '/widgets/count'; this.url = '/api/stores/' + this.store.id + '/widgets/count';
}); });
@ -161,7 +161,7 @@ describe('relations - integration', function () {
}); });
}); });
describe('/store/:id/widgets/count - filtered (matches)', function () { describe('/store/:id/widgets/count - filtered (matches)', function() {
beforeEach(function() { beforeEach(function() {
this.url = '/api/stores/' + this.store.id + '/widgets/count?where[name]=foo'; this.url = '/api/stores/' + this.store.id + '/widgets/count?where[name]=foo';
}); });
@ -175,7 +175,7 @@ describe('relations - integration', function () {
}); });
}); });
describe('/store/:id/widgets/count - filtered (no matches)', function () { describe('/store/:id/widgets/count - filtered (no matches)', function() {
beforeEach(function() { beforeEach(function() {
this.url = '/api/stores/' + this.store.id + '/widgets/count?where[name]=bar'; this.url = '/api/stores/' + this.store.id + '/widgets/count?where[name]=bar';
}); });
@ -189,8 +189,8 @@ describe('relations - integration', function () {
}); });
}); });
describe('/widgets/:id/store', function () { describe('/widgets/:id/store', function() {
beforeEach(function (done) { beforeEach(function(done) {
var self = this; var self = this;
this.store.widgets.create({ this.store.widgets.create({
name: this.widgetName name: this.widgetName
@ -200,8 +200,8 @@ describe('relations - integration', function () {
done(); done();
}); });
}); });
lt.describe.whenCalledRemotely('GET', '/api/widgets/:id/store', function () { lt.describe.whenCalledRemotely('GET', '/api/widgets/:id/store', function() {
it('should succeed with statusCode 200', function () { it('should succeed with statusCode 200', function() {
assert.equal(this.res.statusCode, 200); assert.equal(this.res.statusCode, 200);
assert.equal(this.res.body.id, this.store.id); assert.equal(this.res.body.id, this.store.id);
}); });
@ -215,10 +215,10 @@ describe('relations - integration', function () {
async.series([ async.series([
// Clean up models // Clean up models
function (done) { function(done) {
app.models.physician.destroyAll(function (err) { app.models.physician.destroyAll(function(err) {
app.models.patient.destroyAll(function (err) { app.models.patient.destroyAll(function(err) {
app.models.appointment.destroyAll(function (err) { app.models.appointment.destroyAll(function(err) {
done(); done();
}); });
}); });
@ -226,44 +226,44 @@ describe('relations - integration', function () {
}, },
// Create a physician // Create a physician
function (done) { function(done) {
app.models.physician.create({ app.models.physician.create({
name: 'ph1' name: 'ph1'
}, function (err, physician) { }, function(err, physician) {
root.physician = physician; root.physician = physician;
done(); done();
}); });
}, },
// Create a patient // Create a patient
connecting ? function (done) { connecting ? function(done) {
root.physician.patients.create({ root.physician.patients.create({
name: 'pa1' name: 'pa1'
}, function (err, patient) { }, function(err, patient) {
root.patient = patient; root.patient = patient;
root.relUrl = '/api/physicians/' + root.physician.id root.relUrl = '/api/physicians/' + root.physician.id
+ '/patients/rel/' + root.patient.id; + '/patients/rel/' + root.patient.id;
done(); done();
}); });
} : function (done) { } : function(done) {
app.models.patient.create({ app.models.patient.create({
name: 'pa1' name: 'pa1'
}, function (err, patient) { }, function(err, patient) {
root.patient = patient; root.patient = patient;
root.relUrl = '/api/physicians/' + root.physician.id root.relUrl = '/api/physicians/' + root.physician.id
+ '/patients/rel/' + root.patient.id; + '/patients/rel/' + root.patient.id;
done(); done();
}); });
}], function (err, done) { }], function(err, done) {
cb(err, root); cb(err, root);
}); });
} }
describe('PUT /physicians/:id/patients/rel/:fk', function () { describe('PUT /physicians/:id/patients/rel/:fk', function() {
before(function (done) { before(function(done) {
var self = this; var self = this;
setup(false, function (err, root) { setup(false, function(err, root) {
self.url = root.relUrl; self.url = root.relUrl;
self.patient = root.patient; self.patient = root.patient;
self.physician = root.physician; self.physician = root.physician;
@ -271,25 +271,25 @@ describe('relations - integration', function () {
}); });
}); });
lt.describe.whenCalledRemotely('PUT', '/api/physicians/:id/patients/rel/:fk', function () { lt.describe.whenCalledRemotely('PUT', '/api/physicians/:id/patients/rel/:fk', function() {
it('should succeed with statusCode 200', function () { it('should succeed with statusCode 200', function() {
assert.equal(this.res.statusCode, 200); assert.equal(this.res.statusCode, 200);
assert.equal(this.res.body.patientId, this.patient.id); assert.equal(this.res.body.patientId, this.patient.id);
assert.equal(this.res.body.physicianId, this.physician.id); assert.equal(this.res.body.physicianId, this.physician.id);
}); });
it('should create a record in appointment', function (done) { it('should create a record in appointment', function(done) {
var self = this; var self = this;
app.models.appointment.find(function (err, apps) { app.models.appointment.find(function(err, apps) {
assert.equal(apps.length, 1); assert.equal(apps.length, 1);
assert.equal(apps[0].patientId, self.patient.id); assert.equal(apps[0].patientId, self.patient.id);
done(); done();
}); });
}); });
it('should connect physician to patient', function (done) { it('should connect physician to patient', function(done) {
var self = this; var self = this;
self.physician.patients(function (err, patients) { self.physician.patients(function(err, patients) {
assert.equal(patients.length, 1); assert.equal(patients.length, 1);
assert.equal(patients[0].id, self.patient.id); assert.equal(patients[0].id, self.patient.id);
done(); done();
@ -298,11 +298,11 @@ describe('relations - integration', function () {
}); });
}); });
describe('PUT /physicians/:id/patients/rel/:fk with data', function () { describe('PUT /physicians/:id/patients/rel/:fk with data', function() {
before(function (done) { before(function(done) {
var self = this; var self = this;
setup(false, function (err, root) { setup(false, function(err, root) {
self.url = root.relUrl; self.url = root.relUrl;
self.patient = root.patient; self.patient = root.patient;
self.physician = root.physician; self.physician = root.physician;
@ -313,17 +313,17 @@ describe('relations - integration', function () {
var NOW = Date.now(); var NOW = Date.now();
var data = { date: new Date(NOW) }; var data = { date: new Date(NOW) };
lt.describe.whenCalledRemotely('PUT', '/api/physicians/:id/patients/rel/:fk', data, function () { lt.describe.whenCalledRemotely('PUT', '/api/physicians/:id/patients/rel/:fk', data, function() {
it('should succeed with statusCode 200', function () { it('should succeed with statusCode 200', function() {
assert.equal(this.res.statusCode, 200); assert.equal(this.res.statusCode, 200);
assert.equal(this.res.body.patientId, this.patient.id); assert.equal(this.res.body.patientId, this.patient.id);
assert.equal(this.res.body.physicianId, this.physician.id); assert.equal(this.res.body.physicianId, this.physician.id);
assert.equal(new Date(this.res.body.date).getTime(), NOW); assert.equal(new Date(this.res.body.date).getTime(), NOW);
}); });
it('should create a record in appointment', function (done) { it('should create a record in appointment', function(done) {
var self = this; var self = this;
app.models.appointment.find(function (err, apps) { app.models.appointment.find(function(err, apps) {
assert.equal(apps.length, 1); assert.equal(apps.length, 1);
assert.equal(apps[0].patientId, self.patient.id); assert.equal(apps[0].patientId, self.patient.id);
assert.equal(apps[0].physicianId, self.physician.id); assert.equal(apps[0].physicianId, self.physician.id);
@ -332,9 +332,9 @@ describe('relations - integration', function () {
}); });
}); });
it('should connect physician to patient', function (done) { it('should connect physician to patient', function(done) {
var self = this; var self = this;
self.physician.patients(function (err, patients) { self.physician.patients(function(err, patients) {
assert.equal(patients.length, 1); assert.equal(patients.length, 1);
assert.equal(patients[0].id, self.patient.id); assert.equal(patients[0].id, self.patient.id);
done(); done();
@ -343,11 +343,11 @@ describe('relations - integration', function () {
}); });
}); });
describe('HEAD /physicians/:id/patients/rel/:fk', function () { describe('HEAD /physicians/:id/patients/rel/:fk', function() {
before(function (done) { before(function(done) {
var self = this; var self = this;
setup(true, function (err, root) { setup(true, function(err, root) {
self.url = root.relUrl; self.url = root.relUrl;
self.patient = root.patient; self.patient = root.patient;
self.physician = root.physician; self.physician = root.physician;
@ -355,18 +355,18 @@ describe('relations - integration', function () {
}); });
}); });
lt.describe.whenCalledRemotely('HEAD', '/api/physicians/:id/patients/rel/:fk', function () { lt.describe.whenCalledRemotely('HEAD', '/api/physicians/:id/patients/rel/:fk', function() {
it('should succeed with statusCode 200', function () { it('should succeed with statusCode 200', function() {
assert.equal(this.res.statusCode, 200); assert.equal(this.res.statusCode, 200);
}); });
}); });
}); });
describe('HEAD /physicians/:id/patients/rel/:fk that does not exist', function () { describe('HEAD /physicians/:id/patients/rel/:fk that does not exist', function() {
before(function (done) { before(function(done) {
var self = this; var self = this;
setup(true, function (err, root) { setup(true, function(err, root) {
self.url = '/api/physicians/' + root.physician.id self.url = '/api/physicians/' + root.physician.id
+ '/patients/rel/' + '999'; + '/patients/rel/' + '999';
self.patient = root.patient; self.patient = root.patient;
@ -375,18 +375,18 @@ describe('relations - integration', function () {
}); });
}); });
lt.describe.whenCalledRemotely('HEAD', '/api/physicians/:id/patients/rel/:fk', function () { lt.describe.whenCalledRemotely('HEAD', '/api/physicians/:id/patients/rel/:fk', function() {
it('should succeed with statusCode 404', function () { it('should succeed with statusCode 404', function() {
assert.equal(this.res.statusCode, 404); assert.equal(this.res.statusCode, 404);
}); });
}); });
}); });
describe('DELETE /physicians/:id/patients/rel/:fk', function () { describe('DELETE /physicians/:id/patients/rel/:fk', function() {
before(function (done) { before(function(done) {
var self = this; var self = this;
setup(true, function (err, root) { setup(true, function(err, root) {
self.url = root.relUrl; self.url = root.relUrl;
self.patient = root.patient; self.patient = root.patient;
self.physician = root.physician; self.physician = root.physician;
@ -394,41 +394,41 @@ describe('relations - integration', function () {
}); });
}); });
it('should create a record in appointment', function (done) { it('should create a record in appointment', function(done) {
var self = this; var self = this;
app.models.appointment.find(function (err, apps) { app.models.appointment.find(function(err, apps) {
assert.equal(apps.length, 1); assert.equal(apps.length, 1);
assert.equal(apps[0].patientId, self.patient.id); assert.equal(apps[0].patientId, self.patient.id);
done(); done();
}); });
}); });
it('should connect physician to patient', function (done) { it('should connect physician to patient', function(done) {
var self = this; var self = this;
self.physician.patients(function (err, patients) { self.physician.patients(function(err, patients) {
assert.equal(patients.length, 1); assert.equal(patients.length, 1);
assert.equal(patients[0].id, self.patient.id); assert.equal(patients[0].id, self.patient.id);
done(); done();
}); });
}); });
lt.describe.whenCalledRemotely('DELETE', '/api/physicians/:id/patients/rel/:fk', function () { lt.describe.whenCalledRemotely('DELETE', '/api/physicians/:id/patients/rel/:fk', function() {
it('should succeed with statusCode 204', function () { it('should succeed with statusCode 204', function() {
assert.equal(this.res.statusCode, 204); assert.equal(this.res.statusCode, 204);
}); });
it('should remove the record in appointment', function (done) { it('should remove the record in appointment', function(done) {
var self = this; var self = this;
app.models.appointment.find(function (err, apps) { app.models.appointment.find(function(err, apps) {
assert.equal(apps.length, 0); assert.equal(apps.length, 0);
done(); done();
}); });
}); });
it('should remove the connection between physician and patient', function (done) { it('should remove the connection between physician and patient', function(done) {
var self = this; var self = this;
// Need to refresh the cache // Need to refresh the cache
self.physician.patients(true, function (err, patients) { self.physician.patients(true, function(err, patients) {
assert.equal(patients.length, 0); assert.equal(patients.length, 0);
done(); done();
}); });
@ -436,11 +436,11 @@ describe('relations - integration', function () {
}); });
}); });
describe('GET /physicians/:id/patients/:fk', function () { describe('GET /physicians/:id/patients/:fk', function() {
before(function (done) { before(function(done) {
var self = this; var self = this;
setup(true, function (err, root) { setup(true, function(err, root) {
self.url = '/api/physicians/' + root.physician.id self.url = '/api/physicians/' + root.physician.id
+ '/patients/' + root.patient.id; + '/patients/' + root.patient.id;
self.patient = root.patient; self.patient = root.patient;
@ -449,19 +449,19 @@ describe('relations - integration', function () {
}); });
}); });
lt.describe.whenCalledRemotely('GET', '/api/physicians/:id/patients/:fk', function () { lt.describe.whenCalledRemotely('GET', '/api/physicians/:id/patients/:fk', function() {
it('should succeed with statusCode 200', function () { it('should succeed with statusCode 200', function() {
assert.equal(this.res.statusCode, 200); assert.equal(this.res.statusCode, 200);
assert.equal(this.res.body.id, this.physician.id); assert.equal(this.res.body.id, this.physician.id);
}); });
}); });
}); });
describe('DELETE /physicians/:id/patients/:fk', function () { describe('DELETE /physicians/:id/patients/:fk', function() {
before(function (done) { before(function(done) {
var self = this; var self = this;
setup(true, function (err, root) { setup(true, function(err, root) {
self.url = '/api/physicians/' + root.physician.id self.url = '/api/physicians/' + root.physician.id
+ '/patients/' + root.patient.id; + '/patients/' + root.patient.id;
self.patient = root.patient; self.patient = root.patient;
@ -470,31 +470,31 @@ describe('relations - integration', function () {
}); });
}); });
lt.describe.whenCalledRemotely('DELETE', '/api/physicians/:id/patients/:fk', function () { lt.describe.whenCalledRemotely('DELETE', '/api/physicians/:id/patients/:fk', function() {
it('should succeed with statusCode 204', function () { it('should succeed with statusCode 204', function() {
assert.equal(this.res.statusCode, 204); assert.equal(this.res.statusCode, 204);
}); });
it('should remove the record in appointment', function (done) { it('should remove the record in appointment', function(done) {
var self = this; var self = this;
app.models.appointment.find(function (err, apps) { app.models.appointment.find(function(err, apps) {
assert.equal(apps.length, 0); assert.equal(apps.length, 0);
done(); done();
}); });
}); });
it('should remove the connection between physician and patient', function (done) { it('should remove the connection between physician and patient', function(done) {
var self = this; var self = this;
// Need to refresh the cache // Need to refresh the cache
self.physician.patients(true, function (err, patients) { self.physician.patients(true, function(err, patients) {
assert.equal(patients.length, 0); assert.equal(patients.length, 0);
done(); done();
}); });
}); });
it('should remove the record in patient', function (done) { it('should remove the record in patient', function(done) {
var self = this; var self = this;
app.models.patient.find(function (err, patients) { app.models.patient.find(function(err, patients) {
assert.equal(patients.length, 0); assert.equal(patients.length, 0);
done(); done();
}); });

View File

@ -46,7 +46,7 @@ describe('RemoteConnector', function() {
}); });
}); });
it('should support the save method', function (done) { it('should support the save method', function(done) {
var calledServerCreate = false; var calledServerCreate = false;
var RemoteModel = loopback.PersistedModel.extend('TestModel'); var RemoteModel = loopback.PersistedModel.extend('TestModel');
RemoteModel.attachTo(this.remote); RemoteModel.attachTo(this.remote);

View File

@ -26,7 +26,7 @@ describe('remoting coercion', function() {
foo: 'bar' foo: 'bar'
}) })
.end(function(err) { .end(function(err) {
if(err) return done(err); if (err) return done(err);
assert(called); assert(called);
done(); done();
}); });

View File

@ -5,28 +5,28 @@ var SIMPLE_APP = path.join(__dirname, 'fixtures', 'simple-integration-app');
var app = require(path.join(SIMPLE_APP, 'app.js')); var app = require(path.join(SIMPLE_APP, 'app.js'));
var assert = require('assert'); var assert = require('assert');
describe('remoting - integration', function () { describe('remoting - integration', function() {
lt.beforeEach.withApp(app); lt.beforeEach.withApp(app);
lt.beforeEach.givenModel('store'); lt.beforeEach.givenModel('store');
afterEach(function (done) { afterEach(function(done) {
this.app.models.store.destroyAll(done); this.app.models.store.destroyAll(done);
}); });
describe('app.remotes.options', function () { describe('app.remotes.options', function() {
it('should load remoting options', function () { it('should load remoting options', function() {
var remotes = app.remotes(); var remotes = app.remotes();
assert.deepEqual(remotes.options, {'json': {'limit': '1kb', 'strict': false}, assert.deepEqual(remotes.options, {'json': {'limit': '1kb', 'strict': false},
'urlencoded': {'limit': '8kb', 'extended': true}}); 'urlencoded': {'limit': '8kb', 'extended': true}});
}); });
it('rest handler', function () { it('rest handler', function() {
var handler = app.handler('rest'); var handler = app.handler('rest');
assert(handler); assert(handler);
}); });
it('should accept request that has entity below 1kb', function (done) { it('should accept request that has entity below 1kb', function(done) {
// Build an object that is smaller than 1kb // Build an object that is smaller than 1kb
var name = ''; var name = '';
for (var i = 0; i < 256; i++) { for (var i = 0; i < 256; i++) {
@ -36,7 +36,7 @@ describe('remoting - integration', function () {
this.http.send({ this.http.send({
'name': name 'name': name
}); });
this.http.end(function (err) { this.http.end(function(err) {
if (err) return done(err); if (err) return done(err);
this.req = this.http.req; this.req = this.http.req;
this.res = this.http.res; this.res = this.http.res;
@ -45,7 +45,7 @@ describe('remoting - integration', function () {
}.bind(this)); }.bind(this));
}); });
it('should reject request that has entity beyond 1kb', function (done) { it('should reject request that has entity beyond 1kb', function(done) {
// Build an object that is larger than 1kb // Build an object that is larger than 1kb
var name = ''; var name = '';
for (var i = 0; i < 2048; i++) { for (var i = 0; i < 2048; i++) {
@ -55,7 +55,7 @@ describe('remoting - integration', function () {
this.http.send({ this.http.send({
'name': name 'name': name
}); });
this.http.end(function (err) { this.http.end(function(err) {
if (err) return done(err); if (err) return done(err);
this.req = this.http.req; this.req = this.http.req;
this.res = this.http.res; this.res = this.http.res;
@ -148,7 +148,6 @@ describe('remoting - integration', function () {
expect(methods).to.include.members(expectedMethods); expect(methods).to.include.members(expectedMethods);
}); });
it('should have correct signatures for belongsTo methods', it('should have correct signatures for belongsTo methods',
function() { function() {
@ -168,7 +167,6 @@ describe('remoting - integration', function () {
expect(methods).to.include.members(expectedMethods); expect(methods).to.include.members(expectedMethods);
}); });
it('should have correct signatures for hasMany methods', it('should have correct signatures for hasMany methods',
function() { function() {

View File

@ -23,7 +23,7 @@ describe('Replication / Change APIs', function() {
this.createInitalData = function(cb) { this.createInitalData = function(cb) {
SourceModel.create({name: 'foo'}, function(err, inst) { SourceModel.create({name: 'foo'}, function(err, inst) {
if(err) return cb(err); if (err) return cb(err);
test.model = inst; test.model = inst;
// give loopback a chance to register the change // give loopback a chance to register the change
@ -36,10 +36,10 @@ describe('Replication / Change APIs', function() {
}); });
describe('Model.changes(since, filter, callback)', function() { describe('Model.changes(since, filter, callback)', function() {
it('Get changes since the given checkpoint', function (done) { it('Get changes since the given checkpoint', function(done) {
var test = this; var test = this;
this.SourceModel.create({name: 'foo'}, function(err) { this.SourceModel.create({name: 'foo'}, function(err) {
if(err) return done(err); if (err) return done(err);
setTimeout(function() { setTimeout(function() {
test.SourceModel.changes(test.startingCheckpoint, {}, function(err, changes) { test.SourceModel.changes(test.startingCheckpoint, {}, function(err, changes) {
assert.equal(changes.length, 1); assert.equal(changes.length, 1);
@ -51,7 +51,7 @@ describe('Replication / Change APIs', function() {
}); });
describe('Model.replicate(since, targetModel, options, callback)', function() { describe('Model.replicate(since, targetModel, options, callback)', function() {
it('Replicate data using the target model', function (done) { it('Replicate data using the target model', function(done) {
var test = this; var test = this;
var options = {}; var options = {};
var sourceData; var sourceData;
@ -68,20 +68,20 @@ describe('Replication / Change APIs', function() {
async.parallel([ async.parallel([
function(cb) { function(cb) {
test.SourceModel.find(function(err, result) { test.SourceModel.find(function(err, result) {
if(err) return cb(err); if (err) return cb(err);
sourceData = result; sourceData = result;
cb(); cb();
}); });
}, },
function(cb) { function(cb) {
test.TargetModel.find(function(err, result) { test.TargetModel.find(function(err, result) {
if(err) return cb(err); if (err) return cb(err);
targetData = result; targetData = result;
cb(); cb();
}); });
} }
], function(err) { ], function(err) {
if(err) return done(err); if (err) return done(err);
assert.deepEqual(sourceData, targetData); assert.deepEqual(sourceData, targetData);
done(); done();
@ -103,22 +103,22 @@ describe('Replication / Change APIs', function() {
async.parallel([ async.parallel([
function(cb) { function(cb) {
SourceModel.findOne(function(err, inst) { SourceModel.findOne(function(err, inst) {
if(err) return cb(err); if (err) return cb(err);
inst.name = 'source update'; inst.name = 'source update';
inst.save(cb); inst.save(cb);
}); });
}, },
function(cb) { function(cb) {
TargetModel.findOne(function(err, inst) { TargetModel.findOne(function(err, inst) {
if(err) return cb(err); if (err) return cb(err);
inst.name = 'target update'; inst.name = 'target update';
inst.save(cb); inst.save(cb);
}); });
} }
], function(err) { ], function(err) {
if(err) return done(err); if (err) return done(err);
SourceModel.replicate(TargetModel, function(err, conflicts) { SourceModel.replicate(TargetModel, function(err, conflicts) {
if(err) return done(err); if (err) return done(err);
test.conflicts = conflicts; test.conflicts = conflicts;
test.conflict = conflicts[0]; test.conflict = conflicts[0];
done(); done();
@ -175,22 +175,22 @@ describe('Replication / Change APIs', function() {
async.parallel([ async.parallel([
function(cb) { function(cb) {
SourceModel.findOne(function(err, inst) { SourceModel.findOne(function(err, inst) {
if(err) return cb(err); if (err) return cb(err);
test.model = inst; test.model = inst;
inst.remove(cb); inst.remove(cb);
}); });
}, },
function(cb) { function(cb) {
TargetModel.findOne(function(err, inst) { TargetModel.findOne(function(err, inst) {
if(err) return cb(err); if (err) return cb(err);
inst.name = 'target update'; inst.name = 'target update';
inst.save(cb); inst.save(cb);
}); });
} }
], function(err) { ], function(err) {
if(err) return done(err); if (err) return done(err);
SourceModel.replicate(TargetModel, function(err, conflicts) { SourceModel.replicate(TargetModel, function(err, conflicts) {
if(err) return done(err); if (err) return done(err);
test.conflicts = conflicts; test.conflicts = conflicts;
test.conflict = conflicts[0]; test.conflict = conflicts[0];
done(); done();
@ -244,7 +244,7 @@ describe('Replication / Change APIs', function() {
async.parallel([ async.parallel([
function(cb) { function(cb) {
SourceModel.findOne(function(err, inst) { SourceModel.findOne(function(err, inst) {
if(err) return cb(err); if (err) return cb(err);
test.model = inst; test.model = inst;
inst.name = 'source update'; inst.name = 'source update';
inst.save(cb); inst.save(cb);
@ -252,14 +252,14 @@ describe('Replication / Change APIs', function() {
}, },
function(cb) { function(cb) {
TargetModel.findOne(function(err, inst) { TargetModel.findOne(function(err, inst) {
if(err) return cb(err); if (err) return cb(err);
inst.remove(cb); inst.remove(cb);
}); });
} }
], function(err) { ], function(err) {
if(err) return done(err); if (err) return done(err);
SourceModel.replicate(TargetModel, function(err, conflicts) { SourceModel.replicate(TargetModel, function(err, conflicts) {
if(err) return done(err); if (err) return done(err);
test.conflicts = conflicts; test.conflicts = conflicts;
test.conflict = conflicts[0]; test.conflict = conflicts[0];
done(); done();
@ -313,21 +313,21 @@ describe('Replication / Change APIs', function() {
async.parallel([ async.parallel([
function(cb) { function(cb) {
SourceModel.findOne(function(err, inst) { SourceModel.findOne(function(err, inst) {
if(err) return cb(err); if (err) return cb(err);
test.model = inst; test.model = inst;
inst.remove(cb); inst.remove(cb);
}); });
}, },
function(cb) { function(cb) {
TargetModel.findOne(function(err, inst) { TargetModel.findOne(function(err, inst) {
if(err) return cb(err); if (err) return cb(err);
inst.remove(cb); inst.remove(cb);
}); });
} }
], function(err) { ], function(err) {
if(err) return done(err); if (err) return done(err);
SourceModel.replicate(TargetModel, function(err, conflicts) { SourceModel.replicate(TargetModel, function(err, conflicts) {
if(err) return done(err); if (err) return done(err);
test.conflicts = conflicts; test.conflicts = conflicts;
test.conflict = conflicts[0]; test.conflict = conflicts[0];
done(); done();

View File

@ -86,7 +86,7 @@ describe('loopback.rest', function() {
app.use(loopback.rest()); app.use(loopback.rest());
request(app).get('/mymodels') request(app).get('/mymodels')
.set('Accept', 'text/html,application/xml;q=0.9,*/*;q=0.8') .set('Accept', 'text/html,application/xml;q= 0.9,*/*;q= 0.8')
.expect('Content-Type', 'application/json; charset=utf-8') .expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, done); .expect(200, done);
}); });

View File

@ -10,7 +10,7 @@ function checkResult(err, result) {
assert(!err); assert(!err);
} }
describe('role model', function () { describe('role model', function() {
var ds; var ds;
beforeEach(function() { beforeEach(function() {
@ -22,22 +22,22 @@ describe('role model', function () {
RoleMapping.attachTo(ds); RoleMapping.attachTo(ds);
}); });
it('should define role/role relations', function () { it('should define role/role relations', function() {
Role.create({name: 'user'}, function (err, userRole) { Role.create({name: 'user'}, function(err, userRole) {
Role.create({name: 'admin'}, function (err, adminRole) { Role.create({name: 'admin'}, function(err, adminRole) {
userRole.principals.create({principalType: RoleMapping.ROLE, principalId: adminRole.id}, function (err, mapping) { userRole.principals.create({principalType: RoleMapping.ROLE, principalId: adminRole.id}, function(err, mapping) {
Role.find(function (err, roles) { Role.find(function(err, roles) {
assert.equal(roles.length, 2); assert.equal(roles.length, 2);
}); });
RoleMapping.find(function (err, mappings) { RoleMapping.find(function(err, mappings) {
assert.equal(mappings.length, 1); assert.equal(mappings.length, 1);
assert.equal(mappings[0].principalType, RoleMapping.ROLE); assert.equal(mappings[0].principalType, RoleMapping.ROLE);
assert.equal(mappings[0].principalId, adminRole.id); assert.equal(mappings[0].principalId, adminRole.id);
}); });
userRole.principals(function (err, principals) { userRole.principals(function(err, principals) {
assert.equal(principals.length, 1); assert.equal(principals.length, 1);
}); });
userRole.roles(function (err, roles) { userRole.roles(function(err, roles) {
assert.equal(roles.length, 1); assert.equal(roles.length, 1);
}); });
}); });
@ -46,25 +46,25 @@ describe('role model', function () {
}); });
it('should define role/user relations', function () { it('should define role/user relations', function() {
User.create({name: 'Raymond', email: 'x@y.com', password: 'foobar'}, function (err, user) { User.create({name: 'Raymond', email: 'x@y.com', password: 'foobar'}, function(err, user) {
// console.log('User: ', user.id); // console.log('User: ', user.id);
Role.create({name: 'userRole'}, function (err, role) { Role.create({name: 'userRole'}, function(err, role) {
role.principals.create({principalType: RoleMapping.USER, principalId: user.id}, function (err, p) { role.principals.create({principalType: RoleMapping.USER, principalId: user.id}, function(err, p) {
Role.find(function (err, roles) { Role.find(function(err, roles) {
assert(!err); assert(!err);
assert.equal(roles.length, 1); assert.equal(roles.length, 1);
assert.equal(roles[0].name, 'userRole'); assert.equal(roles[0].name, 'userRole');
}); });
role.principals(function (err, principals) { role.principals(function(err, principals) {
assert(!err); assert(!err);
// console.log(principals); // console.log(principals);
assert.equal(principals.length, 1); assert.equal(principals.length, 1);
assert.equal(principals[0].principalType, RoleMapping.USER); assert.equal(principals[0].principalType, RoleMapping.USER);
assert.equal(principals[0].principalId, user.id); assert.equal(principals[0].principalId, user.id);
}); });
role.users(function (err, users) { role.users(function(err, users) {
assert(!err); assert(!err);
assert.equal(users.length, 1); assert.equal(users.length, 1);
assert.equal(users[0].principalType, RoleMapping.USER); assert.equal(users[0].principalType, RoleMapping.USER);
@ -76,29 +76,28 @@ describe('role model', function () {
}); });
it('should automatically generate role id', function() {
it('should automatically generate role id', function () { User.create({name: 'Raymond', email: 'x@y.com', password: 'foobar'}, function(err, user) {
User.create({name: 'Raymond', email: 'x@y.com', password: 'foobar'}, function (err, user) {
// console.log('User: ', user.id); // console.log('User: ', user.id);
Role.create({name: 'userRole'}, function (err, role) { Role.create({name: 'userRole'}, function(err, role) {
assert(role.id); assert(role.id);
role.principals.create({principalType: RoleMapping.USER, principalId: user.id}, function (err, p) { role.principals.create({principalType: RoleMapping.USER, principalId: user.id}, function(err, p) {
assert(p.id); assert(p.id);
assert.equal(p.roleId, role.id); assert.equal(p.roleId, role.id);
Role.find(function (err, roles) { Role.find(function(err, roles) {
assert(!err); assert(!err);
assert.equal(roles.length, 1); assert.equal(roles.length, 1);
assert.equal(roles[0].name, 'userRole'); assert.equal(roles[0].name, 'userRole');
}); });
role.principals(function (err, principals) { role.principals(function(err, principals) {
assert(!err); assert(!err);
// console.log(principals); // console.log(principals);
assert.equal(principals.length, 1); assert.equal(principals.length, 1);
assert.equal(principals[0].principalType, RoleMapping.USER); assert.equal(principals[0].principalType, RoleMapping.USER);
assert.equal(principals[0].principalId, user.id); assert.equal(principals[0].principalId, user.id);
}); });
role.users(function (err, users) { role.users(function(err, users) {
assert(!err); assert(!err);
assert.equal(users.length, 1); assert.equal(users.length, 1);
assert.equal(users[0].principalType, RoleMapping.USER); assert.equal(users[0].principalType, RoleMapping.USER);
@ -110,45 +109,45 @@ describe('role model', function () {
}); });
it('should support getRoles() and isInRole()', function () { it('should support getRoles() and isInRole()', function() {
User.create({name: 'Raymond', email: 'x@y.com', password: 'foobar'}, function (err, user) { User.create({name: 'Raymond', email: 'x@y.com', password: 'foobar'}, function(err, user) {
// console.log('User: ', user.id); // console.log('User: ', user.id);
Role.create({name: 'userRole'}, function (err, role) { Role.create({name: 'userRole'}, function(err, role) {
role.principals.create({principalType: RoleMapping.USER, principalId: user.id}, function (err, p) { role.principals.create({principalType: RoleMapping.USER, principalId: user.id}, function(err, p) {
// Role.find(console.log); // Role.find(console.log);
// role.principals(console.log); // role.principals(console.log);
Role.isInRole('userRole', {principalType: RoleMapping.USER, principalId: user.id}, function (err, exists) { Role.isInRole('userRole', {principalType: RoleMapping.USER, principalId: user.id}, function(err, exists) {
assert(!err && exists === true); assert(!err && exists === true);
}); });
Role.isInRole('userRole', {principalType: RoleMapping.APP, principalId: user.id}, function (err, exists) { Role.isInRole('userRole', {principalType: RoleMapping.APP, principalId: user.id}, function(err, exists) {
assert(!err && exists === false); assert(!err && exists === false);
}); });
Role.isInRole('userRole', {principalType: RoleMapping.USER, principalId: 100}, function (err, exists) { Role.isInRole('userRole', {principalType: RoleMapping.USER, principalId: 100}, function(err, exists) {
assert(!err && exists === false); assert(!err && exists === false);
}); });
Role.getRoles({principalType: RoleMapping.USER, principalId: user.id}, function (err, roles) { Role.getRoles({principalType: RoleMapping.USER, principalId: user.id}, function(err, roles) {
assert.equal(roles.length, 3); // everyone, authenticated, userRole assert.equal(roles.length, 3); // everyone, authenticated, userRole
assert(roles.indexOf(role.id) >=0); assert(roles.indexOf(role.id) >= 0);
assert(roles.indexOf(Role.EVERYONE) >=0); assert(roles.indexOf(Role.EVERYONE) >= 0);
assert(roles.indexOf(Role.AUTHENTICATED) >=0); assert(roles.indexOf(Role.AUTHENTICATED) >= 0);
}); });
Role.getRoles({principalType: RoleMapping.APP, principalId: user.id}, function (err, roles) { Role.getRoles({principalType: RoleMapping.APP, principalId: user.id}, function(err, roles) {
assert.equal(roles.length, 2); assert.equal(roles.length, 2);
assert(roles.indexOf(Role.EVERYONE) >=0); assert(roles.indexOf(Role.EVERYONE) >= 0);
assert(roles.indexOf(Role.AUTHENTICATED) >=0); assert(roles.indexOf(Role.AUTHENTICATED) >= 0);
}); });
Role.getRoles({principalType: RoleMapping.USER, principalId: 100}, function (err, roles) { Role.getRoles({principalType: RoleMapping.USER, principalId: 100}, function(err, roles) {
assert.equal(roles.length, 2); assert.equal(roles.length, 2);
assert(roles.indexOf(Role.EVERYONE) >=0); assert(roles.indexOf(Role.EVERYONE) >= 0);
assert(roles.indexOf(Role.AUTHENTICATED) >=0); assert(roles.indexOf(Role.AUTHENTICATED) >= 0);
}); });
Role.getRoles({principalType: RoleMapping.USER, principalId: null}, function (err, roles) { Role.getRoles({principalType: RoleMapping.USER, principalId: null}, function(err, roles) {
assert.equal(roles.length, 2); assert.equal(roles.length, 2);
assert(roles.indexOf(Role.EVERYONE) >=0); assert(roles.indexOf(Role.EVERYONE) >= 0);
assert(roles.indexOf(Role.UNAUTHENTICATED) >=0); assert(roles.indexOf(Role.UNAUTHENTICATED) >= 0);
}); });
}); });
}); });
@ -156,7 +155,7 @@ describe('role model', function () {
}); });
it('should support owner role resolver', function () { it('should support owner role resolver', function() {
var Album = ds.createModel('Album', { var Album = ds.createModel('Album', {
name: String, name: String,
@ -171,36 +170,36 @@ describe('role model', function () {
} }
}); });
User.create({name: 'Raymond', email: 'x@y.com', password: 'foobar'}, function (err, user) { User.create({name: 'Raymond', email: 'x@y.com', password: 'foobar'}, function(err, user) {
Role.isInRole(Role.AUTHENTICATED, {principalType: ACL.USER, principalId: user.id}, function (err, yes) { Role.isInRole(Role.AUTHENTICATED, {principalType: ACL.USER, principalId: user.id}, function(err, yes) {
assert(!err && yes); assert(!err && yes);
}); });
Role.isInRole(Role.AUTHENTICATED, {principalType: ACL.USER, principalId: null}, function (err, yes) { Role.isInRole(Role.AUTHENTICATED, {principalType: ACL.USER, principalId: null}, function(err, yes) {
assert(!err && !yes); assert(!err && !yes);
}); });
Role.isInRole(Role.UNAUTHENTICATED, {principalType: ACL.USER, principalId: user.id}, function (err, yes) { Role.isInRole(Role.UNAUTHENTICATED, {principalType: ACL.USER, principalId: user.id}, function(err, yes) {
assert(!err && !yes); assert(!err && !yes);
}); });
Role.isInRole(Role.UNAUTHENTICATED, {principalType: ACL.USER, principalId: null}, function (err, yes) { Role.isInRole(Role.UNAUTHENTICATED, {principalType: ACL.USER, principalId: null}, function(err, yes) {
assert(!err && yes); assert(!err && yes);
}); });
Role.isInRole(Role.EVERYONE, {principalType: ACL.USER, principalId: user.id}, function (err, yes) { Role.isInRole(Role.EVERYONE, {principalType: ACL.USER, principalId: user.id}, function(err, yes) {
assert(!err && yes); assert(!err && yes);
}); });
Role.isInRole(Role.EVERYONE, {principalType: ACL.USER, principalId: null}, function (err, yes) { Role.isInRole(Role.EVERYONE, {principalType: ACL.USER, principalId: null}, function(err, yes) {
assert(!err && yes); assert(!err && yes);
}); });
// console.log('User: ', user.id); // console.log('User: ', user.id);
Album.create({name: 'Album 1', userId: user.id}, function (err, album1) { Album.create({name: 'Album 1', userId: user.id}, function(err, album1) {
Role.isInRole(Role.OWNER, {principalType: ACL.USER, principalId: user.id, model: Album, id: album1.id}, function (err, yes) { Role.isInRole(Role.OWNER, {principalType: ACL.USER, principalId: user.id, model: Album, id: album1.id}, function(err, yes) {
assert(!err && yes); assert(!err && yes);
}); });
Album.create({name: 'Album 2'}, function (err, album2) { Album.create({name: 'Album 2'}, function(err, album2) {
Role.isInRole(Role.OWNER, {principalType: ACL.USER, principalId: user.id, model: Album, id: album2.id}, function (err, yes) { Role.isInRole(Role.OWNER, {principalType: ACL.USER, principalId: user.id, model: Album, id: album2.id}, function(err, yes) {
assert(!err && !yes); assert(!err && !yes);
}); });
}); });
@ -210,7 +209,3 @@ describe('role model', function () {
}); });
}); });

View File

@ -16,7 +16,7 @@ var RemoteObjects = require('strong-remoting');
// for tests using the built-in User model // for tests using the built-in User model
loopback.User.settings.saltWorkFactor = 4; loopback.User.settings.saltWorkFactor = 4;
beforeEach(function () { beforeEach(function() {
this.app = app = loopback(); this.app = app = loopback();
// setup default data sources // setup default data sources
@ -35,7 +35,7 @@ beforeEach(function () {
loopback.autoAttach(); loopback.autoAttach();
}); });
assertValidDataSource = function (dataSource) { assertValidDataSource = function(dataSource) {
// has methods // has methods
assert.isFunc(dataSource, 'createModel'); assert.isFunc(dataSource, 'createModel');
assert.isFunc(dataSource, 'discoverModelDefinitions'); assert.isFunc(dataSource, 'discoverModelDefinitions');
@ -46,7 +46,7 @@ assertValidDataSource = function (dataSource) {
assert.isFunc(dataSource, 'operations'); assert.isFunc(dataSource, 'operations');
}; };
assert.isFunc = function (obj, name) { assert.isFunc = function(obj, name) {
assert(obj, 'cannot assert function ' + name + ' on object that doesnt exist'); assert(obj, 'cannot assert function ' + name + ' on object that doesnt exist');
assert(typeof obj[name] === 'function', name + ' is not a function'); assert(typeof obj[name] === 'function', name + ' is not a function');
}; };

View File

@ -6,7 +6,7 @@ var userMemory = loopback.createDataSource({
connector: 'memory' connector: 'memory'
}); });
describe('User', function(){ describe('User', function() {
var validCredentials = {email: 'foo@bar.com', password: 'bar'}; var validCredentials = {email: 'foo@bar.com', password: 'bar'};
var validCredentialsEmailVerified = {email: 'foo1@bar.com', password: 'bar1', emailVerified: true}; var validCredentialsEmailVerified = {email: 'foo1@bar.com', password: 'bar1', emailVerified: true};
var validCredentialsEmailVerifiedOverREST = {email: 'foo2@bar.com', password: 'bar2', emailVerified: true}; var validCredentialsEmailVerifiedOverREST = {email: 'foo2@bar.com', password: 'bar2', emailVerified: true};
@ -27,7 +27,7 @@ describe('User', function(){
}); });
beforeEach(function (done) { beforeEach(function(done) {
app.enableAuth(); app.enableAuth();
app.use(loopback.token()); app.use(loopback.token());
app.use(loopback.rest()); app.use(loopback.rest());
@ -38,15 +38,15 @@ describe('User', function(){
}); });
}); });
afterEach(function (done) { afterEach(function(done) {
User.destroyAll(function (err) { User.destroyAll(function(err) {
User.accessToken.destroyAll(done); User.accessToken.destroyAll(done);
}); });
}); });
describe('User.create', function(){ describe('User.create', function() {
it('Create a new user', function(done) { it('Create a new user', function(done) {
User.create({email: 'f@b.com', password: 'bar'}, function (err, user) { User.create({email: 'f@b.com', password: 'bar'}, function(err, user) {
assert(!err); assert(!err);
assert(user.id); assert(user.id);
assert(user.email); assert(user.email);
@ -54,13 +54,13 @@ describe('User', function(){
}); });
}); });
it('credentials/challenges are object types', function (done) { it('credentials/challenges are object types', function(done) {
User.create({email: 'f1@b.com', password: 'bar1', User.create({email: 'f1@b.com', password: 'bar1',
credentials: {cert: 'xxxxx', key: '111'}, credentials: {cert: 'xxxxx', key: '111'},
challenges: {x: 'X', a: 1} challenges: {x: 'X', a: 1}
}, function (err, user) { }, function(err, user) {
assert(!err); assert(!err);
User.findById(user.id, function (err, user) { User.findById(user.id, function(err, user) {
assert(user.id); assert(user.id);
assert(user.email); assert(user.email);
assert.deepEqual(user.credentials, {cert: 'xxxxx', key: '111'}); assert.deepEqual(user.credentials, {cert: 'xxxxx', key: '111'});
@ -70,8 +70,8 @@ describe('User', function(){
}); });
}); });
it('Email is required', function (done) { it('Email is required', function(done) {
User.create({password: '123'}, function (err) { User.create({password: '123'}, function(err) {
assert(err); assert(err);
assert.equal(err.name, 'ValidationError'); assert.equal(err.name, 'ValidationError');
assert.equal(err.statusCode, 422); assert.equal(err.statusCode, 422);
@ -89,22 +89,22 @@ describe('User', function(){
it('Password is required', function(done) { it('Password is required', function(done) {
var u = new User({email: '123@456.com'}); var u = new User({email: '123@456.com'});
User.create({email: 'c@d.com'}, function (err) { User.create({email: 'c@d.com'}, function(err) {
assert(err); assert(err);
done(); done();
}); });
}); });
it('Requires a valid email', function(done) { it('Requires a valid email', function(done) {
User.create({email: 'foo@', password: '123'}, function (err) { User.create({email: 'foo@', password: '123'}, function(err) {
assert(err); assert(err);
done(); done();
}); });
}); });
it('Requires a unique email', function(done) { it('Requires a unique email', function(done) {
User.create({email: 'a@b.com', password: 'foobar'}, function () { User.create({email: 'a@b.com', password: 'foobar'}, function() {
User.create({email: 'a@b.com', password: 'batbaz'}, function (err) { User.create({email: 'a@b.com', password: 'batbaz'}, function(err) {
assert(err, 'should error because the email is not unique!'); assert(err, 'should error because the email is not unique!');
done(); done();
}); });
@ -112,8 +112,8 @@ describe('User', function(){
}); });
it('Requires a unique username', function(done) { it('Requires a unique username', function(done) {
User.create({email: 'a@b.com', username: 'abc', password: 'foobar'}, function () { User.create({email: 'a@b.com', username: 'abc', password: 'foobar'}, function() {
User.create({email: 'b@b.com', username: 'abc', password: 'batbaz'}, function (err) { User.create({email: 'b@b.com', username: 'abc', password: 'batbaz'}, function(err) {
assert(err, 'should error because the username is not unique!'); assert(err, 'should error because the username is not unique!');
done(); done();
}); });
@ -121,8 +121,8 @@ describe('User', function(){
}); });
it('Requires a password to login with basic auth', function(done) { it('Requires a password to login with basic auth', function(done) {
User.create({email: 'b@c.com'}, function (err) { User.create({email: 'b@c.com'}, function(err) {
User.login({email: 'b@c.com'}, function (err, accessToken) { User.login({email: 'b@c.com'}, function(err, accessToken) {
assert(!accessToken, 'should not create a accessToken without a valid password'); assert(!accessToken, 'should not create a accessToken without a valid password');
assert(err, 'should not login without a password'); assert(err, 'should not login without a password');
done(); done();
@ -141,7 +141,7 @@ describe('User', function(){
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200) .expect(200)
.send(validCredentialsEmailVerifiedOverREST) .send(validCredentialsEmailVerifiedOverREST)
.end(function(err, res){ .end(function(err, res) {
assert(!res.body.emailVerified); assert(!res.body.emailVerified);
done(); done();
}); });
@ -150,7 +150,7 @@ describe('User', function(){
describe('User.login', function() { describe('User.login', function() {
it('Login a user by providing credentials', function(done) { it('Login a user by providing credentials', function(done) {
User.login(validCredentials, function (err, accessToken) { User.login(validCredentials, function(err, accessToken) {
assert(accessToken.userId); assert(accessToken.userId);
assert(accessToken.id); assert(accessToken.id);
assert.equal(accessToken.id.length, 64); assert.equal(accessToken.id.length, 64);
@ -160,7 +160,7 @@ describe('User', function(){
}); });
it('Login a user by providing credentials with TTL', function(done) { it('Login a user by providing credentials with TTL', function(done) {
User.login(validCredentialsWithTTL, function (err, accessToken) { User.login(validCredentialsWithTTL, function(err, accessToken) {
assert(accessToken.userId); assert(accessToken.userId);
assert(accessToken.id); assert(accessToken.id);
assert.equal(accessToken.ttl, validCredentialsWithTTL.ttl); assert.equal(accessToken.ttl, validCredentialsWithTTL.ttl);
@ -175,16 +175,16 @@ describe('User', function(){
// Override createAccessToken // Override createAccessToken
User.prototype.createAccessToken = function(ttl, cb) { User.prototype.createAccessToken = function(ttl, cb) {
// Reduce the ttl by half for testing purpose // Reduce the ttl by half for testing purpose
this.accessTokens.create({ttl: ttl /2 }, cb); this.accessTokens.create({ttl: ttl / 2 }, cb);
}; };
User.login(validCredentialsWithTTL, function (err, accessToken) { User.login(validCredentialsWithTTL, function(err, accessToken) {
assert(accessToken.userId); assert(accessToken.userId);
assert(accessToken.id); assert(accessToken.id);
assert.equal(accessToken.ttl, 1800); assert.equal(accessToken.ttl, 1800);
assert.equal(accessToken.id.length, 64); assert.equal(accessToken.id.length, 64);
User.findById(accessToken.userId, function(err, user) { User.findById(accessToken.userId, function(err, user) {
user.createAccessToken(120, function (err, accessToken) { user.createAccessToken(120, function(err, accessToken) {
assert(accessToken.userId); assert(accessToken.userId);
assert(accessToken.id); assert(accessToken.id);
assert.equal(accessToken.ttl, 60); assert.equal(accessToken.ttl, 60);
@ -203,8 +203,8 @@ describe('User', function(){
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200) .expect(200)
.send(validCredentials) .send(validCredentials)
.end(function(err, res){ .end(function(err, res) {
if(err) return done(err); if (err) return done(err);
var accessToken = res.body; var accessToken = res.body;
assert(accessToken.userId); assert(accessToken.userId);
@ -222,7 +222,7 @@ describe('User', function(){
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(401) .expect(401)
.send(invalidCredentials) .send(invalidCredentials)
.end(function(err, res){ .end(function(err, res) {
done(); done();
}); });
}); });
@ -233,7 +233,7 @@ describe('User', function(){
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(400) .expect(400)
.send(incompleteCredentials) .send(incompleteCredentials)
.end(function(err, res){ .end(function(err, res) {
done(); done();
}); });
}); });
@ -245,7 +245,7 @@ describe('User', function(){
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(400) .expect(400)
.send(validCredentials) .send(validCredentials)
.end(function(err, res){ .end(function(err, res) {
done(); done();
}); });
}); });
@ -309,14 +309,14 @@ describe('User', function(){
}); });
it('Login a user by without email verification', function(done) { it('Login a user by without email verification', function(done) {
User.login(validCredentials, function (err, accessToken) { User.login(validCredentials, function(err, accessToken) {
assert(err); assert(err);
done(); done();
}); });
}); });
it('Login a user by with email verification', function(done) { it('Login a user by with email verification', function(done) {
User.login(validCredentialsEmailVerified, function (err, accessToken) { User.login(validCredentialsEmailVerified, function(err, accessToken) {
assertGoodToken(accessToken); assertGoodToken(accessToken);
done(); done();
}); });
@ -328,8 +328,8 @@ describe('User', function(){
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200) .expect(200)
.send(validCredentialsEmailVerified) .send(validCredentialsEmailVerified)
.end(function(err, res){ .end(function(err, res) {
if(err) return done(err); if (err) return done(err);
var accessToken = res.body; var accessToken = res.body;
assertGoodToken(accessToken); assertGoodToken(accessToken);
@ -353,7 +353,8 @@ describe('User', function(){
}); });
describe('User.login requiring realm', function() { describe('User.login requiring realm', function() {
var User, AccessToken; var User;
var AccessToken;
before(function() { before(function() {
User = loopback.User.extend('RealmUser', {}, User = loopback.User.extend('RealmUser', {},
@ -533,8 +534,8 @@ describe('User', function(){
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200) .expect(200)
.send({email: 'foo@bar.com', password: 'bar'}) .send({email: 'foo@bar.com', password: 'bar'})
.end(function(err, res){ .end(function(err, res) {
if(err) return done(err); if (err) return done(err);
var accessToken = res.body; var accessToken = res.body;
assert(accessToken.userId); assert(accessToken.userId);
@ -556,10 +557,10 @@ describe('User', function(){
function verify(token, done) { function verify(token, done) {
assert(token); assert(token);
return function (err) { return function(err) {
if(err) return done(err); if (err) return done(err);
AccessToken.findById(token, function (err, accessToken) { AccessToken.findById(token, function(err, accessToken) {
assert(!accessToken, 'accessToken should not exist after logging out'); assert(!accessToken, 'accessToken should not exist after logging out');
done(err); done(err);
}); });
@ -567,10 +568,10 @@ describe('User', function(){
} }
}); });
describe('user.hasPassword(plain, fn)', function(){ describe('user.hasPassword(plain, fn)', function() {
it('Determine if the password matches the stored password', function(done) { it('Determine if the password matches the stored password', function(done) {
var u = new User({username: 'foo', password: 'bar'}); var u = new User({username: 'foo', password: 'bar'});
u.hasPassword('bar', function (err, isMatch) { u.hasPassword('bar', function(err, isMatch) {
assert(isMatch, 'password doesnt match'); assert(isMatch, 'password doesnt match');
done(); done();
}); });
@ -579,9 +580,9 @@ describe('User', function(){
it('should match a password when saved', function(done) { it('should match a password when saved', function(done) {
var u = new User({username: 'a', password: 'b', email: 'z@z.net'}); var u = new User({username: 'a', password: 'b', email: 'z@z.net'});
u.save(function (err, user) { u.save(function(err, user) {
User.findById(user.id, function (err, uu) { User.findById(user.id, function(err, uu) {
uu.hasPassword('b', function (err, isMatch) { uu.hasPassword('b', function(err, isMatch) {
assert(isMatch); assert(isMatch);
done(); done();
}); });
@ -590,17 +591,17 @@ describe('User', function(){
}); });
it('should match a password after it is changed', function(done) { it('should match a password after it is changed', function(done) {
User.create({email: 'foo@baz.net', username: 'bat', password: 'baz'}, function (err, user) { User.create({email: 'foo@baz.net', username: 'bat', password: 'baz'}, function(err, user) {
User.findById(user.id, function (err, foundUser) { User.findById(user.id, function(err, foundUser) {
assert(foundUser); assert(foundUser);
foundUser.hasPassword('baz', function (err, isMatch) { foundUser.hasPassword('baz', function(err, isMatch) {
assert(isMatch); assert(isMatch);
foundUser.password = 'baz2'; foundUser.password = 'baz2';
foundUser.save(function (err, updatedUser) { foundUser.save(function(err, updatedUser) {
updatedUser.hasPassword('baz2', function (err, isMatch) { updatedUser.hasPassword('baz2', function(err, isMatch) {
assert(isMatch); assert(isMatch);
User.findById(user.id, function (err, uu) { User.findById(user.id, function(err, uu) {
uu.hasPassword('baz2', function (err, isMatch) { uu.hasPassword('baz2', function(err, isMatch) {
assert(isMatch); assert(isMatch);
done(); done();
}); });
@ -613,9 +614,9 @@ describe('User', function(){
}); });
}); });
describe('Verification', function(){ describe('Verification', function() {
describe('user.verify(options, fn)', function(){ describe('user.verify(options, fn)', function() {
it('Verify a user\'s email address', function(done) { it('Verify a user\'s email address', function(done) {
User.afterRemote('create', function(ctx, user, next) { User.afterRemote('create', function(ctx, user, next) {
assert(user, 'afterRemote should include result'); assert(user, 'afterRemote should include result');
@ -629,7 +630,7 @@ describe('User', function(){
host: ctx.req.get('host') host: ctx.req.get('host')
}; };
user.verify(options, function (err, result) { user.verify(options, function(err, result) {
assert(result.email); assert(result.email);
assert(result.email.response); assert(result.email.response);
assert(result.token); assert(result.token);
@ -645,8 +646,8 @@ describe('User', function(){
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200) .expect(200)
.send({email: 'bar@bat.com', password: 'bar'}) .send({email: 'bar@bat.com', password: 'bar'})
.end(function(err, res){ .end(function(err, res) {
if(err) return done(err); if (err) return done(err);
}); });
}); });
@ -664,7 +665,7 @@ describe('User', function(){
headers: {'message-id':'custom-header-value'} headers: {'message-id':'custom-header-value'}
}; };
user.verify(options, function (err, result) { user.verify(options, function(err, result) {
assert(result.email); assert(result.email);
assert.equal(result.email.messageId, 'custom-header-value'); assert.equal(result.email.messageId, 'custom-header-value');
done(); done();
@ -676,18 +677,18 @@ describe('User', function(){
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200) .expect(200)
.send({email: 'bar@bat.com', password: 'bar'}) .send({email: 'bar@bat.com', password: 'bar'})
.end(function(err, res){ .end(function(err, res) {
if(err) return done(err); if (err) return done(err);
}); });
}); });
}); });
describe('User.confirm(options, fn)', function () { describe('User.confirm(options, fn)', function() {
var options; var options;
function testConfirm(testFunc, done) { function testConfirm(testFunc, done) {
User.afterRemote('create', function (ctx, user, next) { User.afterRemote('create', function(ctx, user, next) {
assert(user, 'afterRemote should include result'); assert(user, 'afterRemote should include result');
options = { options = {
@ -699,7 +700,7 @@ describe('User', function(){
host: ctx.req.get('host') host: ctx.req.get('host')
}; };
user.verify(options, function (err, result) { user.verify(options, function(err, result) {
if (err) { if (err) {
return done(err); return done(err);
} }
@ -712,21 +713,21 @@ describe('User', function(){
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(302) .expect(302)
.send({email: 'bar@bat.com', password: 'bar'}) .send({email: 'bar@bat.com', password: 'bar'})
.end(function (err, res) { .end(function(err, res) {
if (err) { if (err) {
return done(err); return done(err);
} }
}); });
} }
it('Confirm a user verification', function (done) { it('Confirm a user verification', function(done) {
testConfirm(function (result, done) { testConfirm(function(result, done) {
request(app) request(app)
.get('/users/confirm?uid=' + (result.uid ) .get('/users/confirm?uid=' + (result.uid)
+ '&token=' + encodeURIComponent(result.token) + '&token=' + encodeURIComponent(result.token)
+ '&redirect=' + encodeURIComponent(options.redirect)) + '&redirect=' + encodeURIComponent(options.redirect))
.expect(302) .expect(302)
.end(function (err, res) { .end(function(err, res) {
if (err) { if (err) {
return done(err); return done(err);
} }
@ -735,14 +736,14 @@ describe('User', function(){
}, done); }, done);
}); });
it('Report error for invalid user id during verification', function (done) { it('Report error for invalid user id during verification', function(done) {
testConfirm(function (result, done) { testConfirm(function(result, done) {
request(app) request(app)
.get('/users/confirm?uid=' + (result.uid + '_invalid') .get('/users/confirm?uid=' + (result.uid + '_invalid')
+ '&token=' + encodeURIComponent(result.token) + '&token=' + encodeURIComponent(result.token)
+ '&redirect=' + encodeURIComponent(options.redirect)) + '&redirect=' + encodeURIComponent(options.redirect))
.expect(404) .expect(404)
.end(function (err, res) { .end(function(err, res) {
if (err) { if (err) {
return done(err); return done(err);
} }
@ -752,14 +753,14 @@ describe('User', function(){
}, done); }, done);
}); });
it('Report error for invalid token during verification', function (done) { it('Report error for invalid token during verification', function(done) {
testConfirm(function (result, done) { testConfirm(function(result, done) {
request(app) request(app)
.get('/users/confirm?uid=' + result.uid .get('/users/confirm?uid=' + result.uid
+ '&token=' + encodeURIComponent(result.token) + '_invalid' + '&token=' + encodeURIComponent(result.token) + '_invalid'
+ '&redirect=' + encodeURIComponent(options.redirect)) + '&redirect=' + encodeURIComponent(options.redirect))
.expect(400) .expect(400)
.end(function (err, res) { .end(function(err, res) {
if (err) return done(err); if (err) return done(err);
assert(res.body.error); assert(res.body.error);
done(); done();
@ -769,25 +770,25 @@ describe('User', function(){
}); });
}); });
describe('Password Reset', function () { describe('Password Reset', function() {
describe('User.resetPassword(options, cb)', function () { describe('User.resetPassword(options, cb)', function() {
it('Creates a temp accessToken to allow a user to change password', function (done) { it('Creates a temp accessToken to allow a user to change password', function(done) {
var calledBack = false; var calledBack = false;
var email = 'foo@bar.com'; var email = 'foo@bar.com';
User.resetPassword({ User.resetPassword({
email: email email: email
}, function () { }, function() {
calledBack = true; calledBack = true;
}); });
User.once('resetPasswordRequest', function (info) { User.once('resetPasswordRequest', function(info) {
assert(info.email); assert(info.email);
assert(info.accessToken); assert(info.accessToken);
assert(info.accessToken.id); assert(info.accessToken.id);
assert.equal(info.accessToken.ttl / 60, 15); assert.equal(info.accessToken.ttl / 60, 15);
assert(calledBack); assert(calledBack);
info.accessToken.user(function (err, user) { info.accessToken.user(function(err, user) {
assert.equal(user.email, email); assert.equal(user.email, email);
done(); done();
}); });

View File

@ -8,11 +8,12 @@ var RemoteObjects = require('strong-remoting');
module.exports = function defineModelTestsWithDataSource(options) { module.exports = function defineModelTestsWithDataSource(options) {
describe('Model Tests', function() { describe('Model Tests', function() {
var User, dataSource; var User;
var dataSource;
if(options.beforeEach) { if (options.beforeEach) {
beforeEach(options.beforeEach); beforeEach(options.beforeEach);
} }
@ -28,7 +29,7 @@ describe('Model Tests', function() {
PersistedModel.extend = function() { PersistedModel.extend = function() {
var extendedModel = extend.apply(PersistedModel, arguments); var extendedModel = extend.apply(PersistedModel, arguments);
if(options.onDefine) { if (options.onDefine) {
options.onDefine.call(test, extendedModel); options.onDefine.call(test, extendedModel);
} }
@ -118,7 +119,7 @@ describe('Model Tests', function() {
it('Asynchronously validate the model', function(done) { it('Asynchronously validate the model', function(done) {
User.validatesNumericalityOf('age', {int: true}); User.validatesNumericalityOf('age', {int: true});
var user = new User({first: 'joe', age: 'flarg'}); var user = new User({first: 'joe', age: 'flarg'});
user.isValid(function (valid) { user.isValid(function(valid) {
assert(valid === false); assert(valid === false);
assert(user.errors.age, 'model should have age error'); assert(user.errors.age, 'model should have age error');
done(); done();
@ -149,14 +150,14 @@ describe('Model Tests', function() {
describe('model.updateAttributes(data, [callback])', function() { describe('model.updateAttributes(data, [callback])', function() {
it('Save specified attributes to the attached data source', function(done) { it('Save specified attributes to the attached data source', function(done) {
User.create({first: 'joe', age: 100}, function (err, user) { User.create({first: 'joe', age: 100}, function(err, user) {
assert(!err); assert(!err);
assert.equal(user.first, 'joe'); assert.equal(user.first, 'joe');
user.updateAttributes({ user.updateAttributes({
first: 'updatedFirst', first: 'updatedFirst',
last: 'updatedLast' last: 'updatedLast'
}, function (err, updatedUser) { }, function(err, updatedUser) {
assert(!err); assert(!err);
assert.equal(updatedUser.first, 'updatedFirst'); assert.equal(updatedUser.first, 'updatedFirst');
assert.equal(updatedUser.last, 'updatedLast'); assert.equal(updatedUser.last, 'updatedLast');
@ -169,11 +170,11 @@ describe('Model Tests', function() {
describe('Model.upsert(data, callback)', function() { describe('Model.upsert(data, callback)', function() {
it('Update when record with id=data.id found, insert otherwise', function(done) { it('Update when record with id=data.id found, insert otherwise', function(done) {
User.upsert({first: 'joe', id: 7}, function (err, user) { User.upsert({first: 'joe', id: 7}, function(err, user) {
assert(!err); assert(!err);
assert.equal(user.first, 'joe'); assert.equal(user.first, 'joe');
User.upsert({first: 'bob', id: 7}, function (err, updatedUser) { User.upsert({first: 'bob', id: 7}, function(err, updatedUser) {
assert(!err); assert(!err);
assert.equal(updatedUser.first, 'bob'); assert.equal(updatedUser.first, 'bob');
done(); done();
@ -184,11 +185,11 @@ describe('Model Tests', function() {
describe('model.destroy([callback])', function() { describe('model.destroy([callback])', function() {
it('Remove a model from the attached data source', function(done) { it('Remove a model from the attached data source', function(done) {
User.create({first: 'joe', last: 'bob'}, function (err, user) { User.create({first: 'joe', last: 'bob'}, function(err, user) {
User.findById(user.id, function (err, foundUser) { User.findById(user.id, function(err, foundUser) {
assert.equal(user.id, foundUser.id); assert.equal(user.id, foundUser.id);
foundUser.destroy(function () { foundUser.destroy(function() {
User.findById(user.id, function (err, notFound) { User.findById(user.id, function(err, notFound) {
assert.equal(notFound, null); assert.equal(notFound, null);
done(); done();
}); });
@ -198,11 +199,11 @@ describe('Model Tests', function() {
}); });
}); });
describe('Model.deleteById(id, [callback])', function () { describe('Model.deleteById(id, [callback])', function() {
it('Delete a model instance from the attached data source', function (done) { it('Delete a model instance from the attached data source', function(done) {
User.create({first: 'joe', last: 'bob'}, function (err, user) { User.create({first: 'joe', last: 'bob'}, function(err, user) {
User.deleteById(user.id, function (err) { User.deleteById(user.id, function(err) {
User.findById(user.id, function (err, notFound) { User.findById(user.id, function(err, notFound) {
assert.equal(notFound, null); assert.equal(notFound, null);
done(); done();
}); });
@ -213,8 +214,8 @@ describe('Model Tests', function() {
describe('Model.findById(id, callback)', function() { describe('Model.findById(id, callback)', function() {
it('Find an instance by id', function(done) { it('Find an instance by id', function(done) {
User.create({first: 'michael', last: 'jordan', id: 23}, function () { User.create({first: 'michael', last: 'jordan', id: 23}, function() {
User.findById(23, function (err, user) { User.findById(23, function(err, user) {
assert.equal(user.id, 23); assert.equal(user.id, 23);
assert.equal(user.first, 'michael'); assert.equal(user.first, 'michael');
assert.equal(user.last, 'jordan'); assert.equal(user.last, 'jordan');
@ -232,8 +233,8 @@ describe('Model Tests', function() {
.task(User, 'create', {first: 'jan'}) .task(User, 'create', {first: 'jan'})
.task(User, 'create', {first: 'sam'}) .task(User, 'create', {first: 'sam'})
.task(User, 'create', {first: 'suzy'}) .task(User, 'create', {first: 'suzy'})
.on('done', function () { .on('done', function() {
User.count({age: {gt: 99}}, function (err, count) { User.count({age: {gt: 99}}, function(err, count) {
assert.equal(count, 2); assert.equal(count, 2);
done(); done();
}); });
@ -241,6 +242,6 @@ describe('Model Tests', function() {
}); });
}); });
}); });
}; };