-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
shared.js
310 lines (278 loc) · 7.89 KB
/
shared.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
'use strict';
const expect = require('chai').expect;
const { setTimeout } = require('timers');
// helpers for using chai.expect in the assert style
const assert = {
equal: function (a, b) {
expect(a).to.equal(b);
},
deepEqual: function (a, b) {
expect(a).to.eql(b);
},
strictEqual: function (a, b) {
expect(a).to.eql(b);
},
notEqual: function (a, b) {
expect(a).to.not.equal(b);
},
ok: function (a) {
expect(a).to.be.ok;
},
throws: function (func) {
expect(func).to.throw;
}
};
function delay(timeout) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve();
}, timeout);
});
}
function dropCollection(dbObj, collectionName) {
return dbObj.dropCollection(collectionName).catch(ignoreNsNotFound);
}
function filterForCommands(commands, bag) {
if (typeof commands === 'function') {
return function (event) {
if (commands(event.commandName)) bag.push(event);
};
}
commands = Array.isArray(commands) ? commands : [commands];
return function (event) {
if (commands.indexOf(event.commandName) !== -1) bag.push(event);
};
}
function filterOutCommands(commands, bag) {
if (typeof commands === 'function') {
return function (event) {
if (!commands(event.commandName)) bag.push(event);
};
}
commands = Array.isArray(commands) ? commands : [commands];
return function (event) {
if (commands.indexOf(event.commandName) === -1) bag.push(event);
};
}
function ignoreNsNotFound(err) {
if (!err.message.match(/ns not found/)) throw err;
}
function setupDatabase(configuration, dbsToClean) {
dbsToClean = Array.isArray(dbsToClean) ? dbsToClean : [];
var configDbName = configuration.db;
var client = configuration.newClient(configuration.writeConcernMax(), {
maxPoolSize: 1
});
dbsToClean.push(configDbName);
return client
.connect()
.then(() =>
dbsToClean.reduce(
(result, dbName) =>
result
.then(() =>
client.db(dbName).command({ dropAllUsersFromDatabase: 1, writeConcern: { w: 1 } })
)
.then(() => client.db(dbName).dropDatabase({ writeConcern: { w: 1 } })),
Promise.resolve()
)
)
.then(
() => client.close(),
err => client.close(() => Promise.reject(err))
);
}
/** @typedef {(client: MongoClient) => Promise | (client: MongoClient, done: Function) => void} withClientCallback */
/**
* Safely perform a test with provided MongoClient, ensuring client won't leak.
*
* @param {string|MongoClient} [client] if not provided, `withClient` must be bound to test function `this`
* @param {withClientCallback} callback the test function
*/
function withClient(client, callback) {
let connectionString;
if (arguments.length === 1) {
callback = client;
client = undefined;
} else {
if (typeof client === 'string') {
connectionString = client;
client = undefined;
}
}
if (callback.length === 2) {
const cb = callback;
callback = client => new Promise(resolve => cb(client, resolve));
}
function cleanup(err) {
return new Promise((resolve, reject) => {
try {
client.close(closeErr => {
const finalErr = err || closeErr;
if (finalErr) {
return reject(finalErr);
}
return resolve();
});
} catch (e) {
return reject(err || e);
}
});
}
function lambda() {
if (!client) {
client = this.configuration.newClient(connectionString);
}
return client
.connect()
.then(callback)
.then(err => {
cleanup();
if (err) {
throw err;
}
}, cleanup);
}
if (this && this.configuration) {
return lambda.call(this);
}
return lambda;
}
/** @typedef {(client: MongoClient, events: Array, done: Function) => void} withMonitoredClientCallback */
/**
* Perform a test with a monitored MongoClient that will filter for certain commands.
*
* @param {string|Array|Function} commands commands to filter for
* @param {object} [options] options to pass on to configuration.newClient
* @param {object} [options.queryOptions] connection string options
* @param {object} [options.clientOptions] MongoClient options
* @param {withMonitoredClientCallback} callback the test function
*/
function withMonitoredClient(commands, options, callback) {
if (arguments.length === 2) {
callback = options;
options = {};
}
if (!Object.prototype.hasOwnProperty.call(callback, 'prototype')) {
throw new Error('withMonitoredClient callback can not be arrow function');
}
return function () {
const monitoredClient = this.configuration.newClient(
Object.assign({}, options.queryOptions),
Object.assign({ monitorCommands: true }, options.clientOptions)
);
const events = [];
monitoredClient.on('commandStarted', filterForCommands(commands, events));
return withClient(monitoredClient, (client, done) =>
callback.bind(this)(client, events, done)
)();
};
}
/**
* Safely perform a test with an arbitrary cursor.
*
* @param {{close: () => void}} cursor any cursor that needs to be closed
* @param {(cursor: object, done: Mocha.Done) => void} body test body
* @param {Function} done called after cleanup
*/
function withCursor(cursor, body, done) {
let clean = false;
function cleanup(testErr) {
if (clean) return;
clean = true;
return cursor.close(closeErr => done(testErr || closeErr));
}
try {
body(cursor, cleanup);
} catch (err) {
cleanup(err);
}
}
/**
* A class for listening on specific events
*
* @example
* beforeEach(function() {
* // capture all commandStarted events from client. Get by doing this.commandStarted.events;
* this.commandStarted = new EventCollector(this.client, 'commandStarted');
* });
* @example
* beforeEach(function() {
* // same as above, but only allows 'insert' and 'find' events
* this.commandStarted = new EventCollector(this.client, 'commandStarted', {
* include: ['insert', 'find']
* });
* });
* @example
* beforeEach(function() {
* // same as above, but excludes 'insert' events
* this.commandStarted = new EventCollector(this.client, 'commandStarted', {
* exclude: ['insert']
* });
* });
*/
class APMEventCollector {
constructor(client, eventName, options) {
this._client = client;
this._eventName = eventName;
this._events = [];
this._listener = e => this._events.push(e);
this._client.on(this._eventName, this._listener);
options = options || {};
const include = this._buildSet(options.include);
if (include.size > 0) {
this._include = include;
}
this._exclude = this._buildSet(options.exclude);
}
_buildSet(input) {
if (Array.isArray(input)) {
return new Set(input.map(x => x.toLowerCase()));
} else if (typeof input === 'string') {
return new Set([input.toLowerCase()]);
}
return new Set();
}
get events() {
let events = this._events;
if (this._include) {
events = events.filter(e => this._include.has(e.commandName.toLowerCase()));
}
return events.filter(e => !this._exclude.has(e.commandName.toLowerCase()));
}
clear() {
this._events = [];
}
teardown() {
this._client.removeListener(this._eventName, this._listener);
}
}
// simplified `withClient` helper that only uses callbacks
function withClientV2(callback) {
return function testFunction(done) {
const client = this.configuration.newClient({ monitorCommands: true });
client.connect(err => {
if (err) return done(err);
this.defer(() => client.close());
try {
callback.call(this, client, done);
} catch (err) {
done(err);
}
});
};
}
module.exports = {
assert,
delay,
dropCollection,
filterForCommands,
filterOutCommands,
ignoreNsNotFound,
setupDatabase,
withClient,
withClientV2,
withMonitoredClient,
withCursor,
APMEventCollector
};