/
support.js
298 lines (236 loc) · 7.82 KB
/
support.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
'use strict';
const fs = require('fs');
const path = require('path');
const { isDeepStrictEqual } = require('util');
const _ = require('lodash');
const Sequelize = require('sequelize');
const Config = require('./config/config');
const chai = require('chai');
const expect = chai.expect;
const AbstractQueryGenerator = require('sequelize/lib/dialects/abstract/query-generator');
const distDir = path.resolve(__dirname, '../dist');
chai.use(require('chai-datetime'));
chai.use(require('chai-as-promised'));
chai.use(require('sinon-chai'));
chai.config.includeStack = true;
chai.should();
// Make sure errors get thrown when testing
process.on('uncaughtException', e => {
console.error('An unhandled exception occurred:');
throw e;
});
let onNextUnhandledRejection = null;
let unhandledRejections = null;
process.on('unhandledRejection', e => {
if (unhandledRejections) {
unhandledRejections.push(e);
}
const onNext = onNextUnhandledRejection;
if (onNext) {
onNextUnhandledRejection = null;
onNext(e);
}
if (onNext || unhandledRejections) {
return;
}
console.error('An unhandled rejection occurred:');
throw e;
});
if (global.afterEach) {
afterEach(() => {
onNextUnhandledRejection = null;
unhandledRejections = null;
});
}
let lastSqliteInstance;
const Support = {
Sequelize,
/**
* Returns a Promise that will reject with the next unhandled rejection that occurs
* during this test (instead of failing the test)
*/
nextUnhandledRejection() {
return new Promise((resolve, reject) => {
onNextUnhandledRejection = reject;
});
},
/**
* Pushes all unhandled rejections that occur during this test onto destArray
* (instead of failing the test).
*
* @param {Error[]} destArray the array to push unhandled rejections onto. If you omit this,
* one will be created and returned for you.
*
* @returns {Error[]} destArray
*/
captureUnhandledRejections(destArray = []) {
unhandledRejections = destArray;
return unhandledRejections;
},
async prepareTransactionTest(sequelize) {
const dialect = Support.getTestDialect();
if (dialect === 'sqlite') {
const p = path.join(__dirname, 'tmp', 'db.sqlite');
if (lastSqliteInstance) {
await lastSqliteInstance.close();
}
if (fs.existsSync(p)) {
fs.unlinkSync(p);
}
const options = { ...sequelize.options, storage: p };
const _sequelize = new Sequelize(sequelize.config.database, null, null, options);
await _sequelize.sync({ force: true });
lastSqliteInstance = _sequelize;
return _sequelize;
}
return sequelize;
},
createSequelizeInstance(options) {
options = options || {};
options.dialect = this.getTestDialect();
const config = Config[options.dialect];
const 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,
dialectOptions: options.dialectOptions || config.dialectOptions || {},
minifyAliases: options.minifyAliases || config.minifyAliases,
});
if (process.env.DIALECT === 'postgres-native') {
sequelizeOptions.native = true;
}
if (config.storage || config.storage === '') {
sequelizeOptions.storage = config.storage;
}
return this.getSequelizeInstance(config.database, config.username, config.password, sequelizeOptions);
},
getConnectionOptionsWithoutPool() {
// Do not break existing config object - shallow clone before `delete config.pool`
const config = { ...Config[this.getTestDialect()] };
delete config.pool;
return config;
},
getSequelizeInstance(db, user, pass, options) {
options = options || {};
options.dialect = options.dialect || this.getTestDialect();
return new Sequelize(db, user, pass, options);
},
async clearDatabase(sequelize) {
const qi = sequelize.getQueryInterface();
await qi.dropAllTables();
sequelize.modelManager.models = [];
sequelize.models = {};
if (qi.dropAllEnums) {
await qi.dropAllEnums();
}
await this.dropTestSchemas(sequelize);
},
async dropTestSchemas(sequelize) {
const queryInterface = sequelize.getQueryInterface();
if (!queryInterface.queryGenerator._dialect.supports.schemas) {
return this.sequelize.drop({});
}
const schemas = await sequelize.showAllSchemas();
const schemasPromise = [];
for (const schema of schemas) {
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(error => error)));
},
getSupportedDialects() {
return fs.readdirSync(path.join(distDir, 'lib/dialects'))
.filter(file => !file.includes('.js') && !file.includes('abstract'));
},
getAbstractQueryGenerator(sequelize) {
class ModdedQueryGenerator extends AbstractQueryGenerator {
quoteIdentifier(x) {
return x;
}
}
const queryGenerator = new ModdedQueryGenerator({
sequelize,
_dialect: sequelize.dialect,
});
return queryGenerator;
},
getTestDialect() {
let envDialect = process.env.DIALECT || 'mysql';
if (envDialect === 'postgres-native') {
envDialect = 'postgres';
}
if (!this.getSupportedDialects().includes(envDialect)) {
throw new Error(`The dialect you have passed is unknown. Did you really mean: ${envDialect}`);
}
return envDialect;
},
getTestDialectTeaser(moduleName) {
let dialect = this.getTestDialect();
if (process.env.DIALECT === 'postgres-native') {
dialect = 'postgres-native';
}
return `[${dialect.toUpperCase()}] ${moduleName}`;
},
getPoolMax() {
return Config[this.getTestDialect()].pool.max;
},
expectsql(query, assertions) {
const expectations = assertions.query || assertions;
let expectation = expectations[Support.sequelize.dialect.name];
if (!expectation) {
if (expectations.default !== undefined) {
expectation = expectations.default;
if (typeof expectation === 'string') {
expectation = expectation
.replace(/\[/g, Support.sequelize.dialect.TICK_CHAR_LEFT)
.replace(/\]/g, Support.sequelize.dialect.TICK_CHAR_RIGHT);
}
} else {
throw new Error(`Undefined expectation for "${Support.sequelize.dialect.name}"! (expectations: ${JSON.stringify(expectations)})`);
}
}
if (query instanceof Error) {
expect(query.message).to.equal(expectation.message);
} else {
expect(query.query || query).to.equal(expectation);
}
if (assertions.bind) {
const bind = assertions.bind[Support.sequelize.dialect.name] || assertions.bind.default || assertions.bind;
expect(query.bind).to.deep.equal(bind);
}
},
rand() {
return Math.floor(Math.random() * 10e5);
},
isDeepEqualToOneOf(actual, expectedOptions) {
return expectedOptions.some(expected => isDeepStrictEqual(actual, expected));
},
/**
* Reduces insignificant whitespace from SQL string.
*
* @param {string} sql the SQL string
* @returns {string} the SQL string with insignificant whitespace removed.
*/
minifySql(sql) {
// replace all consecutive whitespaces with a single plain space character
return sql.replace(/\s+/g, ' ')
// remove space before coma
.replace(/ ,/g, ',')
// remove whitespace at start & end
.trim();
},
};
if (global.beforeEach) {
before(function () {
this.sequelize = Support.sequelize;
});
beforeEach(function () {
this.sequelize = Support.sequelize;
});
}
Support.sequelize = Support.createSequelizeInstance();
module.exports = Support;