/
cls.test.js
437 lines (375 loc) · 13 KB
/
cls.test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
'use strict';
const chai = require('chai');
const expect = chai.expect;
const Support = require('./support');
const { Sequelize, DataTypes } = require('@sequelize/core');
const cls = require('cls-hooked');
const current = Support.sequelize;
const delay = require('delay');
const sinon = require('sinon');
if (current.dialect.supports.transactions) {
describe(Support.getTestDialectTeaser('CLS (Async hooks)'), () => {
before(() => {
current.constructor.useCLS(cls.createNamespace('sequelize'));
});
after(() => {
cls.destroyNamespace('sequelize');
delete Sequelize._cls;
});
beforeEach(async function () {
this.sequelize = await Support.prepareTransactionTest(this.sequelize);
this.ns = cls.getNamespace('sequelize');
this.User = this.sequelize.define('user', {
name: DataTypes.STRING,
});
await this.sequelize.sync({ force: true });
});
describe('context', () => {
it('does not use continuation storage on manually managed transactions', async function () {
await Sequelize._clsRun(async () => {
const transaction = await this.sequelize.transaction();
expect(this.ns.get('transaction')).not.to.be.ok;
await transaction.rollback();
});
});
it('supports several concurrent transactions', async function () {
let t1id;
let t2id;
await Promise.all([
this.sequelize.transaction(async () => {
t1id = this.ns.get('transaction').id;
}),
this.sequelize.transaction(async () => {
t2id = this.ns.get('transaction').id;
}),
]);
expect(t1id).to.be.ok;
expect(t2id).to.be.ok;
expect(t1id).not.to.equal(t2id);
});
it('supports nested promise chains', async function () {
await this.sequelize.transaction(async () => {
const tid = this.ns.get('transaction').id;
await this.User.findAll();
expect(this.ns.get('transaction').id).to.be.ok;
expect(this.ns.get('transaction').id).to.equal(tid);
});
});
it('does not leak variables to the outer scope', async function () {
// This is a little tricky. We want to check the values in the outer scope, when the transaction has been successfully set up, but before it has been comitted.
// We can't just call another function from inside that transaction, since that would transfer the context to that function - exactly what we are trying to prevent;
let transactionSetup = false;
let transactionEnded = false;
const clsTask = this.sequelize.transaction(async () => {
transactionSetup = true;
await delay(500);
expect(this.ns.get('transaction')).to.be.ok;
transactionEnded = true;
});
await new Promise(resolve => {
// Wait for the transaction to be setup
const interval = setInterval(() => {
if (transactionSetup) {
clearInterval(interval);
resolve();
}
}, 200);
});
expect(transactionEnded).not.to.be.ok;
expect(this.ns.get('transaction')).not.to.be.ok;
// Just to make sure it didn't change between our last check and the assertion
expect(transactionEnded).not.to.be.ok;
await clsTask; // ensure we don't leak the promise
});
it('does not leak variables to the following promise chain', async function () {
await this.sequelize.transaction(() => {});
expect(this.ns.get('transaction')).not.to.be.ok;
});
it('does not leak outside findOrCreate', async function () {
await this.User.findOrCreate({
where: {
name: 'Kafka',
},
logging(sql) {
if (/default/.test(sql)) {
throw new Error('The transaction was not properly assigned');
}
},
});
await this.User.findAll();
});
});
describe('sequelize.query integration', () => {
it('automagically uses the transaction in all calls', async function () {
await this.sequelize.transaction(async () => {
await this.User.create({ name: 'bob' });
return Promise.all([
expect(this.User.findAll({ transaction: null })).to.eventually.have.length(0),
expect(this.User.findAll({})).to.eventually.have.length(1),
]);
});
});
it('automagically uses the transaction in all calls with async/await', async function () {
await this.sequelize.transaction(async () => {
await this.User.create({ name: 'bob' });
expect(await this.User.findAll({ transaction: null })).to.have.length(0);
expect(await this.User.findAll({})).to.have.length(1);
});
});
});
// reason for this test: https://github.com/sequelize/sequelize/issues/12973
describe('Model Hook integration', () => {
function testHooks({ method, hooks: hookNames, optionPos, execute, getModel }) {
it(`passes the transaction to hooks {${hookNames.join(',')}} when calling ${method}`, async function () {
await this.sequelize.transaction(async transaction => {
const hooks = Object.create(null);
for (const hookName of hookNames) {
hooks[hookName] = sinon.spy();
}
const User = Reflect.apply(getModel, this, []);
for (const [hookName, spy] of Object.entries(hooks)) {
User[hookName](spy);
}
await Reflect.apply(execute, this, [User]);
const spyMatcher = [];
// ignore all arguments until we get to the option bag.
for (let i = 0; i < optionPos; i++) {
spyMatcher.push(sinon.match.any);
}
// find the transaction in the option bag
spyMatcher.push(sinon.match.has('transaction', transaction));
for (const [hookName, spy] of Object.entries(hooks)) {
expect(
spy,
`hook ${hookName} did not receive the transaction from CLS.`,
).to.have.been.calledWith(...spyMatcher);
}
});
});
}
testHooks({
method: 'Model.bulkCreate',
hooks: ['beforeBulkCreate', 'beforeCreate', 'afterCreate', 'afterBulkCreate'],
optionPos: 1,
async execute(User) {
await User.bulkCreate([{ name: 'bob' }], { individualHooks: true });
},
getModel() {
return this.User;
},
});
testHooks({
method: 'Model.findAll',
hooks: ['beforeFind', 'beforeFindAfterExpandIncludeAll', 'beforeFindAfterOptions'],
optionPos: 0,
async execute(User) {
await User.findAll();
},
getModel() {
return this.User;
},
});
testHooks({
method: 'Model.findAll',
hooks: ['afterFind'],
optionPos: 1,
async execute(User) {
await User.findAll();
},
getModel() {
return this.User;
},
});
testHooks({
method: 'Model.count',
hooks: ['beforeCount'],
optionPos: 0,
async execute(User) {
await User.count();
},
getModel() {
return this.User;
},
});
testHooks({
method: 'Model.upsert',
hooks: ['beforeUpsert', 'afterUpsert'],
optionPos: 1,
async execute(User) {
await User.upsert({
id: 1,
name: 'bob',
});
},
getModel() {
return this.User;
},
});
testHooks({
method: 'Model.destroy',
hooks: ['beforeBulkDestroy', 'afterBulkDestroy'],
optionPos: 0,
async execute(User) {
await User.destroy({ where: { name: 'bob' } });
},
getModel() {
return this.User;
},
});
testHooks({
method: 'Model.destroy with individualHooks',
hooks: ['beforeDestroy', 'beforeDestroy'],
optionPos: 1,
async execute(User) {
await User.create({ name: 'bob' });
await User.destroy({ where: { name: 'bob' }, individualHooks: true });
},
getModel() {
return this.User;
},
});
testHooks({
method: 'Model#destroy',
hooks: ['beforeDestroy', 'beforeDestroy'],
optionPos: 1,
async execute(User) {
const user = await User.create({ name: 'bob' });
await user.destroy();
},
getModel() {
return this.User;
},
});
testHooks({
method: 'Model.update',
hooks: ['beforeBulkUpdate', 'afterBulkUpdate'],
optionPos: 0,
async execute(User) {
await User.update({ name: 'alice' }, { where: { name: 'bob' } });
},
getModel() {
return this.User;
},
});
testHooks({
method: 'Model.update with individualHooks',
hooks: ['beforeUpdate', 'afterUpdate'],
optionPos: 1,
async execute(User) {
await User.create({ name: 'bob' });
await User.update({ name: 'alice' }, { where: { name: 'bob' }, individualHooks: true });
},
getModel() {
return this.User;
},
});
testHooks({
method: 'Model#save (isNewRecord)',
hooks: ['beforeCreate', 'afterCreate'],
optionPos: 1,
async execute(User) {
const user = User.build({ name: 'bob' });
user.name = 'alice';
await user.save();
},
getModel() {
return this.User;
},
});
testHooks({
method: 'Model#save (!isNewRecord)',
hooks: ['beforeUpdate', 'afterUpdate'],
optionPos: 1,
async execute(User) {
const user = await User.create({ name: 'bob' });
user.name = 'alice';
await user.save();
},
getModel() {
return this.User;
},
});
describe('paranoid restore', () => {
beforeEach(async function () {
this.ParanoidUser = this.sequelize.define('ParanoidUser', {
name: DataTypes.STRING,
}, { paranoid: true });
await this.ParanoidUser.sync({ force: true });
});
testHooks({
method: 'Model.restore',
hooks: ['beforeBulkRestore', 'afterBulkRestore'],
optionPos: 0,
async execute() {
const User = this.ParanoidUser;
await User.restore({ where: { name: 'bob' } });
},
getModel() {
return this.ParanoidUser;
},
});
testHooks({
method: 'Model.restore with individualHooks',
hooks: ['beforeRestore', 'afterRestore'],
optionPos: 1,
async execute() {
const User = this.ParanoidUser;
await User.create({ name: 'bob' });
await User.destroy({ where: { name: 'bob' } });
await User.restore({ where: { name: 'bob' }, individualHooks: true });
},
getModel() {
return this.ParanoidUser;
},
});
testHooks({
method: 'Model#restore',
hooks: ['beforeRestore', 'afterRestore'],
optionPos: 1,
async execute() {
const User = this.ParanoidUser;
const user = await User.create({ name: 'bob' });
await user.destroy();
await user.restore();
},
getModel() {
return this.ParanoidUser;
},
});
});
});
it('CLS namespace is stored in Sequelize._cls', function () {
expect(Sequelize._cls).to.equal(this.ns);
});
it('promises returned by sequelize.query are correctly patched', async function () {
await this.sequelize.transaction(async t => {
await this.sequelize.query('select 1', { type: Sequelize.QueryTypes.SELECT });
return expect(this.ns.get('transaction')).to.equal(t);
});
});
it('custom logging with benchmarking has correct CLS context', async function () {
const logger = sinon.spy(() => {
return this.ns.get('value');
});
const sequelize = Support.createSequelizeInstance({
logging: logger,
benchmark: true,
});
const result = this.ns.runPromise(async () => {
this.ns.set('value', 1);
await delay(500);
return sequelize.query('select 1;');
});
await this.ns.runPromise(() => {
this.ns.set('value', 2);
return sequelize.query('select 2;');
});
await result;
expect(logger.calledTwice).to.be.true;
expect(logger.firstCall.args[0]).to.be.match(/Executed \((\d*|default)\): select 2/);
expect(logger.firstCall.returnValue).to.be.equal(2);
expect(logger.secondCall.args[0]).to.be.match(/Executed \((\d*|default)\): select 1/);
expect(logger.secondCall.returnValue).to.be.equal(1);
});
});
}