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

Commit c14972b9 by Andy Edwards Committed by GitHub

refactor: asyncify test/unit (#12223)

1 parent 6d116f87
......@@ -89,7 +89,7 @@ const Support = {
lastSqliteInstance = _sequelize;
return _sequelize;
}
return Promise.resolve(sequelize);
return sequelize;
},
createSequelizeInstance(options) {
......@@ -145,24 +145,22 @@ const Support = {
await this.dropTestSchemas(sequelize);
},
dropTestSchemas(sequelize) {
async dropTestSchemas(sequelize) {
const queryInterface = sequelize.getQueryInterface();
if (!queryInterface.queryGenerator._dialect.supports.schemas) {
return this.sequelize.drop({});
}
return sequelize.showAllSchemas().then(schemas => {
const schemasPromise = [];
schemas.forEach(schema => {
const schemaName = schema.name ? schema.name : schema;
if (schemaName !== sequelize.config.database) {
schemasPromise.push(sequelize.dropSchema(schemaName));
}
});
return Promise.all(schemasPromise.map(p => p.catch(e => e)))
.then(() => {}, () => {});
const schemas = await sequelize.showAllSchemas();
const schemasPromise = [];
schemas.forEach(schema => {
const schemaName = schema.name ? schema.name : schema;
if (schemaName !== sequelize.config.database) {
schemasPromise.push(sequelize.dropSchema(schemaName));
}
});
await Promise.all(schemasPromise.map(p => p.catch(e => e)));
},
getSupportedDialects() {
......
......@@ -180,14 +180,13 @@ describe(Support.getTestDialectTeaser('belongsToMany'), () => {
this.destroy.restore();
});
it('uses one insert into statement', function() {
return user.setTasks([task1, task2]).then(() => {
expect(this.findAll).to.have.been.calledOnce;
expect(this.bulkCreate).to.have.been.calledOnce;
});
it('uses one insert into statement', async function() {
await user.setTasks([task1, task2]);
expect(this.findAll).to.have.been.calledOnce;
expect(this.bulkCreate).to.have.been.calledOnce;
});
it('uses one delete from statement', function() {
it('uses one delete from statement', async function() {
this.findAll
.onFirstCall().resolves([])
.onSecondCall().resolves([
......@@ -195,12 +194,10 @@ describe(Support.getTestDialectTeaser('belongsToMany'), () => {
{ userId: 42, taskId: 16 }
]);
return user.setTasks([task1, task2]).then(() => {
return user.setTasks(null);
}).then(() => {
expect(this.findAll).to.have.been.calledTwice;
expect(this.destroy).to.have.been.calledOnce;
});
await user.setTasks([task1, task2]);
await user.setTasks(null);
expect(this.findAll).to.have.been.calledTwice;
expect(this.destroy).to.have.been.calledOnce;
});
});
......
......@@ -46,14 +46,13 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
this.update.restore();
});
it('uses one update statement for addition', function() {
return user.setTasks([task1, task2]).then(() => {
expect(this.findAll).to.have.been.calledOnce;
expect(this.update).to.have.been.calledOnce;
});
it('uses one update statement for addition', async function() {
await user.setTasks([task1, task2]);
expect(this.findAll).to.have.been.calledOnce;
expect(this.update).to.have.been.calledOnce;
});
it('uses one delete from statement', function() {
it('uses one delete from statement', async function() {
this.findAll
.onFirstCall().resolves([])
.onSecondCall().resolves([
......@@ -61,13 +60,11 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
{ userId: 42, taskId: 16 }
]);
return user.setTasks([task1, task2]).then(() => {
this.update.resetHistory();
return user.setTasks(null);
}).then(() => {
expect(this.findAll).to.have.been.calledTwice;
expect(this.update).to.have.been.calledOnce;
});
await user.setTasks([task1, task2]);
this.update.resetHistory();
await user.setTasks(null);
expect(this.findAll).to.have.been.calledTwice;
expect(this.update).to.have.been.calledOnce;
});
});
......@@ -143,7 +140,7 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
idC = Math.random().toString(),
foreignKey = 'user_id';
it('should fetch associations for a single instance', () => {
it('should fetch associations for a single instance', async () => {
const findAll = stub(Task, 'findAll').resolves([
Task.build({}),
Task.build({})
......@@ -159,15 +156,16 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
expect(findAll).to.have.been.calledOnce;
expect(findAll.firstCall.args[0].where).to.deep.equal(where);
return actual.then(results => {
try {
const results = await actual;
expect(results).to.be.an('array');
expect(results.length).to.equal(2);
}).finally(() => {
} finally {
findAll.restore();
});
}
});
it('should fetch associations for multiple source instances', () => {
it('should fetch associations for multiple source instances', async () => {
const findAll = stub(Task, 'findAll').returns(
Promise.resolve([
Task.build({
......@@ -196,16 +194,17 @@ describe(Support.getTestDialectTeaser('hasMany'), () => {
expect(findAll.firstCall.args[0].where[foreignKey]).to.have.property(Op.in);
expect(findAll.firstCall.args[0].where[foreignKey][Op.in]).to.deep.equal([idA, idB, idC]);
return actual.then(result => {
try {
const result = await actual;
expect(result).to.be.an('object');
expect(Object.keys(result)).to.deep.equal([idA, idB, idC]);
expect(result[idA].length).to.equal(3);
expect(result[idB].length).to.equal(1);
expect(result[idC].length).to.equal(0);
}).finally(() => {
} finally {
findAll.restore();
});
}
});
});
describe('association hooks', () => {
......
......@@ -20,7 +20,7 @@ describe('connection manager', () => {
this.sequelize = Support.createSequelizeInstance();
});
it('should resolve connection on dialect connection manager', function() {
it('should resolve connection on dialect connection manager', async function() {
const connection = {};
this.dialect.connectionManager.connect.resolves(connection);
......@@ -28,12 +28,11 @@ describe('connection manager', () => {
const config = {};
return expect(connectionManager._connect(config)).to.eventually.equal(connection).then(() => {
expect(this.dialect.connectionManager.connect).to.have.been.calledWith(config);
});
await expect(connectionManager._connect(config)).to.eventually.equal(connection);
expect(this.dialect.connectionManager.connect).to.have.been.calledWith(config);
});
it('should let beforeConnect hook modify config', function() {
it('should let beforeConnect hook modify config', async function() {
const username = Math.random().toString(),
password = Math.random().toString();
......@@ -45,25 +44,23 @@ describe('connection manager', () => {
const connectionManager = new ConnectionManager(this.dialect, this.sequelize);
return connectionManager._connect({}).then(() => {
expect(this.dialect.connectionManager.connect).to.have.been.calledWith({
username,
password
});
await connectionManager._connect({});
expect(this.dialect.connectionManager.connect).to.have.been.calledWith({
username,
password
});
});
it('should call afterConnect', function() {
it('should call afterConnect', async function() {
const spy = sinon.spy();
this.sequelize.afterConnect(spy);
const connectionManager = new ConnectionManager(this.dialect, this.sequelize);
return connectionManager._connect({}).then(() => {
expect(spy.callCount).to.equal(1);
expect(spy.firstCall.args[0]).to.equal(this.connection);
expect(spy.firstCall.args[1]).to.eql({});
});
await connectionManager._connect({});
expect(spy.callCount).to.equal(1);
expect(spy.firstCall.args[0]).to.equal(this.connection);
expect(spy.firstCall.args[1]).to.eql({});
});
});
......@@ -80,28 +77,26 @@ describe('connection manager', () => {
this.sequelize = Support.createSequelizeInstance();
});
it('should call beforeDisconnect', function() {
it('should call beforeDisconnect', async function() {
const spy = sinon.spy();
this.sequelize.beforeDisconnect(spy);
const connectionManager = new ConnectionManager(this.dialect, this.sequelize);
return connectionManager._disconnect(this.connection).then(() => {
expect(spy.callCount).to.equal(1);
expect(spy.firstCall.args[0]).to.equal(this.connection);
});
await connectionManager._disconnect(this.connection);
expect(spy.callCount).to.equal(1);
expect(spy.firstCall.args[0]).to.equal(this.connection);
});
it('should call afterDisconnect', function() {
it('should call afterDisconnect', async function() {
const spy = sinon.spy();
this.sequelize.afterDisconnect(spy);
const connectionManager = new ConnectionManager(this.dialect, this.sequelize);
return connectionManager._disconnect(this.connection).then(() => {
expect(spy.callCount).to.equal(1);
expect(spy.firstCall.args[0]).to.equal(this.connection);
});
await connectionManager._disconnect(this.connection);
expect(spy.callCount).to.equal(1);
expect(spy.firstCall.args[0]).to.equal(this.connection);
});
});
});
......@@ -37,7 +37,7 @@ if (dialect === 'mssql') {
this.connectionStub.restore();
});
it('connectionManager._connect() does not delete `domain` from config.dialectOptions', function() {
it('connectionManager._connect() does not delete `domain` from config.dialectOptions', async function() {
this.connectionStub.returns({
STATE: {},
state: '',
......@@ -53,12 +53,11 @@ if (dialect === 'mssql') {
});
expect(this.config.dialectOptions.domain).to.equal('TEST.COM');
return this.instance.dialect.connectionManager._connect(this.config).then(() => {
expect(this.config.dialectOptions.domain).to.equal('TEST.COM');
});
await this.instance.dialect.connectionManager._connect(this.config);
expect(this.config.dialectOptions.domain).to.equal('TEST.COM');
});
it('connectionManager._connect() should reject if end was called and connect was not', function() {
it('connectionManager._connect() should reject if end was called and connect was not', async function() {
this.connectionStub.returns({
STATE: {},
state: '',
......@@ -73,14 +72,15 @@ if (dialect === 'mssql') {
on: () => {}
});
return this.instance.dialect.connectionManager._connect(this.config)
.catch(err => {
expect(err.name).to.equal('SequelizeConnectionError');
expect(err.parent.message).to.equal('Connection was closed by remote server');
});
try {
await this.instance.dialect.connectionManager._connect(this.config);
} catch (err) {
expect(err.name).to.equal('SequelizeConnectionError');
expect(err.parent.message).to.equal('Connection was closed by remote server');
}
});
it('connectionManager._connect() should call connect if state is initialized', function() {
it('connectionManager._connect() should call connect if state is initialized', async function() {
const connectStub = sinon.stub();
const INITIALIZED = { name: 'INITIALIZED' };
this.connectionStub.returns({
......@@ -98,10 +98,8 @@ if (dialect === 'mssql') {
on: () => {}
});
return this.instance.dialect.connectionManager._connect(this.config)
.then(() => {
expect(connectStub.called).to.equal(true);
});
await this.instance.dialect.connectionManager._connect(this.config);
expect(connectStub.called).to.equal(true);
});
});
}
......@@ -31,13 +31,11 @@ if (dialect === 'mssql') {
});
describe('beginTransaction', () => {
it('should call beginTransaction with correct arguments', () => {
return query._run(connectionStub, 'BEGIN TRANSACTION')
.then(() => {
expect(connectionStub.beginTransaction.called).to.equal(true);
expect(connectionStub.beginTransaction.args[0][1]).to.equal('transactionName');
expect(connectionStub.beginTransaction.args[0][2]).to.equal(tediousIsolationLevel.REPEATABLE_READ);
});
it('should call beginTransaction with correct arguments', async () => {
await query._run(connectionStub, 'BEGIN TRANSACTION');
expect(connectionStub.beginTransaction.called).to.equal(true);
expect(connectionStub.beginTransaction.args[0][1]).to.equal('transactionName');
expect(connectionStub.beginTransaction.args[0][2]).to.equal(tediousIsolationLevel.REPEATABLE_READ);
});
});
......
......@@ -19,7 +19,7 @@ describe('[MYSQL/MARIADB Specific] Query', () => {
console.log.restore();
});
it('check iterable', () => {
it('check iterable', async () => {
const validWarning = [];
const invalidWarning = {};
const warnings = [validWarning, undefined, invalidWarning];
......@@ -28,10 +28,9 @@ describe('[MYSQL/MARIADB Specific] Query', () => {
const stub = sinon.stub(query, 'run');
stub.onFirstCall().resolves(warnings);
return query.logWarnings('dummy-results').then(results => {
expect('dummy-results').to.equal(results);
expect(true).to.equal(console.log.calledOnce);
});
const results = await query.logWarnings('dummy-results');
expect('dummy-results').to.equal(results);
expect(true).to.equal(console.log.calledOnce);
});
});
});
......@@ -51,21 +51,21 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
expect(_validateAndRunHooks).to.not.have.been.called;
});
it('fulfills when validation is successful', function() {
it('fulfills when validation is successful', async function() {
const instanceValidator = new InstanceValidator(this.User.build());
const result = instanceValidator.validate();
return expect(result).to.be.fulfilled;
await expect(result).to.be.fulfilled;
});
it('rejects with a validation error when validation fails', function() {
it('rejects with a validation error when validation fails', async function() {
const instanceValidator = new InstanceValidator(this.User.build({ fails: true }));
const result = instanceValidator.validate();
return expect(result).to.be.rejectedWith(SequelizeValidationError);
await expect(result).to.be.rejectedWith(SequelizeValidationError);
});
it('has a useful default error message for not null validation failures', () => {
it('has a useful default error message for not null validation failures', async () => {
const User = Support.sequelize.define('user', {
name: {
type: Support.Sequelize.STRING,
......@@ -76,7 +76,7 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
const instanceValidator = new InstanceValidator(User.build());
const result = instanceValidator.validate();
return expect(result).to.be.rejectedWith(SequelizeValidationError, /user\.name cannot be null/);
await expect(result).to.be.rejectedWith(SequelizeValidationError, /user\.name cannot be null/);
});
});
......@@ -86,19 +86,18 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
sinon.stub(this.successfulInstanceValidator, '_validate').resolves();
});
it('should run beforeValidate and afterValidate hooks when _validate is successful', function() {
it('should run beforeValidate and afterValidate hooks when _validate is successful', async function() {
const beforeValidate = sinon.spy();
const afterValidate = sinon.spy();
this.User.beforeValidate(beforeValidate);
this.User.afterValidate(afterValidate);
return expect(this.successfulInstanceValidator._validateAndRunHooks()).to.be.fulfilled.then(() => {
expect(beforeValidate).to.have.been.calledOnce;
expect(afterValidate).to.have.been.calledOnce;
});
await expect(this.successfulInstanceValidator._validateAndRunHooks()).to.be.fulfilled;
expect(beforeValidate).to.have.been.calledOnce;
expect(afterValidate).to.have.been.calledOnce;
});
it('should run beforeValidate hook but not afterValidate hook when _validate is unsuccessful', function() {
it('should run beforeValidate hook but not afterValidate hook when _validate is unsuccessful', async function() {
const failingInstanceValidator = new InstanceValidator(this.User.build());
sinon.stub(failingInstanceValidator, '_validate').rejects(new Error());
const beforeValidate = sinon.spy();
......@@ -106,52 +105,48 @@ describe(Support.getTestDialectTeaser('InstanceValidator'), () => {
this.User.beforeValidate(beforeValidate);
this.User.afterValidate(afterValidate);
return expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected.then(() => {
expect(beforeValidate).to.have.been.calledOnce;
expect(afterValidate).to.not.have.been.called;
});
await expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected;
expect(beforeValidate).to.have.been.calledOnce;
expect(afterValidate).to.not.have.been.called;
});
it('should emit an error from after hook when afterValidate fails', function() {
it('should emit an error from after hook when afterValidate fails', async function() {
this.User.afterValidate(() => {
throw new Error('after validation error');
});
return expect(this.successfulInstanceValidator._validateAndRunHooks()).to.be.rejectedWith('after validation error');
await expect(this.successfulInstanceValidator._validateAndRunHooks()).to.be.rejectedWith('after validation error');
});
describe('validatedFailed hook', () => {
it('should call validationFailed hook when validation fails', function() {
it('should call validationFailed hook when validation fails', async function() {
const failingInstanceValidator = new InstanceValidator(this.User.build());
sinon.stub(failingInstanceValidator, '_validate').rejects(new Error());
const validationFailedHook = sinon.spy();
this.User.validationFailed(validationFailedHook);
return expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected.then(() => {
expect(validationFailedHook).to.have.been.calledOnce;
});
await expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected;
expect(validationFailedHook).to.have.been.calledOnce;
});
it('should not replace the validation error in validationFailed hook by default', function() {
it('should not replace the validation error in validationFailed hook by default', async function() {
const failingInstanceValidator = new InstanceValidator(this.User.build());
sinon.stub(failingInstanceValidator, '_validate').rejects(new SequelizeValidationError());
const validationFailedHook = sinon.stub().resolves();
this.User.validationFailed(validationFailedHook);
return expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected.then(err => {
expect(err.name).to.equal('SequelizeValidationError');
});
const err = await expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected;
expect(err.name).to.equal('SequelizeValidationError');
});
it('should replace the validation error if validationFailed hook creates a new error', function() {
it('should replace the validation error if validationFailed hook creates a new error', async function() {
const failingInstanceValidator = new InstanceValidator(this.User.build());
sinon.stub(failingInstanceValidator, '_validate').rejects(new SequelizeValidationError());
const validationFailedHook = sinon.stub().throws(new Error('validation failed hook error'));
this.User.validationFailed(validationFailedHook);
return expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected.then(err => {
expect(err.message).to.equal('validation failed hook error');
});
const err = await expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected;
expect(err.message).to.equal('validation failed hook error');
});
});
});
......
......@@ -8,7 +8,7 @@ const chai = require('chai'),
describe(Support.getTestDialectTeaser('Instance'), () => {
describe('build', () => {
it('should populate NOW default values', () => {
it('should populate NOW default values', async () => {
const Model = current.define('Model', {
created_time: {
type: DataTypes.DATE,
......@@ -45,7 +45,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
expect(instance.get('updated_time')).to.be.ok;
expect(instance.get('updated_time')).to.be.an.instanceof(Date);
return instance.validate();
await instance.validate();
});
it('should populate explicitly undefined UUID primary keys', () => {
......
......@@ -78,9 +78,7 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
describe('custom setter', () => {
before(function() {
this.stubCreate = sinon.stub(current.getQueryInterface(), 'insert').callsFake(instance => {
return Promise.resolve([instance, 1]);
});
this.stubCreate = sinon.stub(current.getQueryInterface(), 'insert').callsFake(async instance => [instance, 1]);
});
after(function() {
......@@ -103,52 +101,48 @@ describe(Support.getTestDialectTeaser('Instance'), () => {
}
});
it('does not set field to changed if field is set to the same value with custom setter using primitive value', () => {
it('does not set field to changed if field is set to the same value with custom setter using primitive value', async () => {
const user = User.build({
phoneNumber: '+1 234 567'
});
return user.save().then(() => {
expect(user.changed('phoneNumber')).to.be.false;
await user.save();
expect(user.changed('phoneNumber')).to.be.false;
user.set('phoneNumber', '+1 (0) 234567'); // Canonical equivalent of existing phone number
expect(user.changed('phoneNumber')).to.be.false;
});
user.set('phoneNumber', '+1 (0) 234567');// Canonical equivalent of existing phone number
expect(user.changed('phoneNumber')).to.be.false;
});
it('sets field to changed if field is set to the another value with custom setter using primitive value', () => {
it('sets field to changed if field is set to the another value with custom setter using primitive value', async () => {
const user = User.build({
phoneNumber: '+1 234 567'
});
return user.save().then(() => {
expect(user.changed('phoneNumber')).to.be.false;
await user.save();
expect(user.changed('phoneNumber')).to.be.false;
user.set('phoneNumber', '+1 (0) 765432'); // Canonical non-equivalent of existing phone number
expect(user.changed('phoneNumber')).to.be.true;
});
user.set('phoneNumber', '+1 (0) 765432');// Canonical non-equivalent of existing phone number
expect(user.changed('phoneNumber')).to.be.true;
});
it('does not set field to changed if field is set to the same value with custom setter using object', () => {
it('does not set field to changed if field is set to the same value with custom setter using object', async () => {
const user = User.build({
phoneNumber: '+1 234 567'
});
return user.save().then(() => {
expect(user.changed('phoneNumber')).to.be.false;
await user.save();
expect(user.changed('phoneNumber')).to.be.false;
user.set('phoneNumber', { country: '1', area: '234', local: '567' }); // Canonical equivalent of existing phone number
expect(user.changed('phoneNumber')).to.be.false;
});
user.set('phoneNumber', { country: '1', area: '234', local: '567' });// Canonical equivalent of existing phone number
expect(user.changed('phoneNumber')).to.be.false;
});
it('sets field to changed if field is set to the another value with custom setter using object', () => {
it('sets field to changed if field is set to the another value with custom setter using object', async () => {
const user = User.build({
phoneNumber: '+1 234 567'
});
return user.save().then(() => {
expect(user.changed('phoneNumber')).to.be.false;
await user.save();
expect(user.changed('phoneNumber')).to.be.false;
user.set('phoneNumber', { country: '1', area: '765', local: '432' }); // Canonical non-equivalent of existing phone number
expect(user.changed('phoneNumber')).to.be.true;
});
user.set('phoneNumber', { country: '1', area: '765', local: '432' });// Canonical non-equivalent of existing phone number
expect(user.changed('phoneNumber')).to.be.true;
});
});
});
......
......@@ -30,14 +30,14 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
describe('validations', () => {
it('should not fail for renamed fields', function() {
return this.Model.bulkCreate([
it('should not fail for renamed fields', async function() {
await this.Model.bulkCreate([
{ accountId: 42 }
], { validate: true }).then(() => {
expect(this.stub.getCall(0).args[1]).to.deep.equal([
{ account_id: 42, id: null }
]);
});
], { validate: true });
expect(this.stub.getCall(0).args[1]).to.deep.equal([
{ account_id: 42, id: null }
]);
});
});
});
......
......@@ -38,32 +38,28 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
describe('should pass the same options to model.aggregate as findAndCountAll', () => {
it('with includes', function() {
it('with includes', async function() {
const queryObject = {
include: [this.Project]
};
return this.User.count(queryObject)
.then(() => this.User.findAndCountAll(queryObject))
.then(() => {
const count = this.stub.getCall(0).args;
const findAndCountAll = this.stub.getCall(1).args;
expect(count).to.eql(findAndCountAll);
});
await this.User.count(queryObject);
await this.User.findAndCountAll(queryObject);
const count = this.stub.getCall(0).args;
const findAndCountAll = this.stub.getCall(1).args;
expect(count).to.eql(findAndCountAll);
});
it('attributes should be stripped in case of findAndCountAll', function() {
it('attributes should be stripped in case of findAndCountAll', async function() {
const queryObject = {
attributes: ['username']
};
return this.User.count(queryObject)
.then(() => this.User.findAndCountAll(queryObject))
.then(() => {
const count = this.stub.getCall(0).args;
const findAndCountAll = this.stub.getCall(1).args;
expect(count).not.to.eql(findAndCountAll);
count[2].attributes = undefined;
expect(count).to.eql(findAndCountAll);
});
await this.User.count(queryObject);
await this.User.findAndCountAll(queryObject);
const count = this.stub.getCall(0).args;
const findAndCountAll = this.stub.getCall(1).args;
expect(count).not.to.eql(findAndCountAll);
count[2].attributes = undefined;
expect(count).to.eql(findAndCountAll);
});
});
......
......@@ -30,14 +30,13 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.count.resetBehavior();
});
it('with errors in count and findAll both', function() {
return this.User.findAndCountAll({})
.then(() => {
throw new Error();
})
.catch(() => {
expect(this.stub.callCount).to.eql(0);
});
it('with errors in count and findAll both', async function() {
try {
await this.User.findAndCountAll({});
throw new Error();
} catch (err) {
expect(this.stub.callCount).to.eql(0);
}
});
});
});
......
......@@ -19,34 +19,34 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.sinon.restore();
});
it('should return the result of the first find call if not empty', function() {
it('should return the result of the first find call if not empty', async function() {
const result = {},
where = { prop: Math.random().toString() },
findSpy = this.sinon.stub(Model, 'findOne').resolves(result);
return expect(Model.findCreateFind({
await expect(Model.findCreateFind({
where
})).to.eventually.eql([result, false]).then(() => {
expect(findSpy).to.have.been.calledOnce;
expect(findSpy.getCall(0).args[0].where).to.equal(where);
});
})).to.eventually.eql([result, false]);
expect(findSpy).to.have.been.calledOnce;
expect(findSpy.getCall(0).args[0].where).to.equal(where);
});
it('should create if first find call is empty', function() {
it('should create if first find call is empty', async function() {
const result = {},
where = { prop: Math.random().toString() },
createSpy = this.sinon.stub(Model, 'create').resolves(result);
this.sinon.stub(Model, 'findOne').resolves(null);
return expect(Model.findCreateFind({
await expect(Model.findCreateFind({
where
})).to.eventually.eql([result, true]).then(() => {
expect(createSpy).to.have.been.calledWith(where);
});
})).to.eventually.eql([result, true]);
expect(createSpy).to.have.been.calledWith(where);
});
it('should do a second find if create failed do to unique constraint', function() {
it('should do a second find if create failed do to unique constraint', async function() {
const result = {},
where = { prop: Math.random().toString() },
findSpy = this.sinon.stub(Model, 'findOne');
......@@ -56,12 +56,12 @@ describe(Support.getTestDialectTeaser('Model'), () => {
findSpy.onFirstCall().resolves(null);
findSpy.onSecondCall().resolves(result);
return expect(Model.findCreateFind({
await expect(Model.findCreateFind({
where
})).to.eventually.eql([result, false]).then(() => {
expect(findSpy).to.have.been.calledTwice;
expect(findSpy.getCall(1).args[0].where).to.equal(where);
});
})).to.eventually.eql([result, false]);
expect(findSpy).to.have.been.calledTwice;
expect(findSpy.getCall(1).args[0].where).to.equal(where);
});
});
});
......@@ -34,25 +34,23 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.clsStub.restore();
});
it('should use transaction from cls if available', function() {
it('should use transaction from cls if available', async function() {
const options = {
where: {
name: 'John'
}
};
return this.User.findOrCreate(options)
.then(() => {
expect.fail('expected to fail');
})
.catch(err => {
if (!/abort/.test(err.message)) throw err;
expect(this.clsStub.calledOnce).to.equal(true, 'expected to ask for transaction');
});
try {
await this.User.findOrCreate(options);
expect.fail('expected to fail');
} catch (err) {
if (!/abort/.test(err.message)) throw err;
expect(this.clsStub.calledOnce).to.equal(true, 'expected to ask for transaction');
}
});
it('should not use transaction from cls if provided as argument', function() {
it('should not use transaction from cls if provided as argument', async function() {
const options = {
where: {
name: 'John'
......@@ -60,14 +58,13 @@ describe(Support.getTestDialectTeaser('Model'), () => {
transaction: { id: 123 }
};
return this.User.findOrCreate(options)
.then(() => {
expect.fail('expected to fail');
})
.catch(err => {
if (!/abort/.test(err.message)) throw err;
expect(this.clsStub.called).to.equal(false);
});
try {
await this.User.findOrCreate(options);
expect.fail('expected to fail');
} catch (err) {
if (!/abort/.test(err.message)) throw err;
expect(this.clsStub.called).to.equal(false);
}
});
});
});
......@@ -71,63 +71,63 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
describe('attributes include / exclude', () => {
it('allows me to include additional attributes', function() {
return Model.findAll({
it('allows me to include additional attributes', async function() {
await Model.findAll({
attributes: {
include: ['foobar']
}
}).then(() => {
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'id',
'name',
'foobar'
]);
});
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'id',
'name',
'foobar'
]);
});
it('allows me to exclude attributes', function() {
return Model.findAll({
it('allows me to exclude attributes', async function() {
await Model.findAll({
attributes: {
exclude: ['name']
}
}).then(() => {
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'id'
]);
});
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'id'
]);
});
it('include takes precendence over exclude', function() {
return Model.findAll({
it('include takes precendence over exclude', async function() {
await Model.findAll({
attributes: {
exclude: ['name'],
include: ['name']
}
}).then(() => {
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'id',
'name'
]);
});
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'id',
'name'
]);
});
it('works for models without PK #4607', function() {
it('works for models without PK #4607', async function() {
const Model = current.define('model', {}, { timestamps: false });
const Foo = current.define('foo');
Model.hasOne(Foo);
Model.removeAttribute('id');
return Model.findAll({
await Model.findAll({
attributes: {
include: ['name']
},
include: [Foo]
}).then(() => {
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'name'
]);
});
expect(this.stub.getCall(0).args[2].attributes).to.deep.equal([
'name'
]);
});
});
......
......@@ -23,15 +23,14 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
describe('should not add limit when querying on a primary key', () => {
it('with id primary key', function() {
it('with id primary key', async function() {
const Model = current.define('model');
return Model.findOne({ where: { id: 42 } }).then(() => {
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
await Model.findOne({ where: { id: 42 } });
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
it('with custom primary key', function() {
it('with custom primary key', async function() {
const Model = current.define('model', {
uid: {
type: DataTypes.INTEGER,
......@@ -40,12 +39,11 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}
});
return Model.findOne({ where: { uid: 42 } }).then(() => {
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
await Model.findOne({ where: { uid: 42 } });
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
it('with blob primary key', function() {
it('with blob primary key', async function() {
const Model = current.define('model', {
id: {
type: DataTypes.BLOB,
......@@ -54,22 +52,20 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}
});
return Model.findOne({ where: { id: Buffer.from('foo') } }).then(() => {
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
await Model.findOne({ where: { id: Buffer.from('foo') } });
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
});
it('should add limit when using { $ gt on the primary key', function() {
it('should add limit when using { $ gt on the primary key', async function() {
const Model = current.define('model');
return Model.findOne({ where: { id: { [Op.gt]: 42 } } }).then(() => {
expect(this.stub.getCall(0).args[0]).to.be.an('object').to.have.property('limit');
});
await Model.findOne({ where: { id: { [Op.gt]: 42 } } });
expect(this.stub.getCall(0).args[0]).to.be.an('object').to.have.property('limit');
});
describe('should not add limit when querying on an unique key', () => {
it('with custom unique key', function() {
it('with custom unique key', async function() {
const Model = current.define('model', {
unique: {
type: DataTypes.INTEGER,
......@@ -77,12 +73,11 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}
});
return Model.findOne({ where: { unique: 42 } }).then(() => {
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
await Model.findOne({ where: { unique: 42 } });
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
it('with blob unique key', function() {
it('with blob unique key', async function() {
const Model = current.define('model', {
unique: {
type: DataTypes.BLOB,
......@@ -90,13 +85,12 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}
});
return Model.findOne({ where: { unique: Buffer.from('foo') } }).then(() => {
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
await Model.findOne({ where: { unique: Buffer.from('foo') } });
expect(this.stub.getCall(0).args[0]).to.be.an('object').not.to.have.property('limit');
});
});
it('should add limit when using multi-column unique key', function() {
it('should add limit when using multi-column unique key', async function() {
const Model = current.define('model', {
unique1: {
type: DataTypes.INTEGER,
......@@ -108,9 +102,8 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}
});
return Model.findOne({ where: { unique1: 42 } }).then(() => {
expect(this.stub.getCall(0).args[0]).to.be.an('object').to.have.property('limit');
});
await Model.findOne({ where: { unique1: 42 } });
expect(this.stub.getCall(0).args[0]).to.be.an('object').to.have.property('limit');
});
});
});
......@@ -32,16 +32,14 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
describe('properly clones input values', () => {
it('with default options', function() {
return this.User.update(this.updates, { where: { secretValue: '1' } }).then(() => {
expect(this.updates).to.be.deep.eql(this.cloneUpdates);
});
it('with default options', async function() {
await this.User.update(this.updates, { where: { secretValue: '1' } });
expect(this.updates).to.be.deep.eql(this.cloneUpdates);
});
it('when using fields option', function() {
return this.User.update(this.updates, { where: { secretValue: '1' }, fields: ['name'] }).then(() => {
expect(this.updates).to.be.deep.eql(this.cloneUpdates);
});
it('when using fields option', async function() {
await this.User.update(this.updates, { where: { secretValue: '1' }, fields: ['name'] });
expect(this.updates).to.be.deep.eql(this.cloneUpdates);
});
});
......
......@@ -51,48 +51,45 @@ describe(Support.getTestDialectTeaser('Model'), () => {
this.stub.restore();
});
it('skip validations for missing fields', function() {
return expect(this.User.upsert({
it('skip validations for missing fields', async function() {
await expect(this.User.upsert({
name: 'Grumpy Cat'
})).not.to.be.rejectedWith(Sequelize.ValidationError);
});
it('creates new record with correct field names', function() {
return this.User
it('creates new record with correct field names', async function() {
await this.User
.upsert({
name: 'Young Cat',
virtualValue: 999
})
.then(() => {
expect(Object.keys(this.stub.getCall(0).args[1])).to.deep.equal([
'name', 'value', 'created_at', 'updatedAt'
]);
});
expect(Object.keys(this.stub.getCall(0).args[1])).to.deep.equal([
'name', 'value', 'created_at', 'updatedAt'
]);
});
it('creates new record with timestamps disabled', function() {
return this.UserNoTime
it('creates new record with timestamps disabled', async function() {
await this.UserNoTime
.upsert({
name: 'Young Cat'
})
.then(() => {
expect(Object.keys(this.stub.getCall(0).args[1])).to.deep.equal([
'name'
]);
});
expect(Object.keys(this.stub.getCall(0).args[1])).to.deep.equal([
'name'
]);
});
it('updates all changed fields by default', function() {
return this.User
it('updates all changed fields by default', async function() {
await this.User
.upsert({
name: 'Old Cat',
virtualValue: 111
})
.then(() => {
expect(Object.keys(this.stub.getCall(0).args[2])).to.deep.equal([
'name', 'value', 'updatedAt'
]);
});
expect(Object.keys(this.stub.getCall(0).args[2])).to.deep.equal([
'name', 'value', 'updatedAt'
]);
});
});
}
......
......@@ -33,7 +33,7 @@ describe('Transaction', () => {
this.stubConnection.restore();
});
it('should run auto commit query only when needed', function() {
it('should run auto commit query only when needed', async function() {
const expectations = {
all: [
'START TRANSACTION;'
......@@ -45,13 +45,13 @@ describe('Transaction', () => {
'BEGIN TRANSACTION;'
]
};
return current.transaction(() => {
await current.transaction(async () => {
expect(this.stub.args.map(arg => arg[0])).to.deep.equal(expectations[dialect] || expectations.all);
return Promise.resolve();
});
});
it('should set isolation level correctly', function() {
it('should set isolation level correctly', async function() {
const expectations = {
all: [
'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;',
......@@ -69,9 +69,9 @@ describe('Transaction', () => {
'BEGIN TRANSACTION;'
]
};
return current.transaction({ isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.READ_UNCOMMITTED }, () => {
await current.transaction({ isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.READ_UNCOMMITTED }, async () => {
expect(this.stub.args.map(arg => arg[0])).to.deep.equal(expectations[dialect] || expectations.all);
return Promise.resolve();
});
});
});
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!