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

Commit 6afabd46 by Matt Broadstone

clean and lint tests, enable jshint on tests

Ran fixjsstlye on all the tests, fixed any outstanding errors, and
enabled jshint for checking tests in continuous integration.
1 parent 4e107803
Showing with 1112 additions and 1102 deletions
......@@ -26,7 +26,7 @@ test-only:
./node_modules/mocha/bin/mocha --globals setImmediate,clearImmediate --check-leaks --colors -t 10000 --reporter $(REPORTER) $(TESTS); \
jshint:
./node_modules/.bin/jshint lib
./node_modules/.bin/jshint lib test
cover:
rm -rf coverage \
......
'use strict';
module.exports = function(sequelize, DataTypes) {
return sequelize.define('Project' + parseInt(Math.random() * 9999999999999999), {
name: DataTypes.STRING
})
}
\ No newline at end of file
});
};
"use strict";
'use strict';
/* jshint camelcase: false, expr: true */
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + "/../../lib/data-types")
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + '/../../lib/data-types')
, Sequelize = require('../../index')
, Promise = Sequelize.Promise
, assert = require('assert');
, Promise = Sequelize.Promise
, assert = require('assert');
chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Alias"), function() {
it('should uppercase the first letter in alias getter, but not in eager loading', function () {
describe(Support.getTestDialectTeaser('Alias'), function() {
it('should uppercase the first letter in alias getter, but not in eager loading', function() {
var User = this.sequelize.define('user', {})
, Task = this.sequelize.define('task', {});
User.hasMany(Task, { as: 'assignments', 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 });
}).then(function (user) {
}).then(function(user) {
expect(user.getAssignments).to.be.ok;
return Task.create({ id: 1, userId: 1 });
}).then(function (task) {
}).then(function(task) {
expect(task.getOwner).to.be.ok;
return Promise.all([
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(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', {})
, Task = this.sequelize.define('task', {});
User.hasMany(Task, { as: 'ASSIGNMENTS', 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 });
}).then(function (user){
}).then(function(user) {
expect(user.getASSIGNMENTS).to.be.ok;
return Task.create({ id: 1, userId: 1 });
}).then(function (task) {
}).then(function(task) {
expect(task.getOWNER).to.be.ok;
return Promise.all([
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(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', {})
, Task = this.sequelize.define('task', {});
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 });
}).then(function (user) {
}).then(function(user) {
expect(user.getTaskz).to.be.ok;
expect(user.addTask).to.be.ok;
expect(user.addTaskz).to.be.ok;
}).then(function () {
}).then(function() {
return User.find({ where: { id: 1 }, include: [{model: Task, as: 'taskz'}] });
}).then(function (user) {
}).then(function(user) {
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', {})
, Task = this.sequelize.define('task', {}, {
name: {
......@@ -94,15 +93,15 @@ describe(Support.getTestDialectTeaser("Alias"), function() {
User.hasMany(Task);
return this.sequelize.sync({ force: true }).then(function () {
return this.sequelize.sync({ force: true }).then(function() {
return User.create({ id: 1 });
}).then(function (user) {
}).then(function(user) {
expect(user.getAssignments).to.be.ok;
expect(user.addAssignment).to.be.ok;
expect(user.addAssignments).to.be.ok;
}).then(function () {
}).then(function() {
return User.find({ where: { id: 1 }, include: [Task] });
}).then(function (user) {
}).then(function(user) {
expect(user.assignments).to.be.ok;
});
});
......
/* jshint camelcase: false, expr: true */
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + "/../../lib/data-types")
'use strict';
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) {
var User = this.sequelize.define('User', {username: 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);
User.hasMany(Project)
User.hasMany(Project);
Task.belongsTo(Project);
Project.hasMany(Task);
......@@ -53,36 +54,35 @@ describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() {
User
]}
]
}).done(function(err, tasks){
expect(err).not.to.be.ok
}).done(function(err, tasks) {
expect(err).not.to.be.ok;
try{
try {
expect(tasks.length).to.be.equal(2);
expect(tasks[0].title).to.be.equal('fight empire');
expect(tasks[1].title).to.be.equal('stablish republic');
done();
}catch(e){
}catch (e) {
done(e);
}
})
});
});
});
});
})
})
});
});
it('avoids duplicated tables in query', function(done) {
var User = this.sequelize.define('User', {username: 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);
User.hasMany(Project)
User.hasMany(Project);
Task.belongsTo(Project);
Project.hasMany(Task);
this.sequelize.sync({ force: true }).success(function() {
User.bulkCreate([{
username: 'leia'
......@@ -119,29 +119,29 @@ describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() {
User
]}
]
}).success(function(tasks){
try{
}).success(function(tasks) {
try {
expect(tasks.length).to.be.equal(2);
expect(tasks[0].title).to.be.equal('fight empire');
expect(tasks[1].title).to.be.equal('stablish republic');
done();
}catch(e){
}catch (e) {
done(e);
}
})
});
});
});
});
})
})
});
});
it('can filter through hasMany', function(done) {
var User = this.sequelize.define('User', {username: 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);
User.hasMany(Project)
User.hasMany(Project);
Task.belongsTo(Project);
Project.hasMany(Task);
......@@ -181,27 +181,27 @@ describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() {
Task
]}
]
}).done(function(err, users){
try{
}).done(function(err, users) {
try {
expect(users.length).to.be.equal(1);
expect(users[0].username).to.be.equal('leia');
done();
}catch(e){
}catch (e) {
done(e);
}
})
});
});
});
});
})
})
});
});
it('can filter through hasMany connector', function(done) {
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);
User.hasMany(Project)
User.hasMany(Project);
this.sequelize.sync({ force: true }).success(function() {
User.bulkCreate([{
......@@ -214,12 +214,12 @@ describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() {
},{
title: 'empire'
}]).success(function() {
User.find(1).success(function(user){
Project.find(1).success(function(project){
user.setProjects([project]).success(function(){
User.find(2).success(function(user){
Project.find(2).success(function(project){
user.setProjects([project]).success(function(){
User.find(1).success(function(user) {
Project.find(1).success(function(project) {
user.setProjects([project]).success(function() {
User.find(2).success(function(user) {
Project.find(2).success(function(project) {
user.setProjects([project]).success(function() {
User.findAll({
where: {
'Projects.title': 'republic'
......@@ -227,15 +227,15 @@ describe(Support.getTestDialectTeaser("Multiple Level Filters"), function() {
include: [
{model: Project}
]
}).success(function(users){
try{
}).success(function(users) {
try {
expect(users.length).to.be.equal(1);
expect(users[0].username).to.be.equal('leia');
done();
}catch(e){
}catch (e) {
done(e);
}
})
});
});
});
});
......
"use strict";
/* jshint camelcase: false, expr: true */
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + "/../../lib/data-types")
, Sequelize = require(__dirname + "/../../index")
, Promise = Sequelize.Promise
'use strict';
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + '/../../lib/data-types')
, Sequelize = require(__dirname + '/../../index')
, Promise = Sequelize.Promise
, _ = require('lodash');
chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Self"), function() {
it('supports freezeTableName', function () {
describe(Support.getTestDialectTeaser('Self'), function() {
it('supports freezeTableName', function() {
var Group = this.sequelize.define('Group', {}, {
tableName: 'user_group',
timestamps: false,
......@@ -21,7 +20,7 @@ describe(Support.getTestDialectTeaser("Self"), function() {
});
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({
include: [{
model: Group,
......@@ -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 });
Person.hasMany(Person, { as: 'Children', foreignKey: 'parent_id'});
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([
Person.create({ name: 'Mary' }),
Person.create({ name: 'John' }),
Person.create({ name: 'Chris' })
]);
}).spread(function (mary, john, chris) {
}).spread(function(mary, john, chris) {
return mary.setChildren([john, chris]);
});
});
......@@ -63,15 +62,15 @@ describe(Support.getTestDialectTeaser("Self"), function() {
expect(foreignIdentifiers.length).to.equal(2);
expect(rawAttributes.length).to.equal(4);
expect(foreignIdentifiers).to.have.members([ 'PersonId', 'ChildId' ]);
expect(rawAttributes).to.have.members([ 'createdAt', 'updatedAt', 'PersonId', 'ChildId' ]);
expect(foreignIdentifiers).to.have.members(['PersonId', 'ChildId']);
expect(rawAttributes).to.have.members(['createdAt', 'updatedAt', 'PersonId', 'ChildId']);
return this.sequelize.sync({ force: true }).then(function() {
return self.sequelize.Promise.all([
Person.create({ name: 'Mary' }),
Person.create({ name: 'John' }),
Person.create({ name: 'Chris' })
]).spread(function (mary, john, chris) {
]).spread(function(mary, john, chris) {
return mary.setParents([john]).then(function() {
return chris.addParent(john);
}).then(function() {
......@@ -105,8 +104,8 @@ describe(Support.getTestDialectTeaser("Self"), function() {
expect(foreignIdentifiers.length).to.equal(2);
expect(rawAttributes.length).to.equal(2);
expect(foreignIdentifiers).to.have.members([ 'preexisting_parent', 'preexisting_child' ]);
expect(rawAttributes).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']);
return this.sequelize.sync({ force: true }).bind(this).then(function() {
return Promise.all([
......@@ -114,7 +113,7 @@ describe(Support.getTestDialectTeaser("Self"), function() {
Person.create({ name: 'John' }),
Person.create({ name: 'Chris' })
]);
}).spread(function (mary, john, chris) {
}).spread(function(mary, john, chris) {
this.mary = mary;
this.chris = chris;
this.john = john;
......@@ -124,14 +123,14 @@ describe(Support.getTestDialectTeaser("Self"), function() {
expect(sql).to.have.string('preexisting_parent');
}
});
}).then(function () {
}).then(function() {
return this.mary.addParent(this.chris).on('sql', function(sql) {
if (sql.match(/INSERT/)) {
expect(sql).to.have.string('preexisting_child');
expect(sql).to.have.string('preexisting_parent');
}
});
}).then(function () {
}).then(function() {
return this.john.getChildren().on('sql', function(sql) {
var whereClause = sql.split('FROM')[1]; // look only in the whereClause
expect(whereClause).to.have.string('preexisting_child');
......
'use strict';
module.exports = {
username: process.env.SEQ_USER || "root",
password: process.env.SEQ_PW || null,
......
var path = require('path')
var path = require('path');
module.exports = {
configFile: path.resolve('config', 'database.json'),
migrationsPath: path.resolve('db', 'migrate')
}
};
var chai = require('chai')
, expect = chai.expect
, config = require(__dirname + "/config/config")
, Support = require(__dirname + '/support')
, dialect = Support.getTestDialect()
, Sequelize = require(__dirname + '/../index')
'use strict';
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() {
it("when we don't have the correct server details", function() {
if (dialect === 'mariadb') {
console.log('This dialect doesn\'t support me :(')
expect(true).to.be.true // Silence Buster
console.log('This dialect doesn\'t support me :(');
expect(true).to.be.true; // Silence Buster
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') {
// 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') {
return expect(seq.query('select 1 as hello')).to.eventually.be.rejectedWith([seq.HostNotReachableError, seq.InvalidConnectionError]);
} 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() {
if (dialect === 'mariadb') {
console.log('This dialect doesn\'t support me :(')
expect(true).to.be.true // Silence Buster
console.log('This dialect doesn\'t support me :(');
expect(true).to.be.true; // Silence Buster
return;
}
......@@ -41,86 +43,86 @@ describe(Support.getTestDialectTeaser("Configuration"), function() {
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') {
// 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 {
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) {
expect(function() {
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.')
done()
})
})
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.');
done();
});
});
describe('Instantiation with a URL string', function() {
it('should accept username, password, host, port, and database', function() {
var sequelize = new Sequelize('mysql://user:pass@example.com:9821/dbname')
var config = sequelize.config
var options = sequelize.options
var sequelize = new Sequelize('mysql://user:pass@example.com:9821/dbname');
var config = sequelize.config;
var options = sequelize.options;
expect(options.dialect).to.equal('mysql')
expect(options.dialect).to.equal('mysql');
expect(config.database).to.equal('dbname')
expect(config.host).to.equal('example.com')
expect(config.username).to.equal('user')
expect(config.password).to.equal('pass')
expect(config.port).to.equal('9821')
})
expect(config.database).to.equal('dbname');
expect(config.host).to.equal('example.com');
expect(config.username).to.equal('user');
expect(config.password).to.equal('pass');
expect(config.port).to.equal('9821');
});
it('should work with no authentication options', function(done) {
var sequelize = new Sequelize('mysql://example.com:9821/dbname')
var config = sequelize.config
var sequelize = new Sequelize('mysql://example.com:9821/dbname');
var config = sequelize.config;
expect(config.username).to.not.be.ok
expect(config.password).to.be.null
done()
})
expect(config.username).to.not.be.ok;
expect(config.password).to.be.null;
done();
});
it('should use the default port when no other is specified', function() {
var sequelize = new Sequelize('dbname', 'root', 'pass', {
dialect: dialect
})
, config = sequelize.config
, port
, port;
if (Support.dialectIsMySQL()) {
port = 3306
} else if (dialect === "postgres" || dialect === "postgres-native") {
port = 5432
port = 3306;
} else if (dialect === 'postgres' || dialect === 'postgres-native') {
port = 5432;
} else {
// 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() {
it('should accept two parameters (database, username)', function(done) {
var sequelize = new Sequelize('dbname', 'root')
var config = sequelize.config
var sequelize = new Sequelize('dbname', 'root');
var config = sequelize.config;
expect(config.database).to.equal('dbname')
expect(config.username).to.equal('root')
done()
})
expect(config.database).to.equal('dbname');
expect(config.username).to.equal('root');
done();
});
it('should accept three parameters (database, username, password)', function(done) {
var sequelize = new Sequelize('dbname', 'root', 'pass')
var config = sequelize.config
var sequelize = new Sequelize('dbname', 'root', 'pass');
var config = sequelize.config;
expect(config.database).to.equal('dbname')
expect(config.username).to.equal('root')
expect(config.password).to.equal('pass')
done()
})
expect(config.database).to.equal('dbname');
expect(config.username).to.equal('root');
expect(config.password).to.equal('pass');
done();
});
it('should accept four parameters (database, username, password, options)', function(done) {
var sequelize = new Sequelize('dbname', 'root', 'pass', {
......@@ -129,17 +131,17 @@ describe(Support.getTestDialectTeaser("Configuration"), function() {
supportBigNumbers: true,
bigNumberStrings: true
}
})
var config = sequelize.config
expect(config.database).to.equal('dbname')
expect(config.username).to.equal('root')
expect(config.password).to.equal('pass')
expect(config.port).to.equal(999)
expect(config.dialectOptions.supportBigNumbers).to.be.true
expect(config.dialectOptions.bigNumberStrings).to.be.true
done()
})
})
})
});
var config = sequelize.config;
expect(config.database).to.equal('dbname');
expect(config.username).to.equal('root');
expect(config.password).to.equal('pass');
expect(config.port).to.equal(999);
expect(config.dialectOptions.supportBigNumbers).to.be.true;
expect(config.dialectOptions.bigNumberStrings).to.be.true;
done();
});
});
});
var chai = require('chai')
, expect = chai.expect
'use strict';
var chai = require('chai')
, expect = chai.expect
, 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() {
it('should return false when comparing DECIMAL and DECIMAL(10,2)', function(done) {
expect(Sequelize.DECIMAL).to.not.equal(Sequelize.DECIMAL(10,2))
done()
})
expect(Sequelize.DECIMAL).to.not.equal(Sequelize.DECIMAL(10, 2));
done();
});
it('DECIMAL(10,2) should be an instance of DECIMAL', function(done) {
expect(Sequelize.DECIMAL(10,2)).to.be.an.instanceof(Sequelize.DECIMAL)
done()
})
expect(Sequelize.DECIMAL(10, 2)).to.be.an.instanceof(Sequelize.DECIMAL);
done();
});
it('should return false when comparing FLOAT and FLOAT(11)', function(done) {
expect(Sequelize.FLOAT).to.not.equal(Sequelize.FLOAT(11))
done()
})
expect(Sequelize.FLOAT).to.not.equal(Sequelize.FLOAT(11));
done();
});
it('FLOAT(11) should be an instance of FLOAT', function(done) {
expect(Sequelize.FLOAT(11)).to.be.an.instanceof(Sequelize.FLOAT)
done()
})
expect(Sequelize.FLOAT(11)).to.be.an.instanceof(Sequelize.FLOAT);
done();
});
it('should return false when comparing STRING and STRING(4096)', function(done) {
expect(Sequelize.STRING).to.not.equal(Sequelize.STRING(4096))
done()
})
expect(Sequelize.STRING).to.not.equal(Sequelize.STRING(4096));
done();
});
it('STRING(4096) should be an instance of STRING', function(done) {
expect(Sequelize.STRING(4096)).to.be.an.instanceof(Sequelize.STRING)
done()
})
expect(Sequelize.STRING(4096)).to.be.an.instanceof(Sequelize.STRING);
done();
});
it('should return false when comparing BIGINT and BIGINT(11)', function(done) {
expect(Sequelize.BIGINT).to.not.equal(Sequelize.BIGINT(11))
done()
})
expect(Sequelize.BIGINT).to.not.equal(Sequelize.BIGINT(11));
done();
});
it('BIGINT(11) should be an instance of BIGINT', function(done) {
expect(Sequelize.BIGINT(11)).to.be.an.instanceof(Sequelize.BIGINT)
done()
})
expect(Sequelize.BIGINT(11)).to.be.an.instanceof(Sequelize.BIGINT);
done();
});
var tests = [
[Sequelize.STRING, 'STRING', 'VARCHAR(255)'],
......@@ -70,46 +72,46 @@ describe(Support.getTestDialectTeaser('DataTypes'), function() {
[Sequelize.INTEGER, 'INTEGER', 'INTEGER'],
[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.ZEROFILL,'INTEGER(11).UNSIGNED.ZEROFILL','INTEGER(11) UNSIGNED 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).UNSIGNED.ZEROFILL, 'INTEGER(11).UNSIGNED.ZEROFILL', 'INTEGER(11) UNSIGNED 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.BIGINT, 'BIGINT', 'BIGINT'],
[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.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.UNSIGNED, 'BIGINT(11).ZEROFILL.UNSIGNED', 'BIGINT(11) UNSIGNED ZEROFILL'],
[Sequelize.FLOAT, 'FLOAT', 'FLOAT'],
[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.ZEROFILL,'FLOAT(11).UNSIGNED.ZEROFILL','FLOAT(11) UNSIGNED 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).UNSIGNED.ZEROFILL, 'FLOAT(11).UNSIGNED.ZEROFILL', 'FLOAT(11) UNSIGNED 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, 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.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.UNSIGNED,'FLOAT(11,12).ZEROFILL.UNSIGNED', '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.UNSIGNED, 'FLOAT(11,12).ZEROFILL.UNSIGNED', 'FLOAT(11,12) UNSIGNED ZEROFILL'],
[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) {
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)';
}
expect(test[0].toString()).to.equal(test[2])
done()
})
})
})
expect(test[0].toString()).to.equal(test[2]);
done();
});
});
});
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../../support')
, DataTypes = require(__dirname + "/../../../lib/data-types")
'use strict';
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()) {
describe('[MYSQL Specific] Associations', function() {
describe('many-to-many', 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})
, Table1 = this.sequelize.define('wp_table1', {foo: DataTypes.STRING})
, self = this
, self = this;
Table1.hasMany(Table2)
Table2.hasMany(Table1)
Table1.hasMany(Table2);
Table2.hasMany(Table1);
Table1.sync({ force: true }).success(function() {
Table2.sync({ force: true }).success(function() {
expect(self.sequelize.daoFactoryManager.getDAO('wp_table1swp_table2s')).to.exist
done()
})
})
})
})
expect(self.sequelize.daoFactoryManager.getDAO('wp_table1swp_table2s')).to.exist;
done();
});
});
});
});
describe('when join table name is specified', function() {
beforeEach(function(done){
beforeEach(function(done) {
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'})
Table2.hasMany(Table1, {joinTableName: 'table1_to_table2'})
Table1.hasMany(Table2, {joinTableName: 'table1_to_table2'});
Table2.hasMany(Table1, {joinTableName: 'table1_to_table2'});
Table1.sync({ force: true }).success(function() {
Table2.sync({ force: true }).success(function() {
done()
})
})
})
done();
});
});
});
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('table1_to_table2')).to.exist
})
})
})
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('table1_to_table2')).to.exist;
});
});
});
describe('HasMany', function() {
beforeEach(function(done) {
//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.Task = this.sequelize.define('Task' + Math.ceil(Math.random()*10000000), { name: DataTypes.STRING })
this.users = null
this.tasks = null
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.users = null;
this.tasks = null;
this.User.hasMany(this.Task, {as:'Tasks', through: 'UserTasks'})
this.Task.hasMany(this.User, {as:'Users', through: 'UserTasks'})
this.User.hasMany(this.Task, {as: 'Tasks', through: 'UserTasks'});
this.Task.hasMany(this.User, {as: 'Users', through: 'UserTasks'});
var self = this
, users = []
, tasks = []
, tasks = [];
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) {
tasks[tasks.length] = {name: 'Task' + Math.random()}
tasks[tasks.length] = {name: 'Task' + Math.random()};
}
this.sequelize.sync({ force: true }).success(function() {
self.User.bulkCreate(users).success(function() {
self.Task.bulkCreate(tasks).success(function() {
done()
})
})
})
})
done();
});
});
});
});
describe('addDAO / getDAO', function() {
beforeEach(function(done) {
var self = this
var self = this;
self.user = null
self.task = null
self.user = null;
self.task = null;
self.User.all().success(function(_users) {
self.Task.all().success(function(_tasks) {
self.user = _users[0]
self.task = _tasks[0]
done()
})
})
})
self.user = _users[0];
self.task = _tasks[0];
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) {
expect(_tasks.length).to.equal(0)
expect(_tasks.length).to.equal(0);
self.user.addTask(self.task).on('success', function() {
self.user.getTasks().on('success', function(_tasks) {
expect(_tasks.length).to.equal(1)
done()
})
})
})
})
})
expect(_tasks.length).to.equal(1);
done();
});
});
});
});
});
describe('removeDAO', function() {
beforeEach(function(done) {
var self = this
var self = this;
self.user = null
self.tasks = null
self.user = null;
self.tasks = null;
self.User.all().success(function(_users) {
self.Task.all().success(function(_tasks) {
self.user = _users[0]
self.tasks = _tasks
done()
})
})
})
self.user = _users[0];
self.tasks = _tasks;
done();
});
});
});
it("should correctly remove associated objects", function(done) {
var self = this
it('should correctly remove associated objects', function(done) {
var self = this;
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.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.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.getTasks().on('success', function(_tasks) {
expect(_tasks).to.have.length(self.tasks.length - 3)
done()
})
})
})
})
})
})
})
})
})
})
})
expect(_tasks).to.have.length(self.tasks.length - 3);
done();
});
});
});
});
});
});
});
});
});
});
});
}
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../../support')
, sinon = require('sinon')
, DataTypes = require(__dirname + "/../../../lib/data-types")
'use strict';
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()) {
describe('[MYSQL Specific] Connector Manager', function() {
it('works correctly after being idle', function(done) {
var User = this.sequelize.define('User', { username: DataTypes.STRING })
, spy = sinon.spy()
, spy = sinon.spy();
User.sync({force: true}).on('success', function() {
User.create({username: 'user1'}).on('success', function() {
User.count().on('success', function(count) {
expect(count).to.equal(1)
spy()
expect(count).to.equal(1);
spy();
setTimeout(function() {
User.count().on('success', function(count) {
expect(count).to.equal(1)
spy()
expect(count).to.equal(1);
spy();
if (spy.calledTwice) {
done()
done();
}
})
}, 1000)
})
})
})
})
});
}, 1000);
});
});
});
});
it('accepts new queries after shutting down a connection', function(done) {
// Create a sequelize instance with pooling disabled
var sequelize = Support.createSequelizeInstance({ pool: false })
var User = sequelize.define('User', { username: DataTypes.STRING })
var sequelize = Support.createSequelizeInstance({ pool: false });
var User = sequelize.define('User', { username: DataTypes.STRING });
User.sync({force: true}).on('success', function() {
User.create({username: 'user1'}).on('success', function() {
......@@ -43,39 +45,39 @@ if (Support.dialectIsMySQL()) {
setTimeout(function() {
// 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) {
expect(count[0].count).to.equal(1)
done()
expect(count[0].count).to.equal(1);
done();
}).error(function(error) {
expect(error).to.not.exist
})
}, 100)
})
})
})
expect(error).to.not.exist;
});
}, 100);
});
});
});
// This should run only on direct mysql
if (Support.dialectIsMySQL(true)) {
it('should maintain connection', function () {
var sequelize = Support.createSequelizeInstance({pool: {min: 1, max: 1, handleDisconnects: true, idle: 5000}}),
cm = sequelize.connectionManager,
conn;
it('should maintain connection', function() {
var sequelize = Support.createSequelizeInstance({pool: {min: 1, max: 1, handleDisconnects: true, idle: 5000}})
, cm = sequelize.connectionManager
, conn;
return sequelize.sync()
.then(function () {
.then(function() {
return cm.getConnection();
})
.then(function (connection) {
.then(function(connection) {
// Save current connection
conn = connection;
})
.then(function () {
.then(function() {
return cm.releaseConnection(conn);
})
.then(function () {
.then(function() {
// Get next available connection
return cm.getConnection();
})
.then(function (connection) {
.then(function(connection) {
// Old threadId should be different from current new one
expect(conn.threadId).to.be.equal(connection.threadId);
expect(cm.validate(conn)).to.be.ok;
......@@ -83,30 +85,31 @@ if (Support.dialectIsMySQL()) {
return cm.releaseConnection(connection);
});
});
it('should work with handleDisconnects', function () {
var sequelize = Support.createSequelizeInstance({pool: {min: 1, max: 1, handleDisconnects: true, idle: 5000}}),
cm = sequelize.connectionManager,
conn;
it('should work with handleDisconnects', function() {
var sequelize = Support.createSequelizeInstance({pool: {min: 1, max: 1, handleDisconnects: true, idle: 5000}})
, cm = sequelize.connectionManager
, conn;
return sequelize.sync()
.then(function (){
.then(function() {
return cm.getConnection();
})
.then(function (connection) {
.then(function(connection) {
// Save current connection
conn = connection;
// simulate a unexpected end
connection._protocol.end();
})
.then(function () {
.then(function() {
return cm.releaseConnection(conn);
})
.then(function () {
.then(function() {
// Get next available connection
return cm.getConnection();
})
.then(function (connection) {
.then(function(connection) {
// Old threadId should be different from current new one
expect(conn.threadId).to.not.be.equal(connection.threadId);
expect(cm.validate(conn)).to.not.be.ok;
......
/* jshint camelcase: false */
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../../support')
, dialect = Support.getTestDialect()
, hstore = require("../../../lib/dialects/postgres/hstore")
'use strict';
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/)) {
describe('[POSTGRES Specific] hstore', function() {
describe('stringify', 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() {
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() {
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) {
expect(hstore.stringify({foo : ""})).to.equal('"foo"=>\"\"')
done()
})
expect(hstore.stringify({foo: ''})).to.equal('"foo"=>\"\"');
done();
});
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() {
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() {
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() {
expect(hstore.stringify({ test: 'value' })).to.equal('"test"=>"value"')
})
expect(hstore.stringify({ test: 'value' })).to.equal('"test"=>"value"');
});
})
});
describe('parse', 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() {
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() {
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() {
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() {
expect(hstore.parse('"foo"=>"\\\\"')).to.deep.equal({foo : "\\"})
})
expect(hstore.parse('"foo"=>"\\\\"')).to.deep.equal({foo: '\\'});
});
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() {
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() {
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};
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};
expect(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 */
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]
'use strict';
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') {
describe('[SQLITE Specific] DAOFactory', function() {
after(function(done) {
this.sequelize.options.storage = ':memory:'
done()
})
this.sequelize.options.storage = ':memory:';
done();
});
beforeEach(function(done) {
this.sequelize.options.storage = dbFile
this.sequelize.options.storage = dbFile;
this.User = this.sequelize.define('User', {
age: DataTypes.INTEGER,
name: DataTypes.STRING,
bio: DataTypes.TEXT
})
});
this.User.sync({ force: true }).success(function() {
done()
})
})
done();
});
});
storages.forEach(function(storage) {
describe('with storage "' + storage + '"', function() {
after(function(done) {
if (storage === dbFile) {
require("fs").writeFile(dbFile, '', function() {
done()
})
require('fs').writeFile(dbFile, '', function() {
done();
});
}
})
});
describe('create', function() {
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) {
expect(user.age).to.equal(21)
expect(user.name).to.equal('John Wayne')
expect(user.bio).to.equal('noot noot')
expect(user.age).to.equal(21);
expect(user.name).to.equal('John Wayne');
expect(user.bio).to.equal('noot noot');
self.User.all().success(function(users) {
var usernames = users.map(function(user) {
return user.name
})
expect(usernames).to.contain('John Wayne')
done()
})
})
})
return user.name;
});
expect(usernames).to.contain('John Wayne');
done();
});
});
});
it('should allow the creation of an object with options as attribute', function(done) {
var Person = this.sequelize.define('Person', {
name: DataTypes.STRING,
options: DataTypes.TEXT
})
});
Person.sync({ force: true }).success(function() {
var options = JSON.stringify({ foo: 'bar', bar: 'foo' })
var options = JSON.stringify({ foo: 'bar', bar: 'foo' });
Person.create({
name: 'John Doe',
options: options
}).success(function(people) {
expect(people.options).to.deep.equal(options)
done()
})
})
})
expect(people.options).to.deep.equal(options);
done();
});
});
});
it('should allow the creation of an object with a boolean (true) as attribute', function(done) {
var Person = this.sequelize.define('Person', {
name: DataTypes.STRING,
has_swag: DataTypes.BOOLEAN
})
});
Person.sync({ force: true }).success(function() {
Person.create({
name: 'John Doe',
has_swag: true
}).success(function(people) {
expect(people.has_swag).to.be.ok
done()
})
})
})
expect(people.has_swag).to.be.ok;
done();
});
});
});
it('should allow the creation of an object with a boolean (false) as attribute', function(done) {
var Person = this.sequelize.define('Person', {
name: DataTypes.STRING,
has_swag: DataTypes.BOOLEAN
})
});
Person.sync({ force: true }).success(function() {
Person.create({
name: 'John Doe',
has_swag: false
}).success(function(people) {
expect(people.has_swag).to.not.be.ok
done()
})
})
})
})
expect(people.has_swag).to.not.be.ok;
done();
});
});
});
});
describe('.find', function() {
beforeEach(function(done) {
this.User.create({name: 'user', bio: 'footbar'}).success(function() {
done()
})
})
it("finds normal lookups", function(done) {
this.User.find({ where: { name:'user' } }).success(function(user) {
expect(user.name).to.equal('user')
done()
})
})
it.skip("should make aliased attributes available", function(done) {
this.User.find({ where: { name:'user' }, attributes: ['id', ['name', 'username']] }).success(function(user) {
expect(user.username).to.equal('user')
done()
})
})
})
done();
});
});
it('finds normal lookups', function(done) {
this.User.find({ where: { name: 'user' } }).success(function(user) {
expect(user.name).to.equal('user');
done();
});
});
it.skip('should make aliased attributes available', function(done) {
this.User.find({ where: { name: 'user' }, attributes: ['id', ['name', 'username']] }).success(function(user) {
expect(user.username).to.equal('user');
done();
});
});
});
describe('.all', function() {
beforeEach(function(done) {
......@@ -138,54 +139,54 @@ if (dialect === 'sqlite') {
{name: 'user', bio: 'foobar'},
{name: 'user', bio: 'foobar'}
]).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) {
expect(users).to.have.length(2)
done()
})
})
})
expect(users).to.have.length(2);
done();
});
});
});
describe('.min', function() {
it("should return the min value", function(done) {
it('should return the min value', function(done) {
var self = this
, users = []
, users = [];
for (var i = 2; i < 5; i++) {
users[users.length] = {age: i}
users[users.length] = {age: i};
}
this.User.bulkCreate(users).success(function() {
self.User.min('age').on('success', function(min) {
expect(min).to.equal(2)
done()
})
})
})
})
expect(min).to.equal(2);
done();
});
});
});
});
describe('.max', function() {
it("should return the max value", function(done) {
it('should return the max value', function(done) {
var self = this
, users = []
, users = [];
for (var i = 2; i <= 5; i++) {
users[users.length] = {age: i}
users[users.length] = {age: i};
}
this.User.bulkCreate(users).success(function() {
self.User.max('age').on('success', function(min) {
expect(min).to.equal(5)
done()
})
})
})
})
})
})
})
expect(min).to.equal(5);
done();
});
});
});
});
});
});
});
}
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../../support')
, DataTypes = require(__dirname + "/../../../lib/data-types")
, dialect = Support.getTestDialect()
'use strict';
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') {
describe('[SQLITE Specific] DAO', function() {
beforeEach(function(done) {
this.User = this.sequelize.define('User', {
username: DataTypes.STRING
})
});
this.User.sync({ force: true }).success(function() {
done()
})
})
done();
});
});
describe('findAll', function() {
it("handles dates correctly", function(done) {
it('handles dates correctly', function(done) {
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() {
self.User.create({ username: 'new user' }).success(function() {
self.User.findAll({
where: ['createdAt > ?', new Date(2012, 01, 01)]
where: ['createdAt > ?', new Date(2012, 1, 1)]
}).success(function(users) {
expect(users).to.have.length(1)
done()
})
})
})
})
})
})
expect(users).to.have.length(1);
done();
});
});
});
});
});
});
}
"use strict";
'use strict';
/* jshint camelcase: false */
var chai = require('chai')
, sinon = require('sinon')
, expect = chai.expect
......@@ -10,7 +9,7 @@ var chai = require('chai')
chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Sequelize Errors"), function () {
describe(Support.getTestDialectTeaser('Sequelize Errors'), function () {
describe('API Surface', function() {
it('Should have the Error constructors exposed', function() {
expect(Sequelize).to.have.property('Error');
......
......@@ -5332,9 +5332,9 @@ describe(Support.getTestDialectTeaser('Hooks'), function() {
});
});
});
// 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('cascade', function() {
......@@ -5354,7 +5354,7 @@ describe(Support.getTestDialectTeaser('Hooks'), function() {
this.Projects.hasMany(this.Tasks, {onDelete: 'cascade', hooks: true});
this.Projects.hasMany(this.MiniTasks, {onDelete: 'cascade', hooks: true});
this.Tasks.belongsTo(this.Projects, {hooks: true});
this.Tasks.hasMany(this.MiniTasks, {onDelete: 'cascade', hooks: true});
......@@ -5502,7 +5502,7 @@ describe(Support.getTestDialectTeaser('Hooks'), function() {
this.Projects.hasMany(this.Tasks, {onDelete: 'cascade', hooks: true});
this.Projects.hasMany(this.MiniTasks, {onDelete: 'cascade', hooks: true});
this.Tasks.belongsTo(this.Projects, {hooks: true});
this.Tasks.hasMany(this.MiniTasks, {onDelete: 'cascade', hooks: true});
......
/* jshint camelcase: false */
/* jshint expr: true */
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
'use strict';
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, Sequelize = require(__dirname + '/../../index')
, DataTypes = require(__dirname + "/../../lib/data-types")
, datetime = require('chai-datetime')
, async = require('async');
, DataTypes = require(__dirname + '/../../lib/data-types')
, datetime = require('chai-datetime')
, async = require('async');
chai.use(datetime)
chai.config.includeStack = true
chai.use(datetime);
chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Include"), function () {
describe('find', function () {
it('should include a non required model, with conditions and two includes N:M 1:M', function ( done ) {
describe(Support.getTestDialectTeaser('Include'), function() {
describe('find', function() {
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 })
, B = this.sequelize.define('B', { 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 () {
B.belongsTo(D);
B.hasMany(C, {
through: 'BC',
through: 'BC'
});
C.hasMany(B, {
through: 'BC',
through: 'BC'
});
D.hasMany(B);
this.sequelize.sync({ force: true }).done(function ( err ) {
expect( err ).not.to.be.ok;
this.sequelize.sync({ force: true }).done(function(err ) {
expect(err).not.to.be.ok;
A.find({
include: [
......@@ -43,14 +43,14 @@ describe(Support.getTestDialectTeaser("Include"), function () {
{ model: D }
]}
]
}).done( function ( err ) {
expect( err ).not.to.be.ok;
}).done(function(err ) {
expect(err).not.to.be.ok;
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 })
, Task = this.sequelize.define('Task', {
deletedAt: {
......@@ -63,27 +63,27 @@ describe(Support.getTestDialectTeaser("Include"), function () {
return this.sequelize.sync({
force: true
}).then(function () {
}).then(function() {
return User.create();
}).then(function (user) {
}).then(function(user) {
return Task.bulkCreate([
{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({
include: [
{model: Task, where: {deletedAt: null}, required: false}
]
});
}).then(function (user) {
}).then(function(user) {
expect(user).to.be.ok;
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', {
name: DataTypes.STRING(40)
})
......@@ -96,12 +96,12 @@ describe(Support.getTestDialectTeaser("Include"), function () {
return this.sequelize
.sync({force: true})
.then(function () {
.then(function() {
return A.create({
name: 'Foobar'
});
})
.then(function () {
.then(function() {
return A.find({
where: {name: 'Foobar'},
include: [
......@@ -109,7 +109,7 @@ describe(Support.getTestDialectTeaser("Include"), function () {
]
});
})
.then(function (a) {
.then(function(a) {
expect(a).to.not.equal(null);
expect(a.get('bs')).to.deep.equal([]);
});
......@@ -136,7 +136,7 @@ describe(Support.getTestDialectTeaser("Include"), function () {
return this.sequelize
.sync({ force: true })
.then(function () {
.then(function() {
return A.find({
include: [
{
......@@ -149,14 +149,14 @@ describe(Support.getTestDialectTeaser("Include"), function () {
]
}
]
})
});
})
.then(function (a) {
.then(function(a) {
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', {})
, B = this.sequelize.define('b', {})
, C = this.sequelize.define('c', {})
......@@ -188,23 +188,23 @@ describe(Support.getTestDialectTeaser("Include"), function () {
H
];
this.sequelize.sync().done(function () {
this.sequelize.sync().done(function() {
async.auto({
a: function (callback) {
a: function(callback) {
A.create({}).done(callback);
},
singleChain: function (callback) {
singleChain: function(callback) {
var previousInstance;
async.eachSeries(singles, function (model, callback) {
async.eachSeries(singles, function(model, callback) {
var values = {};
if (model.name === 'g') {
values.name = 'yolo';
}
model.create(values).done(function (err, instance) {
model.create(values).done(function(err, instance) {
if (previousInstance) {
previousInstance["set"+Sequelize.Utils.uppercaseFirst(model.name)](instance).done(function () {
previousInstance['set'+ Sequelize.Utils.uppercaseFirst(model.name)](instance).done(function() {
previousInstance = instance;
callback();
});
......@@ -215,10 +215,10 @@ describe(Support.getTestDialectTeaser("Include"), function () {
});
}, callback);
},
ab: ['a', 'singleChain', function (callback, results) {
ab: ['a', 'singleChain', function(callback, results) {
results.a.setB(b).done(callback);
}]
}, function () {
}, function() {
A.find({
include: [
......@@ -238,7 +238,7 @@ describe(Support.getTestDialectTeaser("Include"), function () {
]}
]}
]
}).done(function (err, a) {
}).done(function(err, a) {
expect(err).not.to.be.ok;
expect(a.b.c.d.e.f.g.h).to.be.ok;
done();
......
/* jshint camelcase: false */
/* jshint expr: true */
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + "/../../lib/data-types")
, datetime = require('chai-datetime')
, Promise = require('bluebird');
chai.use(datetime)
chai.config.includeStack = true
describe(Support.getTestDialectTeaser("Include"), function () {
describe('findAndCountAll', function () {
it( 'Try to include a required model. Result rows should match count', function ( done ) {
'use strict';
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + '/../../lib/data-types')
, datetime = require('chai-datetime')
, Promise = require('bluebird');
chai.use(datetime);
chai.config.includeStack = true;
describe(Support.getTestDialectTeaser('Include'), function() {
describe('findAndCountAll', function() {
it('Try to include a required model. Result rows should match count', function(done ) {
var DT = DataTypes,
S = this.sequelize,
User = S.define('User', { name: DT.STRING(40) }, { paranoid: true }),
SomeConnection = S.define('SomeConnection', {
m: DT.STRING(40),
fk: DT.INTEGER,
u: DT.INTEGER,
u: DT.INTEGER
}, { paranoid: true }),
A = S.define('A', { 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
User.hasMany( SomeConnection, { foreignKey: 'u' })
User.hasMany(SomeConnection, { foreignKey: 'u' });
SomeConnection.belongsTo( User, { foreignKey: 'u' })
SomeConnection.belongsTo( A, { foreignKey: 'fk', constraints: false })
SomeConnection.belongsTo( B, { foreignKey: 'fk', constraints: false })
SomeConnection.belongsTo( C, { foreignKey: 'fk', constraints: false })
SomeConnection.belongsTo(User, { foreignKey: 'u' });
SomeConnection.belongsTo(A, { foreignKey: 'fk', constraints: false });
SomeConnection.belongsTo(B, { foreignKey: 'fk', constraints: false });
SomeConnection.belongsTo(C, { foreignKey: 'fk', constraints: false });
A.hasMany( SomeConnection, { foreignKey: 'fk', constraints: false })
B.hasMany( SomeConnection, { foreignKey: 'fk', constraints: false })
C.hasMany( SomeConnection, { foreignKey: 'fk', constraints: false })
A.hasMany(SomeConnection, { foreignKey: 'fk', constraints: false });
B.hasMany(SomeConnection, { foreignKey: 'fk', constraints: false });
C.hasMany(SomeConnection, { foreignKey: 'fk', constraints: false });
// 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
User.bulkCreate([
......@@ -48,7 +48,7 @@ describe(Support.getTestDialectTeaser("Include"), function () {
{ name: 'Google' },
{ name: 'Yahoo' },
{ 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
{ u: 1, m: 'A', fk: 1 }, // 1 // Will be deleted
......@@ -74,32 +74,32 @@ describe(Support.getTestDialectTeaser("Include"), function () {
{ u: 3, m: 'A', fk: 3 },
{ u: 2, m: 'B', fk: 2 },
{ u: 1, m: 'A', fk: 4 }, // 4
{ u: 4, m: 'A', fk: 2 },
]).done( function ( err, conns ) { expect( err ).not.to.be.ok; expect( conns ).to.be.length( 24 )
{ u: 4, m: 'A', fk: 2 }
]).done(function(err, conns ) { expect(err).not.to.be.ok; expect(conns).to.be.length(24);
A.bulkCreate([
{ name: 'Just' },
{ name: 'for' },
{ name: 'testing' },
{ name: 'proposes' },
{ name: 'only' },
]).done( function ( err, as ) { expect( err ).not.to.be.ok; expect( as ).to.be.length( 5 )
{ name: 'only' }
]).done(function(err, as ) { expect(err).not.to.be.ok; expect(as).to.be.length(5);
B.bulkCreate([
{ name: 'this should not' },
{ 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([
{ 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
SomeConnection.destroy({where: {
m: 'A',
u: 1,
fk: [ 1, 2 ],
}}).done( function ( err ) { expect( err ).not.to.be.ok
fk: [1, 2]
}}).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 )
A.findAndCountAll({
......@@ -112,52 +112,52 @@ describe(Support.getTestDialectTeaser("Include"), function () {
}
}],
limit: 5,
limit: 5
})
.done( function ( err, result ) {
.done(function(err, result ) {
// Test variables
expect( err ).not.to.be.ok
expect( result.count ).to.be.equal( 2 )
expect( result.rows.length ).to.be.equal( 2 )
expect(err).not.to.be.ok;
expect(result.count).to.be.equal(2);
expect(result.rows.length).to.be.equal(2);
done()
done();
// Last and most important queries - END
})
});
// Delete some of conns to prove the concept - END
})
});
// Create an enviroment - END
})
})
})
})
})
});
});
});
});
});
// Sync them - END
})
});
})
it('should count on a where and not use an uneeded include', function () {
var Project = this.sequelize.define('Project', {
});
it('should count on a where and not use an uneeded include', function() {
var Project = this.sequelize.define('Project', {
id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
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 },
user_name: { type: DataTypes.STRING }
})
});
User.hasMany(Project);
var userId = null
return User.sync({force: true}).then(function () {
var userId = null;
return User.sync({force: true}).then(function() {
return Project.sync({force: true});
}).then(function() {
return Promise.all([User.create(), Project.create(), Project.create(), Project.create()]);
......@@ -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
, Foo = s.define('Foo', {})
, Bar = s.define('Bar', {});
......@@ -196,11 +196,11 @@ describe(Support.getTestDialectTeaser("Include"), function () {
return Foo.findAndCountAll({
include: [{ model: Bar, required: true }],
limit: 2
}).tap(function () {
}).tap(function() {
return Foo.findAll({
include: [{ model: Bar, required: true }],
limit: 2
}).then(function (items) {
}).then(function(items) {
expect(items.length).to.equal(2);
});
});
......@@ -213,4 +213,4 @@ describe(Support.getTestDialectTeaser("Include"), function () {
});
});
});
});
\ No newline at end of file
});
/* jshint camelcase: false */
/* jshint expr: true */
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + "/../../lib/data-types")
, datetime = require('chai-datetime')
'use strict';
chai.use(datetime)
chai.config.includeStack = true
var chai = require('chai')
, 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,
DT = DataTypes,
A = this.A = S.define( 'A', { 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 }),
D = this.D = S.define( 'D', { 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 }),
C = this.C = S.define('C', { name: DT.STRING }, { paranoid: true }),
D = this.D = S.define('D', { name: DT.STRING }, { paranoid: true });
A.belongsTo( B )
A.hasMany( D )
A.hasMany( C )
A.belongsTo(B);
A.hasMany(D);
A.hasMany(C);
B.hasMany( A )
B.hasMany( C )
B.hasMany(A);
B.hasMany(C);
C.belongsTo( A )
C.belongsTo( B )
C.belongsTo(A);
C.belongsTo(B);
D.hasMany( A )
D.hasMany(A);
S.sync({ force: true }).done(function ( err ) {
expect( err ).not.to.be.ok
done()
})
S.sync({ force: true }).done(function(err ) {
expect(err).not.to.be.ok;
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,
Test = S.define('Test',{
Test = S.define('Test', {
name: DataTypes.STRING
},{
timestamps: false,
paranoid: true
});
S.sync({ force: true }).done(function () {
Test.find(1).done(function ( err ) {
expect( err ).to.be.not.ok
done()
})
})
S.sync({ force: true }).done(function() {
Test.find(1).done(function(err ) {
expect(err).to.be.not.ok;
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,
B = this.B,
......@@ -66,21 +66,21 @@ describe(Support.getTestDialectTeaser("Paranoid"), function () {
include: [
{
model: B,
required: false,
required: false
}
],
}
]
};
A.find( options ).done(function ( err ) {
expect( err ).not.to.be.ok
expect( options.include[0].required ).to.be.equal( false )
A.find(options).done(function(err ) {
expect(err).not.to.be.ok;
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,
B = this.B,
......@@ -88,17 +88,17 @@ describe(Support.getTestDialectTeaser("Paranoid"), function () {
include: [
{
model: B,
required: true,
required: true
}
],
}
]
};
A.find( options ).done(function ( err ) {
expect( err ).not.to.be.ok
expect( options.include[0].required ).to.be.equal( true )
A.find(options).done(function(err ) {
expect(err).not.to.be.ok;
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 */
/* jshint expr: true */
var chai = require('chai')
var chai = require('chai')
, Sequelize = require('../../index')
, Promise = Sequelize.Promise
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + "/../../lib/data-types")
, dialect = Support.getTestDialect()
, datetime = require('chai-datetime');
, Promise = Sequelize.Promise
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + '/../../lib/data-types')
, dialect = Support.getTestDialect()
, datetime = require('chai-datetime');
chai.use(datetime);
chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Model"), function () {
describe('attributes', function () {
describe('set', function () {
it('should only be called once when used on a join model called with an association getter', function () {
describe(Support.getTestDialectTeaser('Model'), function() {
describe('attributes', function() {
describe('set', function() {
it('should only be called once when used on a join model called with an association getter', function() {
var self = this;
self.callCount = 0;
this.Student = this.sequelize.define('student', {
no: {type:Sequelize.INTEGER, primaryKey:true},
name: Sequelize.STRING,
no: {type: Sequelize.INTEGER, primaryKey: true},
name: Sequelize.STRING
}, {
tableName: "student",
tableName: 'student',
timestamps: false
});
this.Course = this.sequelize.define('course', {
no: {type:Sequelize.INTEGER,primaryKey:true},
name: Sequelize.STRING,
no: {type: Sequelize.INTEGER, primaryKey: true},
name: Sequelize.STRING
},{
tableName: 'course',
timestamps: false
});
this.Score = this.sequelize.define('score',{
this.Score = this.sequelize.define('score', {
score: Sequelize.INTEGER,
test_value: {
type: Sequelize.INTEGER,
set: function(v) {
self.callCount++;
this.setDataValue('test_value', v+1);
this.setDataValue('test_value', v + 1);
}
}
}, {
......@@ -54,22 +52,22 @@ describe(Support.getTestDialectTeaser("Model"), function () {
this.Student.hasMany(this.Course, {through: this.Score, foreignKey: 'StudentId'});
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(
self.Student.create({no:1, name:'ryan'}),
self.Course.create({no:100, name:'history'})
).spread(function(student, course){
self.Student.create({no: 1, name: 'ryan'}),
self.Course.create({no: 100, name: 'history'})
).spread(function(student, course) {
return student.addCourse(course, {score: 98, test_value: 1000});
}).then(function(){
}).then(function() {
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);
});
})
.then(function(){
.then(function() {
return Promise.join(
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) {
......
"use strict";
'use strict';
/* jshint camelcase: false */
/* jshint expr: true */
var chai = require('chai')
var chai = require('chai')
, Sequelize = require('../../../index')
, Promise = Sequelize.Promise
, expect = chai.expect
, Support = require(__dirname + '/../../support')
, DataTypes = require(__dirname + "/../../../lib/data-types")
, dialect = Support.getTestDialect()
, datetime = require('chai-datetime');
, Promise = Sequelize.Promise
, expect = chai.expect
, Support = require(__dirname + '/../../support')
, DataTypes = require(__dirname + '/../../../lib/data-types')
, dialect = Support.getTestDialect()
, datetime = require('chai-datetime');
chai.use(datetime);
chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Model"), function () {
describe('attributes', function () {
describe('types', function () {
describe('VIRTUAL', function () {
beforeEach(function () {
describe(Support.getTestDialectTeaser('Model'), function() {
describe('attributes', function() {
describe('types', function() {
describe('VIRTUAL', function() {
beforeEach(function() {
this.User = this.sequelize.define('user', {
storage: Sequelize.STRING,
field1: {
type: Sequelize.VIRTUAL,
set: function (val) {
set: function(val) {
this.setDataValue('storage', val);
this.setDataValue('field1', val);
},
get: function () {
get: function() {
return this.getDataValue('field1');
}
},
field2: {
type: Sequelize.VIRTUAL,
get: function () {
get: function() {
return 42;
}
},
......@@ -58,7 +56,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
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({
field1: 'field1_value',
field2: 'field2_value'
......@@ -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 });
});
it('should be ignored in table creation', function () {
return this.sequelize.getQueryInterface().describeTable(this.User.tableName).then(function (fields) {
it('should be ignored in table creation', function() {
return this.sequelize.getQueryInterface().describeTable(this.User.tableName).then(function(fields) {
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([
this.User.find().on('sql', this.sqlAssert),
this.User.findAll().on('sql', this.sqlAssert),
......@@ -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', {
text: Sequelize.TEXT,
someBoolean: {
......@@ -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' }]);
}).then(function () {
}).then(function() {
var boolQuery = 'EXISTS(SELECT 1) AS "someBoolean"';
if (dialect === 'mssql') {
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)] });
}).then(function (post) {
return Post.find({ attributes: ['id', 'text', Sequelize.literal(boolQuery)] });
}).then(function(post) {
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({
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
expect(user.virtualWithDefault).to.equal('cake');
......@@ -124,19 +122,19 @@ describe(Support.getTestDialectTeaser("Model"), function () {
return user.updateAttributes({
field1: 'something else'
});
}).then(function (user) {
}).then(function(user) {
expect(user.virtualWithDefault).to.equal('cake');
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;
return this.User.bulkCreate([{
field1: 'something'
}]).on('sql', this.sqlAssert).then(function () {
}]).on('sql', this.sqlAssert).then(function() {
return self.User.findAll();
}).then(function (users) {
}).then(function(users) {
expect(users[0].storage).to.equal('something');
});
});
......
"use strict";
'use strict';
/* jshint camelcase: false */
/* jshint expr: true */
var chai = require('chai')
var chai = require('chai')
, Sequelize = require('../../index')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + "/../../lib/data-types")
, datetime = require('chai-datetime');
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + '/../../lib/data-types')
, datetime = require('chai-datetime');
chai.use(datetime);
chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Model"), function () {
describe(Support.getTestDialectTeaser('Model'), function() {
beforeEach(function() {
return Support.prepareTransactionTest(this.sequelize).bind(this).then(function(sequelize) {
this.sequelize = sequelize;
this.User = this.sequelize.define('User', {
username: DataTypes.STRING,
secretValue: DataTypes.STRING,
data: DataTypes.STRING,
intVal: DataTypes.INTEGER,
theDate: DataTypes.DATE,
aBool: DataTypes.BOOLEAN
username: DataTypes.STRING,
secretValue: DataTypes.STRING,
data: DataTypes.STRING,
intVal: DataTypes.INTEGER,
theDate: DataTypes.DATE,
aBool: DataTypes.BOOLEAN
});
return this.User.sync({ force: true });
......@@ -78,7 +76,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
canBeDan: {
where: {
username: {
in: 'dan'
in : 'dan'
}
}
},
......@@ -87,12 +85,12 @@ describe(Support.getTestDialectTeaser("Model"), function () {
where: {
other_value: value
}
}
};
},
complexFunction: function(email, accessLevel) {
return {
where: ['email like ? AND access_level >= ?', email + '%', accessLevel]
}
};
},
lowAccess: {
where: {
......@@ -120,7 +118,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}.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) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1);
......@@ -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) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(2);
......@@ -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;
return this.ScopeMe.create({username: 'escape\'d', email: 'fake@fakemail.com'}).then(function(){
return self.ScopeMe.scope('escape').all().then(function(users){
return this.ScopeMe.create({username: 'escape\'d', email: 'fake@fakemail.com'}).then(function() {
return self.ScopeMe.scope('escape').all().then(function(users) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1);
expect(users[0].username).to.equal('escape\'d');
......@@ -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) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(2);
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[0].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[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) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1);
......@@ -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) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1);
......@@ -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) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1);
......@@ -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) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1);
......@@ -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) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(2);
......@@ -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) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1);
......@@ -216,31 +214,31 @@ describe(Support.getTestDialectTeaser("Model"), function () {
});
});
describe("should not overwrite", function () {
it("default scope with values from previous finds", function () {
return this.ScopeMe.findAll({ where: { other_value: 10 }}).bind(this).then(function (users) {
describe('should not overwrite', function() {
it('default scope with values from previous finds', function() {
return this.ScopeMe.findAll({ where: { other_value: 10 }}).bind(this).then(function(users) {
expect(users).to.have.length(1);
return this.ScopeMe.findAll();
}).then(function (users) {
}).then(function(users) {
// This should not have other_value: 10
expect(users).to.have.length(2);
});
});
it("other scopes with values from previous finds", function () {
return this.ScopeMe.scope('highValue').findAll({ where: { access_level: 10 }}).bind(this).then(function (users) {
it('other scopes with values from previous finds', function() {
return this.ScopeMe.scope('highValue').findAll({ where: { access_level: 10 }}).bind(this).then(function(users) {
expect(users).to.have.length(1);
return this.ScopeMe.scope('highValue').findAll();
}).then(function (users) {
}).then(function(users) {
// This should not have other_value: 10
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) {
expect(users).to.have.length(1);
expect(users[0].other_value).to.equal(11);
......@@ -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) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(2);
......@@ -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) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(2);
......@@ -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) {
expect(users).to.be.an.instanceof(Array);
expect(users.length).to.equal(1);
......@@ -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) {
expect(users).to.be.an.instanceof(Array);
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) {
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')
, tobi = this.ScopeMe.scope({method: ['actualValue', 11]});
......
"use strict";
'use strict';
/* jshint camelcase: false */
/* jshint expr: true */
var chai = require('chai')
, sinon = require('sinon')
var chai = require('chai')
, sinon = require('sinon')
, Sequelize = require('../../index')
, Promise = Sequelize.Promise
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + "/../../lib/data-types")
, dialect = Support.getTestDialect()
, datetime = require('chai-datetime')
, _ = require('lodash')
, assert = require('assert')
, current = Support.sequelize;
, Promise = Sequelize.Promise
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + '/../../lib/data-types')
, dialect = Support.getTestDialect()
, datetime = require('chai-datetime')
, _ = require('lodash')
, assert = require('assert')
, current = Support.sequelize;
chai.use(datetime);
chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Model"), function () {
beforeEach(function () {
describe(Support.getTestDialectTeaser('Model'), function() {
beforeEach(function() {
this.clock = sinon.useFakeTimers();
this.User = this.sequelize.define('user', {
......@@ -31,20 +29,20 @@ describe(Support.getTestDialectTeaser("Model"), function () {
bar: {
unique: 'foobar',
type: DataTypes.INTEGER
},
}
});
return this.sequelize.sync({ force: true });
});
afterEach(function () {
afterEach(function() {
this.clock.restore();
});
if (current.dialect.supports.upserts) {
describe('upsert', function () {
it('works with upsert on id', function () {
return this.User.upsert({ id: 42, username: 'john' }).bind(this).then(function (created) {
describe('upsert', function() {
it('works with upsert on id', function() {
return this.User.upsert({ id: 42, username: 'john' }).bind(this).then(function(created) {
if (dialect === 'sqlite') {
expect(created).not.to.be.defined;
} else {
......@@ -53,7 +51,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
this.clock.tick(2000); // Make sure to pass some time so updatedAt != createdAt
return this.User.upsert({ id: 42, username: 'doe' });
}).then(function (created) {
}).then(function(created) {
if (dialect === 'sqlite') {
expect(created).not.to.be.defined;
} else {
......@@ -61,15 +59,15 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}
return this.User.find(42);
}).then(function (user) {
}).then(function(user) {
expect(user.createdAt).to.be.defined;
expect(user.username).to.equal('doe');
expect(user.updatedAt).to.be.afterTime(user.createdAt);
});
});
it('works with upsert on a composite key', function () {
return this.User.upsert({ foo: 'baz', bar: 19, username: 'john' }).bind(this).then(function (created) {
it('works with upsert on a composite key', function() {
return this.User.upsert({ foo: 'baz', bar: 19, username: 'john' }).bind(this).then(function(created) {
if (dialect === 'sqlite') {
expect(created).not.to.be.defined;
} else {
......@@ -78,7 +76,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
this.clock.tick(2000); // Make sure to pass some time so updatedAt != createdAt
return this.User.upsert({ foo: 'baz', bar: 19, username: 'doe' });
}).then(function (created) {
}).then(function(created) {
if (dialect === 'sqlite') {
expect(created).not.to.be.defined;
} else {
......@@ -86,7 +84,7 @@ describe(Support.getTestDialectTeaser("Model"), function () {
}
return this.User.find({ where: { foo: 'baz', bar: 19 }});
}).then(function (user) {
}).then(function(user) {
expect(user.createdAt).to.be.defined;
expect(user.username).to.equal('doe');
expect(user.updatedAt).to.be.afterTime(user.createdAt);
......
/* jshint camelcase: false, expr: true */
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + "/../../lib/data-types")
'use strict';
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, DataTypes = require(__dirname + '/../../lib/data-types')
, Sequelize = require('../../index')
, Promise = Sequelize.Promise
, assert = require('assert');
, Promise = Sequelize.Promise
, assert = require('assert');
chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("CounterCache"), function() {
describe(Support.getTestDialectTeaser('CounterCache'), function() {
it('adds an integer column', function() {
var User = this.sequelize.define('User', {})
var User = this.sequelize.define('User', {})
, Group = this.sequelize.define('Group', {});
User.hasMany(Group, { counterCache: true });
......@@ -21,7 +22,7 @@ describe(Support.getTestDialectTeaser("CounterCache"), function() {
});
it('supports `as`', function() {
var User = this.sequelize.define('User', {})
var User = this.sequelize.define('User', {})
, Group = this.sequelize.define('Group', {});
User.hasMany(Group, { counterCache: { as: 'countDemGroups' } });
......@@ -30,23 +31,23 @@ describe(Support.getTestDialectTeaser("CounterCache"), function() {
});
it('inits at 0', function() {
var User = this.sequelize.define('User', {})
var User = this.sequelize.define('User', {})
, Group = this.sequelize.define('Group', {});
User.hasMany(Group, { counterCache: true });
return this.sequelize.sync({ force: true }).then(function () {
return this.sequelize.sync({ force: true }).then(function() {
return User.create();
}).then(function (user) {
}).then(function(user) {
expect(user.countGroups).to.equal(0);
});
});
describe('hooks', function () {
describe('hooks', function() {
var User, Group;
beforeEach(function() {
User = this.sequelize.define('User', {});
User = this.sequelize.define('User', {});
Group = this.sequelize.define('Group', {});
User.hasMany(Group, { counterCache: true });
......@@ -55,13 +56,13 @@ describe(Support.getTestDialectTeaser("CounterCache"), function() {
});
it('increments', function() {
return User.create().then(function (user) {
return User.create().then(function(user) {
expect(user.countGroups).to.equal(0);
return user.createGroup().return(user);
}).then(function (user) {
return user.createGroup().return (user);
}).then(function(user) {
return User.find(user.id);
}).then(function (user) {
}).then(function(user) {
expect(user.countGroups).to.equal(1);
});
});
......@@ -69,41 +70,41 @@ describe(Support.getTestDialectTeaser("CounterCache"), function() {
it('decrements', function() {
var user;
return User.create().then(function (tmpUser) {
return User.create().then(function(tmpUser) {
user = tmpUser;
return user.createGroup();
}).then(function (group) {
}).then(function(group) {
return group.destroy();
}).then(function () {
}).then(function() {
return user.reload();
}).then(function () {
}).then(function() {
expect(user.countGroups).to.equal(0);
});
});
it('works on update', function () {
it('works on update', function() {
var user, otherUser;
return User.create().then(function (tmpUser) {
return User.create().then(function(tmpUser) {
otherUser = tmpUser;
return User.create();
}).then(function (tmpUser) {
}).then(function(tmpUser) {
user = tmpUser;
return user.createGroup();
}).tap(function (group) {
}).tap(function(group) {
return user.reload();
}).tap(function () {
}).tap(function() {
expect(user.countGroups).to.equal(1);
}).then(function (group) {
}).then(function(group) {
group.UserId = otherUser.id;
return group.save();
}).then(function () {
}).then(function() {
return Promise.all([user.reload(), otherUser.reload()]);
}).then(function () {
}).then(function() {
expect(user.countGroups).to.equal(0);
expect(otherUser.countGroups).to.equal(1);
});
});
});
})
});
......@@ -7,7 +7,7 @@ var chai = require('chai')
chai.config.includeStack = true;
describe(Support.getTestDialectTeaser('Schema'), function () {
describe(Support.getTestDialectTeaser('Schema'), function() {
beforeEach(function() {
return this.sequelize.createSchema('testschema');
});
......@@ -26,7 +26,7 @@ describe(Support.getTestDialectTeaser('Schema'), function () {
return this.User.sync({ force: true });
});
it('supports increment', function () {
it('supports increment', function() {
return this.User.create({ aNumber: 1 }).then(function(user) {
return user.increment('aNumber', { by: 3 });
}).then(function(result) {
......@@ -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 user.decrement('aNumber', { by: 3 });
}).then(function(result) {
......
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/support')
, Promise = require(__dirname + '/../lib/promise')
, Transaction = require(__dirname + '/../lib/transaction')
, current = Support.sequelize;
'use strict';
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) {
describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () {
describe(Support.getTestDialectTeaser('Sequelize#transaction'), function() {
this.timeout(4000);
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
.sequelize
.transaction().then(function(t) { t.commit(); })
.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
.sequelize
.transaction().then(function(t) { t.rollback(); })
......@@ -35,11 +36,11 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () {
return sequelize.sync({ force: true }).success(function() {
return sequelize.transaction();
}).then(function (t) {
}).then(function(t) {
expect(t).to.be.ok;
var query = 'select sleep(2);';
switch(Support.getTestDialect()) {
switch (Support.getTestDialect()) {
case 'postgres':
query = 'select pg_sleep(2);';
break;
......@@ -62,15 +63,15 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () {
.getQueryInterface()
.QueryGenerator
.insertQuery(User.tableName, dao.values, User.rawAttributes);
}).then(function () {
}).then(function() {
return Promise.delay(1000);
}).then(function () {
}).then(function() {
return sequelize.query(query, null, {
raw: true,
plain: true,
transaction: t
});
}).then(function () {
}).then(function() {
return t.commit();
});
}).then(function() {
......@@ -79,7 +80,7 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () {
expect(users[0].name).to.equal('foo');
done();
});
}).catch(done);
}).catch (done);
});
});
}
......@@ -90,7 +91,7 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () {
// not sure if we can test this in sqlite ...
// how could we enforce an authentication error in sqlite?
} else {
it("gets triggered once an error occurs", function(done) {
it('gets triggered once an error occurs', function(done) {
var sequelize = Support.createSequelizeInstance();
// lets overwrite the host to get an error
......@@ -98,7 +99,7 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () {
sequelize
.transaction().then(function() {})
.catch(function(err) {
.catch (function(err) {
expect(err).to.not.be.undefined;
done();
});
......@@ -107,12 +108,12 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), 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) {
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 }
})
});
sequelize
.sync({ force: true })
......@@ -126,41 +127,41 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () {
setTimeout(function() {
transaction
.commit()
.then(function() { return Test.count() })
.then(function() { return Test.count(); })
.then(function(count) {
expect(count).to.equal(1)
done()
})
}, 1000)
})
})
})
})
})
})
expect(count).to.equal(1);
done();
});
}, 1000);
});
});
});
});
});
});
describe('concurrency', function() {
describe('having tables with uniqueness constraints', function() {
beforeEach(function(done) {
var self = this
var self = this;
Support.prepareTransactionTest(this.sequelize, function(sequelize) {
self.sequelize = sequelize
self.sequelize = sequelize;
self.Model = sequelize.define('Model', {
name: { type: Support.Sequelize.STRING, unique: true }
}, {
timestamps: false
})
});
self.Model
.sync({ force: true })
.success(function() { done() })
})
})
.success(function() { done(); });
});
});
it("triggers the error event for the second transactions", function(done) {
var self = this
it('triggers the error event for the second transactions', function(done) {
var self = this;
this.sequelize.transaction().then(function(t1) {
self.sequelize.transaction().then(function(t2) {
......@@ -173,18 +174,18 @@ describe(Support.getTestDialectTeaser("Sequelize#transaction"), function () {
.create({ name: 'omnom' }, { transaction: t2 })
.error(function(err) {
t2.rollback().success(function() {
expect(err).to.be.defined
done()
})
})
setTimeout(function() { t1.commit() }, 100)
})
})
})
})
})
})
})
expect(err).to.be.defined;
done();
});
});
setTimeout(function() { t1.commit(); }, 100);
});
});
});
});
});
});
});
}
var chai = require('chai')
, sinonChai = require("sinon-chai")
, sinon = require('sinon')
, fs = require('fs')
, path = require('path')
, expect = chai.expect
, assert = chai.assert
, Support = require(__dirname + '/../support')
'use strict';
chai.use(sinonChai)
chai.config.includeStack = true
var chai = require('chai')
, 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() {
beforeEach(function() {
this.spy = sinon.spy(console, 'log')
})
this.spy = sinon.spy(console, 'log');
});
afterEach(function() {
console.log.restore()
})
console.log.restore();
});
describe("with disabled logging", function() {
describe('with disabled logging', 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() {
this.sequelize.log()
expect(this.spy.calledOnce).to.be.false
})
})
it('does not call the log method of the logger', function() {
this.sequelize.log();
expect(this.spy.calledOnce).to.be.false;
});
});
describe('with default logging options', 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() {
this.sequelize.log()
expect(this.spy.calledOnce).to.be.true
})
this.sequelize.log();
expect(this.spy.calledOnce).to.be.true;
});
it('logs an empty string as info event', function() {
this.sequelize.log()
expect(this.spy.calledOnce).to.be.true
})
})
this.sequelize.log();
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() {
this.sequelize.log('my message')
expect(this.spy.withArgs('my message').calledOnce).to.be.true
})
})
this.sequelize.log('my message');
expect(this.spy.withArgs('my message').calledOnce).to.be.true;
});
});
describe("called with more than two arguments", function() {
it("passes the arguments to the logger", function() {
this.sequelize.log('error', 'my message', 1, { a: 1 })
expect(this.spy.withArgs('error', 'my message', 1, { a: 1 }).calledOnce).to.be.true
})
})
})
describe('called with more than two arguments', function() {
it('passes the arguments to the logger', function() {
this.sequelize.log('error', 'my message', 1, { a: 1 });
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() {
this.spy = sinon.spy()
this.sequelize = new Support.Sequelize('db', 'user', 'pw', { logging: this.spy })
})
this.spy = sinon.spy();
this.sequelize = new Support.Sequelize('db', 'user', 'pw', { logging: this.spy });
});
it("calls the custom logger method", function() {
this.sequelize.log('om nom')
expect(this.spy.calledOnce).to.be.true
})
})
})
})
it('calls the custom logger method', function() {
this.sequelize.log('om nom');
expect(this.spy.calledOnce).to.be.true;
});
});
});
});
"use strict";
var fs = require('fs')
, path = require('path')
, _ = require('lodash')
, Sequelize = require(__dirname + "/../index")
, DataTypes = require(__dirname + "/../lib/data-types")
, Config = require(__dirname + "/config/config")
, chai = require("chai")
, chaiAsPromised = require("chai-as-promised");
'use strict';
var fs = require('fs')
, path = require('path')
, _ = require('lodash')
, Sequelize = require(__dirname + '/../index')
, DataTypes = require(__dirname + '/../lib/data-types')
, Config = require(__dirname + '/config/config')
, chai = require('chai')
, expect = chai.expect
, chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
......@@ -44,21 +45,21 @@ var Support = {
if (dialect === '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
if (fs.existsSync(p)) {
resolve(Sequelize.Promise.promisify(fs.unlink)(p));
} else {
resolve();
}
}).then(function () {
var options = Sequelize.Utils._.extend({}, sequelize.options, { storage: p })
}).then(function() {
var options = Sequelize.Utils._.extend({}, sequelize.options, { storage: p })
, _sequelize = new Sequelize(sequelize.config.database, null, null, options);
if (callback) {
_sequelize.sync({ force: true }).success(function() { callback(_sequelize); });
} else {
return _sequelize.sync({ force: true }).return(_sequelize);
return _sequelize.sync({ force: true }).return (_sequelize);
}
});
} else {
......@@ -77,11 +78,11 @@ var Support = {
var config = Config[options.dialect];
var sequelizeOptions = _.defaults(options, {
host: options.host || config.host,
logging: (process.env.SEQ_LOG ? console.log : false),
dialect: options.dialect,
port: options.port || process.env.SEQ_PORT || config.port,
pool: config.pool,
host: options.host || config.host,
logging: (process.env.SEQ_LOG ? console.log : false),
dialect: options.dialect,
port: options.port || process.env.SEQ_PORT || config.port,
pool: config.pool,
dialectOptions: options.dialectOptions || {}
});
......@@ -111,11 +112,11 @@ var Support = {
return sequelize
.getQueryInterface()
.dropAllEnums()
.catch(function (err) {
.catch (function(err) {
console.log('Error in support.clearDatabase() dropAllEnums() :: ', err);
});
})
.catch(function(err) {
.catch (function(err) {
console.log('Error in support.clearDatabase() dropAllTables() :: ', err);
});
},
......@@ -168,7 +169,7 @@ var Support = {
dialect = 'postgres-native';
}
return "[" + dialect.toUpperCase() + "] " + moduleName;
return '[' + dialect.toUpperCase() + '] ' + moduleName;
},
getTestUrl: function(config) {
......@@ -180,12 +181,12 @@ var Support = {
} else {
var credentials = dbConfig.username;
if(dbConfig.password) {
credentials += ":" + dbConfig.password;
if (dbConfig.password) {
credentials += ':' + dbConfig.password;
}
url = config.dialect + "://" + credentials
+ "@" + dbConfig.host + ":" + dbConfig.port + "/" + dbConfig.database;
url = config.dialect + '://' + credentials
+ '@' + dbConfig.host + ':' + dbConfig.port + '/' + dbConfig.database;
}
return url;
}
......@@ -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...
before(function() {
var dialect = Support.getTestDialect();
if (dialect !== "postgres" && dialect !== "postgres-native") {
if (dialect !== 'postgres' && dialect !== 'postgres-native') {
return;
}
......
"use strict";
'use strict';
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/support')
, dialect = Support.getTestDialect()
, Sequelize = require(__dirname + '/../index')
, Promise = Sequelize.Promise
, sinon = require('sinon');
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/support')
, dialect = Support.getTestDialect()
, Sequelize = require(__dirname + '/../index')
, Promise = Sequelize.Promise
, sinon = require('sinon');
if (dialect !== 'sqlite') {
// Sqlite does not support setting timezone
describe(Support.getTestDialectTeaser('Timezone'), function () {
beforeEach(function () {
describe(Support.getTestDialectTeaser('Timezone'), function() {
beforeEach(function() {
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()'
, startQueryTime = Date.now();
......@@ -26,27 +26,27 @@ if (dialect !== 'sqlite') {
now = 'GETDATE()';
}
var query = "SELECT " + now + " as now";
var query = 'SELECT ' + now + ' as now';
return Promise.all([
this.sequelize.query(query),
this.sequelizeWithTimezone.query(query)
]).spread(function (now1, now2) {
var elapsedQueryTime = Date.now() - startQueryTime;
]).spread(function(now1, now2) {
var elapsedQueryTime = (Date.now() - startQueryTime) + 20;
expect(now1[0].now.getTime()).to.be.closeTo(now2[0].now.getTime(), elapsedQueryTime);
});
});
if (Support.dialectIsMySQL()) {
it('handles existing timestamps', function () {
it('handles existing timestamps', function() {
var NormalUser = this.sequelize.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({});
}).then(function (timezonedUser) {
}).then(function(timezonedUser) {
this.timezonedUser = timezonedUser;
return NormalUser.find(timezonedUser.id);
}).then(function (normalUser) {
}).then(function(normalUser) {
// 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 test does not apply to PG, since it stores the timezone along with the timestamp.
......
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/support')
, dialect = Support.getTestDialect()
, Promise = require(__dirname + '/../lib/promise')
'use strict';
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/support')
, dialect = Support.getTestDialect()
, Promise = require(__dirname + '/../lib/promise')
, Transaction = require(__dirname + '/../lib/transaction')
, sinon = require('sinon')
, current = Support.sequelize;
, sinon = require('sinon')
, current = Support.sequelize;
if (current.dialect.supports.transactions) {
describe(Support.getTestDialectTeaser("Transaction"), function () {
describe(Support.getTestDialectTeaser('Transaction'), function() {
this.timeout(4000);
describe('constructor', function() {
it('stores options', function() {
......@@ -35,59 +37,59 @@ describe(Support.getTestDialectTeaser("Transaction"), function () {
});
});
describe('autoCallback', function () {
it('supports automatically committing', function () {
return this.sequelize.transaction(function (t) {
describe('autoCallback', function() {
it('supports automatically committing', function() {
return this.sequelize.transaction(function(t) {
return Promise.resolve();
});
});
it('supports automatically rolling back with a thrown error', function () {
return expect(this.sequelize.transaction(function (t) {
it('supports automatically rolling back with a thrown error', function() {
return expect(this.sequelize.transaction(function(t) {
throw new Error('Yolo');
})).to.eventually.be.rejected;
});
it('supports automatically rolling back with a rejection', function () {
return expect(this.sequelize.transaction(function (t) {
it('supports automatically rolling back with a rejection', function() {
return expect(this.sequelize.transaction(function(t) {
return Promise.reject('Swag');
})).to.eventually.be.rejected;
});
it('errors when no promise chain is returned', function () {
return expect(this.sequelize.transaction(function (t) {
it('errors when no promise chain is returned', function() {
return expect(this.sequelize.transaction(function(t) {
})).to.eventually.be.rejected;
});
});
it('does not allow queries after commit', function () {
it('does not allow queries after commit', function() {
var self = this;
return expect(
this.sequelize.transaction().then(function (t) {
return self.sequelize.query("SELECT 1+1", null, {transaction: t, raw: true}).then(function () {
this.sequelize.transaction().then(function(t) {
return self.sequelize.query('SELECT 1+1', null, {transaction: t, raw: true}).then(function() {
return t.commit();
}).then(function () {
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});
});
})
).to.eventually.be.rejected;
});
it('does not allow queries after rollback', function () {
it('does not allow queries after rollback', function() {
var self = this;
return expect(
this.sequelize.transaction().then(function (t) {
return self.sequelize.query("SELECT 1+1", null, {transaction: t, raw: true}).then(function () {
this.sequelize.transaction().then(function(t) {
return self.sequelize.query('SELECT 1+1', null, {transaction: t, raw: true}).then(function() {
return t.commit();
}).then(function () {
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});
});
})
).to.eventually.be.rejected;
});
if (current.dialect.supports.lock) {
describe('row locking', function () {
describe('row locking', function() {
this.timeout(10000);
it('supports for update', function (done) {
it('supports for update', function(done) {
var User = this.sequelize.define('user', {
username: Support.Sequelize.STRING,
awesome: Support.Sequelize.BOOLEAN
......@@ -96,10 +98,10 @@ describe(Support.getTestDialectTeaser("Transaction"), function () {
, t1Spy = sinon.spy()
, t2Spy = sinon.spy();
this.sequelize.sync({ force: true }).then(function () {
this.sequelize.sync({ force: true }).then(function() {
return User.create({ username: 'jan'});
}).then(function () {
self.sequelize.transaction().then(function (t1) {
}).then(function() {
self.sequelize.transaction().then(function(t1) {
return User.find({
where: {
username: 'jan'
......@@ -107,20 +109,20 @@ describe(Support.getTestDialectTeaser("Transaction"), function () {
}, {
lock: t1.LOCK.UPDATE,
transaction: t1
}).then(function (t1Jan) {
}).then(function(t1Jan) {
self.sequelize.transaction({
isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED
}).then(function (t2) {
}).then(function(t2) {
User.find({
where: {
username: 'jan'
},
}
}, {
lock: t2.LOCK.UPDATE,
transaction: t2
}).then(function () {
t2Spy()
t2.commit().then(function () {
}).then(function() {
t2Spy();
t2.commit().then(function() {
expect(t2Spy).to.have.been.calledAfter(t1Spy); // Find should not succeed before t1 has comitted
done();
});
......@@ -128,8 +130,8 @@ describe(Support.getTestDialectTeaser("Transaction"), function () {
t1Jan.updateAttributes({
awesome: true
}, { transaction: t1}).then(function () {
t1Spy()
}, { transaction: t1}).then(function() {
t1Spy();
setTimeout(t1.commit.bind(t1), 2000);
});
});
......@@ -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', {
username: Support.Sequelize.STRING,
awesome: Support.Sequelize.BOOLEAN
......@@ -148,10 +150,10 @@ describe(Support.getTestDialectTeaser("Transaction"), function () {
, t2FindSpy = sinon.spy()
, t2UpdateSpy = sinon.spy();
this.sequelize.sync({ force: true }).then(function () {
this.sequelize.sync({ force: true }).then(function() {
return User.create({ username: 'jan'});
}).then(function () {
self.sequelize.transaction().then(function (t1) {
}).then(function() {
self.sequelize.transaction().then(function(t1) {
return User.find({
where: {
username: 'jan'
......@@ -159,24 +161,24 @@ describe(Support.getTestDialectTeaser("Transaction"), function () {
}, {
lock: t1.LOCK.SHARE,
transaction: t1
}).then(function (t1Jan) {
}).then(function(t1Jan) {
self.sequelize.transaction({
isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED
}).then(function (t2) {
}).then(function(t2) {
User.find({
where: {
username: 'jan'
}
}, { transaction: t2}).then(function (t2Jan) {
}, { transaction: t2}).then(function(t2Jan) {
t2FindSpy();
t2Jan.updateAttributes({
awesome: false
}, {
transaction: t2
}).then(function () {
}).then(function() {
t2UpdateSpy();
t2.commit().then(function () {
t2.commit().then(function() {
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
done();
......@@ -188,8 +190,8 @@ describe(Support.getTestDialectTeaser("Transaction"), function () {
awesome: true
}, {
transaction: t1
}).then(function () {
setTimeout(function () {
}).then(function() {
setTimeout(function() {
t1Spy();
t1.commit();
}, 2000);
......
"use strict";
'use strict';
var chai = require('chai')
, spies = require('chai-spies')
, expect = chai.expect
, Utils = require(__dirname + '/../lib/utils')
var chai = require('chai')
, spies = require('chai-spies')
, expect = chai.expect
, Utils = require(__dirname + '/../lib/utils')
, Support = require(__dirname + '/support');
chai.use(spies);
chai.config.includeStack = true;
describe(Support.getTestDialectTeaser("Utils"), function() {
describe(Support.getTestDialectTeaser('Utils'), 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() {
// noot noot
};
......@@ -22,7 +22,7 @@ describe(Support.getTestDialectTeaser("Utils"), function() {
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() {
alert(1); // noot noot
};
......@@ -33,7 +33,7 @@ describe(Support.getTestDialectTeaser("Utils"), function() {
expect(result).not.to.match(/.*noot.*/);
});
it("removes range comments", function() {
it('removes range comments', function() {
var s = function() {
alert(1); /*
noot noot
......@@ -53,7 +53,7 @@ describe(Support.getTestDialectTeaser("Utils"), function() {
describe('argsArePrimaryKeys', 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() {
......@@ -61,10 +61,10 @@ describe(Support.getTestDialectTeaser("Utils"), 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;
});
});
......@@ -134,7 +134,7 @@ describe(Support.getTestDialectTeaser("Utils"), function() {
describe('expectation', 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() {
});
if (Support.getTestDialect() === 'postgres') {
describe('json', function () {
describe('json', function() {
var queryGenerator = require('../lib/dialects/postgres/query-generator.js');
it('successfully parses a complex nested condition hash', function() {
......@@ -163,17 +163,17 @@ describe(Support.getTestDialectTeaser("Utils"), function() {
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';
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';
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 value = '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() {
});
}
describe('inflection', function () {
it('works better than lingo ;)', function () {
describe('inflection', function() {
it('works better than lingo ;)', function() {
expect(Utils.pluralize('buy')).to.equal('buys');
expect(Utils.pluralize('holiday')).to.equal('holidays');
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!