不要怂,就是干,撸起袖子干!

Commit a3e737cd by Mick Hansen

Merge pull request #2762 from mbroadst/lint-tests

clean and lint tests, enable jshint on tests
2 parents 4e107803 6afabd46
Showing with 1112 additions and 1102 deletions
...@@ -26,7 +26,7 @@ test-only: ...@@ -26,7 +26,7 @@ test-only:
./node_modules/mocha/bin/mocha --globals setImmediate,clearImmediate --check-leaks --colors -t 10000 --reporter $(REPORTER) $(TESTS); \ ./node_modules/mocha/bin/mocha --globals setImmediate,clearImmediate --check-leaks --colors -t 10000 --reporter $(REPORTER) $(TESTS); \
jshint: jshint:
./node_modules/.bin/jshint lib ./node_modules/.bin/jshint lib test
cover: cover:
rm -rf coverage \ rm -rf coverage \
......
'use strict';
module.exports = function(sequelize, DataTypes) { module.exports = function(sequelize, DataTypes) {
return sequelize.define('Project' + parseInt(Math.random() * 9999999999999999), { return sequelize.define('Project' + parseInt(Math.random() * 9999999999999999), {
name: DataTypes.STRING name: DataTypes.STRING
}) });
} };
\ No newline at end of file
"use strict"; 'use strict';
/* jshint camelcase: false, expr: true */ var chai = require('chai')
var chai = require('chai') , expect = chai.expect
, expect = chai.expect , Support = require(__dirname + '/../support')
, Support = require(__dirname + '/../support') , DataTypes = require(__dirname + '/../../lib/data-types')
, DataTypes = require(__dirname + "/../../lib/data-types")
, Sequelize = require('../../index') , Sequelize = require('../../index')
, Promise = Sequelize.Promise , Promise = Sequelize.Promise
, assert = require('assert'); , assert = require('assert');
chai.config.includeStack = true; chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Alias"), function() { describe(Support.getTestDialectTeaser('Alias'), function() {
it('should uppercase the first letter in alias getter, but not in eager loading', function () { it('should uppercase the first letter in alias getter, but not in eager loading', function() {
var User = this.sequelize.define('user', {}) var User = this.sequelize.define('user', {})
, Task = this.sequelize.define('task', {}); , Task = this.sequelize.define('task', {});
User.hasMany(Task, { as: 'assignments', foreignKey: 'userId' }); User.hasMany(Task, { as: 'assignments', foreignKey: 'userId' });
Task.belongsTo(User, { as: 'owner', foreignKey: 'userId' }); Task.belongsTo(User, { as: 'owner', foreignKey: 'userId' });
return this.sequelize.sync({ force: true }).then(function () { return this.sequelize.sync({ force: true }).then(function() {
return User.create({ id: 1 }); return User.create({ id: 1 });
}).then(function (user) { }).then(function(user) {
expect(user.getAssignments).to.be.ok; expect(user.getAssignments).to.be.ok;
return Task.create({ id: 1, userId: 1 }); return Task.create({ id: 1, userId: 1 });
}).then(function (task) { }).then(function(task) {
expect(task.getOwner).to.be.ok; expect(task.getOwner).to.be.ok;
return Promise.all([ return Promise.all([
User.find({ where: { id: 1 }, include: [{model: Task, as: 'assignments'}] }), User.find({ where: { id: 1 }, include: [{model: Task, as: 'assignments'}] }),
Task.find({ where: { id: 1 }, include: [{model: User, as: 'owner'}] }), Task.find({ where: { id: 1 }, include: [{model: User, as: 'owner'}] })
]); ]);
}).spread(function (user, task) { }).spread(function(user, task) {
expect(user.assignments).to.be.ok; expect(user.assignments).to.be.ok;
expect(task.owner).to.be.ok; expect(task.owner).to.be.ok;
}); });
}); });
it('shouldnt touch the passed alias', function () { it('shouldnt touch the passed alias', function() {
var User = this.sequelize.define('user', {}) var User = this.sequelize.define('user', {})
, Task = this.sequelize.define('task', {}); , Task = this.sequelize.define('task', {});
User.hasMany(Task, { as: 'ASSIGNMENTS', foreignKey: 'userId' }); User.hasMany(Task, { as: 'ASSIGNMENTS', foreignKey: 'userId' });
Task.belongsTo(User, { as: 'OWNER', foreignKey: 'userId' }); Task.belongsTo(User, { as: 'OWNER', foreignKey: 'userId' });
return this.sequelize.sync({ force: true }).then(function () { return this.sequelize.sync({ force: true }).then(function() {
return User.create({ id: 1 }); return User.create({ id: 1 });
}).then(function (user){ }).then(function(user) {
expect(user.getASSIGNMENTS).to.be.ok; expect(user.getASSIGNMENTS).to.be.ok;
return Task.create({ id: 1, userId: 1 }); return Task.create({ id: 1, userId: 1 });
}).then(function (task) { }).then(function(task) {
expect(task.getOWNER).to.be.ok; expect(task.getOWNER).to.be.ok;
return Promise.all([ return Promise.all([
User.find({ where: { id: 1 }, include: [{model: Task, as: 'ASSIGNMENTS'}] }), User.find({ where: { id: 1 }, include: [{model: Task, as: 'ASSIGNMENTS'}] }),
Task.find({ where: { id: 1 }, include: [{model: User, as: 'OWNER'}] }), Task.find({ where: { id: 1 }, include: [{model: User, as: 'OWNER'}] })
]); ]);
}).spread(function (user, task) { }).spread(function(user, task) {
expect(user.ASSIGNMENTS).to.be.ok; expect(user.ASSIGNMENTS).to.be.ok;
expect(task.OWNER).to.be.ok; expect(task.OWNER).to.be.ok;
}); });
}); });
it('should allow me to pass my own plural and singular forms to hasMany', function () { it('should allow me to pass my own plural and singular forms to hasMany', function() {
var User = this.sequelize.define('user', {}) var User = this.sequelize.define('user', {})
, Task = this.sequelize.define('task', {}); , Task = this.sequelize.define('task', {});
User.hasMany(Task, { as: { singular: 'task', plural: 'taskz'} }); User.hasMany(Task, { as: { singular: 'task', plural: 'taskz'} });
return this.sequelize.sync({ force: true }).then(function () { return this.sequelize.sync({ force: true }).then(function() {
return User.create({ id: 1 }); return User.create({ id: 1 });
}).then(function (user) { }).then(function(user) {
expect(user.getTaskz).to.be.ok; expect(user.getTaskz).to.be.ok;
expect(user.addTask).to.be.ok; expect(user.addTask).to.be.ok;
expect(user.addTaskz).to.be.ok; expect(user.addTaskz).to.be.ok;
}).then(function () { }).then(function() {
return User.find({ where: { id: 1 }, include: [{model: Task, as: 'taskz'}] }); return User.find({ where: { id: 1 }, include: [{model: Task, as: 'taskz'}] });
}).then(function (user) { }).then(function(user) {
expect(user.taskz).to.be.ok; expect(user.taskz).to.be.ok;
}); });
}); });
it('should allow me to define plural and singular forms on the model', function () { it('should allow me to define plural and singular forms on the model', function() {
var User = this.sequelize.define('user', {}) var User = this.sequelize.define('user', {})
, Task = this.sequelize.define('task', {}, { , Task = this.sequelize.define('task', {}, {
name: { name: {
...@@ -94,15 +93,15 @@ describe(Support.getTestDialectTeaser("Alias"), function() { ...@@ -94,15 +93,15 @@ describe(Support.getTestDialectTeaser("Alias"), function() {
User.hasMany(Task); User.hasMany(Task);
return this.sequelize.sync({ force: true }).then(function () { return this.sequelize.sync({ force: true }).then(function() {
return User.create({ id: 1 }); return User.create({ id: 1 });
}).then(function (user) { }).then(function(user) {
expect(user.getAssignments).to.be.ok; expect(user.getAssignments).to.be.ok;
expect(user.addAssignment).to.be.ok; expect(user.addAssignment).to.be.ok;
expect(user.addAssignments).to.be.ok; expect(user.addAssignments).to.be.ok;
}).then(function () { }).then(function() {
return User.find({ where: { id: 1 }, include: [Task] }); return User.find({ where: { id: 1 }, include: [Task] });
}).then(function (user) { }).then(function(user) {
expect(user.assignments).to.be.ok; expect(user.assignments).to.be.ok;
}); });
}); });
......
/* jshint camelcase: false, expr: true */ 'use strict';
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + "/../../lib/data-types")
chai.config.includeStack = true var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + '/../../lib/data-types');
describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() { chai.config.includeStack = true;
describe(Support.getTestDialectTeaser('Multiple Level Filters'), function() {
it('can filter through belongsTo', function(done) { it('can filter through belongsTo', function(done) {
var User = this.sequelize.define('User', {username: DataTypes.STRING }) var User = this.sequelize.define('User', {username: DataTypes.STRING })
, Task = this.sequelize.define('Task', {title: DataTypes.STRING }) , Task = this.sequelize.define('Task', {title: DataTypes.STRING })
, Project = this.sequelize.define('Project', { title: DataTypes.STRING }) , Project = this.sequelize.define('Project', { title: DataTypes.STRING });
Project.belongsTo(User); Project.belongsTo(User);
User.hasMany(Project) User.hasMany(Project);
Task.belongsTo(Project); Task.belongsTo(Project);
Project.hasMany(Task); Project.hasMany(Task);
...@@ -53,36 +54,35 @@ describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() { ...@@ -53,36 +54,35 @@ describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() {
User User
]} ]}
] ]
}).done(function(err, tasks){ }).done(function(err, tasks) {
expect(err).not.to.be.ok expect(err).not.to.be.ok;
try{ try {
expect(tasks.length).to.be.equal(2); expect(tasks.length).to.be.equal(2);
expect(tasks[0].title).to.be.equal('fight empire'); expect(tasks[0].title).to.be.equal('fight empire');
expect(tasks[1].title).to.be.equal('stablish republic'); expect(tasks[1].title).to.be.equal('stablish republic');
done(); done();
}catch(e){ }catch (e) {
done(e); done(e);
} }
}) });
}); });
}); });
}); });
}) });
}) });
it('avoids duplicated tables in query', function(done) { it('avoids duplicated tables in query', function(done) {
var User = this.sequelize.define('User', {username: DataTypes.STRING }) var User = this.sequelize.define('User', {username: DataTypes.STRING })
, Task = this.sequelize.define('Task', {title: DataTypes.STRING }) , Task = this.sequelize.define('Task', {title: DataTypes.STRING })
, Project = this.sequelize.define('Project', { title: DataTypes.STRING }) , Project = this.sequelize.define('Project', { title: DataTypes.STRING });
Project.belongsTo(User); Project.belongsTo(User);
User.hasMany(Project) User.hasMany(Project);
Task.belongsTo(Project); Task.belongsTo(Project);
Project.hasMany(Task); Project.hasMany(Task);
this.sequelize.sync({ force: true }).success(function() { this.sequelize.sync({ force: true }).success(function() {
User.bulkCreate([{ User.bulkCreate([{
username: 'leia' username: 'leia'
...@@ -119,29 +119,29 @@ describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() { ...@@ -119,29 +119,29 @@ describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() {
User User
]} ]}
] ]
}).success(function(tasks){ }).success(function(tasks) {
try{ try {
expect(tasks.length).to.be.equal(2); expect(tasks.length).to.be.equal(2);
expect(tasks[0].title).to.be.equal('fight empire'); expect(tasks[0].title).to.be.equal('fight empire');
expect(tasks[1].title).to.be.equal('stablish republic'); expect(tasks[1].title).to.be.equal('stablish republic');
done(); done();
}catch(e){ }catch (e) {
done(e); done(e);
} }
}) });
}); });
}); });
}); });
}) });
}) });
it('can filter through hasMany', function(done) { it('can filter through hasMany', function(done) {
var User = this.sequelize.define('User', {username: DataTypes.STRING }) var User = this.sequelize.define('User', {username: DataTypes.STRING })
, Task = this.sequelize.define('Task', {title: DataTypes.STRING }) , Task = this.sequelize.define('Task', {title: DataTypes.STRING })
, Project = this.sequelize.define('Project', { title: DataTypes.STRING }) , Project = this.sequelize.define('Project', { title: DataTypes.STRING });
Project.belongsTo(User); Project.belongsTo(User);
User.hasMany(Project) User.hasMany(Project);
Task.belongsTo(Project); Task.belongsTo(Project);
Project.hasMany(Task); Project.hasMany(Task);
...@@ -181,27 +181,27 @@ describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() { ...@@ -181,27 +181,27 @@ describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() {
Task Task
]} ]}
] ]
}).done(function(err, users){ }).done(function(err, users) {
try{ try {
expect(users.length).to.be.equal(1); expect(users.length).to.be.equal(1);
expect(users[0].username).to.be.equal('leia'); expect(users[0].username).to.be.equal('leia');
done(); done();
}catch(e){ }catch (e) {
done(e); done(e);
} }
}) });
}); });
}); });
}); });
}) });
}) });
it('can filter through hasMany connector', function(done) { it('can filter through hasMany connector', function(done) {
var User = this.sequelize.define('User', {username: DataTypes.STRING }) var User = this.sequelize.define('User', {username: DataTypes.STRING })
, Project = this.sequelize.define('Project', { title: DataTypes.STRING }) , Project = this.sequelize.define('Project', { title: DataTypes.STRING });
Project.hasMany(User); Project.hasMany(User);
User.hasMany(Project) User.hasMany(Project);
this.sequelize.sync({ force: true }).success(function() { this.sequelize.sync({ force: true }).success(function() {
User.bulkCreate([{ User.bulkCreate([{
...@@ -214,12 +214,12 @@ describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() { ...@@ -214,12 +214,12 @@ describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() {
},{ },{
title: 'empire' title: 'empire'
}]).success(function() { }]).success(function() {
User.find(1).success(function(user){ User.find(1).success(function(user) {
Project.find(1).success(function(project){ Project.find(1).success(function(project) {
user.setProjects([project]).success(function(){ user.setProjects([project]).success(function() {
User.find(2).success(function(user){ User.find(2).success(function(user) {
Project.find(2).success(function(project){ Project.find(2).success(function(project) {
user.setProjects([project]).success(function(){ user.setProjects([project]).success(function() {
User.findAll({ User.findAll({
where: { where: {
'Projects.title': 'republic' 'Projects.title': 'republic'
...@@ -227,15 +227,15 @@ describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() { ...@@ -227,15 +227,15 @@ describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() {
include: [ include: [
{model: Project} {model: Project}
] ]
}).success(function(users){ }).success(function(users) {
try{ try {
expect(users.length).to.be.equal(1); expect(users.length).to.be.equal(1);
expect(users[0].username).to.be.equal('leia'); expect(users[0].username).to.be.equal('leia');
done(); done();
}catch(e){ }catch (e) {
done(e); done(e);
} }
}) });
}); });
}); });
}); });
......
"use strict"; 'use strict';
/* jshint camelcase: false, expr: true */ var chai = require('chai')
var chai = require('chai') , expect = chai.expect
, expect = chai.expect , Support = require(__dirname + '/../support')
, Support = require(__dirname + '/../support') , DataTypes = require(__dirname + '/../../lib/data-types')
, DataTypes = require(__dirname + "/../../lib/data-types") , Sequelize = require(__dirname + '/../../index')
, Sequelize = require(__dirname + "/../../index") , Promise = Sequelize.Promise
, Promise = Sequelize.Promise
, _ = require('lodash'); , _ = require('lodash');
chai.config.includeStack = true; chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Self"), function() { describe(Support.getTestDialectTeaser('Self'), function() {
it('supports freezeTableName', function () { it('supports freezeTableName', function() {
var Group = this.sequelize.define('Group', {}, { var Group = this.sequelize.define('Group', {}, {
tableName: 'user_group', tableName: 'user_group',
timestamps: false, timestamps: false,
...@@ -21,7 +20,7 @@ describe(Support.getTestDialectTeaser("Self"), function() { ...@@ -21,7 +20,7 @@ describe(Support.getTestDialectTeaser("Self"), function() {
}); });
Group.belongsTo(Group, { as: 'Parent', foreignKey: 'parent_id' }); Group.belongsTo(Group, { as: 'Parent', foreignKey: 'parent_id' });
return Group.sync({force: true}).then(function () { return Group.sync({force: true}).then(function() {
return Group.findAll({ return Group.findAll({
include: [{ include: [{
model: Group, model: Group,
...@@ -31,20 +30,20 @@ describe(Support.getTestDialectTeaser("Self"), function() { ...@@ -31,20 +30,20 @@ describe(Support.getTestDialectTeaser("Self"), function() {
}); });
}); });
it('can handle 1:m associations', function () { it('can handle 1:m associations', function() {
var Person = this.sequelize.define('Person', { name: DataTypes.STRING }); var Person = this.sequelize.define('Person', { name: DataTypes.STRING });
Person.hasMany(Person, { as: 'Children', foreignKey: 'parent_id'}); Person.hasMany(Person, { as: 'Children', foreignKey: 'parent_id'});
expect(Person.rawAttributes.parent_id).to.be.ok; expect(Person.rawAttributes.parent_id).to.be.ok;
return this.sequelize.sync({force: true}).then(function () { return this.sequelize.sync({force: true}).then(function() {
return Promise.all([ return Promise.all([
Person.create({ name: 'Mary' }), Person.create({ name: 'Mary' }),
Person.create({ name: 'John' }), Person.create({ name: 'John' }),
Person.create({ name: 'Chris' }) Person.create({ name: 'Chris' })
]); ]);
}).spread(function (mary, john, chris) { }).spread(function(mary, john, chris) {
return mary.setChildren([john, chris]); return mary.setChildren([john, chris]);
}); });
}); });
...@@ -63,15 +62,15 @@ describe(Support.getTestDialectTeaser("Self"), function() { ...@@ -63,15 +62,15 @@ describe(Support.getTestDialectTeaser("Self"), function() {
expect(foreignIdentifiers.length).to.equal(2); expect(foreignIdentifiers.length).to.equal(2);
expect(rawAttributes.length).to.equal(4); expect(rawAttributes.length).to.equal(4);
expect(foreignIdentifiers).to.have.members([ 'PersonId', 'ChildId' ]); expect(foreignIdentifiers).to.have.members(['PersonId', 'ChildId']);
expect(rawAttributes).to.have.members([ 'createdAt', 'updatedAt', 'PersonId', 'ChildId' ]); expect(rawAttributes).to.have.members(['createdAt', 'updatedAt', 'PersonId', 'ChildId']);
return this.sequelize.sync({ force: true }).then(function() { return this.sequelize.sync({ force: true }).then(function() {
return self.sequelize.Promise.all([ return self.sequelize.Promise.all([
Person.create({ name: 'Mary' }), Person.create({ name: 'Mary' }),
Person.create({ name: 'John' }), Person.create({ name: 'John' }),
Person.create({ name: 'Chris' }) Person.create({ name: 'Chris' })
]).spread(function (mary, john, chris) { ]).spread(function(mary, john, chris) {
return mary.setParents([john]).then(function() { return mary.setParents([john]).then(function() {
return chris.addParent(john); return chris.addParent(john);
}).then(function() { }).then(function() {
...@@ -105,8 +104,8 @@ describe(Support.getTestDialectTeaser("Self"), function() { ...@@ -105,8 +104,8 @@ describe(Support.getTestDialectTeaser("Self"), function() {
expect(foreignIdentifiers.length).to.equal(2); expect(foreignIdentifiers.length).to.equal(2);
expect(rawAttributes.length).to.equal(2); expect(rawAttributes.length).to.equal(2);
expect(foreignIdentifiers).to.have.members([ 'preexisting_parent', 'preexisting_child' ]); expect(foreignIdentifiers).to.have.members(['preexisting_parent', 'preexisting_child']);
expect(rawAttributes).to.have.members([ 'preexisting_parent', 'preexisting_child' ]); expect(rawAttributes).to.have.members(['preexisting_parent', 'preexisting_child']);
return this.sequelize.sync({ force: true }).bind(this).then(function() { return this.sequelize.sync({ force: true }).bind(this).then(function() {
return Promise.all([ return Promise.all([
...@@ -114,7 +113,7 @@ describe(Support.getTestDialectTeaser("Self"), function() { ...@@ -114,7 +113,7 @@ describe(Support.getTestDialectTeaser("Self"), function() {
Person.create({ name: 'John' }), Person.create({ name: 'John' }),
Person.create({ name: 'Chris' }) Person.create({ name: 'Chris' })
]); ]);
}).spread(function (mary, john, chris) { }).spread(function(mary, john, chris) {
this.mary = mary; this.mary = mary;
this.chris = chris; this.chris = chris;
this.john = john; this.john = john;
...@@ -124,14 +123,14 @@ describe(Support.getTestDialectTeaser("Self"), function() { ...@@ -124,14 +123,14 @@ describe(Support.getTestDialectTeaser("Self"), function() {
expect(sql).to.have.string('preexisting_parent'); expect(sql).to.have.string('preexisting_parent');
} }
}); });
}).then(function () { }).then(function() {
return this.mary.addParent(this.chris).on('sql', function(sql) { return this.mary.addParent(this.chris).on('sql', function(sql) {
if (sql.match(/INSERT/)) { if (sql.match(/INSERT/)) {
expect(sql).to.have.string('preexisting_child'); expect(sql).to.have.string('preexisting_child');
expect(sql).to.have.string('preexisting_parent'); expect(sql).to.have.string('preexisting_parent');
} }
}); });
}).then(function () { }).then(function() {
return this.john.getChildren().on('sql', function(sql) { return this.john.getChildren().on('sql', function(sql) {
var whereClause = sql.split('FROM')[1]; // look only in the whereClause var whereClause = sql.split('FROM')[1]; // look only in the whereClause
expect(whereClause).to.have.string('preexisting_child'); expect(whereClause).to.have.string('preexisting_child');
......
'use strict';
module.exports = { module.exports = {
username: process.env.SEQ_USER || "root", username: process.env.SEQ_USER || "root",
password: process.env.SEQ_PW || null, password: process.env.SEQ_PW || null,
......
var path = require('path') var path = require('path');
module.exports = { module.exports = {
configFile: path.resolve('config', 'database.json'), configFile: path.resolve('config', 'database.json'),
migrationsPath: path.resolve('db', 'migrate') migrationsPath: path.resolve('db', 'migrate')
} };
var chai = require('chai') 'use strict';
, expect = chai.expect
, config = require(__dirname + "/config/config")
, Support = require(__dirname + '/support')
, dialect = Support.getTestDialect()
, Sequelize = require(__dirname + '/../index')
chai.config.includeStack = true var chai = require('chai')
, expect = chai.expect
, config = require(__dirname + '/config/config')
, Support = require(__dirname + '/support')
, dialect = Support.getTestDialect()
, Sequelize = require(__dirname + '/../index');
describe(Support.getTestDialectTeaser("Configuration"), function() { chai.config.includeStack = true;
describe(Support.getTestDialectTeaser('Configuration'), function() {
describe('Connections problems should fail with a nice message', function() { describe('Connections problems should fail with a nice message', function() {
it("when we don't have the correct server details", function() { it("when we don't have the correct server details", function() {
if (dialect === 'mariadb') { if (dialect === 'mariadb') {
console.log('This dialect doesn\'t support me :(') console.log('This dialect doesn\'t support me :(');
expect(true).to.be.true // Silence Buster expect(true).to.be.true; // Silence Buster
return; return;
} }
var seq = new Sequelize(config[dialect].database, config[dialect].username, config[dialect].password, {storage: '/path/to/no/where/land', logging: false, host: '0.0.0.1', port: config[dialect].port, dialect: dialect}) var seq = new Sequelize(config[dialect].database, config[dialect].username, config[dialect].password, {storage: '/path/to/no/where/land', logging: false, host: '0.0.0.1', port: config[dialect].port, dialect: dialect});
if (dialect === 'sqlite') { if (dialect === 'sqlite') {
// SQLite doesn't have a breakdown of error codes, so we are unable to discern between the different types of errors. // SQLite doesn't have a breakdown of error codes, so we are unable to discern between the different types of errors.
return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith(seq.ConnectionError, 'SQLITE_CANTOPEN: unable to open database file') return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith(seq.ConnectionError, 'SQLITE_CANTOPEN: unable to open database file');
} else if (dialect === 'mssql') { } else if (dialect === 'mssql') {
return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith([seq.HostNotReachableError, seq.InvalidConnectionError]); return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith([seq.HostNotReachableError, seq.InvalidConnectionError]);
} else { } else {
return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith(seq.InvalidConnectionError, 'connect EINVAL') return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith(seq.InvalidConnectionError, 'connect EINVAL');
} }
}) });
it('when we don\'t have the correct login information', function() { it('when we don\'t have the correct login information', function() {
if (dialect === 'mariadb') { if (dialect === 'mariadb') {
console.log('This dialect doesn\'t support me :(') console.log('This dialect doesn\'t support me :(');
expect(true).to.be.true // Silence Buster expect(true).to.be.true; // Silence Buster
return; return;
} }
...@@ -41,86 +43,86 @@ describe(Support.getTestDialectTeaser("Configuration"), function() { ...@@ -41,86 +43,86 @@ describe(Support.getTestDialectTeaser("Configuration"), function() {
return; return;
} }
var seq = new Sequelize(config[dialect].database, config[dialect].username, 'fakepass123', {logging: false, host: config[dialect].host, port: 1, dialect: dialect}) var seq = new Sequelize(config[dialect].database, config[dialect].username, 'fakepass123', {logging: false, host: config[dialect].host, port: 1, dialect: dialect});
if (dialect === 'sqlite') { if (dialect === 'sqlite') {
// SQLite doesn't require authentication and `select 1 as hello` is a valid query, so this should be fulfilled not rejected for it. // SQLite doesn't require authentication and `select 1 as hello` is a valid query, so this should be fulfilled not rejected for it.
return expect(seq.query('select 1 as hello')).to.eventually.be.fulfilled return expect(seq.query('select 1 as hello')).to.eventually.be.fulfilled;
} else { } else {
return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith(seq.ConnectionRefusedError, 'connect ECONNREFUSED') return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith(seq.ConnectionRefusedError, 'connect ECONNREFUSED');
} }
}) });
it('when we don\'t have a valid dialect.', function(done) { it('when we don\'t have a valid dialect.', function(done) {
expect(function() { expect(function() {
new Sequelize(config[dialect].database, config[dialect].username, config[dialect].password, {host: '0.0.0.1', port: config[dialect].port, dialect: undefined}) new Sequelize(config[dialect].database, config[dialect].username, config[dialect].password, {host: '0.0.0.1', port: config[dialect].port, dialect: undefined});
}).to.throw(Error, 'The dialect undefined is not supported.') }).to.throw(Error, 'The dialect undefined is not supported.');
done() done();
}) });
}) });
describe('Instantiation with a URL string', function() { describe('Instantiation with a URL string', function() {
it('should accept username, password, host, port, and database', function() { it('should accept username, password, host, port, and database', function() {
var sequelize = new Sequelize('mysql://user:pass@example.com:9821/dbname') var sequelize = new Sequelize('mysql://user:pass@example.com:9821/dbname');
var config = sequelize.config var config = sequelize.config;
var options = sequelize.options var options = sequelize.options;
expect(options.dialect).to.equal('mysql') expect(options.dialect).to.equal('mysql');
expect(config.database).to.equal('dbname') expect(config.database).to.equal('dbname');
expect(config.host).to.equal('example.com') expect(config.host).to.equal('example.com');
expect(config.username).to.equal('user') expect(config.username).to.equal('user');
expect(config.password).to.equal('pass') expect(config.password).to.equal('pass');
expect(config.port).to.equal('9821') expect(config.port).to.equal('9821');
}) });
it('should work with no authentication options', function(done) { it('should work with no authentication options', function(done) {
var sequelize = new Sequelize('mysql://example.com:9821/dbname') var sequelize = new Sequelize('mysql://example.com:9821/dbname');
var config = sequelize.config var config = sequelize.config;
expect(config.username).to.not.be.ok expect(config.username).to.not.be.ok;
expect(config.password).to.be.null expect(config.password).to.be.null;
done() done();
}) });
it('should use the default port when no other is specified', function() { it('should use the default port when no other is specified', function() {
var sequelize = new Sequelize('dbname', 'root', 'pass', { var sequelize = new Sequelize('dbname', 'root', 'pass', {
dialect: dialect dialect: dialect
}) })
, config = sequelize.config , config = sequelize.config
, port , port;
if (Support.dialectIsMySQL()) { if (Support.dialectIsMySQL()) {
port = 3306 port = 3306;
} else if (dialect === "postgres" || dialect === "postgres-native") { } else if (dialect === 'postgres' || dialect === 'postgres-native') {
port = 5432 port = 5432;
} else { } else {
// sqlite has no concept of ports when connecting // sqlite has no concept of ports when connecting
return return;
} }
expect(config.port).to.equal(port) expect(config.port).to.equal(port);
}) });
}) });
describe('Intantiation with arguments', function() { describe('Intantiation with arguments', function() {
it('should accept two parameters (database, username)', function(done) { it('should accept two parameters (database, username)', function(done) {
var sequelize = new Sequelize('dbname', 'root') var sequelize = new Sequelize('dbname', 'root');
var config = sequelize.config var config = sequelize.config;
expect(config.database).to.equal('dbname') expect(config.database).to.equal('dbname');
expect(config.username).to.equal('root') expect(config.username).to.equal('root');
done() done();
}) });
it('should accept three parameters (database, username, password)', function(done) { it('should accept three parameters (database, username, password)', function(done) {
var sequelize = new Sequelize('dbname', 'root', 'pass') var sequelize = new Sequelize('dbname', 'root', 'pass');
var config = sequelize.config var config = sequelize.config;
expect(config.database).to.equal('dbname') expect(config.database).to.equal('dbname');
expect(config.username).to.equal('root') expect(config.username).to.equal('root');
expect(config.password).to.equal('pass') expect(config.password).to.equal('pass');
done() done();
}) });
it('should accept four parameters (database, username, password, options)', function(done) { it('should accept four parameters (database, username, password, options)', function(done) {
var sequelize = new Sequelize('dbname', 'root', 'pass', { var sequelize = new Sequelize('dbname', 'root', 'pass', {
...@@ -129,17 +131,17 @@ describe(Support.getTestDialectTeaser("Configuration"), function() { ...@@ -129,17 +131,17 @@ describe(Support.getTestDialectTeaser("Configuration"), function() {
supportBigNumbers: true, supportBigNumbers: true,
bigNumberStrings: true bigNumberStrings: true
} }
}) });
var config = sequelize.config var config = sequelize.config;
expect(config.database).to.equal('dbname') expect(config.database).to.equal('dbname');
expect(config.username).to.equal('root') expect(config.username).to.equal('root');
expect(config.password).to.equal('pass') expect(config.password).to.equal('pass');
expect(config.port).to.equal(999) expect(config.port).to.equal(999);
expect(config.dialectOptions.supportBigNumbers).to.be.true expect(config.dialectOptions.supportBigNumbers).to.be.true;
expect(config.dialectOptions.bigNumberStrings).to.be.true expect(config.dialectOptions.bigNumberStrings).to.be.true;
done() done();
}) });
}) });
}) });
var chai = require('chai') 'use strict';
, expect = chai.expect
var chai = require('chai')
, expect = chai.expect
, Sequelize = require(__dirname + '/../index') , Sequelize = require(__dirname + '/../index')
, Support = require(__dirname + '/support') , Support = require(__dirname + '/support');
chai.config.includeStack = true chai.config.includeStack = true;
describe(Support.getTestDialectTeaser('DataTypes'), function() { describe(Support.getTestDialectTeaser('DataTypes'), function() {
it('should return false when comparing DECIMAL and DECIMAL(10,2)', function(done) { it('should return false when comparing DECIMAL and DECIMAL(10,2)', function(done) {
expect(Sequelize.DECIMAL).to.not.equal(Sequelize.DECIMAL(10,2)) expect(Sequelize.DECIMAL).to.not.equal(Sequelize.DECIMAL(10, 2));
done() done();
}) });
it('DECIMAL(10,2) should be an instance of DECIMAL', function(done) { it('DECIMAL(10,2) should be an instance of DECIMAL', function(done) {
expect(Sequelize.DECIMAL(10,2)).to.be.an.instanceof(Sequelize.DECIMAL) expect(Sequelize.DECIMAL(10, 2)).to.be.an.instanceof(Sequelize.DECIMAL);
done() done();
}) });
it('should return false when comparing FLOAT and FLOAT(11)', function(done) { it('should return false when comparing FLOAT and FLOAT(11)', function(done) {
expect(Sequelize.FLOAT).to.not.equal(Sequelize.FLOAT(11)) expect(Sequelize.FLOAT).to.not.equal(Sequelize.FLOAT(11));
done() done();
}) });
it('FLOAT(11) should be an instance of FLOAT', function(done) { it('FLOAT(11) should be an instance of FLOAT', function(done) {
expect(Sequelize.FLOAT(11)).to.be.an.instanceof(Sequelize.FLOAT) expect(Sequelize.FLOAT(11)).to.be.an.instanceof(Sequelize.FLOAT);
done() done();
}) });
it('should return false when comparing STRING and STRING(4096)', function(done) { it('should return false when comparing STRING and STRING(4096)', function(done) {
expect(Sequelize.STRING).to.not.equal(Sequelize.STRING(4096)) expect(Sequelize.STRING).to.not.equal(Sequelize.STRING(4096));
done() done();
}) });
it('STRING(4096) should be an instance of STRING', function(done) { it('STRING(4096) should be an instance of STRING', function(done) {
expect(Sequelize.STRING(4096)).to.be.an.instanceof(Sequelize.STRING) expect(Sequelize.STRING(4096)).to.be.an.instanceof(Sequelize.STRING);
done() done();
}) });
it('should return false when comparing BIGINT and BIGINT(11)', function(done) { it('should return false when comparing BIGINT and BIGINT(11)', function(done) {
expect(Sequelize.BIGINT).to.not.equal(Sequelize.BIGINT(11)) expect(Sequelize.BIGINT).to.not.equal(Sequelize.BIGINT(11));
done() done();
}) });
it('BIGINT(11) should be an instance of BIGINT', function(done) { it('BIGINT(11) should be an instance of BIGINT', function(done) {
expect(Sequelize.BIGINT(11)).to.be.an.instanceof(Sequelize.BIGINT) expect(Sequelize.BIGINT(11)).to.be.an.instanceof(Sequelize.BIGINT);
done() done();
}) });
var tests = [ var tests = [
[Sequelize.STRING, 'STRING', 'VARCHAR(255)'], [Sequelize.STRING, 'STRING', 'VARCHAR(255)'],
...@@ -70,46 +72,46 @@ describe(Support.getTestDialectTeaser('DataTypes'), function() { ...@@ -70,46 +72,46 @@ describe(Support.getTestDialectTeaser('DataTypes'), function() {
[Sequelize.INTEGER, 'INTEGER', 'INTEGER'], [Sequelize.INTEGER, 'INTEGER', 'INTEGER'],
[Sequelize.INTEGER.UNSIGNED, 'INTEGER.UNSIGNED', 'INTEGER UNSIGNED'], [Sequelize.INTEGER.UNSIGNED, 'INTEGER.UNSIGNED', 'INTEGER UNSIGNED'],
[Sequelize.INTEGER(11), 'INTEGER(11)','INTEGER(11)'], [Sequelize.INTEGER(11), 'INTEGER(11)', 'INTEGER(11)'],
[Sequelize.INTEGER(11).UNSIGNED, 'INTEGER(11).UNSIGNED', 'INTEGER(11) UNSIGNED'], [Sequelize.INTEGER(11).UNSIGNED, 'INTEGER(11).UNSIGNED', 'INTEGER(11) UNSIGNED'],
[Sequelize.INTEGER(11).UNSIGNED.ZEROFILL,'INTEGER(11).UNSIGNED.ZEROFILL','INTEGER(11) UNSIGNED ZEROFILL'], [Sequelize.INTEGER(11).UNSIGNED.ZEROFILL, 'INTEGER(11).UNSIGNED.ZEROFILL', 'INTEGER(11) UNSIGNED ZEROFILL'],
[Sequelize.INTEGER(11).ZEROFILL,'INTEGER(11).ZEROFILL', 'INTEGER(11) ZEROFILL'], [Sequelize.INTEGER(11).ZEROFILL, 'INTEGER(11).ZEROFILL', 'INTEGER(11) ZEROFILL'],
[Sequelize.INTEGER(11).ZEROFILL.UNSIGNED,'INTEGER(11).ZEROFILL.UNSIGNED', 'INTEGER(11) UNSIGNED ZEROFILL'], [Sequelize.INTEGER(11).ZEROFILL.UNSIGNED, 'INTEGER(11).ZEROFILL.UNSIGNED', 'INTEGER(11) UNSIGNED ZEROFILL'],
[Sequelize.BIGINT, 'BIGINT', 'BIGINT'], [Sequelize.BIGINT, 'BIGINT', 'BIGINT'],
[Sequelize.BIGINT.UNSIGNED, 'BIGINT.UNSIGNED', 'BIGINT UNSIGNED'], [Sequelize.BIGINT.UNSIGNED, 'BIGINT.UNSIGNED', 'BIGINT UNSIGNED'],
[Sequelize.BIGINT(11), 'BIGINT(11)','BIGINT(11)'], [Sequelize.BIGINT(11), 'BIGINT(11)', 'BIGINT(11)'],
[Sequelize.BIGINT(11).UNSIGNED, 'BIGINT(11).UNSIGNED', 'BIGINT(11) UNSIGNED'], [Sequelize.BIGINT(11).UNSIGNED, 'BIGINT(11).UNSIGNED', 'BIGINT(11) UNSIGNED'],
[Sequelize.BIGINT(11).UNSIGNED.ZEROFILL, 'BIGINT(11).UNSIGNED.ZEROFILL','BIGINT(11) UNSIGNED ZEROFILL'], [Sequelize.BIGINT(11).UNSIGNED.ZEROFILL, 'BIGINT(11).UNSIGNED.ZEROFILL', 'BIGINT(11) UNSIGNED ZEROFILL'],
[Sequelize.BIGINT(11).ZEROFILL, 'BIGINT(11).ZEROFILL', 'BIGINT(11) ZEROFILL'], [Sequelize.BIGINT(11).ZEROFILL, 'BIGINT(11).ZEROFILL', 'BIGINT(11) ZEROFILL'],
[Sequelize.BIGINT(11).ZEROFILL.UNSIGNED, 'BIGINT(11).ZEROFILL.UNSIGNED', 'BIGINT(11) UNSIGNED ZEROFILL'], [Sequelize.BIGINT(11).ZEROFILL.UNSIGNED, 'BIGINT(11).ZEROFILL.UNSIGNED', 'BIGINT(11) UNSIGNED ZEROFILL'],
[Sequelize.FLOAT, 'FLOAT', 'FLOAT'], [Sequelize.FLOAT, 'FLOAT', 'FLOAT'],
[Sequelize.FLOAT.UNSIGNED, 'FLOAT.UNSIGNED', 'FLOAT UNSIGNED'], [Sequelize.FLOAT.UNSIGNED, 'FLOAT.UNSIGNED', 'FLOAT UNSIGNED'],
[Sequelize.FLOAT(11), 'FLOAT(11)','FLOAT(11)'], [Sequelize.FLOAT(11), 'FLOAT(11)', 'FLOAT(11)'],
[Sequelize.FLOAT(11).UNSIGNED, 'FLOAT(11).UNSIGNED', 'FLOAT(11) UNSIGNED'], [Sequelize.FLOAT(11).UNSIGNED, 'FLOAT(11).UNSIGNED', 'FLOAT(11) UNSIGNED'],
[Sequelize.FLOAT(11).UNSIGNED.ZEROFILL,'FLOAT(11).UNSIGNED.ZEROFILL','FLOAT(11) UNSIGNED ZEROFILL'], [Sequelize.FLOAT(11).UNSIGNED.ZEROFILL, 'FLOAT(11).UNSIGNED.ZEROFILL', 'FLOAT(11) UNSIGNED ZEROFILL'],
[Sequelize.FLOAT(11).ZEROFILL,'FLOAT(11).ZEROFILL', 'FLOAT(11) ZEROFILL'], [Sequelize.FLOAT(11).ZEROFILL, 'FLOAT(11).ZEROFILL', 'FLOAT(11) ZEROFILL'],
[Sequelize.FLOAT(11).ZEROFILL.UNSIGNED,'FLOAT(11).ZEROFILL.UNSIGNED', 'FLOAT(11) UNSIGNED ZEROFILL'], [Sequelize.FLOAT(11).ZEROFILL.UNSIGNED, 'FLOAT(11).ZEROFILL.UNSIGNED', 'FLOAT(11) UNSIGNED ZEROFILL'],
[Sequelize.FLOAT(11, 12), 'FLOAT(11,12)','FLOAT(11,12)'], [Sequelize.FLOAT(11, 12), 'FLOAT(11,12)', 'FLOAT(11,12)'],
[Sequelize.FLOAT(11, 12).UNSIGNED, 'FLOAT(11,12).UNSIGNED', 'FLOAT(11,12) UNSIGNED'], [Sequelize.FLOAT(11, 12).UNSIGNED, 'FLOAT(11,12).UNSIGNED', 'FLOAT(11,12) UNSIGNED'],
[Sequelize.FLOAT(11, 12).UNSIGNED.ZEROFILL,'FLOAT(11,12).UNSIGNED.ZEROFILL','FLOAT(11,12) UNSIGNED ZEROFILL'], [Sequelize.FLOAT(11, 12).UNSIGNED.ZEROFILL, 'FLOAT(11,12).UNSIGNED.ZEROFILL', 'FLOAT(11,12) UNSIGNED ZEROFILL'],
[Sequelize.FLOAT(11, 12).ZEROFILL,'FLOAT(11,12).ZEROFILL', 'FLOAT(11,12) ZEROFILL'], [Sequelize.FLOAT(11, 12).ZEROFILL, 'FLOAT(11,12).ZEROFILL', 'FLOAT(11,12) ZEROFILL'],
[Sequelize.FLOAT(11, 12).ZEROFILL.UNSIGNED,'FLOAT(11,12).ZEROFILL.UNSIGNED', 'FLOAT(11,12) UNSIGNED ZEROFILL'], [Sequelize.FLOAT(11, 12).ZEROFILL.UNSIGNED, 'FLOAT(11,12).ZEROFILL.UNSIGNED', 'FLOAT(11,12) UNSIGNED ZEROFILL'],
[Sequelize.DECIMAL, 'DECIMAL', 'DECIMAL'], [Sequelize.DECIMAL, 'DECIMAL', 'DECIMAL'],
[Sequelize.DECIMAL(10,2), 'DECIMAL(10,2)','DECIMAL(10,2)'] [Sequelize.DECIMAL(10, 2), 'DECIMAL(10,2)', 'DECIMAL(10,2)']
] ];
tests.forEach(function(test) { tests.forEach(function(test) {
it('transforms "' + test[1] + '" to "' + test[2] + '"', function(done) { it('transforms "' + test[1] + '" to "' + test[2] + '"', function(done) {
if (Support.getTestDialect() === 'mssql' && test[1] ==='STRING') { if (Support.getTestDialect() === 'mssql' && test[1] === 'STRING') {
test[2] = 'NVARCHAR(255)'; test[2] = 'NVARCHAR(255)';
} }
expect(test[0].toString()).to.equal(test[2]) expect(test[0].toString()).to.equal(test[2]);
done() done();
}) });
}) });
}) });
var chai = require('chai') 'use strict';
, expect = chai.expect
, Support = require(__dirname + '/../../support')
, DataTypes = require(__dirname + "/../../../lib/data-types")
chai.config.includeStack = true var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../../support')
, DataTypes = require(__dirname + '/../../../lib/data-types');
chai.config.includeStack = true;
if (Support.dialectIsMySQL()) { if (Support.dialectIsMySQL()) {
describe('[MYSQL Specific] Associations', function() { describe('[MYSQL Specific] Associations', function() {
describe('many-to-many', function() { describe('many-to-many', function() {
describe('where tables have the same prefix', function() { describe('where tables have the same prefix', function() {
it("should create a table wp_table1wp_table2s", function(done) { it('should create a table wp_table1wp_table2s', function(done) {
var Table2 = this.sequelize.define('wp_table2', {foo: DataTypes.STRING}) var Table2 = this.sequelize.define('wp_table2', {foo: DataTypes.STRING})
, Table1 = this.sequelize.define('wp_table1', {foo: DataTypes.STRING}) , Table1 = this.sequelize.define('wp_table1', {foo: DataTypes.STRING})
, self = this , self = this;
Table1.hasMany(Table2) Table1.hasMany(Table2);
Table2.hasMany(Table1) Table2.hasMany(Table1);
Table1.sync({ force: true }).success(function() { Table1.sync({ force: true }).success(function() {
Table2.sync({ force: true }).success(function() { Table2.sync({ force: true }).success(function() {
expect(self.sequelize.daoFactoryManager.getDAO('wp_table1swp_table2s')).to.exist expect(self.sequelize.daoFactoryManager.getDAO('wp_table1swp_table2s')).to.exist;
done() done();
}) });
}) });
}) });
}) });
describe('when join table name is specified', function() { describe('when join table name is specified', function() {
beforeEach(function(done){ beforeEach(function(done) {
var Table2 = this.sequelize.define('ms_table1', {foo: DataTypes.STRING}) var Table2 = this.sequelize.define('ms_table1', {foo: DataTypes.STRING})
, Table1 = this.sequelize.define('ms_table2', {foo: DataTypes.STRING}) , Table1 = this.sequelize.define('ms_table2', {foo: DataTypes.STRING});
Table1.hasMany(Table2, {joinTableName: 'table1_to_table2'}) Table1.hasMany(Table2, {joinTableName: 'table1_to_table2'});
Table2.hasMany(Table1, {joinTableName: 'table1_to_table2'}) Table2.hasMany(Table1, {joinTableName: 'table1_to_table2'});
Table1.sync({ force: true }).success(function() { Table1.sync({ force: true }).success(function() {
Table2.sync({ force: true }).success(function() { Table2.sync({ force: true }).success(function() {
done() done();
}) });
}) });
}) });
it("should not use only a specified name", function() { it('should not use only a specified name', function() {
expect(this.sequelize.daoFactoryManager.getDAO('ms_table1sms_table2s')).not.to.exist expect(this.sequelize.daoFactoryManager.getDAO('ms_table1sms_table2s')).not.to.exist;
expect(this.sequelize.daoFactoryManager.getDAO('table1_to_table2')).to.exist expect(this.sequelize.daoFactoryManager.getDAO('table1_to_table2')).to.exist;
}) });
}) });
}) });
describe('HasMany', function() { describe('HasMany', function() {
beforeEach(function(done) { beforeEach(function(done) {
//prevent periods from occurring in the table name since they are used to delimit (table.column) //prevent periods from occurring in the table name since they are used to delimit (table.column)
this.User = this.sequelize.define('User' + Math.ceil(Math.random()*10000000), { name: DataTypes.STRING }) this.User = this.sequelize.define('User' + Math.ceil(Math.random() * 10000000), { name: DataTypes.STRING });
this.Task = this.sequelize.define('Task' + Math.ceil(Math.random()*10000000), { name: DataTypes.STRING }) this.Task = this.sequelize.define('Task' + Math.ceil(Math.random() * 10000000), { name: DataTypes.STRING });
this.users = null this.users = null;
this.tasks = null this.tasks = null;
this.User.hasMany(this.Task, {as:'Tasks', through: 'UserTasks'}) this.User.hasMany(this.Task, {as: 'Tasks', through: 'UserTasks'});
this.Task.hasMany(this.User, {as:'Users', through: 'UserTasks'}) this.Task.hasMany(this.User, {as: 'Users', through: 'UserTasks'});
var self = this var self = this
, users = [] , users = []
, tasks = [] , tasks = [];
for (var i = 0; i < 5; ++i) { for (var i = 0; i < 5; ++i) {
users[users.length] = {name: 'User' + Math.random()} users[users.length] = {name: 'User' + Math.random()};
} }
for (var x = 0; x < 5; ++x) { for (var x = 0; x < 5; ++x) {
tasks[tasks.length] = {name: 'Task' + Math.random()} tasks[tasks.length] = {name: 'Task' + Math.random()};
} }
this.sequelize.sync({ force: true }).success(function() { this.sequelize.sync({ force: true }).success(function() {
self.User.bulkCreate(users).success(function() { self.User.bulkCreate(users).success(function() {
self.Task.bulkCreate(tasks).success(function() { self.Task.bulkCreate(tasks).success(function() {
done() done();
}) });
}) });
}) });
}) });
describe('addDAO / getDAO', function() { describe('addDAO / getDAO', function() {
beforeEach(function(done) { beforeEach(function(done) {
var self = this var self = this;
self.user = null self.user = null;
self.task = null self.task = null;
self.User.all().success(function(_users) { self.User.all().success(function(_users) {
self.Task.all().success(function(_tasks) { self.Task.all().success(function(_tasks) {
self.user = _users[0] self.user = _users[0];
self.task = _tasks[0] self.task = _tasks[0];
done() done();
}) });
}) });
}) });
it('should correctly add an association to the dao', function(done) { it('should correctly add an association to the dao', function(done) {
var self = this var self = this;
self.user.getTasks().on('success', function(_tasks) { self.user.getTasks().on('success', function(_tasks) {
expect(_tasks.length).to.equal(0) expect(_tasks.length).to.equal(0);
self.user.addTask(self.task).on('success', function() { self.user.addTask(self.task).on('success', function() {
self.user.getTasks().on('success', function(_tasks) { self.user.getTasks().on('success', function(_tasks) {
expect(_tasks.length).to.equal(1) expect(_tasks.length).to.equal(1);
done() done();
}) });
}) });
}) });
}) });
}) });
describe('removeDAO', function() { describe('removeDAO', function() {
beforeEach(function(done) { beforeEach(function(done) {
var self = this var self = this;
self.user = null self.user = null;
self.tasks = null self.tasks = null;
self.User.all().success(function(_users) { self.User.all().success(function(_users) {
self.Task.all().success(function(_tasks) { self.Task.all().success(function(_tasks) {
self.user = _users[0] self.user = _users[0];
self.tasks = _tasks self.tasks = _tasks;
done() done();
}) });
}) });
}) });
it("should correctly remove associated objects", function(done) { it('should correctly remove associated objects', function(done) {
var self = this var self = this;
self.user.getTasks().on('success', function(__tasks) { self.user.getTasks().on('success', function(__tasks) {
expect(__tasks.length).to.equal(0) expect(__tasks.length).to.equal(0);
self.user.setTasks(self.tasks).on('success', function() { self.user.setTasks(self.tasks).on('success', function() {
self.user.getTasks().on('success', function(_tasks) { self.user.getTasks().on('success', function(_tasks) {
expect(_tasks.length).to.equal(self.tasks.length) expect(_tasks.length).to.equal(self.tasks.length);
self.user.removeTask(self.tasks[0]).on('success', function() { self.user.removeTask(self.tasks[0]).on('success', function() {
self.user.getTasks().on('success', function(_tasks) { self.user.getTasks().on('success', function(_tasks) {
expect(_tasks.length).to.equal(self.tasks.length - 1) expect(_tasks.length).to.equal(self.tasks.length - 1);
self.user.removeTasks([self.tasks[1], self.tasks[2]]).on('success', function() { self.user.removeTasks([self.tasks[1], self.tasks[2]]).on('success', function() {
self.user.getTasks().on('success', function(_tasks) { self.user.getTasks().on('success', function(_tasks) {
expect(_tasks).to.have.length(self.tasks.length - 3) expect(_tasks).to.have.length(self.tasks.length - 3);
done() done();
}) });
}) });
}) });
}) });
}) });
}) });
}) });
}) });
}) });
}) });
}) });
} }
var chai = require('chai') 'use strict';
, expect = chai.expect
, Support = require(__dirname + '/../../support')
, sinon = require('sinon')
, DataTypes = require(__dirname + "/../../../lib/data-types")
chai.config.includeStack = true var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../../support')
, sinon = require('sinon')
, DataTypes = require(__dirname + '/../../../lib/data-types');
chai.config.includeStack = true;
if (Support.dialectIsMySQL()) { if (Support.dialectIsMySQL()) {
describe('[MYSQL Specific] Connector Manager', function() { describe('[MYSQL Specific] Connector Manager', function() {
it('works correctly after being idle', function(done) { it('works correctly after being idle', function(done) {
var User = this.sequelize.define('User', { username: DataTypes.STRING }) var User = this.sequelize.define('User', { username: DataTypes.STRING })
, spy = sinon.spy() , spy = sinon.spy();
User.sync({force: true}).on('success', function() { User.sync({force: true}).on('success', function() {
User.create({username: 'user1'}).on('success', function() { User.create({username: 'user1'}).on('success', function() {
User.count().on('success', function(count) { User.count().on('success', function(count) {
expect(count).to.equal(1) expect(count).to.equal(1);
spy() spy();
setTimeout(function() { setTimeout(function() {
User.count().on('success', function(count) { User.count().on('success', function(count) {
expect(count).to.equal(1) expect(count).to.equal(1);
spy() spy();
if (spy.calledTwice) { if (spy.calledTwice) {
done() done();
} }
}) });
}, 1000) }, 1000);
}) });
}) });
}) });
}) });
it('accepts new queries after shutting down a connection', function(done) { it('accepts new queries after shutting down a connection', function(done) {
// Create a sequelize instance with pooling disabled // Create a sequelize instance with pooling disabled
var sequelize = Support.createSequelizeInstance({ pool: false }) var sequelize = Support.createSequelizeInstance({ pool: false });
var User = sequelize.define('User', { username: DataTypes.STRING }) var User = sequelize.define('User', { username: DataTypes.STRING });
User.sync({force: true}).on('success', function() { User.sync({force: true}).on('success', function() {
User.create({username: 'user1'}).on('success', function() { User.create({username: 'user1'}).on('success', function() {
...@@ -43,39 +45,39 @@ if (Support.dialectIsMySQL()) { ...@@ -43,39 +45,39 @@ if (Support.dialectIsMySQL()) {
setTimeout(function() { setTimeout(function() {
// This query will be queued just after the `client.end` is executed and before its callback is called // This query will be queued just after the `client.end` is executed and before its callback is called
sequelize.query('SELECT COUNT(*) AS count FROM Users').on('success', function(count) { sequelize.query('SELECT COUNT(*) AS count FROM Users').on('success', function(count) {
expect(count[0].count).to.equal(1) expect(count[0].count).to.equal(1);
done() done();
}).error(function(error) { }).error(function(error) {
expect(error).to.not.exist expect(error).to.not.exist;
}) });
}, 100) }, 100);
}) });
}) });
}) });
// This should run only on direct mysql // This should run only on direct mysql
if (Support.dialectIsMySQL(true)) { if (Support.dialectIsMySQL(true)) {
it('should maintain connection', function () { it('should maintain connection', function() {
var sequelize = Support.createSequelizeInstance({pool: {min: 1, max: 1, handleDisconnects: true, idle: 5000}}), var sequelize = Support.createSequelizeInstance({pool: {min: 1, max: 1, handleDisconnects: true, idle: 5000}})
cm = sequelize.connectionManager, , cm = sequelize.connectionManager
conn; , conn;
return sequelize.sync() return sequelize.sync()
.then(function () { .then(function() {
return cm.getConnection(); return cm.getConnection();
}) })
.then(function (connection) { .then(function(connection) {
// Save current connection // Save current connection
conn = connection; conn = connection;
}) })
.then(function () { .then(function() {
return cm.releaseConnection(conn); return cm.releaseConnection(conn);
}) })
.then(function () { .then(function() {
// Get next available connection // Get next available connection
return cm.getConnection(); return cm.getConnection();
}) })
.then(function (connection) { .then(function(connection) {
// Old threadId should be different from current new one // Old threadId should be different from current new one
expect(conn.threadId).to.be.equal(connection.threadId); expect(conn.threadId).to.be.equal(connection.threadId);
expect(cm.validate(conn)).to.be.ok; expect(cm.validate(conn)).to.be.ok;
...@@ -83,30 +85,31 @@ if (Support.dialectIsMySQL()) { ...@@ -83,30 +85,31 @@ if (Support.dialectIsMySQL()) {
return cm.releaseConnection(connection); return cm.releaseConnection(connection);
}); });
}); });
it('should work with handleDisconnects', function () {
var sequelize = Support.createSequelizeInstance({pool: {min: 1, max: 1, handleDisconnects: true, idle: 5000}}), it('should work with handleDisconnects', function() {
cm = sequelize.connectionManager, var sequelize = Support.createSequelizeInstance({pool: {min: 1, max: 1, handleDisconnects: true, idle: 5000}})
conn; , cm = sequelize.connectionManager
, conn;
return sequelize.sync() return sequelize.sync()
.then(function (){ .then(function() {
return cm.getConnection(); return cm.getConnection();
}) })
.then(function (connection) { .then(function(connection) {
// Save current connection // Save current connection
conn = connection; conn = connection;
// simulate a unexpected end // simulate a unexpected end
connection._protocol.end(); connection._protocol.end();
}) })
.then(function () { .then(function() {
return cm.releaseConnection(conn); return cm.releaseConnection(conn);
}) })
.then(function () { .then(function() {
// Get next available connection // Get next available connection
return cm.getConnection(); return cm.getConnection();
}) })
.then(function (connection) { .then(function(connection) {
// Old threadId should be different from current new one // Old threadId should be different from current new one
expect(conn.threadId).to.not.be.equal(connection.threadId); expect(conn.threadId).to.not.be.equal(connection.threadId);
expect(cm.validate(conn)).to.not.be.ok; expect(cm.validate(conn)).to.not.be.ok;
......
/* jshint camelcase: false */ 'use strict';
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../../support')
, dialect = Support.getTestDialect()
, hstore = require("../../../lib/dialects/postgres/hstore")
chai.config.includeStack = true var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../../support')
, dialect = Support.getTestDialect()
, hstore = require('../../../lib/dialects/postgres/hstore');
chai.config.includeStack = true;
if (dialect.match(/^postgres/)) { if (dialect.match(/^postgres/)) {
describe('[POSTGRES Specific] hstore', function() { describe('[POSTGRES Specific] hstore', function() {
describe('stringify', function() { describe('stringify', function() {
it('should handle empty objects correctly', function() { it('should handle empty objects correctly', function() {
expect(hstore.stringify({ })).to.equal('') expect(hstore.stringify({ })).to.equal('');
}) });
it('should handle null values correctly', function() { it('should handle null values correctly', function() {
expect(hstore.stringify({ null: null })).to.equal('"null"=>NULL') expect(hstore.stringify({ null: null })).to.equal('"null"=>NULL');
}) });
it('should handle null values correctly', function() { it('should handle null values correctly', function() {
expect(hstore.stringify({ foo: null })).to.equal('"foo"=>NULL') expect(hstore.stringify({ foo: null })).to.equal('"foo"=>NULL');
}) });
it('should handle empty string correctly', function(done) { it('should handle empty string correctly', function(done) {
expect(hstore.stringify({foo : ""})).to.equal('"foo"=>\"\"') expect(hstore.stringify({foo: ''})).to.equal('"foo"=>\"\"');
done() done();
}) });
it('should handle a string with backslashes correctly', function() { it('should handle a string with backslashes correctly', function() {
expect(hstore.stringify({foo : "\\"})).to.equal('"foo"=>"\\\\"') expect(hstore.stringify({foo: '\\'})).to.equal('"foo"=>"\\\\"');
}) });
it('should handle a string with double quotes correctly', function() { it('should handle a string with double quotes correctly', function() {
expect(hstore.stringify({foo : '""a"'})).to.equal('"foo"=>"\\"\\"a\\""') expect(hstore.stringify({foo: '""a"'})).to.equal('"foo"=>"\\"\\"a\\""');
}) });
it('should handle a string with single quotes correctly', function() { it('should handle a string with single quotes correctly', function() {
expect(hstore.stringify({foo : "''a'"})).to.equal('"foo"=>"\'\'\'\'a\'\'"') expect(hstore.stringify({foo: "''a'"})).to.equal('"foo"=>"\'\'\'\'a\'\'"');
}) });
it('should handle simple objects correctly', function() { it('should handle simple objects correctly', function() {
expect(hstore.stringify({ test: 'value' })).to.equal('"test"=>"value"') expect(hstore.stringify({ test: 'value' })).to.equal('"test"=>"value"');
}) });
}) });
describe('parse', function() { describe('parse', function() {
it('should handle a null object correctly', function() { it('should handle a null object correctly', function() {
expect(hstore.parse(null)).to.deep.equal(null) expect(hstore.parse(null)).to.deep.equal(null);
}) });
it('should handle empty string correctly', function() { it('should handle empty string correctly', function() {
expect(hstore.parse('"foo"=>\"\"')).to.deep.equal({foo : ""}) expect(hstore.parse('"foo"=>\"\"')).to.deep.equal({foo: ''});
}) });
it('should handle a string with double quotes correctly', function() { it('should handle a string with double quotes correctly', function() {
expect(hstore.parse('"foo"=>"\\\"\\\"a\\\""')).to.deep.equal({foo : "\"\"a\""}) expect(hstore.parse('"foo"=>"\\\"\\\"a\\\""')).to.deep.equal({foo: '\"\"a\"'});
}) });
it('should handle a string with single quotes correctly', function() { it('should handle a string with single quotes correctly', function() {
expect(hstore.parse('"foo"=>"\'\'\'\'a\'\'"')).to.deep.equal({foo : "''a'"}) expect(hstore.parse('"foo"=>"\'\'\'\'a\'\'"')).to.deep.equal({foo: "''a'"});
}) });
it('should handle a string with backslashes correctly', function() { it('should handle a string with backslashes correctly', function() {
expect(hstore.parse('"foo"=>"\\\\"')).to.deep.equal({foo : "\\"}) expect(hstore.parse('"foo"=>"\\\\"')).to.deep.equal({foo: '\\'});
}) });
it('should handle empty objects correctly', function() { it('should handle empty objects correctly', function() {
expect(hstore.parse('')).to.deep.equal({ }) expect(hstore.parse('')).to.deep.equal({ });
}) });
it('should handle simple objects correctly', function() { it('should handle simple objects correctly', function() {
expect(hstore.parse('"test"=>"value"')).to.deep.equal({ test: 'value' }) expect(hstore.parse('"test"=>"value"')).to.deep.equal({ test: 'value' });
}) });
}) });
describe('stringify and parse', function() { describe('stringify and parse', function() {
it('should stringify then parse back the same structure', function(){ it('should stringify then parse back the same structure', function() {
var testObj = {foo : "bar", count : "1", emptyString : "", quotyString : '""', extraQuotyString : '"""a"""""', backslashes : '\\f023', moreBackslashes : '\\f\\0\\2\\1', backslashesAndQuotes : '\\"\\"uhoh"\\"', nully : null}; var testObj = {foo: 'bar', count: '1', emptyString: '', quotyString: '""', extraQuotyString: '"""a"""""', backslashes: '\\f023', moreBackslashes: '\\f\\0\\2\\1', backslashesAndQuotes: '\\"\\"uhoh"\\"', nully: null};
expect(hstore.parse(hstore.stringify(testObj))).to.deep.equal(testObj); expect(hstore.parse(hstore.stringify(testObj))).to.deep.equal(testObj);
expect(hstore.parse(hstore.stringify(hstore.parse(hstore.stringify(testObj))))).to.deep.equal(testObj); expect(hstore.parse(hstore.stringify(hstore.parse(hstore.stringify(testObj))))).to.deep.equal(testObj);
}) });
}) });
}) });
} }
/* jshint camelcase: false */ 'use strict';
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../../support')
, DataTypes = require(__dirname + "/../../../lib/data-types")
, dialect = Support.getTestDialect()
, dbFile = __dirname + '/test.sqlite'
, storages = [dbFile]
chai.config.includeStack = true var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../../support')
, DataTypes = require(__dirname + '/../../../lib/data-types')
, dialect = Support.getTestDialect()
, dbFile = __dirname + '/test.sqlite'
, storages = [dbFile];
chai.config.includeStack = true;
if (dialect === 'sqlite') { if (dialect === 'sqlite') {
describe('[SQLITE Specific] DAOFactory', function() { describe('[SQLITE Specific] DAOFactory', function() {
after(function(done) { after(function(done) {
this.sequelize.options.storage = ':memory:' this.sequelize.options.storage = ':memory:';
done() done();
}) });
beforeEach(function(done) { beforeEach(function(done) {
this.sequelize.options.storage = dbFile this.sequelize.options.storage = dbFile;
this.User = this.sequelize.define('User', { this.User = this.sequelize.define('User', {
age: DataTypes.INTEGER, age: DataTypes.INTEGER,
name: DataTypes.STRING, name: DataTypes.STRING,
bio: DataTypes.TEXT bio: DataTypes.TEXT
}) });
this.User.sync({ force: true }).success(function() { this.User.sync({ force: true }).success(function() {
done() done();
}) });
}) });
storages.forEach(function(storage) { storages.forEach(function(storage) {
describe('with storage "' + storage + '"', function() { describe('with storage "' + storage + '"', function() {
after(function(done) { after(function(done) {
if (storage === dbFile) { if (storage === dbFile) {
require("fs").writeFile(dbFile, '', function() { require('fs').writeFile(dbFile, '', function() {
done() done();
}) });
} }
}) });
describe('create', function() { describe('create', function() {
it('creates a table entry', function(done) { it('creates a table entry', function(done) {
var self = this var self = this;
this.User.create({ age: 21, name: 'John Wayne', bio: 'noot noot' }).success(function(user) { this.User.create({ age: 21, name: 'John Wayne', bio: 'noot noot' }).success(function(user) {
expect(user.age).to.equal(21) expect(user.age).to.equal(21);
expect(user.name).to.equal('John Wayne') expect(user.name).to.equal('John Wayne');
expect(user.bio).to.equal('noot noot') expect(user.bio).to.equal('noot noot');
self.User.all().success(function(users) { self.User.all().success(function(users) {
var usernames = users.map(function(user) { var usernames = users.map(function(user) {
return user.name return user.name;
}) });
expect(usernames).to.contain('John Wayne') expect(usernames).to.contain('John Wayne');
done() done();
}) });
}) });
}) });
it('should allow the creation of an object with options as attribute', function(done) { it('should allow the creation of an object with options as attribute', function(done) {
var Person = this.sequelize.define('Person', { var Person = this.sequelize.define('Person', {
name: DataTypes.STRING, name: DataTypes.STRING,
options: DataTypes.TEXT options: DataTypes.TEXT
}) });
Person.sync({ force: true }).success(function() { Person.sync({ force: true }).success(function() {
var options = JSON.stringify({ foo: 'bar', bar: 'foo' }) var options = JSON.stringify({ foo: 'bar', bar: 'foo' });
Person.create({ Person.create({
name: 'John Doe', name: 'John Doe',
options: options options: options
}).success(function(people) { }).success(function(people) {
expect(people.options).to.deep.equal(options) expect(people.options).to.deep.equal(options);
done() done();
}) });
}) });
}) });
it('should allow the creation of an object with a boolean (true) as attribute', function(done) { it('should allow the creation of an object with a boolean (true) as attribute', function(done) {
var Person = this.sequelize.define('Person', { var Person = this.sequelize.define('Person', {
name: DataTypes.STRING, name: DataTypes.STRING,
has_swag: DataTypes.BOOLEAN has_swag: DataTypes.BOOLEAN
}) });
Person.sync({ force: true }).success(function() { Person.sync({ force: true }).success(function() {
Person.create({ Person.create({
name: 'John Doe', name: 'John Doe',
has_swag: true has_swag: true
}).success(function(people) { }).success(function(people) {
expect(people.has_swag).to.be.ok expect(people.has_swag).to.be.ok;
done() done();
}) });
}) });
}) });
it('should allow the creation of an object with a boolean (false) as attribute', function(done) { it('should allow the creation of an object with a boolean (false) as attribute', function(done) {
var Person = this.sequelize.define('Person', { var Person = this.sequelize.define('Person', {
name: DataTypes.STRING, name: DataTypes.STRING,
has_swag: DataTypes.BOOLEAN has_swag: DataTypes.BOOLEAN
}) });
Person.sync({ force: true }).success(function() { Person.sync({ force: true }).success(function() {
Person.create({ Person.create({
name: 'John Doe', name: 'John Doe',
has_swag: false has_swag: false
}).success(function(people) { }).success(function(people) {
expect(people.has_swag).to.not.be.ok expect(people.has_swag).to.not.be.ok;
done() done();
}) });
}) });
}) });
}) });
describe('.find', function() { describe('.find', function() {
beforeEach(function(done) { beforeEach(function(done) {
this.User.create({name: 'user', bio: 'footbar'}).success(function() { this.User.create({name: 'user', bio: 'footbar'}).success(function() {
done() done();
}) });
}) });
it("finds normal lookups", function(done) { it('finds normal lookups', function(done) {
this.User.find({ where: { name:'user' } }).success(function(user) { this.User.find({ where: { name: 'user' } }).success(function(user) {
expect(user.name).to.equal('user') expect(user.name).to.equal('user');
done() done();
}) });
}) });
it.skip("should make aliased attributes available", function(done) { it.skip('should make aliased attributes available', function(done) {
this.User.find({ where: { name:'user' }, attributes: ['id', ['name', 'username']] }).success(function(user) { this.User.find({ where: { name: 'user' }, attributes: ['id', ['name', 'username']] }).success(function(user) {
expect(user.username).to.equal('user') expect(user.username).to.equal('user');
done() done();
}) });
}) });
}) });
describe('.all', function() { describe('.all', function() {
beforeEach(function(done) { beforeEach(function(done) {
...@@ -138,54 +139,54 @@ if (dialect === 'sqlite') { ...@@ -138,54 +139,54 @@ if (dialect === 'sqlite') {
{name: 'user', bio: 'foobar'}, {name: 'user', bio: 'foobar'},
{name: 'user', bio: 'foobar'} {name: 'user', bio: 'foobar'}
]).success(function() { ]).success(function() {
done() done();
}) });
}) });
it("should return all users", function(done) { it('should return all users', function(done) {
this.User.all().on('success', function(users) { this.User.all().on('success', function(users) {
expect(users).to.have.length(2) expect(users).to.have.length(2);
done() done();
}) });
}) });
}) });
describe('.min', function() { describe('.min', function() {
it("should return the min value", function(done) { it('should return the min value', function(done) {
var self = this var self = this
, users = [] , users = [];
for (var i = 2; i < 5; i++) { for (var i = 2; i < 5; i++) {
users[users.length] = {age: i} users[users.length] = {age: i};
} }
this.User.bulkCreate(users).success(function() { this.User.bulkCreate(users).success(function() {
self.User.min('age').on('success', function(min) { self.User.min('age').on('success', function(min) {
expect(min).to.equal(2) expect(min).to.equal(2);
done() done();
}) });
}) });
}) });
}) });
describe('.max', function() { describe('.max', function() {
it("should return the max value", function(done) { it('should return the max value', function(done) {
var self = this var self = this
, users = [] , users = [];
for (var i = 2; i <= 5; i++) { for (var i = 2; i <= 5; i++) {
users[users.length] = {age: i} users[users.length] = {age: i};
} }
this.User.bulkCreate(users).success(function() { this.User.bulkCreate(users).success(function() {
self.User.max('age').on('success', function(min) { self.User.max('age').on('success', function(min) {
expect(min).to.equal(5) expect(min).to.equal(5);
done() done();
}) });
}) });
}) });
}) });
}) });
}) });
}) });
} }
var chai = require('chai') 'use strict';
, expect = chai.expect
, Support = require(__dirname + '/../../support')
, DataTypes = require(__dirname + "/../../../lib/data-types")
, dialect = Support.getTestDialect()
chai.config.includeStack = true var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../../support')
, DataTypes = require(__dirname + '/../../../lib/data-types')
, dialect = Support.getTestDialect();
chai.config.includeStack = true;
if (dialect === 'sqlite') { if (dialect === 'sqlite') {
describe('[SQLITE Specific] DAO', function() { describe('[SQLITE Specific] DAO', function() {
beforeEach(function(done) { beforeEach(function(done) {
this.User = this.sequelize.define('User', { this.User = this.sequelize.define('User', {
username: DataTypes.STRING username: DataTypes.STRING
}) });
this.User.sync({ force: true }).success(function() { this.User.sync({ force: true }).success(function() {
done() done();
}) });
}) });
describe('findAll', function() { describe('findAll', function() {
it("handles dates correctly", function(done) { it('handles dates correctly', function(done) {
var self = this var self = this
, user = this.User.build({ username: 'user' }) , user = this.User.build({ username: 'user' });
user.dataValues['createdAt'] = new Date(2011, 04, 04) user.dataValues['createdAt'] = new Date(2011, 4, 4);
user.save().success(function() { user.save().success(function() {
self.User.create({ username: 'new user' }).success(function() { self.User.create({ username: 'new user' }).success(function() {
self.User.findAll({ self.User.findAll({
where: ['createdAt > ?', new Date(2012, 01, 01)] where: ['createdAt > ?', new Date(2012, 1, 1)]
}).success(function(users) { }).success(function(users) {
expect(users).to.have.length(1) expect(users).to.have.length(1);
done() done();
}) });
}) });
}) });
}) });
}) });
}) });
} }
"use strict"; 'use strict';
/* jshint camelcase: false */
var chai = require('chai') var chai = require('chai')
, sinon = require('sinon') , sinon = require('sinon')
, expect = chai.expect , expect = chai.expect
...@@ -10,7 +9,7 @@ var chai = require('chai') ...@@ -10,7 +9,7 @@ var chai = require('chai')
chai.config.includeStack = true; chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Sequelize Errors"), function () { describe(Support.getTestDialectTeaser('Sequelize Errors'), function () {
describe('API Surface', function() { describe('API Surface', function() {
it('Should have the Error constructors exposed', function() { it('Should have the Error constructors exposed', function() {
expect(Sequelize).to.have.property('Error'); expect(Sequelize).to.have.property('Error');
......
...@@ -5332,9 +5332,9 @@ describe(Support.getTestDialectTeaser('Hooks'), function() { ...@@ -5332,9 +5332,9 @@ describe(Support.getTestDialectTeaser('Hooks'), function() {
}); });
}); });
}); });
// NOTE: Reenable when FK constraints create table query is fixed when using hooks // NOTE: Reenable when FK constraints create table query is fixed when using hooks
if (dialect !== "mssql") { if (dialect !== 'mssql') {
describe('multiple 1:M', function () { describe('multiple 1:M', function () {
describe('cascade', function() { describe('cascade', function() {
...@@ -5354,7 +5354,7 @@ describe(Support.getTestDialectTeaser('Hooks'), function() { ...@@ -5354,7 +5354,7 @@ describe(Support.getTestDialectTeaser('Hooks'), function() {
this.Projects.hasMany(this.Tasks, {onDelete: 'cascade', hooks: true}); this.Projects.hasMany(this.Tasks, {onDelete: 'cascade', hooks: true});
this.Projects.hasMany(this.MiniTasks, {onDelete: 'cascade', hooks: true}); this.Projects.hasMany(this.MiniTasks, {onDelete: 'cascade', hooks: true});
this.Tasks.belongsTo(this.Projects, {hooks: true}); this.Tasks.belongsTo(this.Projects, {hooks: true});
this.Tasks.hasMany(this.MiniTasks, {onDelete: 'cascade', hooks: true}); this.Tasks.hasMany(this.MiniTasks, {onDelete: 'cascade', hooks: true});
...@@ -5502,7 +5502,7 @@ describe(Support.getTestDialectTeaser('Hooks'), function() { ...@@ -5502,7 +5502,7 @@ describe(Support.getTestDialectTeaser('Hooks'), function() {
this.Projects.hasMany(this.Tasks, {onDelete: 'cascade', hooks: true}); this.Projects.hasMany(this.Tasks, {onDelete: 'cascade', hooks: true});
this.Projects.hasMany(this.MiniTasks, {onDelete: 'cascade', hooks: true}); this.Projects.hasMany(this.MiniTasks, {onDelete: 'cascade', hooks: true});
this.Tasks.belongsTo(this.Projects, {hooks: true}); this.Tasks.belongsTo(this.Projects, {hooks: true});
this.Tasks.hasMany(this.MiniTasks, {onDelete: 'cascade', hooks: true}); this.Tasks.hasMany(this.MiniTasks, {onDelete: 'cascade', hooks: true});
......
/* jshint camelcase: false */ 'use strict';
/* jshint expr: true */
var chai = require('chai') var chai = require('chai')
, expect = chai.expect , expect = chai.expect
, Support = require(__dirname + '/../support') , Support = require(__dirname + '/../support')
, Sequelize = require(__dirname + '/../../index') , Sequelize = require(__dirname + '/../../index')
, DataTypes = require(__dirname + "/../../lib/data-types") , DataTypes = require(__dirname + '/../../lib/data-types')
, datetime = require('chai-datetime') , datetime = require('chai-datetime')
, async = require('async'); , async = require('async');
chai.use(datetime) chai.use(datetime);
chai.config.includeStack = true chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Include"), function () { describe(Support.getTestDialectTeaser('Include'), function() {
describe('find', function () { describe('find', function() {
it('should include a non required model, with conditions and two includes N:M 1:M', function ( done ) { it('should include a non required model, with conditions and two includes N:M 1:M', function(done ) {
var A = this.sequelize.define('A', { name: DataTypes.STRING(40) }, { paranoid: true }) var A = this.sequelize.define('A', { name: DataTypes.STRING(40) }, { paranoid: true })
, B = this.sequelize.define('B', { name: DataTypes.STRING(40) }, { paranoid: true }) , B = this.sequelize.define('B', { name: DataTypes.STRING(40) }, { paranoid: true })
, C = this.sequelize.define('C', { name: DataTypes.STRING(40) }, { paranoid: true }) , C = this.sequelize.define('C', { name: DataTypes.STRING(40) }, { paranoid: true })
...@@ -24,17 +24,17 @@ describe(Support.getTestDialectTeaser("Include"), function () { ...@@ -24,17 +24,17 @@ describe(Support.getTestDialectTeaser("Include"), function () {
B.belongsTo(D); B.belongsTo(D);
B.hasMany(C, { B.hasMany(C, {
through: 'BC', through: 'BC'
}); });
C.hasMany(B, { C.hasMany(B, {
through: 'BC', through: 'BC'
}); });
D.hasMany(B); D.hasMany(B);
this.sequelize.sync({ force: true }).done(function ( err ) { this.sequelize.sync({ force: true }).done(function(err ) {
expect( err ).not.to.be.ok; expect(err).not.to.be.ok;
A.find({ A.find({
include: [ include: [
...@@ -43,14 +43,14 @@ describe(Support.getTestDialectTeaser("Include"), function () { ...@@ -43,14 +43,14 @@ describe(Support.getTestDialectTeaser("Include"), function () {
{ model: D } { model: D }
]} ]}
] ]
}).done( function ( err ) { }).done(function(err ) {
expect( err ).not.to.be.ok; expect(err).not.to.be.ok;
done(); done();
}); });
}); });
}); });
it('should include a model with a where condition but no required', function () { it('should include a model with a where condition but no required', function() {
var User = this.sequelize.define('User', {}, { paranoid: false }) var User = this.sequelize.define('User', {}, { paranoid: false })
, Task = this.sequelize.define('Task', { , Task = this.sequelize.define('Task', {
deletedAt: { deletedAt: {
...@@ -63,27 +63,27 @@ describe(Support.getTestDialectTeaser("Include"), function () { ...@@ -63,27 +63,27 @@ describe(Support.getTestDialectTeaser("Include"), function () {
return this.sequelize.sync({ return this.sequelize.sync({
force: true force: true
}).then(function () { }).then(function() {
return User.create(); return User.create();
}).then(function (user) { }).then(function(user) {
return Task.bulkCreate([ return Task.bulkCreate([
{userId: user.get('id'), deletedAt: new Date()}, {userId: user.get('id'), deletedAt: new Date()},
{userId: user.get('id'), deletedAt: new Date()}, {userId: user.get('id'), deletedAt: new Date()},
{userId: user.get('id'), deletedAt: new Date()} {userId: user.get('id'), deletedAt: new Date()}
]); ]);
}).then(function () { }).then(function() {
return User.find({ return User.find({
include: [ include: [
{model: Task, where: {deletedAt: null}, required: false} {model: Task, where: {deletedAt: null}, required: false}
] ]
}); });
}).then(function (user) { }).then(function(user) {
expect(user).to.be.ok; expect(user).to.be.ok;
expect(user.Tasks.length).to.equal(0); expect(user.Tasks.length).to.equal(0);
}); });
}); });
it("should still pull the main record when an included model is not required and has where restrictions without matches", function () { it('should still pull the main record when an included model is not required and has where restrictions without matches', function() {
var A = this.sequelize.define('a', { var A = this.sequelize.define('a', {
name: DataTypes.STRING(40) name: DataTypes.STRING(40)
}) })
...@@ -96,12 +96,12 @@ describe(Support.getTestDialectTeaser("Include"), function () { ...@@ -96,12 +96,12 @@ describe(Support.getTestDialectTeaser("Include"), function () {
return this.sequelize return this.sequelize
.sync({force: true}) .sync({force: true})
.then(function () { .then(function() {
return A.create({ return A.create({
name: 'Foobar' name: 'Foobar'
}); });
}) })
.then(function () { .then(function() {
return A.find({ return A.find({
where: {name: 'Foobar'}, where: {name: 'Foobar'},
include: [ include: [
...@@ -109,7 +109,7 @@ describe(Support.getTestDialectTeaser("Include"), function () { ...@@ -109,7 +109,7 @@ describe(Support.getTestDialectTeaser("Include"), function () {
] ]
}); });
}) })
.then(function (a) { .then(function(a) {
expect(a).to.not.equal(null); expect(a).to.not.equal(null);
expect(a.get('bs')).to.deep.equal([]); expect(a.get('bs')).to.deep.equal([]);
}); });
...@@ -136,7 +136,7 @@ describe(Support.getTestDialectTeaser("Include"), function () { ...@@ -136,7 +136,7 @@ describe(Support.getTestDialectTeaser("Include"), function () {
return this.sequelize return this.sequelize
.sync({ force: true }) .sync({ force: true })
.then(function () { .then(function() {
return A.find({ return A.find({
include: [ include: [
{ {
...@@ -149,14 +149,14 @@ describe(Support.getTestDialectTeaser("Include"), function () { ...@@ -149,14 +149,14 @@ describe(Support.getTestDialectTeaser("Include"), function () {
] ]
} }
] ]
}) });
}) })
.then(function (a) { .then(function(a) {
expect(a).to.not.exist; expect(a).to.not.exist;
}); });
}); });
it('should support many levels of belongsTo (with a lower level having a where)', function (done) { it('should support many levels of belongsTo (with a lower level having a where)', function(done) {
var A = this.sequelize.define('a', {}) var A = this.sequelize.define('a', {})
, B = this.sequelize.define('b', {}) , B = this.sequelize.define('b', {})
, C = this.sequelize.define('c', {}) , C = this.sequelize.define('c', {})
...@@ -188,23 +188,23 @@ describe(Support.getTestDialectTeaser("Include"), function () { ...@@ -188,23 +188,23 @@ describe(Support.getTestDialectTeaser("Include"), function () {
H H
]; ];
this.sequelize.sync().done(function () { this.sequelize.sync().done(function() {
async.auto({ async.auto({
a: function (callback) { a: function(callback) {
A.create({}).done(callback); A.create({}).done(callback);
}, },
singleChain: function (callback) { singleChain: function(callback) {
var previousInstance; var previousInstance;
async.eachSeries(singles, function (model, callback) { async.eachSeries(singles, function(model, callback) {
var values = {}; var values = {};
if (model.name === 'g') { if (model.name === 'g') {
values.name = 'yolo'; values.name = 'yolo';
} }
model.create(values).done(function (err, instance) { model.create(values).done(function(err, instance) {
if (previousInstance) { if (previousInstance) {
previousInstance["set"+Sequelize.Utils.uppercaseFirst(model.name)](instance).done(function () { previousInstance['set'+ Sequelize.Utils.uppercaseFirst(model.name)](instance).done(function() {
previousInstance = instance; previousInstance = instance;
callback(); callback();
}); });
...@@ -215,10 +215,10 @@ describe(Support.getTestDialectTeaser("Include"), function () { ...@@ -215,10 +215,10 @@ describe(Support.getTestDialectTeaser("Include"), function () {
}); });
}, callback); }, callback);
}, },
ab: ['a', 'singleChain', function (callback, results) { ab: ['a', 'singleChain', function(callback, results) {
results.a.setB(b).done(callback); results.a.setB(b).done(callback);
}] }]
}, function () { }, function() {
A.find({ A.find({
include: [ include: [
...@@ -238,7 +238,7 @@ describe(Support.getTestDialectTeaser("Include"), function () { ...@@ -238,7 +238,7 @@ describe(Support.getTestDialectTeaser("Include"), function () {
]} ]}
]} ]}
] ]
}).done(function (err, a) { }).done(function(err, a) {
expect(err).not.to.be.ok; expect(err).not.to.be.ok;
expect(a.b.c.d.e.f.g.h).to.be.ok; expect(a.b.c.d.e.f.g.h).to.be.ok;
done(); done();
......
/* jshint camelcase: false */ 'use strict';
/* jshint expr: true */
var chai = require('chai') var chai = require('chai')
, expect = chai.expect , expect = chai.expect
, Support = require(__dirname + '/../support') , Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + "/../../lib/data-types") , DataTypes = require(__dirname + '/../../lib/data-types')
, datetime = require('chai-datetime') , datetime = require('chai-datetime')
, Promise = require('bluebird'); , Promise = require('bluebird');
chai.use(datetime) chai.use(datetime);
chai.config.includeStack = true chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Include"), function () { describe(Support.getTestDialectTeaser('Include'), function() {
describe('findAndCountAll', function () { describe('findAndCountAll', function() {
it( 'Try to include a required model. Result rows should match count', function ( done ) { it('Try to include a required model. Result rows should match count', function(done ) {
var DT = DataTypes, var DT = DataTypes,
S = this.sequelize, S = this.sequelize,
User = S.define('User', { name: DT.STRING(40) }, { paranoid: true }), User = S.define('User', { name: DT.STRING(40) }, { paranoid: true }),
SomeConnection = S.define('SomeConnection', { SomeConnection = S.define('SomeConnection', {
m: DT.STRING(40), m: DT.STRING(40),
fk: DT.INTEGER, fk: DT.INTEGER,
u: DT.INTEGER, u: DT.INTEGER
}, { paranoid: true }), }, { paranoid: true }),
A = S.define('A', { name: DT.STRING(40) }, { paranoid: true }), A = S.define('A', { name: DT.STRING(40) }, { paranoid: true }),
B = S.define('B', { name: DT.STRING(40) }, { paranoid: true }), B = S.define('B', { name: DT.STRING(40) }, { paranoid: true }),
C = S.define('C', { name: DT.STRING(40) }, { paranoid: true }) C = S.define('C', { name: DT.STRING(40) }, { paranoid: true });
// Associate them // Associate them
User.hasMany( SomeConnection, { foreignKey: 'u' }) User.hasMany(SomeConnection, { foreignKey: 'u' });
SomeConnection.belongsTo( User, { foreignKey: 'u' }) SomeConnection.belongsTo(User, { foreignKey: 'u' });
SomeConnection.belongsTo( A, { foreignKey: 'fk', constraints: false }) SomeConnection.belongsTo(A, { foreignKey: 'fk', constraints: false });
SomeConnection.belongsTo( B, { foreignKey: 'fk', constraints: false }) SomeConnection.belongsTo(B, { foreignKey: 'fk', constraints: false });
SomeConnection.belongsTo( C, { foreignKey: 'fk', constraints: false }) SomeConnection.belongsTo(C, { foreignKey: 'fk', constraints: false });
A.hasMany( SomeConnection, { foreignKey: 'fk', constraints: false }) A.hasMany(SomeConnection, { foreignKey: 'fk', constraints: false });
B.hasMany( SomeConnection, { foreignKey: 'fk', constraints: false }) B.hasMany(SomeConnection, { foreignKey: 'fk', constraints: false });
C.hasMany( SomeConnection, { foreignKey: 'fk', constraints: false }) C.hasMany(SomeConnection, { foreignKey: 'fk', constraints: false });
// Sync them // Sync them
S.sync({ force: true }).done( function ( err ) { expect( err ).not.to.be.ok; S.sync({ force: true }).done(function(err ) { expect(err).not.to.be.ok;
// Create an enviroment // Create an enviroment
User.bulkCreate([ User.bulkCreate([
...@@ -48,7 +48,7 @@ describe(Support.getTestDialectTeaser("Include"), function () { ...@@ -48,7 +48,7 @@ describe(Support.getTestDialectTeaser("Include"), function () {
{ name: 'Google' }, { name: 'Google' },
{ name: 'Yahoo' }, { name: 'Yahoo' },
{ name: '404' } { name: '404' }
]).done( function ( err, users ) { expect( err ).not.to.be.ok; expect( users ).to.be.length( 5 ) ]).done(function(err, users ) { expect(err).not.to.be.ok; expect(users).to.be.length(5);
SomeConnection.bulkCreate([ // Lets count, m: A and u: 1 SomeConnection.bulkCreate([ // Lets count, m: A and u: 1
{ u: 1, m: 'A', fk: 1 }, // 1 // Will be deleted { u: 1, m: 'A', fk: 1 }, // 1 // Will be deleted
...@@ -74,32 +74,32 @@ describe(Support.getTestDialectTeaser("Include"), function () { ...@@ -74,32 +74,32 @@ describe(Support.getTestDialectTeaser("Include"), function () {
{ u: 3, m: 'A', fk: 3 }, { u: 3, m: 'A', fk: 3 },
{ u: 2, m: 'B', fk: 2 }, { u: 2, m: 'B', fk: 2 },
{ u: 1, m: 'A', fk: 4 }, // 4 { u: 1, m: 'A', fk: 4 }, // 4
{ u: 4, m: 'A', fk: 2 }, { u: 4, m: 'A', fk: 2 }
]).done( function ( err, conns ) { expect( err ).not.to.be.ok; expect( conns ).to.be.length( 24 ) ]).done(function(err, conns ) { expect(err).not.to.be.ok; expect(conns).to.be.length(24);
A.bulkCreate([ A.bulkCreate([
{ name: 'Just' }, { name: 'Just' },
{ name: 'for' }, { name: 'for' },
{ name: 'testing' }, { name: 'testing' },
{ name: 'proposes' }, { name: 'proposes' },
{ name: 'only' }, { name: 'only' }
]).done( function ( err, as ) { expect( err ).not.to.be.ok; expect( as ).to.be.length( 5 ) ]).done(function(err, as ) { expect(err).not.to.be.ok; expect(as).to.be.length(5);
B.bulkCreate([ B.bulkCreate([
{ name: 'this should not' }, { name: 'this should not' },
{ name: 'be loaded' } { name: 'be loaded' }
]).done( function ( err, bs ) { expect( err ).not.to.be.ok; expect( bs ).to.be.length( 2 ) ]).done(function(err, bs ) { expect(err).not.to.be.ok; expect(bs).to.be.length(2);
C.bulkCreate([ C.bulkCreate([
{ name: 'because we only want A' } { name: 'because we only want A' }
]).done( function ( err, cs ) { expect( err ).not.to.be.ok; expect( cs ).to.be.length( 1 ) ]).done(function(err, cs ) { expect(err).not.to.be.ok; expect(cs).to.be.length(1);
// Delete some of conns to prove the concept // Delete some of conns to prove the concept
SomeConnection.destroy({where: { SomeConnection.destroy({where: {
m: 'A', m: 'A',
u: 1, u: 1,
fk: [ 1, 2 ], fk: [1, 2]
}}).done( function ( err ) { expect( err ).not.to.be.ok }}).done(function(err ) { expect(err).not.to.be.ok;
// Last and most important queries ( we connected 4, but deleted 2, witch means we must get 2 only ) // Last and most important queries ( we connected 4, but deleted 2, witch means we must get 2 only )
A.findAndCountAll({ A.findAndCountAll({
...@@ -112,52 +112,52 @@ describe(Support.getTestDialectTeaser("Include"), function () { ...@@ -112,52 +112,52 @@ describe(Support.getTestDialectTeaser("Include"), function () {
} }
}], }],
limit: 5, limit: 5
}) })
.done( function ( err, result ) { .done(function(err, result ) {
// Test variables // Test variables
expect( err ).not.to.be.ok expect(err).not.to.be.ok;
expect( result.count ).to.be.equal( 2 ) expect(result.count).to.be.equal(2);
expect( result.rows.length ).to.be.equal( 2 ) expect(result.rows.length).to.be.equal(2);
done() done();
// Last and most important queries - END // Last and most important queries - END
}) });
// Delete some of conns to prove the concept - END // Delete some of conns to prove the concept - END
}) });
// Create an enviroment - END // Create an enviroment - END
}) });
}) });
}) });
}) });
}) });
// Sync them - END // Sync them - END
}) });
}) });
it('should count on a where and not use an uneeded include', function () { it('should count on a where and not use an uneeded include', function() {
var Project = this.sequelize.define('Project', { var Project = this.sequelize.define('Project', {
id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true }, id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
project_name: { type: DataTypes.STRING} project_name: { type: DataTypes.STRING}
}) });
var User = this.sequelize.define('User', { var User = this.sequelize.define('User', {
id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true }, id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
user_name: { type: DataTypes.STRING } user_name: { type: DataTypes.STRING }
}) });
User.hasMany(Project); User.hasMany(Project);
var userId = null var userId = null;
return User.sync({force: true}).then(function () { return User.sync({force: true}).then(function() {
return Project.sync({force: true}); return Project.sync({force: true});
}).then(function() { }).then(function() {
return Promise.all([User.create(), Project.create(), Project.create(), Project.create()]); return Promise.all([User.create(), Project.create(), Project.create(), Project.create()]);
...@@ -177,7 +177,7 @@ describe(Support.getTestDialectTeaser("Include"), function () { ...@@ -177,7 +177,7 @@ describe(Support.getTestDialectTeaser("Include"), function () {
}); });
}); });
it("should return the correct count and rows when using a required belongsTo and a limit", function() { it('should return the correct count and rows when using a required belongsTo and a limit', function() {
var s = this.sequelize var s = this.sequelize
, Foo = s.define('Foo', {}) , Foo = s.define('Foo', {})
, Bar = s.define('Bar', {}); , Bar = s.define('Bar', {});
...@@ -196,11 +196,11 @@ describe(Support.getTestDialectTeaser("Include"), function () { ...@@ -196,11 +196,11 @@ describe(Support.getTestDialectTeaser("Include"), function () {
return Foo.findAndCountAll({ return Foo.findAndCountAll({
include: [{ model: Bar, required: true }], include: [{ model: Bar, required: true }],
limit: 2 limit: 2
}).tap(function () { }).tap(function() {
return Foo.findAll({ return Foo.findAll({
include: [{ model: Bar, required: true }], include: [{ model: Bar, required: true }],
limit: 2 limit: 2
}).then(function (items) { }).then(function(items) {
expect(items.length).to.equal(2); expect(items.length).to.equal(2);
}); });
}); });
...@@ -213,4 +213,4 @@ describe(Support.getTestDialectTeaser("Include"), function () { ...@@ -213,4 +213,4 @@ describe(Support.getTestDialectTeaser("Include"), function () {
}); });
}); });
}); });
}); });
\ No newline at end of file
/* jshint camelcase: false */ 'use strict';
/* jshint expr: true */
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + "/../../lib/data-types")
, datetime = require('chai-datetime')
chai.use(datetime) var chai = require('chai')
chai.config.includeStack = true , expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + '/../../lib/data-types')
, datetime = require('chai-datetime');
describe(Support.getTestDialectTeaser("Paranoid"), function () { chai.use(datetime);
chai.config.includeStack = true;
beforeEach(function ( done ) { describe(Support.getTestDialectTeaser('Paranoid'), function() {
beforeEach(function(done ) {
var S = this.sequelize, var S = this.sequelize,
DT = DataTypes, DT = DataTypes,
A = this.A = S.define( 'A', { name: DT.STRING }, { paranoid: true }), A = this.A = S.define('A', { name: DT.STRING }, { paranoid: true }),
B = this.B = S.define( 'B', { name: DT.STRING }, { paranoid: true }), B = this.B = S.define('B', { name: DT.STRING }, { paranoid: true }),
C = this.C = S.define( 'C', { name: DT.STRING }, { paranoid: true }), C = this.C = S.define('C', { name: DT.STRING }, { paranoid: true }),
D = this.D = S.define( 'D', { name: DT.STRING }, { paranoid: true }) D = this.D = S.define('D', { name: DT.STRING }, { paranoid: true });
A.belongsTo( B ) A.belongsTo(B);
A.hasMany( D ) A.hasMany(D);
A.hasMany( C ) A.hasMany(C);
B.hasMany( A ) B.hasMany(A);
B.hasMany( C ) B.hasMany(C);
C.belongsTo( A ) C.belongsTo(A);
C.belongsTo( B ) C.belongsTo(B);
D.hasMany( A ) D.hasMany(A);
S.sync({ force: true }).done(function ( err ) { S.sync({ force: true }).done(function(err ) {
expect( err ).not.to.be.ok expect(err).not.to.be.ok;
done() done();
}) });
}) });
it('paranoid with timestamps: false should be ignored / not crash', function (done) { it('paranoid with timestamps: false should be ignored / not crash', function(done) {
var S = this.sequelize, var S = this.sequelize,
Test = S.define('Test',{ Test = S.define('Test', {
name: DataTypes.STRING name: DataTypes.STRING
},{ },{
timestamps: false, timestamps: false,
paranoid: true paranoid: true
}); });
S.sync({ force: true }).done(function () { S.sync({ force: true }).done(function() {
Test.find(1).done(function ( err ) { Test.find(1).done(function(err ) {
expect( err ).to.be.not.ok expect(err).to.be.not.ok;
done() done();
}) });
}) });
}) });
it( 'test if non required is marked as false', function ( done ) { it('test if non required is marked as false', function(done ) {
var A = this.A, var A = this.A,
B = this.B, B = this.B,
...@@ -66,21 +66,21 @@ describe(Support.getTestDialectTeaser("Paranoid"), function () { ...@@ -66,21 +66,21 @@ describe(Support.getTestDialectTeaser("Paranoid"), function () {
include: [ include: [
{ {
model: B, model: B,
required: false, required: false
} }
], ]
} };
A.find( options ).done(function ( err ) { A.find(options).done(function(err ) {
expect( err ).not.to.be.ok expect(err).not.to.be.ok;
expect( options.include[0].required ).to.be.equal( false ) expect(options.include[0].required).to.be.equal(false);
done() done();
}) });
}) });
it( 'test if required is marked as true', function ( done ) { it('test if required is marked as true', function(done ) {
var A = this.A, var A = this.A,
B = this.B, B = this.B,
...@@ -88,17 +88,17 @@ describe(Support.getTestDialectTeaser("Paranoid"), function () { ...@@ -88,17 +88,17 @@ describe(Support.getTestDialectTeaser("Paranoid"), function () {
include: [ include: [
{ {
model: B, model: B,
required: true, required: true
} }
], ]
} };
A.find( options ).done(function ( err ) { A.find(options).done(function(err ) {
expect( err ).not.to.be.ok expect(err).not.to.be.ok;
expect( options.include[0].required ).to.be.equal( true ) expect(options.include[0].required).to.be.equal(true);
done() done();
}) });
}) });
}) });
\ No newline at end of file
This diff could not be displayed because it is too large.
"use strict"; 'use strict';
/* jshint camelcase: false */ var chai = require('chai')
/* jshint expr: true */
var chai = require('chai')
, Sequelize = require('../../index') , Sequelize = require('../../index')
, Promise = Sequelize.Promise , Promise = Sequelize.Promise
, expect = chai.expect , expect = chai.expect
, Support = require(__dirname + '/../support') , Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + "/../../lib/data-types") , DataTypes = require(__dirname + '/../../lib/data-types')
, dialect = Support.getTestDialect() , dialect = Support.getTestDialect()
, datetime = require('chai-datetime'); , datetime = require('chai-datetime');
chai.use(datetime); chai.use(datetime);
chai.config.includeStack = true; chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Model"), function () { describe(Support.getTestDialectTeaser('Model'), function() {
describe('attributes', function () { describe('attributes', function() {
describe('set', function () { describe('set', function() {
it('should only be called once when used on a join model called with an association getter', function () { it('should only be called once when used on a join model called with an association getter', function() {
var self = this; var self = this;
self.callCount = 0; self.callCount = 0;
this.Student = this.sequelize.define('student', { this.Student = this.sequelize.define('student', {
no: {type:Sequelize.INTEGER, primaryKey:true}, no: {type: Sequelize.INTEGER, primaryKey: true},
name: Sequelize.STRING, name: Sequelize.STRING
}, { }, {
tableName: "student", tableName: 'student',
timestamps: false timestamps: false
}); });
this.Course = this.sequelize.define('course', { this.Course = this.sequelize.define('course', {
no: {type:Sequelize.INTEGER,primaryKey:true}, no: {type: Sequelize.INTEGER, primaryKey: true},
name: Sequelize.STRING, name: Sequelize.STRING
},{ },{
tableName: 'course', tableName: 'course',
timestamps: false timestamps: false
}); });
this.Score = this.sequelize.define('score',{ this.Score = this.sequelize.define('score', {
score: Sequelize.INTEGER, score: Sequelize.INTEGER,
test_value: { test_value: {
type: Sequelize.INTEGER, type: Sequelize.INTEGER,
set: function(v) { set: function(v) {
self.callCount++; self.callCount++;
this.setDataValue('test_value', v+1); this.setDataValue('test_value', v + 1);
} }
} }
}, { }, {
...@@ -54,22 +52,22 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -54,22 +52,22 @@ describe(Support.getTestDialectTeaser("Model"), function () {
this.Student.hasMany(this.Course, {through: this.Score, foreignKey: 'StudentId'}); this.Student.hasMany(this.Course, {through: this.Score, foreignKey: 'StudentId'});
this.Course.hasMany(this.Student, {through: this.Score, foreignKey: 'CourseId'}); this.Course.hasMany(this.Student, {through: this.Score, foreignKey: 'CourseId'});
return this.sequelize.sync({force:true}).then(function () { return this.sequelize.sync({force: true}).then(function() {
return Promise.join( return Promise.join(
self.Student.create({no:1, name:'ryan'}), self.Student.create({no: 1, name: 'ryan'}),
self.Course.create({no:100, name:'history'}) self.Course.create({no: 100, name: 'history'})
).spread(function(student, course){ ).spread(function(student, course) {
return student.addCourse(course, {score: 98, test_value: 1000}); return student.addCourse(course, {score: 98, test_value: 1000});
}).then(function(){ }).then(function() {
expect(self.callCount).to.equal(1); expect(self.callCount).to.equal(1);
return self.Score.find({StudentId: 1, CourseId: 100}).then(function(score){ return self.Score.find({StudentId: 1, CourseId: 100}).then(function(score) {
expect(score.test_value).to.equal(1001); expect(score.test_value).to.equal(1001);
}); });
}) })
.then(function(){ .then(function() {
return Promise.join( return Promise.join(
self.Student.build({no: 1}).getCourses({where: {no: 100}}), self.Student.build({no: 1}).getCourses({where: {no: 100}}),
self.Score.find({StudentId: 1, CourseId:100}) self.Score.find({StudentId: 1, CourseId: 100})
); );
}) })
.spread(function(courses, score) { .spread(function(courses, score) {
......
"use strict"; 'use strict';
/* jshint camelcase: false */ var chai = require('chai')
/* jshint expr: true */
var chai = require('chai')
, Sequelize = require('../../../index') , Sequelize = require('../../../index')
, Promise = Sequelize.Promise , Promise = Sequelize.Promise
, expect = chai.expect , expect = chai.expect
, Support = require(__dirname + '/../../support') , Support = require(__dirname + '/../../support')
, DataTypes = require(__dirname + "/../../../lib/data-types") , DataTypes = require(__dirname + '/../../../lib/data-types')
, dialect = Support.getTestDialect() , dialect = Support.getTestDialect()
, datetime = require('chai-datetime'); , datetime = require('chai-datetime');
chai.use(datetime); chai.use(datetime);
chai.config.includeStack = true; chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Model"), function () { describe(Support.getTestDialectTeaser('Model'), function() {
describe('attributes', function () { describe('attributes', function() {
describe('types', function () { describe('types', function() {
describe('VIRTUAL', function () { describe('VIRTUAL', function() {
beforeEach(function () { beforeEach(function() {
this.User = this.sequelize.define('user', { this.User = this.sequelize.define('user', {
storage: Sequelize.STRING, storage: Sequelize.STRING,
field1: { field1: {
type: Sequelize.VIRTUAL, type: Sequelize.VIRTUAL,
set: function (val) { set: function(val) {
this.setDataValue('storage', val); this.setDataValue('storage', val);
this.setDataValue('field1', val); this.setDataValue('field1', val);
}, },
get: function () { get: function() {
return this.getDataValue('field1'); return this.getDataValue('field1');
} }
}, },
field2: { field2: {
type: Sequelize.VIRTUAL, type: Sequelize.VIRTUAL,
get: function () { get: function() {
return 42; return 42;
} }
}, },
...@@ -58,7 +56,7 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -58,7 +56,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
return this.sequelize.sync({ force: true }); return this.sequelize.sync({ force: true });
}); });
it('should not be ignored in dataValues get', function () { it('should not be ignored in dataValues get', function() {
var user = this.User.build({ var user = this.User.build({
field1: 'field1_value', field1: 'field1_value',
field2: 'field2_value' field2: 'field2_value'
...@@ -67,13 +65,13 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -67,13 +65,13 @@ describe(Support.getTestDialectTeaser("Model"), function () {
expect(user.get()).to.deep.equal({ storage: 'field1_value', field1: 'field1_value', virtualWithDefault: 'cake', field2: 42, id: null }); expect(user.get()).to.deep.equal({ storage: 'field1_value', field1: 'field1_value', virtualWithDefault: 'cake', field2: 42, id: null });
}); });
it('should be ignored in table creation', function () { it('should be ignored in table creation', function() {
return this.sequelize.getQueryInterface().describeTable(this.User.tableName).then(function (fields) { return this.sequelize.getQueryInterface().describeTable(this.User.tableName).then(function(fields) {
expect(Object.keys(fields).length).to.equal(2); expect(Object.keys(fields).length).to.equal(2);
}); });
}); });
it('should be ignored in find, findAll and includes', function () { it('should be ignored in find, findAll and includes', function() {
return Promise.all([ return Promise.all([
this.User.find().on('sql', this.sqlAssert), this.User.find().on('sql', this.sqlAssert),
this.User.findAll().on('sql', this.sqlAssert), this.User.findAll().on('sql', this.sqlAssert),
...@@ -90,7 +88,7 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -90,7 +88,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
]); ]);
}); });
it("should allow me to store selected values", function () { it('should allow me to store selected values', function() {
var Post = this.sequelize.define('Post', { var Post = this.sequelize.define('Post', {
text: Sequelize.TEXT, text: Sequelize.TEXT,
someBoolean: { someBoolean: {
...@@ -98,25 +96,25 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -98,25 +96,25 @@ describe(Support.getTestDialectTeaser("Model"), function () {
} }
}); });
return this.sequelize.sync({ force: true}).then(function () { return this.sequelize.sync({ force: true}).then(function() {
return Post.bulkCreate([{ text: 'text1' },{ text: 'text2' }]); return Post.bulkCreate([{ text: 'text1' },{ text: 'text2' }]);
}).then(function () { }).then(function() {
var boolQuery = 'EXISTS(SELECT 1) AS "someBoolean"'; var boolQuery = 'EXISTS(SELECT 1) AS "someBoolean"';
if (dialect === 'mssql') { if (dialect === 'mssql') {
boolQuery = 'CAST(CASE WHEN EXISTS(SELECT 1) THEN 1 ELSE 0 END AS BIT) AS "someBoolean"'; boolQuery = 'CAST(CASE WHEN EXISTS(SELECT 1) THEN 1 ELSE 0 END AS BIT) AS "someBoolean"';
} }
return Post.find({ attributes: ['id','text', Sequelize.literal(boolQuery)] }); return Post.find({ attributes: ['id', 'text', Sequelize.literal(boolQuery)] });
}).then(function (post) { }).then(function(post) {
expect(post.get('someBoolean')).to.be.ok; expect(post.get('someBoolean')).to.be.ok;
expect(post.get().someBoolean).to.be.ok; expect(post.get().someBoolean).to.be.ok;
}); });
}); });
it('should be ignored in create and updateAttributes', function () { it('should be ignored in create and updateAttributes', function() {
return this.User.create({ return this.User.create({
field1: 'something' field1: 'something'
}).then(function (user) { }).then(function(user) {
// We already verified that the virtual is not added to the table definition, so if this succeeds, were good // We already verified that the virtual is not added to the table definition, so if this succeeds, were good
expect(user.virtualWithDefault).to.equal('cake'); expect(user.virtualWithDefault).to.equal('cake');
...@@ -124,19 +122,19 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -124,19 +122,19 @@ describe(Support.getTestDialectTeaser("Model"), function () {
return user.updateAttributes({ return user.updateAttributes({
field1: 'something else' field1: 'something else'
}); });
}).then(function (user) { }).then(function(user) {
expect(user.virtualWithDefault).to.equal('cake'); expect(user.virtualWithDefault).to.equal('cake');
expect(user.storage).to.equal('something else'); expect(user.storage).to.equal('something else');
}); });
}); });
it('should be ignored in bulkCreate and and bulkUpdate', function () { it('should be ignored in bulkCreate and and bulkUpdate', function() {
var self = this; var self = this;
return this.User.bulkCreate([{ return this.User.bulkCreate([{
field1: 'something' field1: 'something'
}]).on('sql', this.sqlAssert).then(function () { }]).on('sql', this.sqlAssert).then(function() {
return self.User.findAll(); return self.User.findAll();
}).then(function (users) { }).then(function(users) {
expect(users[0].storage).to.equal('something'); expect(users[0].storage).to.equal('something');
}); });
}); });
......
"use strict"; 'use strict';
/* jshint camelcase: false */ var chai = require('chai')
/* jshint expr: true */
var chai = require('chai')
, Sequelize = require('../../index') , Sequelize = require('../../index')
, expect = chai.expect , expect = chai.expect
, Support = require(__dirname + '/../support') , Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + "/../../lib/data-types") , DataTypes = require(__dirname + '/../../lib/data-types')
, datetime = require('chai-datetime'); , datetime = require('chai-datetime');
chai.use(datetime); chai.use(datetime);
chai.config.includeStack = true; chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Model"), function () { describe(Support.getTestDialectTeaser('Model'), function() {
beforeEach(function() { beforeEach(function() {
return Support.prepareTransactionTest(this.sequelize).bind(this).then(function(sequelize) { return Support.prepareTransactionTest(this.sequelize).bind(this).then(function(sequelize) {
this.sequelize = sequelize; this.sequelize = sequelize;
this.User = this.sequelize.define('User', { this.User = this.sequelize.define('User', {
username: DataTypes.STRING, username: DataTypes.STRING,
secretValue: DataTypes.STRING, secretValue: DataTypes.STRING,
data: DataTypes.STRING, data: DataTypes.STRING,
intVal: DataTypes.INTEGER, intVal: DataTypes.INTEGER,
theDate: DataTypes.DATE, theDate: DataTypes.DATE,
aBool: DataTypes.BOOLEAN aBool: DataTypes.BOOLEAN
}); });
return this.User.sync({ force: true }); return this.User.sync({ force: true });
...@@ -78,7 +76,7 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -78,7 +76,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
canBeDan: { canBeDan: {
where: { where: {
username: { username: {
in: 'dan' in : 'dan'
} }
} }
}, },
...@@ -87,12 +85,12 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -87,12 +85,12 @@ describe(Support.getTestDialectTeaser("Model"), function () {
where: { where: {
other_value: value other_value: value
} }
} };
}, },
complexFunction: function(email, accessLevel) { complexFunction: function(email, accessLevel) {
return { return {
where: ['email like ? AND access_level >= ?', email + '%', accessLevel] where: ['email like ? AND access_level >= ?', email + '%', accessLevel]
} };
}, },
lowAccess: { lowAccess: {
where: { where: {
...@@ -120,7 +118,7 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -120,7 +118,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}.bind(this)); }.bind(this));
}); });
it("should be able use where in scope", function() { it('should be able use where in scope', function() {
return this.ScopeMe.scope({where: { parent_id: 2 }}).findAll().then(function(users) { return this.ScopeMe.scope({where: { parent_id: 2 }}).findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array); expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
...@@ -128,7 +126,7 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -128,7 +126,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}); });
}); });
it("should be able to combine scope and findAll where clauses", function() { it('should be able to combine scope and findAll where clauses', function() {
return this.ScopeMe.scope({where: { parent_id: 1 }}).findAll({ where: {access_level: 3}}).then(function(users) { return this.ScopeMe.scope({where: { parent_id: 1 }}).findAll({ where: {access_level: 3}}).then(function(users) {
expect(users).to.be.an.instanceof(Array); expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(2); expect(users.length).to.equal(2);
...@@ -137,10 +135,10 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -137,10 +135,10 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}); });
}); });
it("should have no problems with escaping SQL", function() { it('should have no problems with escaping SQL', function() {
var self = this; var self = this;
return this.ScopeMe.create({username: 'escape\'d', email: 'fake@fakemail.com'}).then(function(){ return this.ScopeMe.create({username: 'escape\'d', email: 'fake@fakemail.com'}).then(function() {
return self.ScopeMe.scope('escape').all().then(function(users){ return self.ScopeMe.scope('escape').all().then(function(users) {
expect(users).to.be.an.instanceof(Array); expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
expect(users[0].username).to.equal('escape\'d'); expect(users[0].username).to.equal('escape\'d');
...@@ -148,18 +146,18 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -148,18 +146,18 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}); });
}); });
it("should be able to use a defaultScope if declared", function() { it('should be able to use a defaultScope if declared', function() {
return this.ScopeMe.all().then(function(users) { return this.ScopeMe.all().then(function(users) {
expect(users).to.be.an.instanceof(Array); expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(2); expect(users.length).to.equal(2);
expect([10,5].indexOf(users[0].access_level) !== -1).to.be.true; expect([10, 5].indexOf(users[0].access_level) !== -1).to.be.true;
expect([10,5].indexOf(users[1].access_level) !== -1).to.be.true; expect([10, 5].indexOf(users[1].access_level) !== -1).to.be.true;
expect(['dan', 'tobi'].indexOf(users[0].username) !== -1).to.be.true; expect(['dan', 'tobi'].indexOf(users[0].username) !== -1).to.be.true;
expect(['dan', 'tobi'].indexOf(users[1].username) !== -1).to.be.true; expect(['dan', 'tobi'].indexOf(users[1].username) !== -1).to.be.true;
}); });
}); });
it("should be able to amend the default scope with a find object", function() { it('should be able to amend the default scope with a find object', function() {
return this.ScopeMe.findAll({where: {username: 'dan'}}).then(function(users) { return this.ScopeMe.findAll({where: {username: 'dan'}}).then(function(users) {
expect(users).to.be.an.instanceof(Array); expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
...@@ -167,7 +165,7 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -167,7 +165,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}); });
}); });
it("should be able to override the default scope", function() { it('should be able to override the default scope', function() {
return this.ScopeMe.scope('fakeEmail').findAll().then(function(users) { return this.ScopeMe.scope('fakeEmail').findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array); expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
...@@ -175,7 +173,7 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -175,7 +173,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}); });
}); });
it("should be able to combine two scopes", function() { it('should be able to combine two scopes', function() {
return this.ScopeMe.scope(['sequelizeTeam', 'highValue']).findAll().then(function(users) { return this.ScopeMe.scope(['sequelizeTeam', 'highValue']).findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array); expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
...@@ -191,7 +189,7 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -191,7 +189,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}); });
}); });
it("should be able to handle multiple function scopes", function() { it('should be able to handle multiple function scopes', function() {
return this.ScopeMe.scope([{method: ['actualValue', 10]}, {method: ['complexFunction', 'dan', '5']}]).findAll().then(function(users) { return this.ScopeMe.scope([{method: ['actualValue', 10]}, {method: ['complexFunction', 'dan', '5']}]).findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array); expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
...@@ -199,7 +197,7 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -199,7 +197,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}); });
}); });
it("should be able to stack the same field in the where clause", function() { it('should be able to stack the same field in the where clause', function() {
return this.ScopeMe.scope(['canBeDan', 'canBeTony']).findAll().then(function(users) { return this.ScopeMe.scope(['canBeDan', 'canBeTony']).findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array); expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(2); expect(users.length).to.equal(2);
...@@ -208,7 +206,7 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -208,7 +206,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}); });
}); });
it("should be able to merge scopes", function() { it('should be able to merge scopes', function() {
return this.ScopeMe.scope(['highValue', 'isTony', {merge: true, method: ['actualValue', 7]}]).findAll().then(function(users) { return this.ScopeMe.scope(['highValue', 'isTony', {merge: true, method: ['actualValue', 7]}]).findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array); expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
...@@ -216,31 +214,31 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -216,31 +214,31 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}); });
}); });
describe("should not overwrite", function () { describe('should not overwrite', function() {
it("default scope with values from previous finds", function () { it('default scope with values from previous finds', function() {
return this.ScopeMe.findAll({ where: { other_value: 10 }}).bind(this).then(function (users) { return this.ScopeMe.findAll({ where: { other_value: 10 }}).bind(this).then(function(users) {
expect(users).to.have.length(1); expect(users).to.have.length(1);
return this.ScopeMe.findAll(); return this.ScopeMe.findAll();
}).then(function (users) { }).then(function(users) {
// This should not have other_value: 10 // This should not have other_value: 10
expect(users).to.have.length(2); expect(users).to.have.length(2);
}); });
}); });
it("other scopes with values from previous finds", function () { it('other scopes with values from previous finds', function() {
return this.ScopeMe.scope('highValue').findAll({ where: { access_level: 10 }}).bind(this).then(function (users) { return this.ScopeMe.scope('highValue').findAll({ where: { access_level: 10 }}).bind(this).then(function(users) {
expect(users).to.have.length(1); expect(users).to.have.length(1);
return this.ScopeMe.scope('highValue').findAll(); return this.ScopeMe.scope('highValue').findAll();
}).then(function (users) { }).then(function(users) {
// This should not have other_value: 10 // This should not have other_value: 10
expect(users).to.have.length(2); expect(users).to.have.length(2);
}); });
}); });
it("function scopes", function () { it('function scopes', function() {
return this.ScopeMe.scope({method: ['actualValue', 11]}).findAll().bind(this).then(function(users) { return this.ScopeMe.scope({method: ['actualValue', 11]}).findAll().bind(this).then(function(users) {
expect(users).to.have.length(1); expect(users).to.have.length(1);
expect(users[0].other_value).to.equal(11); expect(users[0].other_value).to.equal(11);
...@@ -253,7 +251,7 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -253,7 +251,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}); });
}); });
it("should give us the correct order if we declare an order in our scope", function() { it('should give us the correct order if we declare an order in our scope', function() {
return this.ScopeMe.scope('sequelizeTeam', 'orderScope').findAll().then(function(users) { return this.ScopeMe.scope('sequelizeTeam', 'orderScope').findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array); expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(2); expect(users.length).to.equal(2);
...@@ -262,7 +260,7 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -262,7 +260,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}); });
}); });
it("should give us the correct order as well as a limit if we declare such in our scope", function() { it('should give us the correct order as well as a limit if we declare such in our scope', function() {
return this.ScopeMe.scope(['orderScope', 'limitScope']).findAll().then(function(users) { return this.ScopeMe.scope(['orderScope', 'limitScope']).findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array); expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(2); expect(users.length).to.equal(2);
...@@ -271,7 +269,7 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -271,7 +269,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}); });
}); });
it("should have no problems combining scopes and traditional where object", function() { it('should have no problems combining scopes and traditional where object', function() {
return this.ScopeMe.scope('sequelizeTeam').findAll({where: {other_value: 10}}).then(function(users) { return this.ScopeMe.scope('sequelizeTeam').findAll({where: {other_value: 10}}).then(function(users) {
expect(users).to.be.an.instanceof(Array); expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1); expect(users.length).to.equal(1);
...@@ -281,20 +279,20 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -281,20 +279,20 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}); });
}); });
it("should be able to remove all scopes", function() { it('should be able to remove all scopes', function() {
return this.ScopeMe.scope(null).findAll().then(function(users) { return this.ScopeMe.scope(null).findAll().then(function(users) {
expect(users).to.be.an.instanceof(Array); expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(4); expect(users.length).to.equal(4);
}); });
}); });
it("should have no problem performing findOrCreate", function() { it('should have no problem performing findOrCreate', function() {
return this.ScopeMe.findOrCreate({ where: {username: 'fake'}}).spread(function(user) { return this.ScopeMe.findOrCreate({ where: {username: 'fake'}}).spread(function(user) {
expect(user.username).to.equal('fake'); expect(user.username).to.equal('fake');
}); });
}); });
it("should be able to hold multiple scope objects", function() { it('should be able to hold multiple scope objects', function() {
var sequelizeTeam = this.ScopeMe.scope('sequelizeTeam', 'orderScope') var sequelizeTeam = this.ScopeMe.scope('sequelizeTeam', 'orderScope')
, tobi = this.ScopeMe.scope({method: ['actualValue', 11]}); , tobi = this.ScopeMe.scope({method: ['actualValue', 11]});
......
"use strict"; 'use strict';
/* jshint camelcase: false */ var chai = require('chai')
/* jshint expr: true */ , sinon = require('sinon')
var chai = require('chai')
, sinon = require('sinon')
, Sequelize = require('../../index') , Sequelize = require('../../index')
, Promise = Sequelize.Promise , Promise = Sequelize.Promise
, expect = chai.expect , expect = chai.expect
, Support = require(__dirname + '/../support') , Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + "/../../lib/data-types") , DataTypes = require(__dirname + '/../../lib/data-types')
, dialect = Support.getTestDialect() , dialect = Support.getTestDialect()
, datetime = require('chai-datetime') , datetime = require('chai-datetime')
, _ = require('lodash') , _ = require('lodash')
, assert = require('assert') , assert = require('assert')
, current = Support.sequelize; , current = Support.sequelize;
chai.use(datetime); chai.use(datetime);
chai.config.includeStack = true; chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Model"), function () { describe(Support.getTestDialectTeaser('Model'), function() {
beforeEach(function () { beforeEach(function() {
this.clock = sinon.useFakeTimers(); this.clock = sinon.useFakeTimers();
this.User = this.sequelize.define('user', { this.User = this.sequelize.define('user', {
...@@ -31,20 +29,20 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -31,20 +29,20 @@ describe(Support.getTestDialectTeaser("Model"), function () {
bar: { bar: {
unique: 'foobar', unique: 'foobar',
type: DataTypes.INTEGER type: DataTypes.INTEGER
}, }
}); });
return this.sequelize.sync({ force: true }); return this.sequelize.sync({ force: true });
}); });
afterEach(function () { afterEach(function() {
this.clock.restore(); this.clock.restore();
}); });
if (current.dialect.supports.upserts) { if (current.dialect.supports.upserts) {
describe('upsert', function () { describe('upsert', function() {
it('works with upsert on id', function () { it('works with upsert on id', function() {
return this.User.upsert({ id: 42, username: 'john' }).bind(this).then(function (created) { return this.User.upsert({ id: 42, username: 'john' }).bind(this).then(function(created) {
if (dialect === 'sqlite') { if (dialect === 'sqlite') {
expect(created).not.to.be.defined; expect(created).not.to.be.defined;
} else { } else {
...@@ -53,7 +51,7 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -53,7 +51,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
this.clock.tick(2000); // Make sure to pass some time so updatedAt != createdAt this.clock.tick(2000); // Make sure to pass some time so updatedAt != createdAt
return this.User.upsert({ id: 42, username: 'doe' }); return this.User.upsert({ id: 42, username: 'doe' });
}).then(function (created) { }).then(function(created) {
if (dialect === 'sqlite') { if (dialect === 'sqlite') {
expect(created).not.to.be.defined; expect(created).not.to.be.defined;
} else { } else {
...@@ -61,15 +59,15 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -61,15 +59,15 @@ describe(Support.getTestDialectTeaser("Model"), function () {
} }
return this.User.find(42); return this.User.find(42);
}).then(function (user) { }).then(function(user) {
expect(user.createdAt).to.be.defined; expect(user.createdAt).to.be.defined;
expect(user.username).to.equal('doe'); expect(user.username).to.equal('doe');
expect(user.updatedAt).to.be.afterTime(user.createdAt); expect(user.updatedAt).to.be.afterTime(user.createdAt);
}); });
}); });
it('works with upsert on a composite key', function () { it('works with upsert on a composite key', function() {
return this.User.upsert({ foo: 'baz', bar: 19, username: 'john' }).bind(this).then(function (created) { return this.User.upsert({ foo: 'baz', bar: 19, username: 'john' }).bind(this).then(function(created) {
if (dialect === 'sqlite') { if (dialect === 'sqlite') {
expect(created).not.to.be.defined; expect(created).not.to.be.defined;
} else { } else {
...@@ -78,7 +76,7 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -78,7 +76,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
this.clock.tick(2000); // Make sure to pass some time so updatedAt != createdAt this.clock.tick(2000); // Make sure to pass some time so updatedAt != createdAt
return this.User.upsert({ foo: 'baz', bar: 19, username: 'doe' }); return this.User.upsert({ foo: 'baz', bar: 19, username: 'doe' });
}).then(function (created) { }).then(function(created) {
if (dialect === 'sqlite') { if (dialect === 'sqlite') {
expect(created).not.to.be.defined; expect(created).not.to.be.defined;
} else { } else {
...@@ -86,7 +84,7 @@ describe(Support.getTestDialectTeaser("Model"), function () { ...@@ -86,7 +84,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
} }
return this.User.find({ where: { foo: 'baz', bar: 19 }}); return this.User.find({ where: { foo: 'baz', bar: 19 }});
}).then(function (user) { }).then(function(user) {
expect(user.createdAt).to.be.defined; expect(user.createdAt).to.be.defined;
expect(user.username).to.equal('doe'); expect(user.username).to.equal('doe');
expect(user.updatedAt).to.be.afterTime(user.createdAt); expect(user.updatedAt).to.be.afterTime(user.createdAt);
......
/* jshint camelcase: false, expr: true */ 'use strict';
var chai = require('chai')
, expect = chai.expect var chai = require('chai')
, Support = require(__dirname + '/../support') , expect = chai.expect
, DataTypes = require(__dirname + "/../../lib/data-types") , Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + '/../../lib/data-types')
, Sequelize = require('../../index') , Sequelize = require('../../index')
, Promise = Sequelize.Promise , Promise = Sequelize.Promise
, assert = require('assert'); , assert = require('assert');
chai.config.includeStack = true; chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("CounterCache"), function() { describe(Support.getTestDialectTeaser('CounterCache'), function() {
it('adds an integer column', function() { it('adds an integer column', function() {
var User = this.sequelize.define('User', {}) var User = this.sequelize.define('User', {})
, Group = this.sequelize.define('Group', {}); , Group = this.sequelize.define('Group', {});
User.hasMany(Group, { counterCache: true }); User.hasMany(Group, { counterCache: true });
...@@ -21,7 +22,7 @@ describe(Support.getTestDialectTeaser("CounterCache"), function() { ...@@ -21,7 +22,7 @@ describe(Support.getTestDialectTeaser("CounterCache"), function() {
}); });
it('supports `as`', function() { it('supports `as`', function() {
var User = this.sequelize.define('User', {}) var User = this.sequelize.define('User', {})
, Group = this.sequelize.define('Group', {}); , Group = this.sequelize.define('Group', {});
User.hasMany(Group, { counterCache: { as: 'countDemGroups' } }); User.hasMany(Group, { counterCache: { as: 'countDemGroups' } });
...@@ -30,23 +31,23 @@ describe(Support.getTestDialectTeaser("CounterCache"), function() { ...@@ -30,23 +31,23 @@ describe(Support.getTestDialectTeaser("CounterCache"), function() {
}); });
it('inits at 0', function() { it('inits at 0', function() {
var User = this.sequelize.define('User', {}) var User = this.sequelize.define('User', {})
, Group = this.sequelize.define('Group', {}); , Group = this.sequelize.define('Group', {});
User.hasMany(Group, { counterCache: true }); User.hasMany(Group, { counterCache: true });
return this.sequelize.sync({ force: true }).then(function () { return this.sequelize.sync({ force: true }).then(function() {
return User.create(); return User.create();
}).then(function (user) { }).then(function(user) {
expect(user.countGroups).to.equal(0); expect(user.countGroups).to.equal(0);
}); });
}); });
describe('hooks', function () { describe('hooks', function() {
var User, Group; var User, Group;
beforeEach(function() { beforeEach(function() {
User = this.sequelize.define('User', {}); User = this.sequelize.define('User', {});
Group = this.sequelize.define('Group', {}); Group = this.sequelize.define('Group', {});
User.hasMany(Group, { counterCache: true }); User.hasMany(Group, { counterCache: true });
...@@ -55,13 +56,13 @@ describe(Support.getTestDialectTeaser("CounterCache"), function() { ...@@ -55,13 +56,13 @@ describe(Support.getTestDialectTeaser("CounterCache"), function() {
}); });
it('increments', function() { it('increments', function() {
return User.create().then(function (user) { return User.create().then(function(user) {
expect(user.countGroups).to.equal(0); expect(user.countGroups).to.equal(0);
return user.createGroup().return(user); return user.createGroup().return (user);
}).then(function (user) { }).then(function(user) {
return User.find(user.id); return User.find(user.id);
}).then(function (user) { }).then(function(user) {
expect(user.countGroups).to.equal(1); expect(user.countGroups).to.equal(1);
}); });
}); });
...@@ -69,41 +70,41 @@ describe(Support.getTestDialectTeaser("CounterCache"), function() { ...@@ -69,41 +70,41 @@ describe(Support.getTestDialectTeaser("CounterCache"), function() {
it('decrements', function() { it('decrements', function() {
var user; var user;
return User.create().then(function (tmpUser) { return User.create().then(function(tmpUser) {
user = tmpUser; user = tmpUser;
return user.createGroup(); return user.createGroup();
}).then(function (group) { }).then(function(group) {
return group.destroy(); return group.destroy();
}).then(function () { }).then(function() {
return user.reload(); return user.reload();
}).then(function () { }).then(function() {
expect(user.countGroups).to.equal(0); expect(user.countGroups).to.equal(0);
}); });
}); });
it('works on update', function () { it('works on update', function() {
var user, otherUser; var user, otherUser;
return User.create().then(function (tmpUser) { return User.create().then(function(tmpUser) {
otherUser = tmpUser; otherUser = tmpUser;
return User.create(); return User.create();
}).then(function (tmpUser) { }).then(function(tmpUser) {
user = tmpUser; user = tmpUser;
return user.createGroup(); return user.createGroup();
}).tap(function (group) { }).tap(function(group) {
return user.reload(); return user.reload();
}).tap(function () { }).tap(function() {
expect(user.countGroups).to.equal(1); expect(user.countGroups).to.equal(1);
}).then(function (group) { }).then(function(group) {
group.UserId = otherUser.id; group.UserId = otherUser.id;
return group.save(); return group.save();
}).then(function () { }).then(function() {
return Promise.all([user.reload(), otherUser.reload()]); return Promise.all([user.reload(), otherUser.reload()]);
}).then(function () { }).then(function() {
expect(user.countGroups).to.equal(0); expect(user.countGroups).to.equal(0);
expect(otherUser.countGroups).to.equal(1); expect(otherUser.countGroups).to.equal(1);
}); });
}); });
}); });
}) });
...@@ -7,7 +7,7 @@ var chai = require('chai') ...@@ -7,7 +7,7 @@ var chai = require('chai')
chai.config.includeStack = true; chai.config.includeStack = true;
describe(Support.getTestDialectTeaser('Schema'), function () { describe(Support.getTestDialectTeaser('Schema'), function() {
beforeEach(function() { beforeEach(function() {
return this.sequelize.createSchema('testschema'); return this.sequelize.createSchema('testschema');
}); });
...@@ -26,7 +26,7 @@ describe(Support.getTestDialectTeaser('Schema'), function () { ...@@ -26,7 +26,7 @@ describe(Support.getTestDialectTeaser('Schema'), function () {
return this.User.sync({ force: true }); return this.User.sync({ force: true });
}); });
it('supports increment', function () { it('supports increment', function() {
return this.User.create({ aNumber: 1 }).then(function(user) { return this.User.create({ aNumber: 1 }).then(function(user) {
return user.increment('aNumber', { by: 3 }); return user.increment('aNumber', { by: 3 });
}).then(function(result) { }).then(function(result) {
...@@ -37,7 +37,7 @@ describe(Support.getTestDialectTeaser('Schema'), function () { ...@@ -37,7 +37,7 @@ describe(Support.getTestDialectTeaser('Schema'), function () {
}); });
}); });
it('supports decrement', function () { it('supports decrement', function() {
return this.User.create({ aNumber: 10 }).then(function(user) { return this.User.create({ aNumber: 10 }).then(function(user) {
return user.decrement('aNumber', { by: 3 }); return user.decrement('aNumber', { by: 3 });
}).then(function(result) { }).then(function(result) {
......
var chai = require('chai') 'use strict';
, expect = chai.expect
, Support = require(__dirname + '/support')
, Promise = require(__dirname + '/../lib/promise')
, Transaction = require(__dirname + '/../lib/transaction')
, current = Support.sequelize;
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/support')
, Promise = require(__dirname + '/../lib/promise')
, Transaction = require(__dirname + '/../lib/transaction')
, current = Support.sequelize;
if (current.dialect.supports.transactions) { if (current.dialect.supports.transactions) {
describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () { describe(Support.getTestDialectTeaser('Sequelize#transaction'), function() {
this.timeout(4000); this.timeout(4000);
describe('success', function() { describe('success', function() {
it("gets triggered once a transaction has been successfully committed", function(done) { it('gets triggered once a transaction has been successfully committed', function(done) {
this this
.sequelize .sequelize
.transaction().then(function(t) { t.commit(); }) .transaction().then(function(t) { t.commit(); })
.success(function() { done(); }); .success(function() { done(); });
}); });
it("gets triggered once a transaction has been successfully rollbacked", function(done) { it('gets triggered once a transaction has been successfully rollbacked', function(done) {
this this
.sequelize .sequelize
.transaction().then(function(t) { t.rollback(); }) .transaction().then(function(t) { t.rollback(); })
...@@ -35,11 +36,11 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () { ...@@ -35,11 +36,11 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () {
return sequelize.sync({ force: true }).success(function() { return sequelize.sync({ force: true }).success(function() {
return sequelize.transaction(); return sequelize.transaction();
}).then(function (t) { }).then(function(t) {
expect(t).to.be.ok; expect(t).to.be.ok;
var query = 'select sleep(2);'; var query = 'select sleep(2);';
switch(Support.getTestDialect()) { switch (Support.getTestDialect()) {
case 'postgres': case 'postgres':
query = 'select pg_sleep(2);'; query = 'select pg_sleep(2);';
break; break;
...@@ -62,15 +63,15 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () { ...@@ -62,15 +63,15 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () {
.getQueryInterface() .getQueryInterface()
.QueryGenerator .QueryGenerator
.insertQuery(User.tableName, dao.values, User.rawAttributes); .insertQuery(User.tableName, dao.values, User.rawAttributes);
}).then(function () { }).then(function() {
return Promise.delay(1000); return Promise.delay(1000);
}).then(function () { }).then(function() {
return sequelize.query(query, null, { return sequelize.query(query, null, {
raw: true, raw: true,
plain: true, plain: true,
transaction: t transaction: t
}); });
}).then(function () { }).then(function() {
return t.commit(); return t.commit();
}); });
}).then(function() { }).then(function() {
...@@ -79,7 +80,7 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () { ...@@ -79,7 +80,7 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () {
expect(users[0].name).to.equal('foo'); expect(users[0].name).to.equal('foo');
done(); done();
}); });
}).catch(done); }).catch (done);
}); });
}); });
} }
...@@ -90,7 +91,7 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () { ...@@ -90,7 +91,7 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () {
// not sure if we can test this in sqlite ... // not sure if we can test this in sqlite ...
// how could we enforce an authentication error in sqlite? // how could we enforce an authentication error in sqlite?
} else { } else {
it("gets triggered once an error occurs", function(done) { it('gets triggered once an error occurs', function(done) {
var sequelize = Support.createSequelizeInstance(); var sequelize = Support.createSequelizeInstance();
// lets overwrite the host to get an error // lets overwrite the host to get an error
...@@ -98,7 +99,7 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () { ...@@ -98,7 +99,7 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () {
sequelize sequelize
.transaction().then(function() {}) .transaction().then(function() {})
.catch(function(err) { .catch (function(err) {
expect(err).to.not.be.undefined; expect(err).to.not.be.undefined;
done(); done();
}); });
...@@ -107,12 +108,12 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () { ...@@ -107,12 +108,12 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () {
}); });
describe('complex long running example', function() { describe('complex long running example', function() {
it("works with promise syntax", function(done) { it('works with promise syntax', function(done) {
Support.prepareTransactionTest(this.sequelize, function(sequelize) { Support.prepareTransactionTest(this.sequelize, function(sequelize) {
var Test = sequelize.define('Test', { var Test = sequelize.define('Test', {
id: { type: Support.Sequelize.INTEGER, primaryKey: true, autoIncrement: true}, id: { type: Support.Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
name: { type: Support.Sequelize.STRING } name: { type: Support.Sequelize.STRING }
}) });
sequelize sequelize
.sync({ force: true }) .sync({ force: true })
...@@ -126,41 +127,41 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () { ...@@ -126,41 +127,41 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () {
setTimeout(function() { setTimeout(function() {
transaction transaction
.commit() .commit()
.then(function() { return Test.count() }) .then(function() { return Test.count(); })
.then(function(count) { .then(function(count) {
expect(count).to.equal(1) expect(count).to.equal(1);
done() done();
}) });
}, 1000) }, 1000);
}) });
}) });
}) });
}) });
}) });
}) });
describe('concurrency', function() { describe('concurrency', function() {
describe('having tables with uniqueness constraints', function() { describe('having tables with uniqueness constraints', function() {
beforeEach(function(done) { beforeEach(function(done) {
var self = this var self = this;
Support.prepareTransactionTest(this.sequelize, function(sequelize) { Support.prepareTransactionTest(this.sequelize, function(sequelize) {
self.sequelize = sequelize self.sequelize = sequelize;
self.Model = sequelize.define('Model', { self.Model = sequelize.define('Model', {
name: { type: Support.Sequelize.STRING, unique: true } name: { type: Support.Sequelize.STRING, unique: true }
}, { }, {
timestamps: false timestamps: false
}) });
self.Model self.Model
.sync({ force: true }) .sync({ force: true })
.success(function() { done() }) .success(function() { done(); });
}) });
}) });
it("triggers the error event for the second transactions", function(done) { it('triggers the error event for the second transactions', function(done) {
var self = this var self = this;
this.sequelize.transaction().then(function(t1) { this.sequelize.transaction().then(function(t1) {
self.sequelize.transaction().then(function(t2) { self.sequelize.transaction().then(function(t2) {
...@@ -173,18 +174,18 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () { ...@@ -173,18 +174,18 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () {
.create({ name: 'omnom' }, { transaction: t2 }) .create({ name: 'omnom' }, { transaction: t2 })
.error(function(err) { .error(function(err) {
t2.rollback().success(function() { t2.rollback().success(function() {
expect(err).to.be.defined expect(err).to.be.defined;
done() done();
}) });
}) });
setTimeout(function() { t1.commit() }, 100) setTimeout(function() { t1.commit(); }, 100);
}) });
}) });
}) });
}) });
}) });
}) });
}) });
} }
var chai = require('chai') 'use strict';
, sinonChai = require("sinon-chai")
, sinon = require('sinon')
, fs = require('fs')
, path = require('path')
, expect = chai.expect
, assert = chai.assert
, Support = require(__dirname + '/../support')
chai.use(sinonChai) var chai = require('chai')
chai.config.includeStack = true , sinonChai = require('sinon-chai')
, sinon = require('sinon')
, fs = require('fs')
, path = require('path')
, expect = chai.expect
, assert = chai.assert
, Support = require(__dirname + '/../support');
describe(Support.getTestDialectTeaser("Sequelize"), function () { chai.use(sinonChai);
chai.config.includeStack = true;
describe(Support.getTestDialectTeaser('Sequelize'), function() {
describe('log', function() { describe('log', function() {
beforeEach(function() { beforeEach(function() {
this.spy = sinon.spy(console, 'log') this.spy = sinon.spy(console, 'log');
}) });
afterEach(function() { afterEach(function() {
console.log.restore() console.log.restore();
}) });
describe("with disabled logging", function() { describe('with disabled logging', function() {
beforeEach(function() { beforeEach(function() {
this.sequelize = new Support.Sequelize('db', 'user', 'pw', { logging: false }) this.sequelize = new Support.Sequelize('db', 'user', 'pw', { logging: false });
}) });
it("does not call the log method of the logger", function() { it('does not call the log method of the logger', function() {
this.sequelize.log() this.sequelize.log();
expect(this.spy.calledOnce).to.be.false expect(this.spy.calledOnce).to.be.false;
}) });
}) });
describe('with default logging options', function() { describe('with default logging options', function() {
beforeEach(function() { beforeEach(function() {
this.sequelize = new Support.Sequelize('db', 'user', 'pw') this.sequelize = new Support.Sequelize('db', 'user', 'pw');
}) });
describe("called with no arguments", function() { describe('called with no arguments', function() {
it('calls the log method', function() { it('calls the log method', function() {
this.sequelize.log() this.sequelize.log();
expect(this.spy.calledOnce).to.be.true expect(this.spy.calledOnce).to.be.true;
}) });
it('logs an empty string as info event', function() { it('logs an empty string as info event', function() {
this.sequelize.log() this.sequelize.log();
expect(this.spy.calledOnce).to.be.true expect(this.spy.calledOnce).to.be.true;
}) });
}) });
describe("called with one argument", function() { describe('called with one argument', function() {
it('logs the passed string as info event', function() { it('logs the passed string as info event', function() {
this.sequelize.log('my message') this.sequelize.log('my message');
expect(this.spy.withArgs('my message').calledOnce).to.be.true expect(this.spy.withArgs('my message').calledOnce).to.be.true;
}) });
}) });
describe("called with more than two arguments", function() { describe('called with more than two arguments', function() {
it("passes the arguments to the logger", function() { it('passes the arguments to the logger', function() {
this.sequelize.log('error', 'my message', 1, { a: 1 }) this.sequelize.log('error', 'my message', 1, { a: 1 });
expect(this.spy.withArgs('error', 'my message', 1, { a: 1 }).calledOnce).to.be.true expect(this.spy.withArgs('error', 'my message', 1, { a: 1 }).calledOnce).to.be.true;
}) });
}) });
}) });
describe("with a custom function for logging", function() { describe('with a custom function for logging', function() {
beforeEach(function() { beforeEach(function() {
this.spy = sinon.spy() this.spy = sinon.spy();
this.sequelize = new Support.Sequelize('db', 'user', 'pw', { logging: this.spy }) this.sequelize = new Support.Sequelize('db', 'user', 'pw', { logging: this.spy });
}) });
it("calls the custom logger method", function() { it('calls the custom logger method', function() {
this.sequelize.log('om nom') this.sequelize.log('om nom');
expect(this.spy.calledOnce).to.be.true expect(this.spy.calledOnce).to.be.true;
}) });
}) });
}) });
}) });
"use strict"; 'use strict';
var fs = require('fs') var fs = require('fs')
, path = require('path') , path = require('path')
, _ = require('lodash') , _ = require('lodash')
, Sequelize = require(__dirname + "/../index") , Sequelize = require(__dirname + '/../index')
, DataTypes = require(__dirname + "/../lib/data-types") , DataTypes = require(__dirname + '/../lib/data-types')
, Config = require(__dirname + "/config/config") , Config = require(__dirname + '/config/config')
, chai = require("chai") , chai = require('chai')
, chaiAsPromised = require("chai-as-promised"); , expect = chai.expect
, chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised); chai.use(chaiAsPromised);
...@@ -44,21 +45,21 @@ var Support = { ...@@ -44,21 +45,21 @@ var Support = {
if (dialect === 'sqlite') { if (dialect === 'sqlite') {
var p = path.join(__dirname, 'tmp', 'db.sqlite'); var p = path.join(__dirname, 'tmp', 'db.sqlite');
return new Sequelize.Promise(function (resolve, reject) { return new Sequelize.Promise(function(resolve, reject) {
// We cannot promisify exists, since exists does not follow node callback convention - first argument is a boolean, not an error / null // We cannot promisify exists, since exists does not follow node callback convention - first argument is a boolean, not an error / null
if (fs.existsSync(p)) { if (fs.existsSync(p)) {
resolve(Sequelize.Promise.promisify(fs.unlink)(p)); resolve(Sequelize.Promise.promisify(fs.unlink)(p));
} else { } else {
resolve(); resolve();
} }
}).then(function () { }).then(function() {
var options = Sequelize.Utils._.extend({}, sequelize.options, { storage: p }) var options = Sequelize.Utils._.extend({}, sequelize.options, { storage: p })
, _sequelize = new Sequelize(sequelize.config.database, null, null, options); , _sequelize = new Sequelize(sequelize.config.database, null, null, options);
if (callback) { if (callback) {
_sequelize.sync({ force: true }).success(function() { callback(_sequelize); }); _sequelize.sync({ force: true }).success(function() { callback(_sequelize); });
} else { } else {
return _sequelize.sync({ force: true }).return(_sequelize); return _sequelize.sync({ force: true }).return (_sequelize);
} }
}); });
} else { } else {
...@@ -77,11 +78,11 @@ var Support = { ...@@ -77,11 +78,11 @@ var Support = {
var config = Config[options.dialect]; var config = Config[options.dialect];
var sequelizeOptions = _.defaults(options, { var sequelizeOptions = _.defaults(options, {
host: options.host || config.host, host: options.host || config.host,
logging: (process.env.SEQ_LOG ? console.log : false), logging: (process.env.SEQ_LOG ? console.log : false),
dialect: options.dialect, dialect: options.dialect,
port: options.port || process.env.SEQ_PORT || config.port, port: options.port || process.env.SEQ_PORT || config.port,
pool: config.pool, pool: config.pool,
dialectOptions: options.dialectOptions || {} dialectOptions: options.dialectOptions || {}
}); });
...@@ -111,11 +112,11 @@ var Support = { ...@@ -111,11 +112,11 @@ var Support = {
return sequelize return sequelize
.getQueryInterface() .getQueryInterface()
.dropAllEnums() .dropAllEnums()
.catch(function (err) { .catch (function(err) {
console.log('Error in support.clearDatabase() dropAllEnums() :: ', err); console.log('Error in support.clearDatabase() dropAllEnums() :: ', err);
}); });
}) })
.catch(function(err) { .catch (function(err) {
console.log('Error in support.clearDatabase() dropAllTables() :: ', err); console.log('Error in support.clearDatabase() dropAllTables() :: ', err);
}); });
}, },
...@@ -168,7 +169,7 @@ var Support = { ...@@ -168,7 +169,7 @@ var Support = {
dialect = 'postgres-native'; dialect = 'postgres-native';
} }
return "[" + dialect.toUpperCase() + "] " + moduleName; return '[' + dialect.toUpperCase() + '] ' + moduleName;
}, },
getTestUrl: function(config) { getTestUrl: function(config) {
...@@ -180,12 +181,12 @@ var Support = { ...@@ -180,12 +181,12 @@ var Support = {
} else { } else {
var credentials = dbConfig.username; var credentials = dbConfig.username;
if(dbConfig.password) { if (dbConfig.password) {
credentials += ":" + dbConfig.password; credentials += ':' + dbConfig.password;
} }
url = config.dialect + "://" + credentials url = config.dialect + '://' + credentials
+ "@" + dbConfig.host + ":" + dbConfig.port + "/" + dbConfig.database; + '@' + dbConfig.host + ':' + dbConfig.port + '/' + dbConfig.database;
} }
return url; return url;
} }
...@@ -197,7 +198,7 @@ var sequelize = Support.sequelize = Support.createSequelizeInstance(); ...@@ -197,7 +198,7 @@ var sequelize = Support.sequelize = Support.createSequelizeInstance();
// For Postgres' HSTORE functionality and to properly execute it's commands we'll need this... // For Postgres' HSTORE functionality and to properly execute it's commands we'll need this...
before(function() { before(function() {
var dialect = Support.getTestDialect(); var dialect = Support.getTestDialect();
if (dialect !== "postgres" && dialect !== "postgres-native") { if (dialect !== 'postgres' && dialect !== 'postgres-native') {
return; return;
} }
......
"use strict"; 'use strict';
var chai = require('chai') var chai = require('chai')
, expect = chai.expect , expect = chai.expect
, Support = require(__dirname + '/support') , Support = require(__dirname + '/support')
, dialect = Support.getTestDialect() , dialect = Support.getTestDialect()
, Sequelize = require(__dirname + '/../index') , Sequelize = require(__dirname + '/../index')
, Promise = Sequelize.Promise , Promise = Sequelize.Promise
, sinon = require('sinon'); , sinon = require('sinon');
if (dialect !== 'sqlite') { if (dialect !== 'sqlite') {
// Sqlite does not support setting timezone // Sqlite does not support setting timezone
describe(Support.getTestDialectTeaser('Timezone'), function () { describe(Support.getTestDialectTeaser('Timezone'), function() {
beforeEach(function () { beforeEach(function() {
this.sequelizeWithTimezone = Support.createSequelizeInstance({ this.sequelizeWithTimezone = Support.createSequelizeInstance({
timezone: '+07:00', timezone: '+07:00'
}); });
}); });
it('returns the same value for current timestamp', function () { it('returns the same value for current timestamp', function() {
var now = 'now()' var now = 'now()'
, startQueryTime = Date.now(); , startQueryTime = Date.now();
...@@ -26,27 +26,27 @@ if (dialect !== 'sqlite') { ...@@ -26,27 +26,27 @@ if (dialect !== 'sqlite') {
now = 'GETDATE()'; now = 'GETDATE()';
} }
var query = "SELECT " + now + " as now"; var query = 'SELECT ' + now + ' as now';
return Promise.all([ return Promise.all([
this.sequelize.query(query), this.sequelize.query(query),
this.sequelizeWithTimezone.query(query) this.sequelizeWithTimezone.query(query)
]).spread(function (now1, now2) { ]).spread(function(now1, now2) {
var elapsedQueryTime = Date.now() - startQueryTime; var elapsedQueryTime = (Date.now() - startQueryTime) + 20;
expect(now1[0].now.getTime()).to.be.closeTo(now2[0].now.getTime(), elapsedQueryTime); expect(now1[0].now.getTime()).to.be.closeTo(now2[0].now.getTime(), elapsedQueryTime);
}); });
}); });
if (Support.dialectIsMySQL()) { if (Support.dialectIsMySQL()) {
it('handles existing timestamps', function () { it('handles existing timestamps', function() {
var NormalUser = this.sequelize.define('user', {}) var NormalUser = this.sequelize.define('user', {})
, TimezonedUser = this.sequelizeWithTimezone.define('user', {}); , TimezonedUser = this.sequelizeWithTimezone.define('user', {});
return this.sequelize.sync({ force: true }).bind(this).then(function () { return this.sequelize.sync({ force: true }).bind(this).then(function() {
return TimezonedUser.create({}); return TimezonedUser.create({});
}).then(function (timezonedUser) { }).then(function(timezonedUser) {
this.timezonedUser = timezonedUser; this.timezonedUser = timezonedUser;
return NormalUser.find(timezonedUser.id); return NormalUser.find(timezonedUser.id);
}).then(function (normalUser) { }).then(function(normalUser) {
// Expect 7 hours difference, in milliseconds. // Expect 7 hours difference, in milliseconds.
// This difference is expected since two instances, configured for each their timezone is trying to read the same timestamp // This difference is expected since two instances, configured for each their timezone is trying to read the same timestamp
// this test does not apply to PG, since it stores the timezone along with the timestamp. // this test does not apply to PG, since it stores the timezone along with the timestamp.
......
var chai = require('chai') 'use strict';
, expect = chai.expect
, Support = require(__dirname + '/support') var chai = require('chai')
, dialect = Support.getTestDialect() , expect = chai.expect
, Promise = require(__dirname + '/../lib/promise') , Support = require(__dirname + '/support')
, dialect = Support.getTestDialect()
, Promise = require(__dirname + '/../lib/promise')
, Transaction = require(__dirname + '/../lib/transaction') , Transaction = require(__dirname + '/../lib/transaction')
, sinon = require('sinon') , sinon = require('sinon')
, current = Support.sequelize; , current = Support.sequelize;
if (current.dialect.supports.transactions) { if (current.dialect.supports.transactions) {
describe(Support.getTestDialectTeaser("Transaction"), function () { describe(Support.getTestDialectTeaser('Transaction'), function() {
this.timeout(4000); this.timeout(4000);
describe('constructor', function() { describe('constructor', function() {
it('stores options', function() { it('stores options', function() {
...@@ -35,59 +37,59 @@ describe(Support.getTestDialectTeaser("Transaction"), function () { ...@@ -35,59 +37,59 @@ describe(Support.getTestDialectTeaser("Transaction"), function () {
}); });
}); });
describe('autoCallback', function () { describe('autoCallback', function() {
it('supports automatically committing', function () { it('supports automatically committing', function() {
return this.sequelize.transaction(function (t) { return this.sequelize.transaction(function(t) {
return Promise.resolve(); return Promise.resolve();
}); });
}); });
it('supports automatically rolling back with a thrown error', function () { it('supports automatically rolling back with a thrown error', function() {
return expect(this.sequelize.transaction(function (t) { return expect(this.sequelize.transaction(function(t) {
throw new Error('Yolo'); throw new Error('Yolo');
})).to.eventually.be.rejected; })).to.eventually.be.rejected;
}); });
it('supports automatically rolling back with a rejection', function () { it('supports automatically rolling back with a rejection', function() {
return expect(this.sequelize.transaction(function (t) { return expect(this.sequelize.transaction(function(t) {
return Promise.reject('Swag'); return Promise.reject('Swag');
})).to.eventually.be.rejected; })).to.eventually.be.rejected;
}); });
it('errors when no promise chain is returned', function () { it('errors when no promise chain is returned', function() {
return expect(this.sequelize.transaction(function (t) { return expect(this.sequelize.transaction(function(t) {
})).to.eventually.be.rejected; })).to.eventually.be.rejected;
}); });
}); });
it('does not allow queries after commit', function () { it('does not allow queries after commit', function() {
var self = this; var self = this;
return expect( return expect(
this.sequelize.transaction().then(function (t) { this.sequelize.transaction().then(function(t) {
return self.sequelize.query("SELECT 1+1", null, {transaction: t, raw: true}).then(function () { return self.sequelize.query('SELECT 1+1', null, {transaction: t, raw: true}).then(function() {
return t.commit(); return t.commit();
}).then(function () { }).then(function() {
return self.sequelize.query("SELECT 1+1", null, {transaction: t, raw: true}); return self.sequelize.query('SELECT 1+1', null, {transaction: t, raw: true});
}); });
}) })
).to.eventually.be.rejected; ).to.eventually.be.rejected;
}); });
it('does not allow queries after rollback', function () { it('does not allow queries after rollback', function() {
var self = this; var self = this;
return expect( return expect(
this.sequelize.transaction().then(function (t) { this.sequelize.transaction().then(function(t) {
return self.sequelize.query("SELECT 1+1", null, {transaction: t, raw: true}).then(function () { return self.sequelize.query('SELECT 1+1', null, {transaction: t, raw: true}).then(function() {
return t.commit(); return t.commit();
}).then(function () { }).then(function() {
return self.sequelize.query("SELECT 1+1", null, {transaction: t, raw: true}); return self.sequelize.query('SELECT 1+1', null, {transaction: t, raw: true});
}); });
}) })
).to.eventually.be.rejected; ).to.eventually.be.rejected;
}); });
if (current.dialect.supports.lock) { if (current.dialect.supports.lock) {
describe('row locking', function () { describe('row locking', function() {
this.timeout(10000); this.timeout(10000);
it('supports for update', function (done) { it('supports for update', function(done) {
var User = this.sequelize.define('user', { var User = this.sequelize.define('user', {
username: Support.Sequelize.STRING, username: Support.Sequelize.STRING,
awesome: Support.Sequelize.BOOLEAN awesome: Support.Sequelize.BOOLEAN
...@@ -96,10 +98,10 @@ describe(Support.getTestDialectTeaser("Transaction"), function () { ...@@ -96,10 +98,10 @@ describe(Support.getTestDialectTeaser("Transaction"), function () {
, t1Spy = sinon.spy() , t1Spy = sinon.spy()
, t2Spy = sinon.spy(); , t2Spy = sinon.spy();
this.sequelize.sync({ force: true }).then(function () { this.sequelize.sync({ force: true }).then(function() {
return User.create({ username: 'jan'}); return User.create({ username: 'jan'});
}).then(function () { }).then(function() {
self.sequelize.transaction().then(function (t1) { self.sequelize.transaction().then(function(t1) {
return User.find({ return User.find({
where: { where: {
username: 'jan' username: 'jan'
...@@ -107,20 +109,20 @@ describe(Support.getTestDialectTeaser("Transaction"), function () { ...@@ -107,20 +109,20 @@ describe(Support.getTestDialectTeaser("Transaction"), function () {
}, { }, {
lock: t1.LOCK.UPDATE, lock: t1.LOCK.UPDATE,
transaction: t1 transaction: t1
}).then(function (t1Jan) { }).then(function(t1Jan) {
self.sequelize.transaction({ self.sequelize.transaction({
isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED
}).then(function (t2) { }).then(function(t2) {
User.find({ User.find({
where: { where: {
username: 'jan' username: 'jan'
}, }
}, { }, {
lock: t2.LOCK.UPDATE, lock: t2.LOCK.UPDATE,
transaction: t2 transaction: t2
}).then(function () { }).then(function() {
t2Spy() t2Spy();
t2.commit().then(function () { t2.commit().then(function() {
expect(t2Spy).to.have.been.calledAfter(t1Spy); // Find should not succeed before t1 has comitted expect(t2Spy).to.have.been.calledAfter(t1Spy); // Find should not succeed before t1 has comitted
done(); done();
}); });
...@@ -128,8 +130,8 @@ describe(Support.getTestDialectTeaser("Transaction"), function () { ...@@ -128,8 +130,8 @@ describe(Support.getTestDialectTeaser("Transaction"), function () {
t1Jan.updateAttributes({ t1Jan.updateAttributes({
awesome: true awesome: true
}, { transaction: t1}).then(function () { }, { transaction: t1}).then(function() {
t1Spy() t1Spy();
setTimeout(t1.commit.bind(t1), 2000); setTimeout(t1.commit.bind(t1), 2000);
}); });
}); });
...@@ -138,7 +140,7 @@ describe(Support.getTestDialectTeaser("Transaction"), function () { ...@@ -138,7 +140,7 @@ describe(Support.getTestDialectTeaser("Transaction"), function () {
}); });
}); });
it('supports for share', function (done) { it('supports for share', function(done) {
var User = this.sequelize.define('user', { var User = this.sequelize.define('user', {
username: Support.Sequelize.STRING, username: Support.Sequelize.STRING,
awesome: Support.Sequelize.BOOLEAN awesome: Support.Sequelize.BOOLEAN
...@@ -148,10 +150,10 @@ describe(Support.getTestDialectTeaser("Transaction"), function () { ...@@ -148,10 +150,10 @@ describe(Support.getTestDialectTeaser("Transaction"), function () {
, t2FindSpy = sinon.spy() , t2FindSpy = sinon.spy()
, t2UpdateSpy = sinon.spy(); , t2UpdateSpy = sinon.spy();
this.sequelize.sync({ force: true }).then(function () { this.sequelize.sync({ force: true }).then(function() {
return User.create({ username: 'jan'}); return User.create({ username: 'jan'});
}).then(function () { }).then(function() {
self.sequelize.transaction().then(function (t1) { self.sequelize.transaction().then(function(t1) {
return User.find({ return User.find({
where: { where: {
username: 'jan' username: 'jan'
...@@ -159,24 +161,24 @@ describe(Support.getTestDialectTeaser("Transaction"), function () { ...@@ -159,24 +161,24 @@ describe(Support.getTestDialectTeaser("Transaction"), function () {
}, { }, {
lock: t1.LOCK.SHARE, lock: t1.LOCK.SHARE,
transaction: t1 transaction: t1
}).then(function (t1Jan) { }).then(function(t1Jan) {
self.sequelize.transaction({ self.sequelize.transaction({
isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED
}).then(function (t2) { }).then(function(t2) {
User.find({ User.find({
where: { where: {
username: 'jan' username: 'jan'
} }
}, { transaction: t2}).then(function (t2Jan) { }, { transaction: t2}).then(function(t2Jan) {
t2FindSpy(); t2FindSpy();
t2Jan.updateAttributes({ t2Jan.updateAttributes({
awesome: false awesome: false
}, { }, {
transaction: t2 transaction: t2
}).then(function () { }).then(function() {
t2UpdateSpy(); t2UpdateSpy();
t2.commit().then(function () { t2.commit().then(function() {
expect(t2FindSpy).to.have.been.calledBefore(t1Spy); // The find call should have returned expect(t2FindSpy).to.have.been.calledBefore(t1Spy); // The find call should have returned
expect(t2UpdateSpy).to.have.been.calledAfter(t1Spy); // But the update call should not happen before the first transaction has committed expect(t2UpdateSpy).to.have.been.calledAfter(t1Spy); // But the update call should not happen before the first transaction has committed
done(); done();
...@@ -188,8 +190,8 @@ describe(Support.getTestDialectTeaser("Transaction"), function () { ...@@ -188,8 +190,8 @@ describe(Support.getTestDialectTeaser("Transaction"), function () {
awesome: true awesome: true
}, { }, {
transaction: t1 transaction: t1
}).then(function () { }).then(function() {
setTimeout(function () { setTimeout(function() {
t1Spy(); t1Spy();
t1.commit(); t1.commit();
}, 2000); }, 2000);
......
"use strict"; 'use strict';
var chai = require('chai') var chai = require('chai')
, spies = require('chai-spies') , spies = require('chai-spies')
, expect = chai.expect , expect = chai.expect
, Utils = require(__dirname + '/../lib/utils') , Utils = require(__dirname + '/../lib/utils')
, Support = require(__dirname + '/support'); , Support = require(__dirname + '/support');
chai.use(spies); chai.use(spies);
chai.config.includeStack = true; chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Utils"), function() { describe(Support.getTestDialectTeaser('Utils'), function() {
describe('removeCommentsFromFunctionString', function() { describe('removeCommentsFromFunctionString', function() {
it("removes line comments at the start of a line", function() { it('removes line comments at the start of a line', function() {
var functionWithLineComments = function() { var functionWithLineComments = function() {
// noot noot // noot noot
}; };
...@@ -22,7 +22,7 @@ describe(Support.getTestDialectTeaser("Utils"), function() { ...@@ -22,7 +22,7 @@ describe(Support.getTestDialectTeaser("Utils"), function() {
expect(result).not.to.match(/.*noot.*/); expect(result).not.to.match(/.*noot.*/);
}); });
it("removes lines comments in the middle of a line", function() { it('removes lines comments in the middle of a line', function() {
var functionWithLineComments = function() { var functionWithLineComments = function() {
alert(1); // noot noot alert(1); // noot noot
}; };
...@@ -33,7 +33,7 @@ describe(Support.getTestDialectTeaser("Utils"), function() { ...@@ -33,7 +33,7 @@ describe(Support.getTestDialectTeaser("Utils"), function() {
expect(result).not.to.match(/.*noot.*/); expect(result).not.to.match(/.*noot.*/);
}); });
it("removes range comments", function() { it('removes range comments', function() {
var s = function() { var s = function() {
alert(1); /* alert(1); /*
noot noot noot noot
...@@ -53,7 +53,7 @@ describe(Support.getTestDialectTeaser("Utils"), function() { ...@@ -53,7 +53,7 @@ describe(Support.getTestDialectTeaser("Utils"), function() {
describe('argsArePrimaryKeys', function() { describe('argsArePrimaryKeys', function() {
it("doesn't detect primary keys if primareyKeys and values have different lengths", function() { it("doesn't detect primary keys if primareyKeys and values have different lengths", function() {
expect(Utils.argsArePrimaryKeys([1,2,3], [1])).to.be.false; expect(Utils.argsArePrimaryKeys([1, 2, 3], [1])).to.be.false;
}); });
it("doesn't detect primary keys if primary keys are hashes or arrays", function() { it("doesn't detect primary keys if primary keys are hashes or arrays", function() {
...@@ -61,10 +61,10 @@ describe(Support.getTestDialectTeaser("Utils"), function() { ...@@ -61,10 +61,10 @@ describe(Support.getTestDialectTeaser("Utils"), function() {
}); });
it('detects primary keys if length is correct and data types are matching', function() { it('detects primary keys if length is correct and data types are matching', function() {
expect(Utils.argsArePrimaryKeys([1,2,3], ["INTEGER", "INTEGER", "INTEGER"])).to.be.true; expect(Utils.argsArePrimaryKeys([1, 2, 3], ['INTEGER', 'INTEGER', 'INTEGER'])).to.be.true;
}); });
it("detects primary keys if primary keys are dates and lengths are matching", function() { it('detects primary keys if primary keys are dates and lengths are matching', function() {
expect(Utils.argsArePrimaryKeys([new Date()], ['foo'])).to.be.true; expect(Utils.argsArePrimaryKeys([new Date()], ['foo'])).to.be.true;
}); });
}); });
...@@ -134,7 +134,7 @@ describe(Support.getTestDialectTeaser("Utils"), function() { ...@@ -134,7 +134,7 @@ describe(Support.getTestDialectTeaser("Utils"), function() {
describe('expectation', function() { describe('expectation', function() {
it('uses the instanceof method if the expectation is a class', function() { it('uses the instanceof method if the expectation is a class', function() {
expect(Utils.validateParameter(new Number(1), Number)).to.be.true; expect(Utils.validateParameter(new Number(1), Number)).to.be.true; // jshint ignore:line
}); });
}); });
...@@ -148,7 +148,7 @@ describe(Support.getTestDialectTeaser("Utils"), function() { ...@@ -148,7 +148,7 @@ describe(Support.getTestDialectTeaser("Utils"), function() {
}); });
if (Support.getTestDialect() === 'postgres') { if (Support.getTestDialect() === 'postgres') {
describe('json', function () { describe('json', function() {
var queryGenerator = require('../lib/dialects/postgres/query-generator.js'); var queryGenerator = require('../lib/dialects/postgres/query-generator.js');
it('successfully parses a complex nested condition hash', function() { it('successfully parses a complex nested condition hash', function() {
...@@ -163,17 +163,17 @@ describe(Support.getTestDialectTeaser("Utils"), function() { ...@@ -163,17 +163,17 @@ describe(Support.getTestDialectTeaser("Utils"), function() {
expect(queryGenerator.handleSequelizeMethod(new Utils.json(conditions))).to.deep.equal(expected); expect(queryGenerator.handleSequelizeMethod(new Utils.json(conditions))).to.deep.equal(expected);
}); });
it('successfully parses a string using dot notation', function () { it('successfully parses a string using dot notation', function() {
var path = 'metadata.pg_rating.dk'; var path = 'metadata.pg_rating.dk';
expect(queryGenerator.handleSequelizeMethod(new Utils.json(path))).to.equal("metadata#>>'{pg_rating,dk}'"); expect(queryGenerator.handleSequelizeMethod(new Utils.json(path))).to.equal("metadata#>>'{pg_rating,dk}'");
}); });
it('allows postgres json syntax', function () { it('allows postgres json syntax', function() {
var path = 'metadata->pg_rating->>dk'; var path = 'metadata->pg_rating->>dk';
expect(queryGenerator.handleSequelizeMethod(new Utils.json(path))).to.equal(path); expect(queryGenerator.handleSequelizeMethod(new Utils.json(path))).to.equal(path);
}); });
it('can take a value to compare against', function () { it('can take a value to compare against', function() {
var path = 'metadata.pg_rating.is'; var path = 'metadata.pg_rating.is';
var value = 'U'; var value = 'U';
expect(queryGenerator.handleSequelizeMethod(new Utils.json(path, value))).to.equal("metadata#>>'{pg_rating,is}' = 'U'"); expect(queryGenerator.handleSequelizeMethod(new Utils.json(path, value))).to.equal("metadata#>>'{pg_rating,is}' = 'U'");
...@@ -181,8 +181,8 @@ describe(Support.getTestDialectTeaser("Utils"), function() { ...@@ -181,8 +181,8 @@ describe(Support.getTestDialectTeaser("Utils"), function() {
}); });
} }
describe('inflection', function () { describe('inflection', function() {
it('works better than lingo ;)', function () { it('works better than lingo ;)', function() {
expect(Utils.pluralize('buy')).to.equal('buys'); expect(Utils.pluralize('buy')).to.equal('buys');
expect(Utils.pluralize('holiday')).to.equal('holidays'); expect(Utils.pluralize('holiday')).to.equal('holidays');
expect(Utils.pluralize('days')).to.equal('days'); expect(Utils.pluralize('days')).to.equal('days');
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!